|
| 1 | +package harness |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "path/filepath" |
| 8 | + "strings" |
| 9 | + |
| 10 | + v3 "github.com/harness/godotenv/v3" |
| 11 | +) |
| 12 | + |
| 13 | +const ( |
| 14 | + // ErrorMessageKey is the key used to retrieve or store the error message content. |
| 15 | + ErrorMessageKey = "ERROR_MESSAGE" |
| 16 | + |
| 17 | + // ErrorCodeKey is the key used to identify the specific error code associated with an error. |
| 18 | + ErrorCodeKey = "ERROR_CODE" |
| 19 | + |
| 20 | + // ErrorCategoryKey is the key used to classify the category of the error, which can help in grouping similar types of errors. |
| 21 | + ErrorCategoryKey = "ERROR_CATEGORY" |
| 22 | + |
| 23 | + // MetadataFile is the key for the file that stores metadata associated with an error, such as details about the error's source or context. |
| 24 | + MetadataFile = "ERROR_METADATA_FILE" |
| 25 | + |
| 26 | + // DroneOutputFile is the key for the file where outputs can be exported and utilized in the subsequent steps in Harness CI pipeline. |
| 27 | + DroneOutputFile = "DRONE_OUTPUT" |
| 28 | + |
| 29 | + // HarnessOutputSecretFile is the key for the file where secrets can be exported and utilized in the subsequent steps in Harness CI pipeline. |
| 30 | + HarnessOutputSecretFile = "HARNESS_OUTPUT_SECRET_FILE" |
| 31 | +) |
| 32 | + |
| 33 | +// SetSecret sets a new secret by adding it to the HARNESS_OUTPUT_SECRET_FILE file |
| 34 | +func SetSecret(name, value string) error { |
| 35 | + return UpdateOrRemoveKeyValue(HarnessOutputSecretFile, name, value, false) |
| 36 | +} |
| 37 | + |
| 38 | +// UpdateSecret overwrites the value of an existing secret. |
| 39 | +func UpdateSecret(name, value string) error { |
| 40 | + return UpdateOrRemoveKeyValue(HarnessOutputSecretFile, name, value, false) |
| 41 | +} |
| 42 | + |
| 43 | +// DeleteSecret removes a secret from the file entirely. |
| 44 | +func DeleteSecret(name string) error { |
| 45 | + return UpdateOrRemoveKeyValue(HarnessOutputSecretFile, name, "", true) |
| 46 | +} |
| 47 | + |
| 48 | +// SetOutput sets a new secret by adding it to the DRONE_OUTPUT file |
| 49 | +func SetOutput(name, value string) error { |
| 50 | + return UpdateOrRemoveKeyValue(DroneOutputFile, name, value, false) |
| 51 | +} |
| 52 | + |
| 53 | +// UpdateOutput overwrites the value of an existing output. |
| 54 | +func UpdateOutput(name, value string) error { |
| 55 | + return UpdateOrRemoveKeyValue(DroneOutputFile, name, value, false) |
| 56 | +} |
| 57 | + |
| 58 | +// DeleteOutput removes an output from the file entirely. |
| 59 | +func DeleteOutput(name string) error { |
| 60 | + return UpdateOrRemoveKeyValue(DroneOutputFile, name, "", true) |
| 61 | +} |
| 62 | + |
| 63 | +// SetErrorMetadata sets the error message, error code, and error category, writing them to the CI_ERROR_METADATA file |
| 64 | +func SetErrorMetadata(message, code, category string) error { |
| 65 | + // Write the error message |
| 66 | + if err := UpdateOrRemoveKeyValue(MetadataFile, ErrorMessageKey, message, false); err != nil { |
| 67 | + return err |
| 68 | + } |
| 69 | + |
| 70 | + // Write the error code |
| 71 | + if err := UpdateOrRemoveKeyValue(MetadataFile, ErrorCodeKey, code, false); err != nil { |
| 72 | + return err |
| 73 | + } |
| 74 | + |
| 75 | + // Write the error category |
| 76 | + if err := UpdateOrRemoveKeyValue(MetadataFile, ErrorCategoryKey, category, false); err != nil { |
| 77 | + return err |
| 78 | + } |
| 79 | + |
| 80 | + return nil |
| 81 | +} |
| 82 | + |
| 83 | +// UpdateOrRemoveKeyValue updates or deletes a key-value pair in the specified file. |
| 84 | +func UpdateOrRemoveKeyValue(envVar, key, newValue string, deleteKey bool) error { |
| 85 | + filePath := os.Getenv(envVar) |
| 86 | + if filePath == "" { |
| 87 | + return fmt.Errorf("environment variable %s is not set", envVar) |
| 88 | + } |
| 89 | + |
| 90 | + // Ensure the file exists before reading |
| 91 | + if _, err := os.Stat(filePath); os.IsNotExist(err) { |
| 92 | + _, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) |
| 93 | + if err != nil { |
| 94 | + return fmt.Errorf("failed to create file: %w", err) |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + // Trim trailing newline characters from newValue |
| 99 | + newValue = strings.TrimRight(newValue, "\n") |
| 100 | + |
| 101 | + ext := strings.ToLower(filepath.Ext(filePath)) |
| 102 | + |
| 103 | + if ext == ".env" { |
| 104 | + // Use godotenv for .env files |
| 105 | + data, err := v3.Read(filePath) |
| 106 | + if err != nil { |
| 107 | + return fmt.Errorf("failed to parse .env file: %w", err) |
| 108 | + } |
| 109 | + |
| 110 | + if deleteKey { |
| 111 | + delete(data, key) |
| 112 | + } else { |
| 113 | + data[key] = newValue |
| 114 | + } |
| 115 | + |
| 116 | + err = v3.Write(data, filePath) |
| 117 | + if err != nil { |
| 118 | + return fmt.Errorf("failed to write .env file: %w", err) |
| 119 | + } |
| 120 | + } else { |
| 121 | + // For .out files, process manually |
| 122 | + // For .out files, check for multiline values |
| 123 | + if strings.Contains(newValue, "\n") { |
| 124 | + return fmt.Errorf("multiline values are not allowed for key %s in .out file", key) |
| 125 | + } |
| 126 | + |
| 127 | + lines, err := ReadLines(filePath) |
| 128 | + if err != nil { |
| 129 | + return fmt.Errorf("failed to read file: %w", err) |
| 130 | + } |
| 131 | + |
| 132 | + var updatedLines []string |
| 133 | + found := false |
| 134 | + for _, line := range lines { |
| 135 | + k, v := ParseKeyValue(line, ext) |
| 136 | + if k == key { |
| 137 | + found = true |
| 138 | + if deleteKey { |
| 139 | + continue |
| 140 | + } |
| 141 | + updatedLines = append(updatedLines, FormatKeyValue(k, newValue, ext)) |
| 142 | + } else { |
| 143 | + updatedLines = append(updatedLines, FormatKeyValue(k, v, ext)) |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + if !found && !deleteKey { |
| 148 | + updatedLines = append(updatedLines, FormatKeyValue(key, newValue, ext)) |
| 149 | + } |
| 150 | + |
| 151 | + err = WriteLines(filePath, updatedLines) |
| 152 | + if err != nil { |
| 153 | + return fmt.Errorf("failed to write file: %w", err) |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + return nil |
| 158 | +} |
| 159 | + |
| 160 | +// ReadLines reads lines from a file and returns them as a slice of strings. |
| 161 | +func ReadLines(filename string) ([]string, error) { |
| 162 | + file, err := os.Open(filename) |
| 163 | + if err != nil { |
| 164 | + return nil, err |
| 165 | + } |
| 166 | + defer file.Close() |
| 167 | + |
| 168 | + var lines []string |
| 169 | + scanner := bufio.NewScanner(file) |
| 170 | + for scanner.Scan() { |
| 171 | + lines = append(lines, scanner.Text()) |
| 172 | + } |
| 173 | + return lines, scanner.Err() |
| 174 | +} |
| 175 | + |
| 176 | +// WriteLines writes a slice of strings to a file, each string being written to a new line. |
| 177 | +func WriteLines(filename string, lines []string) error { |
| 178 | + file, err := os.Create(filename) |
| 179 | + if err != nil { |
| 180 | + return fmt.Errorf("failed to create file: %w", err) |
| 181 | + } |
| 182 | + defer file.Close() |
| 183 | + |
| 184 | + for _, line := range lines { |
| 185 | + _, err := file.WriteString(line + "\n") |
| 186 | + if err != nil { |
| 187 | + return fmt.Errorf("failed to write to file: %w", err) |
| 188 | + } |
| 189 | + } |
| 190 | + return nil |
| 191 | +} |
| 192 | + |
| 193 | +// ParseKeyValue parses a key-value pair from a string and returns the key and value. |
| 194 | +func ParseKeyValue(line, ext string) (string, string) { |
| 195 | + if ext == ".out" { |
| 196 | + parts := strings.Fields(line) |
| 197 | + if len(parts) > 1 { |
| 198 | + return strings.TrimSpace(parts[0]), strings.TrimSpace(strings.Join(parts[1:], " ")) |
| 199 | + } |
| 200 | + return strings.TrimSpace(parts[0]), "" |
| 201 | + } |
| 202 | + // .env is handled by godotenv, so this is not used for .env files |
| 203 | + return "", "" |
| 204 | +} |
| 205 | + |
| 206 | +// FormatKeyValue handles formatting for .env and .out files. |
| 207 | +func FormatKeyValue(key, value, ext string) string { |
| 208 | + if ext == ".out" { |
| 209 | + return fmt.Sprintf("%s %s", key, value) |
| 210 | + } |
| 211 | + // For .env files, use godotenv directly; this function won't apply |
| 212 | + return "" |
| 213 | +} |
0 commit comments