forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
109 lines (96 loc) · 2.4 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
106
107
108
109
package pop
import (
"bytes"
"io"
"io/ioutil"
"os"
"path/filepath"
"text/template"
"github.com/pkg/errors"
"github.com/markbates/going/defaults"
"gopkg.in/yaml.v2"
)
var lookupPaths = []string{"", "./config", "/config", "../", "../config", "../..", "../../config"}
// ConfigName is the name of the YAML databases config file
var ConfigName = "database.yml"
func init() {
ap := os.Getenv("APP_PATH")
if ap != "" {
AddLookupPaths(ap)
}
ap = os.Getenv("POP_PATH")
if ap != "" {
AddLookupPaths(ap)
}
LoadConfigFile()
}
// LoadConfigFile loads a POP config file from the configured lookup paths
func LoadConfigFile() error {
path, err := findConfigPath()
if err != nil {
return errors.WithStack(err)
}
Connections = map[string]*Connection{}
Log("Loading config file from %s\n", path)
f, err := os.Open(path)
if err != nil {
return errors.WithStack(err)
}
return LoadFrom(f)
}
// LookupPaths returns the current configuration lookup paths
func LookupPaths() []string {
return lookupPaths
}
// AddLookupPaths add paths to the current lookup paths list
func AddLookupPaths(paths ...string) error {
lookupPaths = append(paths, lookupPaths...)
return LoadConfigFile()
}
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("tried to load pop configuration file, but couldn't find it")
}
// LoadFrom reads a configuration from the reader and sets up the connections
func LoadFrom(r io.Reader) error {
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)
},
})
b, err := ioutil.ReadAll(r)
if err != nil {
return errors.WithStack(err)
}
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
}