forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
102 lines (89 loc) · 1.83 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
package pop
import (
"bytes"
"errors"
"fmt"
"html/template"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/markbates/going/defaults"
"gopkg.in/yaml.v2"
)
var lookupPaths = []string{"", "./config", "/config", "../", "../config", "../..", "../../config"}
var ConfigName = "database.yml"
func init() {
LoadConfig()
}
func LoadConfig() {
path, err := findConfigPath()
if err == nil {
loadConfig(path)
}
}
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 getAppPath() (string, error) {
pwd := os.Getenv("APP_PATH")
if pwd == "" {
b, err := exec.Command("pwd").Output()
if err != nil {
return "", err
}
pwd = string(b)
}
return strings.TrimSuffix(pwd, "\n"), nil
}
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 err
}
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 err
}
var bb bytes.Buffer
err = t.Execute(&bb, nil)
if err != nil {
return err
}
conns := map[string]*ConnectionDetails{}
err = yaml.Unmarshal(bb.Bytes(), &conns)
if err != nil {
return err
}
for n, c := range conns {
con := NewConnection(c)
Connections[n] = con
}
return nil
}