-
Notifications
You must be signed in to change notification settings - Fork 249
/
yaml.go
97 lines (89 loc) · 2.07 KB
/
yaml.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
package yaml
import (
"fmt"
"github.com/ghodss/yaml"
"github.com/jeremywohl/flatten"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func load(data []byte) error {
config := make(map[string]interface{})
err := yaml.Unmarshal(data, &config)
if err != nil {
return err
}
flat, _ := flatten.Flatten(config, "", flatten.UnderscoreStyle)
currentEnv := map[string]bool{}
rawEnv := os.Environ()
for _, rawEnvLine := range rawEnv {
key := strings.Split(rawEnvLine, "=")[0]
currentEnv[key] = true
}
for k, v := range flat {
upperK := strings.ToUpper(k)
if !currentEnv[upperK] {
_ = os.Setenv(upperK, fmt.Sprint(v))
}
}
return nil
}
func LoadReader(reader io.Reader) error {
data, err := ioutil.ReadAll(reader)
if err != nil {
return err
}
return load(data)
}
func loadFile(file string) {
data, _ := ioutil.ReadFile(file)
err := load(data)
if err != nil {
panic(err)
}
}
func Load(env string) {
wd, _ := os.Getwd()
matches, _ := filepath.Glob(filepath.Join(wd, fmt.Sprintf("app-%s-local.%s", env, "y*ml")))
for _, item := range matches {
loadFile(item)
}
if "test" != env {
matches, _ = filepath.Glob(filepath.Join(wd, fmt.Sprintf("app-local.%s", "y*ml")))
for _, item := range matches {
loadFile(item)
}
}
matches, _ = filepath.Glob(filepath.Join(wd, fmt.Sprintf("app-%s.%s", env, "y*ml")))
for _, item := range matches {
loadFile(item)
}
matches, _ = filepath.Glob(filepath.Join(wd, fmt.Sprintf("app.%s", "y*ml")))
for _, item := range matches {
loadFile(item)
}
}
func LoadReaderAsMap(reader io.Reader) (map[string]interface{}, error) {
data, err := ioutil.ReadAll(reader)
if err != nil {
return nil, err
}
return loadAsMap(data)
}
func LoadFileAsMap(file string) (map[string]interface{}, error) {
data, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
return loadAsMap(data)
}
func loadAsMap(data []byte) (map[string]interface{}, error) {
config := make(map[string]interface{})
err := yaml.Unmarshal(data, &config)
if err != nil {
return nil, err
}
return flatten.Flatten(config, "", flatten.DotStyle)
}