-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconfig_file.go
56 lines (44 loc) · 1.26 KB
/
config_file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package getopt
import (
"io/ioutil"
"regexp"
"strings"
)
func mapifyEnvironment(environment []string) (envArray map[string]string) {
envArray = make(map[string]string)
for _, cur := range environment {
envVar := strings.Split(cur, "=")
if len(envVar) > 1 {
envArray[strings.TrimSpace(envVar[0])] = strings.TrimSpace(envVar[1])
}
}
return
}
func readConfigFile(path string) (configEntries []string, err *GetOptError) {
// ignore all lines without a '=' and with invalid key names
validConfigEntry := regexp.MustCompile("^[A-z0-9_.,]+=.*$")
content, ioErr := ioutil.ReadFile(path)
contentStringified := string(content)
if ioErr != nil {
err = &GetOptError{ConfigFileNotFound, ioErr.Error()}
} else {
for _, line := range strings.Split(contentStringified, "\n") {
if validConfigEntry.MatchString(line) {
configEntries = append(configEntries, line)
}
}
}
return
}
func processConfigFile(path string, environment map[string]string) (newEnvironment map[string]string, err *GetOptError) {
newEnvironment = environment
configEntries, err := readConfigFile(strings.TrimSpace(path))
if err == nil {
for key, value := range mapifyEnvironment(configEntries) {
if newEnvironment[key] == "" {
newEnvironment[key] = value
}
}
}
return
}