forked from jinzhu/configor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
429 lines (374 loc) · 12 KB
/
utils.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package configor
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"io/ioutil"
"os"
"path"
"reflect"
"strings"
"time"
"github.com/BurntSushi/toml"
"gopkg.in/yaml.v3"
)
// UnmatchedTomlKeysError errors are returned by the Load function when
// ErrorOnUnmatchedKeys is set to true and there are unmatched keys in the input
// toml config file. The string returned by Error() contains the names of the
// missing keys.
type UnmatchedTomlKeysError struct {
Keys []toml.Key
}
func (e *UnmatchedTomlKeysError) Error() string {
return fmt.Sprintf("There are keys in the config file that do not match any field in the given struct: %v", e.Keys)
}
func (configor *Configor) getENVPrefix(config interface{}) string {
if configor.Config.ENVPrefix == "" {
if prefix := os.Getenv("CONFIGOR_ENV_PREFIX"); prefix != "" {
return prefix
}
return "Configor"
}
return configor.Config.ENVPrefix
}
func (c *Configor) getConfigurationFileWithENVPrefix(file, env string) (string, time.Time, error) {
stat := os.Stat
if c.FS != nil {
stat = func(name string) (os.FileInfo, error) {
return fs.Stat(c.FS, name)
}
}
var (
envFile string
extname = path.Ext(file)
)
if extname == "" {
envFile = fmt.Sprintf("%v.%v", file, env)
} else {
envFile = fmt.Sprintf("%v.%v%v", strings.TrimSuffix(file, extname), env, extname)
}
if fileInfo, err := stat(envFile); err == nil && fileInfo.Mode().IsRegular() {
return envFile, fileInfo.ModTime(), nil
}
return "", time.Now(), fmt.Errorf("failed to find file %v", file)
}
func (configor *Configor) getConfigurationFiles(config *Config, watchMode bool, files ...string) ([]string, map[string]time.Time) {
stat := os.Stat
if config.FS != nil {
stat = func(name string) (os.FileInfo, error) {
return fs.Stat(config.FS, name)
}
}
var resultKeys []string
var results = map[string]time.Time{}
if !watchMode && (configor.Config.Debug || configor.Config.Verbose) {
fmt.Printf("Current environment: '%v'\n", configor.GetEnvironment())
}
for i := len(files) - 1; i >= 0; i-- {
foundFile := false
file := files[i]
// check configuration
if fileInfo, err := stat(file); err == nil && fileInfo.Mode().IsRegular() {
foundFile = true
resultKeys = append(resultKeys, file)
results[file] = fileInfo.ModTime()
}
// check configuration with env
if file, modTime, err := configor.getConfigurationFileWithENVPrefix(file, configor.GetEnvironment()); err == nil {
foundFile = true
resultKeys = append(resultKeys, file)
results[file] = modTime
}
// check example configuration
if !foundFile {
if example, modTime, err := configor.getConfigurationFileWithENVPrefix(file, "example"); err == nil {
if !watchMode && !configor.Silent {
fmt.Printf("Failed to find configuration %v, using example file %v\n", file, example)
}
resultKeys = append(resultKeys, example)
results[example] = modTime
} else if !configor.Silent {
fmt.Printf("Failed to find configuration %v\n", file)
}
}
}
return resultKeys, results
}
func (c *Configor) processFile(config interface{}, file string, errorOnUnmatchedKeys bool) error {
readFile := ioutil.ReadFile
if c.FS != nil {
readFile = func(filename string) ([]byte, error) {
return fs.ReadFile(c.FS, filename)
}
}
data, err := readFile(file)
if err != nil {
return err
}
switch {
case strings.HasSuffix(file, ".yaml") || strings.HasSuffix(file, ".yml"):
if errorOnUnmatchedKeys {
decoder := yaml.NewDecoder(bytes.NewBuffer(data))
decoder.KnownFields(true)
return decoder.Decode(config)
}
return yaml.Unmarshal(data, config)
case strings.HasSuffix(file, ".toml"):
return unmarshalToml(data, config, errorOnUnmatchedKeys)
case strings.HasSuffix(file, ".json"):
return unmarshalJSON(data, config, errorOnUnmatchedKeys)
default:
if err := unmarshalToml(data, config, errorOnUnmatchedKeys); err == nil {
return nil
} else if errUnmatchedKeys, ok := err.(*UnmatchedTomlKeysError); ok {
return errUnmatchedKeys
}
if err := unmarshalJSON(data, config, errorOnUnmatchedKeys); err == nil {
return nil
} else if strings.Contains(err.Error(), "json: unknown field") {
return err
}
var yamlError error
if errorOnUnmatchedKeys {
decoder := yaml.NewDecoder(bytes.NewBuffer(data))
decoder.KnownFields(true)
yamlError = decoder.Decode(config)
} else {
yamlError = yaml.Unmarshal(data, config)
}
if yamlError == nil {
return nil
} else if yErr, ok := yamlError.(*yaml.TypeError); ok {
return yErr
}
return errors.New("failed to decode config")
}
}
// GetStringTomlKeys returns a string array of the names of the keys that are passed in as args
func GetStringTomlKeys(list []toml.Key) []string {
arr := make([]string, len(list))
for index, key := range list {
arr[index] = key.String()
}
return arr
}
func unmarshalToml(data []byte, config interface{}, errorOnUnmatchedKeys bool) error {
metadata, err := toml.Decode(string(data), config)
if err == nil && len(metadata.Undecoded()) > 0 && errorOnUnmatchedKeys {
return &UnmatchedTomlKeysError{Keys: metadata.Undecoded()}
}
return err
}
// unmarshalJSON unmarshals the given data into the config interface.
// If the errorOnUnmatchedKeys boolean is true, an error will be returned if there
// are keys in the data that do not match fields in the config interface.
func unmarshalJSON(data []byte, config interface{}, errorOnUnmatchedKeys bool) error {
reader := strings.NewReader(string(data))
decoder := json.NewDecoder(reader)
if errorOnUnmatchedKeys {
decoder.DisallowUnknownFields()
}
err := decoder.Decode(config)
if err != nil && err != io.EOF {
return err
}
return nil
}
func getPrefixForStruct(prefixes []string, fieldStruct *reflect.StructField) []string {
if fieldStruct.Anonymous && fieldStruct.Tag.Get("anonymous") == "true" {
return prefixes
}
return append(prefixes, fieldStruct.Name)
}
func (configor *Configor) processDefaults(config interface{}) error {
configValue := reflect.Indirect(reflect.ValueOf(config))
if configValue.Kind() != reflect.Struct {
return errors.New("invalid config, should be struct")
}
configType := configValue.Type()
for i := 0; i < configType.NumField(); i++ {
var (
fieldStruct = configType.Field(i)
field = configValue.Field(i)
)
if !field.CanAddr() || !field.CanInterface() {
continue
}
if isBlank := reflect.DeepEqual(field.Interface(), reflect.Zero(field.Type()).Interface()); isBlank {
// Set default configuration if blank
if value := fieldStruct.Tag.Get("default"); value != "" {
if err := yaml.Unmarshal([]byte(value), field.Addr().Interface()); err != nil {
return err
}
}
}
for field.Kind() == reflect.Ptr {
field = field.Elem()
}
switch field.Kind() {
case reflect.Struct:
if err := configor.processDefaults(field.Addr().Interface()); err != nil {
return err
}
case reflect.Slice:
for i := 0; i < field.Len(); i++ {
if reflect.Indirect(field.Index(i)).Kind() == reflect.Struct {
if err := configor.processDefaults(field.Index(i).Addr().Interface()); err != nil {
return err
}
}
}
}
}
return nil
}
func (configor *Configor) processTags(config interface{}, prefixes ...string) error {
configValue := reflect.Indirect(reflect.ValueOf(config))
if configValue.Kind() != reflect.Struct {
return errors.New("invalid config, should be struct")
}
configType := configValue.Type()
for i := 0; i < configType.NumField(); i++ {
var (
envNames []string
fieldStruct = configType.Field(i)
field = configValue.Field(i)
envName = fieldStruct.Tag.Get("env") // read configuration from shell env
envSuffixName = fieldStruct.Tag.Get("envSuffix") // read configuration from shell env
)
if !field.CanAddr() || !field.CanInterface() {
continue
}
if envName != "" {
envNames = append(envNames, envName)
}
if envSuffixName != "" {
envNames = append(
envNames,
strings.Join(append(prefixes, envSuffixName), "_"), // Configor_DB_Name
strings.ToUpper(strings.Join(append(prefixes, envSuffixName), "_")), // CONFIGOR_DB_NAME
)
}
envNames = append(
envNames,
strings.Join(append(prefixes, fieldStruct.Name), "_"),
strings.ToUpper(strings.Join(append(prefixes, fieldStruct.Name), "_")),
)
if configor.Config.Verbose {
fmt.Printf("Trying to load struct `%v`'s field `%v` from env %v\n", configType.Name(), fieldStruct.Name, strings.Join(envNames, ", "))
}
// Load From Shell ENV
for _, env := range envNames {
if value := os.Getenv(env); value != "" {
if configor.Config.Debug || configor.Config.Verbose {
fmt.Printf("Loading configuration for struct `%v`'s field `%v` from env %v...\n", configType.Name(), fieldStruct.Name, env)
}
switch reflect.Indirect(field).Kind() {
case reflect.Bool:
switch strings.ToLower(value) {
case "", "0", "f", "false":
field.Set(reflect.ValueOf(false))
default:
field.Set(reflect.ValueOf(true))
}
case reflect.String:
field.Set(reflect.ValueOf(value))
default:
if err := yaml.Unmarshal([]byte(value), field.Addr().Interface()); err != nil {
return err
}
}
break
}
}
if isBlank := reflect.DeepEqual(field.Interface(), reflect.Zero(field.Type()).Interface()); isBlank && fieldStruct.Tag.Get("required") == "true" {
// return error if it is required but blank
return errors.New(fieldStruct.Name + " is required, but blank")
}
for field.Kind() == reflect.Ptr {
field = field.Elem()
}
if field.Kind() == reflect.Struct {
if err := configor.processTags(field.Addr().Interface(), getPrefixForStruct(prefixes, &fieldStruct)...); err != nil {
return err
}
}
if field.Kind() == reflect.Slice {
if arrLen := field.Len(); arrLen > 0 {
for i := 0; i < arrLen; i++ {
if reflect.Indirect(field.Index(i)).Kind() == reflect.Struct {
if err := configor.processTags(field.Index(i).Addr().Interface(), append(getPrefixForStruct(prefixes, &fieldStruct), fmt.Sprint(i))...); err != nil {
return err
}
}
}
} else {
defer func(field reflect.Value, fieldStruct reflect.StructField) {
if !configValue.IsZero() {
// load slice from env
newVal := reflect.New(field.Type().Elem()).Elem()
if newVal.Kind() == reflect.Struct {
idx := 0
for {
newVal = reflect.New(field.Type().Elem()).Elem()
if err := configor.processTags(newVal.Addr().Interface(), append(getPrefixForStruct(prefixes, &fieldStruct), fmt.Sprint(idx))...); err != nil {
return // err
} else if reflect.DeepEqual(newVal.Interface(), reflect.New(field.Type().Elem()).Elem().Interface()) {
break
} else {
idx++
field.Set(reflect.Append(field, newVal))
}
}
}
}
}(field, fieldStruct)
}
}
}
return nil
}
func (configor *Configor) load(config interface{}, watchMode bool, files ...string) (err error, changed bool) {
defer func() {
if configor.Config.Debug || configor.Config.Verbose {
if err != nil {
fmt.Printf("Failed to load configuration from %v, got %v\n", files, err)
}
fmt.Printf("Configuration:\n %#v\n", config)
}
}()
configFiles, configModTimeMap := configor.getConfigurationFiles(configor.Config, watchMode, files...)
if watchMode {
if len(configModTimeMap) == len(configor.configModTimes) {
var changed bool
for f, t := range configModTimeMap {
if v, ok := configor.configModTimes[f]; !ok || t.After(v) {
changed = true
}
}
if !changed {
return nil, false
}
}
}
// process defaults
configor.processDefaults(config)
for _, file := range configFiles {
if configor.Config.Debug || configor.Config.Verbose {
fmt.Printf("Loading configurations from file '%v'...\n", file)
}
if err = configor.processFile(config, file, configor.GetErrorOnUnmatchedKeys()); err != nil {
return err, true
}
}
configor.configModTimes = configModTimeMap
if prefix := configor.getENVPrefix(config); prefix == "-" {
err = configor.processTags(config)
} else {
err = configor.processTags(config, prefix)
}
return err, true
}