-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathconfig.go
80 lines (70 loc) · 1.62 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
package main
import (
"io/ioutil"
"path/filepath"
"gopkg.in/yaml.v2"
)
type Config struct {
Defaults Receiver `yaml:"defaults"`
Templates []string `yaml:"templates"`
Receivers []*Receiver `yaml:"receivers"`
Options Options `yaml:"options"`
}
type Receiver struct {
Name string `yaml:"name"`
Template string `yaml:"template"`
Sender string `yaml:"sender"`
Subscribe *bool `yaml:"subscribe"`
To []string `yaml:"to"`
}
type Options struct {
KeepAlive bool `yaml:"keep_alive"`
Commands bool `yaml:"commands"`
}
func Load(s []byte) (*Config, error) {
cfg := &Config{}
err := yaml.UnmarshalStrict(s, cfg)
return cfg, err
}
func LoadFile(file string) (*Config, error) {
content, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
cfg, err := Load(content)
if err != nil {
return nil, err
}
resolveFilepaths(filepath.Dir(file), cfg)
expandDefaults(cfg)
return cfg, nil
}
// resolveFilepaths joins all relative paths in a configuration
// with a given base directory.
func resolveFilepaths(baseDir string, cfg *Config) {
join := func(fp string) string {
if len(fp) > 0 && !filepath.IsAbs(fp) {
fp = filepath.Join(baseDir, fp)
}
return fp
}
for i, tf := range cfg.Templates {
cfg.Templates[i] = join(tf)
}
}
func expandDefaults(cfg *Config) {
for _, recv := range cfg.Receivers {
if len(recv.Template) == 0 {
recv.Template = cfg.Defaults.Template
}
if len(recv.Sender) == 0 {
recv.Sender = cfg.Defaults.Sender
}
if len(recv.To) == 0 {
recv.To = cfg.Defaults.To
}
if recv.Subscribe == nil {
recv.Subscribe = cfg.Defaults.Subscribe
}
}
}