forked from krakozaure/tmpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
104 lines (88 loc) · 2.2 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"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 _, keyFile := range KeysList {
for k, v := range getKeyVariables(keyFile) {
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 := os.ReadFile(file)
if err != nil {
log.Fatalf("unable to read file\n%v\n", err)
}
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.Fatalf("unable to load data\n%v\n", err)
}
return vars
}
func getKeyVariables(keyFile string) map[string]interface{} {
kf := strings.SplitN(keyFile, "=", 2)
if len(kf) != 2 {
log.Fatalf("bad key file format: %s", keyFile)
}
key := kf[0]
file := kf[1]
vars := make(map[string]interface{})
var kdata interface{}
bytes, err := os.ReadFile(file)
if err != nil {
log.Fatalf("unable to read file\n%v\n", err)
}
if strings.HasSuffix(file, ".json") {
err = json.Unmarshal(bytes, &kdata)
} else if strings.HasSuffix(file, ".toml") {
err = toml.Unmarshal(bytes, &kdata)
} else if strings.HasSuffix(file, ".yaml") || strings.HasSuffix(file, ".yml") {
err = yaml.Unmarshal(bytes, &kdata)
} else {
err = fmt.Errorf("bad file type: %s", file)
}
if err != nil {
log.Fatalf("unable to load data\n%v\n", err)
}
vars[key] = kdata
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
}