|
| 1 | +// Package kvfile provides utilities to parse line-delimited key/value files |
| 2 | +// such as used for label-files and env-files. |
| 3 | +// |
| 4 | +// # File format |
| 5 | +// |
| 6 | +// key/value files use the following syntax: |
| 7 | +// |
| 8 | +// - File must be valid UTF-8. |
| 9 | +// - BOM headers are removed. |
| 10 | +// - Leading whitespace is removed for each line. |
| 11 | +// - Lines starting with "#" are ignored. |
| 12 | +// - Empty lines are ignored. |
| 13 | +// - Key/Value pairs are provided as "KEY[=<VALUE>]". |
| 14 | +// - Maximum line-length is limited to [bufio.MaxScanTokenSize]. |
| 15 | +// |
| 16 | +// # Interpolation, substitution, and escaping |
| 17 | +// |
| 18 | +// Both keys and values are used as-is; no interpolation, substitution or |
| 19 | +// escaping is supported, and quotes are considered part of the key or value. |
| 20 | +// Whitespace in values (including leading and trailing) is preserved. Given |
| 21 | +// that the file format is line-delimited, neither key, nor value, can contain |
| 22 | +// newlines. |
| 23 | +// |
| 24 | +// # Key/Value pairs |
| 25 | +// |
| 26 | +// Key/Value pairs take the following format: |
| 27 | +// |
| 28 | +// KEY[=<VALUE>] |
| 29 | +// |
| 30 | +// KEY is required and may not contain whitespaces or NUL characters. Any |
| 31 | +// other character (except for the "=" delimiter) are accepted, but it is |
| 32 | +// recommended to use a subset of the POSIX portable character set, as |
| 33 | +// outlined in [Environment Variables]. |
| 34 | +// |
| 35 | +// VALUE is optional, but may be empty. If no value is provided (i.e., no |
| 36 | +// equal sign ("=") is present), the KEY is omitted in the result, but some |
| 37 | +// functions accept a lookup-function to provide a default value for the |
| 38 | +// given key. |
| 39 | +// |
| 40 | +// [Environment Variables]: https://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html |
| 41 | +package kvfile |
| 42 | + |
| 43 | +import ( |
| 44 | + "bufio" |
| 45 | + "bytes" |
| 46 | + "fmt" |
| 47 | + "io" |
| 48 | + "os" |
| 49 | + "strings" |
| 50 | + "unicode" |
| 51 | + "unicode/utf8" |
| 52 | +) |
| 53 | + |
| 54 | +// Parse parses a line-delimited key/value pairs separated by equal sign. |
| 55 | +// It accepts a lookupFn to lookup default values for keys that do not define |
| 56 | +// a value. An error is produced if parsing failed, the content contains invalid |
| 57 | +// UTF-8 characters, or a key contains whitespaces. |
| 58 | +func Parse(filename string, lookupFn func(key string) (value string, found bool)) ([]string, error) { |
| 59 | + fh, err := os.Open(filename) |
| 60 | + if err != nil { |
| 61 | + return []string{}, err |
| 62 | + } |
| 63 | + out, err := parseKeyValueFile(fh, lookupFn) |
| 64 | + _ = fh.Close() |
| 65 | + if err != nil { |
| 66 | + return []string{}, fmt.Errorf("invalid env file (%s): %v", filename, err) |
| 67 | + } |
| 68 | + return out, nil |
| 69 | +} |
| 70 | + |
| 71 | +// ParseFromReader parses a line-delimited key/value pairs separated by equal sign. |
| 72 | +// It accepts a lookupFn to lookup default values for keys that do not define |
| 73 | +// a value. An error is produced if parsing failed, the content contains invalid |
| 74 | +// UTF-8 characters, or a key contains whitespaces. |
| 75 | +func ParseFromReader(r io.Reader, lookupFn func(key string) (value string, found bool)) ([]string, error) { |
| 76 | + return parseKeyValueFile(r, lookupFn) |
| 77 | +} |
| 78 | + |
| 79 | +const whiteSpaces = " \t" |
| 80 | + |
| 81 | +func parseKeyValueFile(r io.Reader, lookupFn func(string) (string, bool)) ([]string, error) { |
| 82 | + lines := []string{} |
| 83 | + scanner := bufio.NewScanner(r) |
| 84 | + utf8bom := []byte{0xEF, 0xBB, 0xBF} |
| 85 | + for currentLine := 1; scanner.Scan(); currentLine++ { |
| 86 | + scannedBytes := scanner.Bytes() |
| 87 | + if !utf8.Valid(scannedBytes) { |
| 88 | + return []string{}, fmt.Errorf("invalid utf8 bytes at line %d: %v", currentLine, scannedBytes) |
| 89 | + } |
| 90 | + // We trim UTF8 BOM |
| 91 | + if currentLine == 1 { |
| 92 | + scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom) |
| 93 | + } |
| 94 | + // trim the line from all leading whitespace first. trailing whitespace |
| 95 | + // is part of the value, and is kept unmodified. |
| 96 | + line := strings.TrimLeftFunc(string(scannedBytes), unicode.IsSpace) |
| 97 | + |
| 98 | + if len(line) == 0 || line[0] == '#' { |
| 99 | + // skip empty lines and comments (lines starting with '#') |
| 100 | + continue |
| 101 | + } |
| 102 | + |
| 103 | + key, _, hasValue := strings.Cut(line, "=") |
| 104 | + if len(key) == 0 { |
| 105 | + return []string{}, fmt.Errorf("no variable name on line '%s'", line) |
| 106 | + } |
| 107 | + |
| 108 | + // leading whitespace was already removed from the line, but |
| 109 | + // variables are not allowed to contain whitespace or have |
| 110 | + // trailing whitespace. |
| 111 | + if strings.ContainsAny(key, whiteSpaces) { |
| 112 | + return []string{}, fmt.Errorf("variable '%s' contains whitespaces", key) |
| 113 | + } |
| 114 | + |
| 115 | + if hasValue { |
| 116 | + // key/value pair is valid and has a value; add the line as-is. |
| 117 | + lines = append(lines, line) |
| 118 | + continue |
| 119 | + } |
| 120 | + |
| 121 | + if lookupFn != nil { |
| 122 | + // No value given; try to look up the value. The value may be |
| 123 | + // empty but if no value is found, the key is omitted. |
| 124 | + if value, found := lookupFn(line); found { |
| 125 | + lines = append(lines, key+"="+value) |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + return lines, scanner.Err() |
| 130 | +} |
0 commit comments