/
config.go
95 lines (83 loc) · 1.73 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
package soko
import (
"fmt"
"os"
"strings"
"github.com/pelletier/go-toml"
)
type Config struct {
Backend string
SectionConfig
}
type SectionConfig map[string]string
const defaultConfigPath = "/etc/soko.toml"
var validKeys = map[string][]string{
"consul": []string{
"url",
},
"openstack": []string{
"username",
"password",
"tenant_name",
"auth_url",
"region",
},
"aws": []string{
"access_key_id",
"secret_access_key",
"region",
},
}
func (c *Config) SetConfigByBackend(data *toml.TomlTree) error {
switch b := c.Backend; b {
case "consul", "openstack", "aws":
cfg := make(SectionConfig, 0)
keys := validKeys[b]
for _, key := range keys {
tomlKey := fmt.Sprintf("%s.%s", b, key)
if v := data.Get(tomlKey); v != nil {
cfg[key] = v.(string)
}
}
c.SectionConfig = cfg
return nil
default:
return fmt.Errorf("Invalid backend: %s", c.Backend)
}
}
func DefaultConfig() (*Config, error) {
if _, err := os.Stat(defaultConfigPath); err != nil {
// If there is no file, returns empty config
return &Config{}, nil
}
data, err := toml.LoadFile(defaultConfigPath)
if err != nil {
return nil, err
}
conf := &Config{}
conf.Backend = data.Get("default.backend").(string)
conf.SetConfigByBackend(data)
return conf, nil
}
func NewConfig(backend string, args []string) (*Config, error) {
conf := &Config{}
conf.Backend = backend
cfg := make(SectionConfig, 0)
keys := validKeys[backend]
for _, arg := range args {
kv := strings.SplitN(arg, "=", 2)
if len(kv) == 2 {
k := kv[0]
v := kv[1]
for _, key := range keys {
if k == key {
cfg[k] = v
}
}
} else {
return nil, fmt.Errorf("Invalud config kv pair: %s", arg)
}
}
conf.SectionConfig = cfg
return conf, nil
}