...
1
16
17 package util
18
19 import (
20 "bufio"
21 "bytes"
22 "fmt"
23 "os"
24 "strings"
25 "unicode"
26 "unicode/utf8"
27
28 "k8s.io/apimachinery/pkg/util/validation"
29 )
30
31 var utf8bom = []byte{0xEF, 0xBB, 0xBF}
32
33
34
35 func processEnvFileLine(line []byte, filePath string,
36 currentLine int) (key, value string, err error) {
37
38 if !utf8.Valid(line) {
39 return ``, ``, fmt.Errorf("env file %s contains invalid utf8 bytes at line %d: %v",
40 filePath, currentLine+1, line)
41 }
42
43
44 if currentLine == 0 {
45 line = bytes.TrimPrefix(line, utf8bom)
46 }
47
48
49 line = bytes.TrimLeftFunc(line, unicode.IsSpace)
50
51
52 if len(line) == 0 || line[0] == '#' {
53 return ``, ``, nil
54 }
55
56 data := strings.SplitN(string(line), "=", 2)
57 key = data[0]
58 if errs := validation.IsEnvVarName(key); len(errs) != 0 {
59 return ``, ``, fmt.Errorf("%q is not a valid key name: %s", key, strings.Join(errs, ";"))
60 }
61
62 if len(data) == 2 {
63 value = data[1]
64 } else {
65
66
67 value = os.Getenv(key)
68 }
69 return
70 }
71
72
73
74 func AddFromEnvFile(filePath string, addTo func(key, value string) error) error {
75 f, err := os.Open(filePath)
76 if err != nil {
77 return err
78 }
79 defer f.Close()
80
81 scanner := bufio.NewScanner(f)
82 currentLine := 0
83 for scanner.Scan() {
84
85
86 scannedBytes := scanner.Bytes()
87 key, value, err := processEnvFileLine(scannedBytes, filePath, currentLine)
88 if err != nil {
89 return err
90 }
91 currentLine++
92
93 if len(key) == 0 {
94
95 continue
96 }
97
98 if err = addTo(key, value); err != nil {
99 return err
100 }
101 }
102 return nil
103 }
104
View as plain text