forked from ilyakaznacheev/cleanenv
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cleanenv.go
639 lines (539 loc) · 15.1 KB
/
cleanenv.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
package cleanenv
import (
"encoding"
"encoding/json"
"flag"
"fmt"
"io"
"net/url"
"os"
"path/filepath"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/joho/godotenv"
"gopkg.in/yaml.v3"
"olympos.io/encoding/edn"
)
const (
// DefaultSeparator is a default list and map separator character
DefaultSeparator = ","
)
// Supported tags
const (
// TagEnv name of the environment variable or a list of names
TagEnv = "env"
// TagEnvLayout value parsing layout (for types like time.Time)
TagEnvLayout = "env-layout"
// TagEnvDefault default value
TagEnvDefault = "env-default"
// TagEnvSeparator custom list and map separator
TagEnvSeparator = "env-separator"
// TagEnvDescription environment variable description
TagEnvDescription = "env-description"
// TagEnvUpd flag to mark a field as updatable
TagEnvUpd = "env-upd"
// TagEnvRequired flag to mark a field as required
TagEnvRequired = "env-required"
// TagEnvPrefix аlag to specify prefix for structure fields
TagEnvPrefix = "env-prefix"
)
// Setter is an interface for a custom value setter.
//
// To implement a custom value setter you need to add a SetValue function to your type that will receive a string raw value:
//
// type MyField string
//
// func (f *MyField) SetValue(s string) error {
// if s == "" {
// return fmt.Errorf("field value can't be empty")
// }
// *f = MyField("my field is: " + s)
// return nil
// }
type Setter interface {
SetValue(string) error
}
// Updater gives an ability to implement custom update function for a field or a whole structure
type Updater interface {
Update() error
}
// ReadConfig reads configuration file and parses it depending on tags in structure provided.
// Then it reads and parses
//
// Example:
//
// type ConfigDatabase struct {
// Port string `yaml:"port" env:"PORT" env-default:"5432"`
// Host string `yaml:"host" env:"HOST" env-default:"localhost"`
// Name string `yaml:"name" env:"NAME" env-default:"postgres"`
// User string `yaml:"user" env:"USER" env-default:"user"`
// Password string `yaml:"password" env:"PASSWORD"`
// }
//
// var cfg ConfigDatabase
//
// err := cleanenv.ReadConfig("config.yml", &cfg)
// if err != nil {
// ...
// }
func ReadConfig(path string, cfg interface{}) error {
err := parseFile(path, cfg)
if err != nil {
return err
}
return readEnvVars(cfg, false)
}
// ReadEnv reads environment variables into the structure.
func ReadEnv(cfg interface{}) error {
return readEnvVars(cfg, false)
}
// UpdateEnv rereads (updates) environment variables in the structure.
func UpdateEnv(cfg interface{}) error {
return readEnvVars(cfg, true)
}
// parseFile parses configuration file according to it's extension
//
// Currently following file extensions are supported:
//
// - yaml
//
// - json
//
// - toml
//
// - env
//
// - edn
func parseFile(path string, cfg interface{}) error {
// open the configuration file
f, err := os.OpenFile(path, os.O_RDONLY|os.O_SYNC, 0)
if err != nil {
return err
}
defer f.Close()
// parse the file depending on the file type
switch ext := strings.ToLower(filepath.Ext(path)); ext {
case ".yaml", ".yml":
err = ParseYAML(f, cfg)
case ".json":
err = ParseJSON(f, cfg)
case ".toml":
err = ParseTOML(f, cfg)
case ".edn":
err = parseEDN(f, cfg)
case ".env":
err = parseENV(f, cfg)
default:
return fmt.Errorf("file format '%s' doesn't supported by the parser", ext)
}
if err != nil {
return fmt.Errorf("config file parsing error: %s", err.Error())
}
return nil
}
// ParseYAML parses YAML from reader to data structure
func ParseYAML(r io.Reader, str interface{}) error {
return yaml.NewDecoder(r).Decode(str)
}
// ParseJSON parses JSON from reader to data structure
func ParseJSON(r io.Reader, str interface{}) error {
return json.NewDecoder(r).Decode(str)
}
// ParseTOML parses TOML from reader to data structure
func ParseTOML(r io.Reader, str interface{}) error {
_, err := toml.NewDecoder(r).Decode(str)
return err
}
// parseEDN parses EDN from reader to data structure
func parseEDN(r io.Reader, str interface{}) error {
return edn.NewDecoder(r).Decode(str)
}
// parseENV, in fact, doesn't fill the structure with environment variable values.
// It just parses ENV file and sets all variables to the environment.
// Thus, the structure should be filled at the next steps.
func parseENV(r io.Reader, _ interface{}) error {
vars, err := godotenv.Parse(r)
if err != nil {
return err
}
for env, val := range vars {
if err = os.Setenv(env, val); err != nil {
return fmt.Errorf("set environment: %w", err)
}
}
return nil
}
// parseSlice parses value into a slice of given type
func parseSlice(valueType reflect.Type, value string, sep string, layout *string) (*reflect.Value, error) {
sliceValue := reflect.MakeSlice(valueType, 0, 0)
if valueType.Elem().Kind() == reflect.Uint8 {
sliceValue = reflect.ValueOf([]byte(value))
} else if len(strings.TrimSpace(value)) != 0 {
values := strings.Split(value, sep)
sliceValue = reflect.MakeSlice(valueType, len(values), len(values))
for i, val := range values {
if err := parseValue(sliceValue.Index(i), val, sep, layout); err != nil {
return nil, err
}
}
}
return &sliceValue, nil
}
// parseMap parses value into a map of given type
func parseMap(valueType reflect.Type, value string, sep string, layout *string) (*reflect.Value, error) {
mapValue := reflect.MakeMap(valueType)
if len(strings.TrimSpace(value)) != 0 {
pairs := strings.Split(value, sep)
for _, pair := range pairs {
kvPair := strings.SplitN(pair, ":", 2)
if len(kvPair) != 2 {
return nil, fmt.Errorf("invalid map item: %q", pair)
}
k := reflect.New(valueType.Key()).Elem()
err := parseValue(k, kvPair[0], sep, layout)
if err != nil {
return nil, err
}
v := reflect.New(valueType.Elem()).Elem()
err = parseValue(v, kvPair[1], sep, layout)
if err != nil {
return nil, err
}
mapValue.SetMapIndex(k, v)
}
}
return &mapValue, nil
}
// structMeta is a structure metadata entity
type structMeta struct {
envList []string
fieldName string
fieldValue reflect.Value
defValue *string
layout *string
separator string
description string
updatable bool
required bool
}
// isFieldValueZero determines if fieldValue empty or not
func (sm *structMeta) isFieldValueZero() bool {
return sm.fieldValue.IsZero()
}
// parseFunc custom value parser function
type parseFunc func(*reflect.Value, string, *string) error
// Any specific supported struct can be added here
var validStructs = map[reflect.Type]parseFunc{
reflect.TypeOf(time.Time{}): func(field *reflect.Value, value string, layout *string) error {
var l string
if layout != nil {
l = *layout
} else {
l = time.RFC3339
}
val, err := time.Parse(l, value)
if err != nil {
return err
}
field.Set(reflect.ValueOf(val))
return nil
},
reflect.TypeOf(url.URL{}): func(field *reflect.Value, value string, _ *string) error {
val, err := url.Parse(value)
if err != nil {
return err
}
field.Set(reflect.ValueOf(*val))
return nil
},
reflect.TypeOf(&time.Location{}): func(field *reflect.Value, value string, _ *string) error {
loc, err := time.LoadLocation(value)
if err != nil {
return err
}
field.Set(reflect.ValueOf(loc))
return nil
},
}
// readStructMetadata reads structure metadata (types, tags, etc.)
func readStructMetadata(cfgRoot interface{}) ([]structMeta, error) {
type cfgNode struct {
Val interface{}
Prefix string
}
cfgStack := []cfgNode{{cfgRoot, ""}}
metas := make([]structMeta, 0)
for i := 0; i < len(cfgStack); i++ {
s := reflect.ValueOf(cfgStack[i].Val)
sPrefix := cfgStack[i].Prefix
// unwrap pointer
if s.Kind() == reflect.Ptr {
s = s.Elem()
}
// process only structures
if s.Kind() != reflect.Struct {
return nil, fmt.Errorf("wrong type %v", s.Kind())
}
typeInfo := s.Type()
// read tags
for idx := 0; idx < s.NumField(); idx++ {
fType := typeInfo.Field(idx)
var (
defValue *string
layout *string
separator string
)
// process nested structure (except of supported ones)
if fld := s.Field(idx); fld.Kind() == reflect.Struct {
//skip unexported
if !fld.CanInterface() {
continue
}
// add structure to parsing stack
if _, found := validStructs[fld.Type()]; !found {
prefix, _ := fType.Tag.Lookup(TagEnvPrefix)
cfgStack = append(cfgStack, cfgNode{fld.Addr().Interface(), sPrefix + prefix})
continue
}
// process time.Time
if l, ok := fType.Tag.Lookup(TagEnvLayout); ok {
layout = &l
}
}
// check is the field value can be changed
if !s.Field(idx).CanSet() {
continue
}
if def, ok := fType.Tag.Lookup(TagEnvDefault); ok {
defValue = &def
}
if sep, ok := fType.Tag.Lookup(TagEnvSeparator); ok {
separator = sep
} else {
separator = DefaultSeparator
}
_, upd := fType.Tag.Lookup(TagEnvUpd)
_, required := fType.Tag.Lookup(TagEnvRequired)
envList := make([]string, 0)
if envs, ok := fType.Tag.Lookup(TagEnv); ok && len(envs) != 0 {
envList = strings.Split(envs, DefaultSeparator)
if sPrefix != "" {
for i := range envList {
envList[i] = sPrefix + envList[i]
}
}
}
metas = append(metas, structMeta{
envList: envList,
fieldName: s.Type().Field(idx).Name,
fieldValue: s.Field(idx),
defValue: defValue,
layout: layout,
separator: separator,
description: fType.Tag.Get(TagEnvDescription),
updatable: upd,
required: required,
})
}
}
return metas, nil
}
// readEnvVars reads environment variables to the provided configuration structure
func readEnvVars(cfg interface{}, update bool) error {
metaInfo, err := readStructMetadata(cfg)
if err != nil {
return err
}
if updater, ok := cfg.(Updater); ok {
if err := updater.Update(); err != nil {
return err
}
}
for _, meta := range metaInfo {
// update only updatable fields
if update && !meta.updatable {
continue
}
var rawValue *string
for _, env := range meta.envList {
if value, ok := os.LookupEnv(env); ok {
rawValue = &value
break
}
}
if rawValue == nil && meta.required && meta.isFieldValueZero() {
return fmt.Errorf(
"field %q is required but the value is not provided",
meta.fieldName,
)
}
if rawValue == nil && meta.isFieldValueZero() {
rawValue = meta.defValue
}
if rawValue == nil {
continue
}
var envName string
if len(meta.envList) > 0 {
envName = meta.envList[0]
}
if err := parseValue(meta.fieldValue, *rawValue, meta.separator, meta.layout); err != nil {
return fmt.Errorf("parsing field %v env %v: %v", meta.fieldName, envName, err)
}
}
return nil
}
// parseValue parses value into the corresponding field.
// In case of maps and slices it uses provided separator to split raw value string
func parseValue(field reflect.Value, value, sep string, layout *string) error {
// TODO: simplify recursion
valueType := field.Type()
// look for supported struct parser
// parsing of struct must be done before checking the implementation `encoding.TextUnmarshaler`
// standard struct types already have the implementation `encoding.TextUnmarshaler` (for example `time.Time`)
if structParser, found := validStructs[valueType]; found {
return structParser(&field, value, layout)
}
if field.CanInterface() {
if ct, ok := field.Interface().(encoding.TextUnmarshaler); ok {
return ct.UnmarshalText([]byte(value))
} else if ctp, ok := field.Addr().Interface().(encoding.TextUnmarshaler); ok {
return ctp.UnmarshalText([]byte(value))
}
if cs, ok := field.Interface().(Setter); ok {
return cs.SetValue(value)
} else if csp, ok := field.Addr().Interface().(Setter); ok {
return csp.SetValue(value)
}
}
switch valueType.Kind() {
// parse string value
case reflect.String:
field.SetString(value)
// parse boolean value
case reflect.Bool:
b, err := strconv.ParseBool(value)
if err != nil {
return err
}
field.SetBool(b)
// parse integer
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32:
number, err := strconv.ParseInt(value, 0, valueType.Bits())
if err != nil {
return err
}
field.SetInt(number)
case reflect.Int64:
if valueType == reflect.TypeOf(time.Duration(0)) {
// try to parse time
d, err := time.ParseDuration(value)
if err != nil {
return err
}
field.SetInt(int64(d))
} else {
// parse regular integer
number, err := strconv.ParseInt(value, 0, valueType.Bits())
if err != nil {
return err
}
field.SetInt(number)
}
// parse unsigned integer value
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
number, err := strconv.ParseUint(value, 0, valueType.Bits())
if err != nil {
return err
}
field.SetUint(number)
// parse floating point value
case reflect.Float32, reflect.Float64:
number, err := strconv.ParseFloat(value, valueType.Bits())
if err != nil {
return err
}
field.SetFloat(number)
// parse sliced value
case reflect.Slice:
sliceValue, err := parseSlice(valueType, value, sep, layout)
if err != nil {
return err
}
field.Set(*sliceValue)
// parse mapped value
case reflect.Map:
mapValue, err := parseMap(valueType, value, sep, layout)
if err != nil {
return err
}
field.Set(*mapValue)
default:
return fmt.Errorf("unsupported type %s.%s", valueType.PkgPath(), valueType.Name())
}
return nil
}
// GetDescription returns a description of environment variables.
// You can provide a custom header text.
func GetDescription(cfg interface{}, headerText *string) (string, error) {
meta, err := readStructMetadata(cfg)
if err != nil {
return "", err
}
var header string
if headerText != nil {
header = *headerText
} else {
header = "Environment variables:"
}
description := make([]string, 0)
for _, m := range meta {
if len(m.envList) == 0 {
continue
}
for idx, env := range m.envList {
elemDescription := fmt.Sprintf("\n %s %s", env, m.fieldValue.Kind())
if idx > 0 {
elemDescription += fmt.Sprintf(" (alternative to %s)", m.envList[0])
}
elemDescription += fmt.Sprintf("\n \t%s", m.description)
if m.defValue != nil {
elemDescription += fmt.Sprintf(" (default %q)", *m.defValue)
}
description = append(description, elemDescription)
}
}
if len(description) == 0 {
return "", nil
}
sort.Strings(description)
return header + strings.Join(description, ""), nil
}
// Usage returns a configuration usage help.
// Other usage instructions can be wrapped in and executed before this usage function.
// The default output is STDERR.
func Usage(cfg interface{}, headerText *string, usageFuncs ...func()) func() {
return FUsage(os.Stderr, cfg, headerText, usageFuncs...)
}
// FUsage prints configuration help into the custom output.
// Other usage instructions can be wrapped in and executed before this usage function
func FUsage(w io.Writer, cfg interface{}, headerText *string, usageFuncs ...func()) func() {
return func() {
for _, fn := range usageFuncs {
fn()
}
_ = flag.Usage
text, err := GetDescription(cfg, headerText)
if err != nil {
return
}
if len(usageFuncs) > 0 {
fmt.Fprintln(w)
}
fmt.Fprintln(w, text)
}
}