1 package vars
2
3 import (
4 "bufio"
5 "fmt"
6 "strings"
7 "unicode"
8
9 "github.com/redhat-developer/odo/pkg/testingutil/filesystem"
10 )
11
12
13
14
15 func GetVariables(fs filesystem.Filesystem, filename string, override []string, lookupEnv func(string) (string, bool)) (map[string]string, error) {
16
17 result := map[string]string{}
18 var err error
19 if len(filename) > 0 {
20 result, err = parseKeyValueFile(fs, filename, lookupEnv)
21 if err != nil {
22 return nil, err
23 }
24 }
25 overrideVars, err := parseKeyValueStrings(override, lookupEnv)
26 if err != nil {
27 return nil, err
28 }
29
30 for k, v := range overrideVars {
31 result[k] = v
32 }
33
34 return result, nil
35 }
36
37
38
39
40
41 func parseKeyValueFile(fs filesystem.Filesystem, filename string, lookupEnv func(string) (string, bool)) (map[string]string, error) {
42 f, err := fs.Open(filename)
43 if err != nil {
44 return nil, err
45 }
46 defer f.Close()
47
48 result := map[string]string{}
49
50 scanner := bufio.NewScanner(f)
51 for scanner.Scan() {
52 scannedText := scanner.Text()
53
54 key, value, err := parseKeyValueString(scannedText, lookupEnv)
55 if err != nil {
56 return nil, err
57 }
58 if len(key) == 0 {
59 continue
60 }
61 result[key] = value
62 }
63
64 return result, nil
65 }
66
67 func parseKeyValueStrings(strs []string, lookupEnv func(string) (string, bool)) (map[string]string, error) {
68 result := map[string]string{}
69
70 for _, str := range strs {
71 key, value, err := parseKeyValueString(str, lookupEnv)
72 if err != nil {
73 return nil, err
74 }
75 if len(key) == 0 {
76 continue
77 }
78 result[key] = value
79 }
80 return result, nil
81 }
82
83
84
85
86
87 func parseKeyValueString(s string, lookupEnv func(string) (string, bool)) (string, string, error) {
88 line := strings.TrimLeftFunc(s, unicode.IsSpace)
89 if len(line) == 0 || strings.HasPrefix(line, "#") {
90 return "", "", nil
91 }
92 parts := strings.SplitN(line, "=", 2)
93 key := parts[0]
94
95
96
97 if len(key) == 0 {
98 return "", "", NewErrBadKey(fmt.Sprintf("no key defined in line %q", s))
99 }
100
101 var value string
102 if len(parts) > 1 {
103 value = parts[1]
104 } else {
105 var found bool
106 value, found = lookupEnv(key)
107 if !found {
108 return "", "", nil
109 }
110 }
111
112 return key, value, nil
113 }
114
View as plain text