/
loader.go
262 lines (229 loc) · 6.76 KB
/
loader.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package config
import (
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"cuelang.org/go/cue/format"
"cuelang.org/go/cue/parser"
"github.com/ghodss/yaml"
)
type (
// LoadConfig provides configuration for the loader
LoadConfig struct {
legacy bool
logLegacy bool
additionalConfig []string
basedir string
debug bool
cueDebugPath []string
cueDebugCallback func([]byte, error)
}
// LoadOption to be passed to Load(, ...)
LoadOption func(*LoadConfig)
)
var (
envRegex = regexp.MustCompile(`%%ENV:([^%\n]+)%%(([^%\n]+)%%)?`)
lineRegex = regexp.MustCompile(": line (.*):")
)
// DebugLog enables/disabled detailed debug logging
func DebugLog(debug bool) LoadOption {
return func(config *LoadConfig) {
config.debug = debug
}
}
// CueDebug enables a cue.Instance debugger. This is part of a dev-api and might change!
func CueDebug(path []string, callback func([]byte, error)) LoadOption {
return func(config *LoadConfig) {
config.cueDebugPath = path
config.cueDebugCallback = callback
}
}
// LegacyMapping controls if flamingo legacy config mapping happens
func LegacyMapping(mapLegacy, logLegacy bool) LoadOption {
return func(config *LoadConfig) {
config.legacy = mapLegacy
config.logLegacy = logLegacy
}
}
// AdditionalConfig adds additional config values (yaml strings) to the config
func AdditionalConfig(addtionalConfig []string) LoadOption {
return func(config *LoadConfig) {
config.additionalConfig = append(config.additionalConfig, addtionalConfig...)
}
}
// Load configuration in basedir
func Load(root *Area, basedir string, options ...LoadOption) error {
config := &LoadConfig{
legacy: true,
basedir: basedir,
}
for _, option := range options {
option(config)
}
if err := loadConfigFromBasedir(root, config); err != nil {
return err
}
if config.cueDebugCallback != nil {
if err := root.loadConfig(false, false); err != nil {
log.Println(err)
}
config.cueDebugCallback(format.Node(root.cueInstance.Lookup(config.cueDebugPath...).Syntax(), format.Simplify()))
}
return root.loadConfig(config.legacy, config.logLegacy)
}
func loadConfigFromBasedir(root *Area, config *LoadConfig) error {
if err := load(root, config.basedir, "/", config); err != nil {
return err
}
// load additional single context file
for _, file := range strings.Split(os.Getenv("CONTEXTFILE"), ":") {
file = strings.TrimSuffix(file, filepath.Ext(file))
if file == "" {
continue
}
loadLogged(root, loadYamlFile, file, config.debug)
loadLogged(root, loadCueFile, file, config.debug)
}
for _, add := range config.additionalConfig {
if config.debug {
log.Printf("Loading %q", add)
}
if err := loadYamlConfig(root, []byte(add)); err != nil {
return err
}
}
return nil
}
// LoadConfigFile loads a config
// Deprecated: do not arbitrarily load anything anymore, use Area.Load
func LoadConfigFile(area *Area, file string) error {
log.Println("WARNING! config.LoadConfigFile is deprecated!")
if err := loadYamlFile(area, file); err != nil {
return err
}
if err := loadCueFile(area, file); err != nil {
return err
}
return nil
}
func loadLogged(area *Area, loader func(*Area, string) error, filename string, debug bool) {
if debug {
log.Printf("Loading %q", filename)
}
if err := loader(area, filename); err != nil && debug {
log.Printf("Error: %s", err)
}
}
func load(area *Area, basedir, curdir string, config *LoadConfig) error {
loadLogged(area, loadYamlFile, filepath.Join(basedir, curdir, "config"), config.debug)
loadLogged(area, loadCueFile, filepath.Join(basedir, curdir, "config"), config.debug)
loadLogged(area, loadYamlRoutesFile, filepath.Join(basedir, curdir, "routes"), config.debug)
for _, context := range strings.Split(os.Getenv("CONTEXT"), ":") {
if context == "" {
continue
}
loadLogged(area, loadYamlFile, filepath.Join(basedir, curdir, "config_"+context+""), config.debug)
loadLogged(area, loadCueFile, filepath.Join(basedir, curdir, "config_"+context+""), config.debug)
loadLogged(area, loadYamlRoutesFile, filepath.Join(basedir, curdir, "routes_"+context+""), config.debug)
}
loadLogged(area, loadYamlFile, filepath.Join(basedir, curdir, "config_local"), config.debug)
loadLogged(area, loadCueFile, filepath.Join(basedir, curdir, "config_local"), config.debug)
loadLogged(area, loadYamlRoutesFile, filepath.Join(basedir, curdir, "routes_local"), config.debug)
for _, child := range area.Childs {
if err := load(child, basedir, filepath.Join(curdir, child.Name), config); err != nil {
return err
}
}
return nil
}
func loadCueFile(area *Area, filename string) error {
f, err := os.Open(filename + ".cue")
if f != nil {
_ = f.Close()
}
if err != nil {
return nil
}
file, err := parser.ParseFile(filename+".cue", nil)
if err != nil {
return err
}
area.cueConfig = cueAstMergeFile(area.cueConfig, file)
return nil
}
func loadYamlFile(area *Area, filename string) error {
config, err := os.ReadFile(filename + ".yml")
if err == nil {
return loadYamlConfig(area, config)
}
config, err = os.ReadFile(filename + ".yaml")
if err == nil {
return loadYamlConfig(area, config)
}
return fmt.Errorf("can not load %s.yml nor %s.yaml", filename, filename)
}
func loadYamlConfig(area *Area, config []byte) error {
config = envRegex.ReplaceAllFunc(
config,
func(a []byte) []byte {
value := os.Getenv(string(envRegex.FindSubmatch(a)[1]))
if value == "" {
value = string(envRegex.FindSubmatch(a)[3])
}
return []byte(value)
},
)
cfg := make(Map)
if err := yaml.Unmarshal(config, &cfg); err != nil {
log.Print(errorLineDebug(err, config))
panic(err)
}
if area.loadedConfig == nil {
area.loadedConfig = make(Map)
}
return area.loadedConfig.Add(cfg)
}
// errorLineDebug returns the lines where the error occurred (if possible)
func errorLineDebug(err error, config []byte) string {
matches := lineRegex.FindStringSubmatch(err.Error())
if len(matches) != 2 {
return ""
}
line, aerr := strconv.Atoi(matches[1])
if aerr != nil {
return ""
}
errorLines := fmt.Sprintln("")
lines := strings.Split(string(config), "\n")
first := line - 10
last := line + 10
if first < 0 {
first = 0
}
if last > len(lines) {
last = len(lines)
}
for i := first; i < last; i++ {
if i == line {
errorLines = errorLines + fmt.Sprintln(">", i+1, lines[i])
} else {
errorLines = errorLines + fmt.Sprintln(" ", i+1, lines[i])
}
}
return errorLines
}
func loadYamlRoutesFile(area *Area, filename string) error {
routes, err := os.ReadFile(filename + ".yml")
if err == nil {
return yaml.Unmarshal(routes, &area.Routes)
}
routes, err = os.ReadFile(filename + ".yaml")
if err == nil {
return yaml.Unmarshal(routes, &area.Routes)
}
return fmt.Errorf("can not load %s.yml nor %s.yaml %v", filename, filename, errorLineDebug(err, routes))
}