forked from marianogappa/sql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
112 lines (93 loc) · 2.45 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
110
111
112
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"os/user"
"strings"
)
const DefaultMaxAppServerConnections = 5
type settings struct {
MaxAppServerConnections int64
Databases map[string]database
DatabaseGroups map[string][]string
}
type database struct {
AppServer string
DbServer string
DbName string
User string
Pass string
SQLType string
}
func getConfigPaths(fileName string) []string {
var paths []string
usr, err := user.Current()
if err != nil {
usage("Couldn't obtain the current user err=%v", err)
}
home := usr.HomeDir
xdgHome := os.Getenv("XDG_CONFIG_HOME")
if xdgHome == "" {
xdgHome = fmt.Sprintf("%v/.config/", home)
}
xdgHome += fmt.Sprintf("sql/%v", fileName)
paths = append(paths, xdgHome)
xdgConfigDirs := strings.Split(os.Getenv("XDG_CONFIG_DIRS"), ":")
xdgConfigDirs = append(xdgConfigDirs, "/etc/xdg")
for _, d := range xdgConfigDirs {
if d != "" {
paths = append(paths, fmt.Sprintf("%v/sql/%v", d, fileName))
}
}
paths = append(paths, fmt.Sprintf("%v/%v", home, fileName))
return paths
}
func readFileContent(paths []string) ([]byte, error) {
var byts []byte
var err error
for _, p := range paths {
if byts, err = ioutil.ReadFile(p); err != nil {
continue
}
break
}
return byts, err
}
func mustReadDatabasesConfigFile() map[string]database {
databases := map[string]database{}
fileName := ".databases.json"
paths := getConfigPaths(fileName)
byts, err := readFileContent(paths)
if err != nil {
usage("Couldn't find .%v in the following paths [%v]. err=%v", fileName, paths, err)
}
err = json.Unmarshal(byts, &databases)
if err != nil {
usage("Found but couldn't JSON unmarshal .databases.json. Looked like this:\n\n%v\n\nerr=%v", string(byts), err)
}
if len(databases) == 0 {
usage("Couldn't find any database configurations on .databases.json. Looked like this:\n\n%v\n", string(byts))
}
return databases
}
func mustReadSettings() *settings {
s := new(settings)
fileName := ".settings.json"
paths := getConfigPaths(fileName)
byts, err := readFileContent(paths)
if err == nil {
err = json.Unmarshal(byts, s)
if err != nil {
usage("Found but couldn't JSON unmarshal %v. Looked like this:\n\n%v\n\nerr=%v", fileName, string(byts), err)
}
}
if s.MaxAppServerConnections == 0 {
s.MaxAppServerConnections = DefaultMaxAppServerConnections
}
if len(s.Databases) == 0 {
s.Databases = mustReadDatabasesConfigFile()
}
return s
}