-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
105 lines (81 loc) · 1.54 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 cypress
import (
"io"
"io/ioutil"
"time"
"github.com/naoina/toml"
"github.com/naoina/toml/ast"
)
type Config struct {
trees []*ast.Table
}
func ParseConfig(r io.Reader) (*Config, error) {
var cfg Config
err := cfg.Add(r)
if err != nil {
return nil, err
}
return &cfg, nil
}
func LoadMergedConfig(path string, cfg *Config) error {
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
tree, err := toml.Parse(data)
if err != nil {
return err
}
cfg.trees = append(cfg.trees, tree)
return nil
}
type Duration struct {
time.Duration
}
func (d *Duration) UnmarshalTOML(data []byte) error {
var err error
d.Duration, err = time.ParseDuration(string(data[1 : len(data)-1]))
return err
}
func subTable(name string, t *ast.Table) (*ast.Table, bool) {
sv, ok := t.Fields[name]
if !ok {
return nil, false
}
sub, ok := sv.(*ast.Table)
if !ok {
return nil, false
}
return sub, true
}
func (cfg *Config) Add(r io.Reader) error {
data, err := ioutil.ReadAll(r)
if err != nil {
return err
}
tree, err := toml.Parse(data)
if err != nil {
return err
}
cfg.trees = append(cfg.trees, tree)
return nil
}
func (cfg *Config) AddString(s string) error {
tree, err := toml.Parse([]byte(s))
if err != nil {
return err
}
cfg.trees = append(cfg.trees, tree)
return nil
}
func (cfg *Config) Load(name string, v interface{}) error {
for _, tree := range cfg.trees {
if sub, ok := subTable(name, tree); ok {
err := toml.UnmarshalTable(sub, v)
if err != nil {
return err
}
}
}
return nil
}