-
Notifications
You must be signed in to change notification settings - Fork 0
/
dotenv_decoder.go
122 lines (103 loc) · 2.47 KB
/
dotenv_decoder.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
package envconf
import (
"go/ast"
"reflect"
encodingx "github.com/go-courier/x/encoding"
reflectx "github.com/go-courier/x/reflect"
)
func NewDotEnvDecoder(envVars *EnvVars) *DotEnvDecoder {
return &DotEnvDecoder{
envVars: envVars,
}
}
type DotEnvDecoder struct {
envVars *EnvVars
}
func (d *DotEnvDecoder) Decode(v interface{}) error {
walker := NewPathWalker()
rv, ok := v.(reflect.Value)
if !ok {
rv = reflect.ValueOf(v)
}
return d.scanAndSetValue(walker, rv)
}
func (d *DotEnvDecoder) scanAndSetValue(walker *PathWalker, rv reflect.Value) error {
kind := rv.Kind()
if kind != reflect.Ptr && rv.CanAddr() {
if defaultsSetter, ok := rv.Addr().Interface().(interface{ SetDefaults() }); ok {
defaultsSetter.SetDefaults()
}
}
switch kind {
case reflect.Ptr:
if rv.IsNil() {
rv.Set(reflectx.New(rv.Type()))
}
return d.scanAndSetValue(walker, rv.Elem())
case reflect.Func, reflect.Interface, reflect.Chan, reflect.Map:
// skip
default:
typ := rv.Type()
if typ.Implements(interfaceTextUnmarshaller) || reflect.PtrTo(typ).Implements(interfaceTextUnmarshaller) {
v := d.envVars.Get(walker.String())
if v != nil {
if err := encodingx.UnmarshalText(rv, []byte(v.Value)); err != nil {
return err
}
}
return nil
}
switch kind {
case reflect.Array, reflect.Slice:
n := d.envVars.Len(walker.String())
if kind == reflect.Slice && rv.IsNil() {
rv.Set(reflect.MakeSlice(rv.Type(), n, n))
}
for i := 0; i < rv.Len(); i++ {
walker.Enter(i)
if err := d.scanAndSetValue(walker, rv.Index(i)); err != nil {
return err
}
walker.Exit()
}
case reflect.Struct:
tpe := rv.Type()
for i := 0; i < rv.NumField(); i++ {
field := tpe.Field(i)
flags := (map[string]bool)(nil)
name := field.Name
if !ast.IsExported(name) {
continue
}
if tag, ok := field.Tag.Lookup("env"); ok {
n, fs := tagValueAndFlags(tag)
if n == "-" {
continue
}
if n != "" {
name = n
}
flags = fs
}
inline := flags == nil && reflectx.Deref(field.Type).Kind() == reflect.Struct && field.Anonymous
if !inline {
walker.Enter(name)
}
if err := d.scanAndSetValue(walker, rv.Field(i)); err != nil {
return err
}
if !inline {
walker.Exit()
}
}
default:
v := d.envVars.Get(walker.String())
if v != nil {
if err := encodingx.UnmarshalText(rv, []byte(v.Value)); err != nil {
return err
}
}
}
}
return nil
}