-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
67 lines (56 loc) · 1.34 KB
/
context.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
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"strings"
"github.com/BurntSushi/toml"
"gopkg.in/yaml.v3"
)
var ctx = make(map[string]interface{})
func loadContext() {
for _, file := range FilesList {
for k, v := range getFileVariables(file) {
ctx[k] = v
}
}
for k, v := range getCliVariables() {
ctx[k] = v
}
}
func getFileVariables(file string) map[string]interface{} {
vars := make(map[string]interface{})
bytes, err := ioutil.ReadFile(file)
if err != nil {
log.Printf("unable to read file\n%v\n", err)
return vars
}
if strings.HasSuffix(file, ".json") {
err = json.Unmarshal(bytes, &vars)
} else if strings.HasSuffix(file, ".toml") {
err = toml.Unmarshal(bytes, &vars)
} else if strings.HasSuffix(file, ".yaml") || strings.HasSuffix(file, ".yml") {
err = yaml.Unmarshal(bytes, &vars)
} else {
err = fmt.Errorf("bad file type: %s", file)
}
if err != nil {
log.Printf("unable to load data\n%v\n", err)
}
return vars
}
func getCliVariables() map[string]string {
vars := make(map[string]string)
for _, pair := range VarsList {
kv := strings.SplitN(pair, "=", 2)
v := kv[1]
if strings.HasPrefix(v, "\"") && strings.HasSuffix(v, "\"") {
v = v[1 : len(v)-1]
} else if strings.HasPrefix(v, "'") && strings.HasSuffix(v, "'") {
v = v[1 : len(v)-1]
}
vars[kv[0]] = v
}
return vars
}