forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
105 lines (92 loc) · 2.05 KB
/
config.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
105
package pop
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"log"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/markbates/going/defaults"
"gopkg.in/yaml.v2"
)
var lookupPaths = []string{"", "./config", "/config", "../", "../config", "../..", "../../config"}
var ConfigName = "database.yml"
func init() {
ap := os.Getenv("APP_PATH")
if ap != "" {
AddLookupPaths(ap)
}
ap = os.Getenv("POP_PATH")
if ap != "" {
AddLookupPaths(ap)
}
LoadConfig()
}
func LoadConfig() {
path, err := findConfigPath()
if err == nil {
Connections = map[string]*Connection{}
err = loadConfig(path)
if err != nil {
log.Fatal(err)
}
}
}
func LookupPaths() []string {
return lookupPaths
}
func AddLookupPaths(paths ...string) {
lookupPaths = append(paths, lookupPaths...)
LoadConfig()
}
func findConfigPath() (string, error) {
for _, p := range LookupPaths() {
path, _ := filepath.Abs(filepath.Join(p, ConfigName))
if _, err := os.Stat(path); err == nil {
return path, err
}
}
return "", errors.New("[POP]: Tried to load configuration file, but couldn't find it.")
}
func loadConfig(path string) error {
if Debug {
fmt.Printf("[POP]: Loading config file from %s\n", path)
}
b, err := ioutil.ReadFile(path)
if err != nil {
return errors.Wrapf(err, "couldn't read file %s", path)
}
tmpl := template.New("test")
tmpl.Funcs(map[string]interface{}{
"envOr": func(s1, s2 string) string {
return defaults.String(os.Getenv(s1), s2)
},
"env": func(s1 string) string {
return os.Getenv(s1)
},
})
t, err := tmpl.Parse(string(b))
if err != nil {
return errors.Wrap(err, "couldn't parse config template")
}
var bb bytes.Buffer
err = t.Execute(&bb, nil)
if err != nil {
return errors.Wrap(err, "couldn't execute config template")
}
deets := map[string]*ConnectionDetails{}
err = yaml.Unmarshal(bb.Bytes(), &deets)
if err != nil {
return errors.Wrap(err, "couldn't unmarshal config to yaml")
}
for n, d := range deets {
con, err := NewConnection(d)
if err != nil {
return err
}
Connections[n] = con
}
return nil
}