-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathconfig.go
More file actions
92 lines (77 loc) · 1.54 KB
/
Copy pathconfig.go
File metadata and controls
92 lines (77 loc) · 1.54 KB
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
package git_backup
import (
"bytes"
"io"
"os"
"text/template"
"gopkg.in/yaml.v3"
)
type Config struct {
Github []*GithubConfig `yaml:"github"`
GitLab []*GitLabConfig `yaml:"gitlab"`
}
func (c *Config) GetSources() []RepositorySource {
sources := make([]RepositorySource, len(c.Github)+len(c.GitLab))
offset := 0
for i := 0; i < len(c.Github); i++ {
sources[offset] = c.Github[i]
offset++
}
for i := 0; i < len(c.GitLab); i++ {
sources[offset] = c.GitLab[i]
offset++
}
return sources
}
func (c *Config) setDefaults() {
if c.Github != nil {
for _, config := range c.Github {
config.setDefaults()
}
}
if c.GitLab != nil {
for _, config := range c.GitLab {
config.setDefaults()
}
}
}
func LoadFile(path string) (out Config, err error) {
handle, err := os.Open(path)
if err != nil {
return
}
defer func() {
err = handle.Close()
}()
out, err = LoadReader(handle)
return
}
func LoadReader(reader io.Reader) (out Config, err error) {
data, err := io.ReadAll(reader)
if err != nil {
return
}
rendered, err := parse(string(data))
if err != nil {
return
}
dec := yaml.NewDecoder(rendered)
dec.KnownFields(true)
err = dec.Decode(&out)
out.setDefaults()
return
}
func parse(rawTemplate string) (rendered io.Reader, err error) {
fmap := template.FuncMap{
"env": os.Getenv,
}
tmpl := template.New("").Funcs(fmap).Option("missingkey=error")
tmpl, err = tmpl.Parse(rawTemplate)
if err != nil {
return
}
buf := &bytes.Buffer{}
err = tmpl.Execute(buf, nil)
rendered = bytes.NewReader(buf.Bytes())
return
}