-
Notifications
You must be signed in to change notification settings - Fork 1
/
apply_env_overrides.go
180 lines (150 loc) · 3.77 KB
/
apply_env_overrides.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
package config
import (
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
)
var (
ErrNotSlice = errors.New("should be a slice")
ErrNotSettable = errors.New("should be settable")
ErrPrefixRequired = errors.New("prefix is required")
)
var camelCaseRegex = regexp.MustCompile("(^[A-Za-z])|_([A-Za-z])")
// ToCamelCase converts string to camel case
func ToCamelCase(str string) string {
return camelCaseRegex.ReplaceAllStringFunc(strings.ToLower(str), func(s string) string {
return strings.ToUpper(strings.Replace(s, "_", "", -1))
})
}
// applyEnvOverridesToSlice merges elements of slice with ENV
func applyEnvOverridesToSlice(prefix string, dst interface{}) error {
if prefix == "" {
return ErrPrefixRequired
}
rv, ok := dst.(reflect.Value)
if !ok {
// fallback
rv = reflect.ValueOf(dst)
if rv.Kind() != reflect.Ptr {
return ErrNotPointer
}
}
riv := indirectWalk(rv)
rit := indirectType(riv.Type())
if rit.Kind() != reflect.Slice {
return ErrNotSlice
}
if !rv.CanSet() && !riv.CanSet() {
return fmt.Errorf("not settable type: %s %s at prefix: %s: %v", rv.Type(), riv.Type(), prefix, ErrNotSettable)
}
parseKeyVal, err := regexp.Compile(prefix + "_(\\d+)_(\\w+)=(.+)")
if err != nil {
return err
}
sliceOf := rit.Elem()
mapConfigs := make(map[int]reflect.Value)
envs := environ()
if !isZero(rv) {
l := riv.Len()
for i := 0; i < l; i++ {
value := reflect.Indirect(riv.Index(i))
// set defaults for element, it was created after first defaults was applied
if err := applyDefaultToEmpty(reflect.StructField{}, value); err != nil {
return err
}
mapConfigs[i] = value
}
}
for _, keyVal := range envs {
if strings.HasPrefix(keyVal, prefix) {
matches := parseKeyVal.FindStringSubmatch(keyVal)
if len(matches) != 4 {
continue
}
index, err := strconv.ParseInt(matches[1], 10, 64)
if err != nil {
return err
}
i := int(index)
envKey := matches[2]
value := matches[3]
if _, ok := mapConfigs[i]; !ok {
value := reflect.Indirect(reflect.New(sliceOf))
// set defaults for new created element
if err := applyDefaultToEmpty(reflect.StructField{}, value); err != nil {
return err
}
mapConfigs[i] = value
}
v := mapConfigs[i]
f, ok := fieldByEnvconfig(v, envKey)
if !ok {
// fallback in case field with
name := ToCamelCase(matches[2])
f = v.FieldByName(name)
if (f == reflect.Value{}) {
return fmt.Errorf("field %s not found", name)
}
}
if err := setValue(f, value); err != nil {
return err
}
}
}
if len(mapConfigs) == 0 {
return nil
}
values := make([]reflect.Value, len(mapConfigs))
for i, item := range mapConfigs {
values[i] = item
}
ptr := reflect.New(rit)
tmp := ptr.Elem()
tmp.Set(reflect.Append(tmp, values...))
if rv.CanSet() {
setPtrValue(rv, ptr, tmp)
return nil
}
setPtrValue(riv, ptr, tmp)
return nil
}
// setPtrValue set as Ptr or Value
func setPtrValue(dst, ptr, val reflect.Value) {
if dst.Kind() == reflect.Ptr {
dst.Set(ptr)
} else {
dst.Set(val)
}
}
// fieldByEnvconfig lookup field by `envconfig` tag
func fieldByEnvconfig(v reflect.Value, key string) (rv reflect.Value, ok bool) {
for i, l := 0, v.NumField(); i < l; i++ {
envconfig := v.Type().Field(i).Tag.Get(envConfigTag)
if key == envconfig {
return v.Field(i), true
}
}
return
}
// applyDefaultToEmpty applies default to empty field only
func applyDefaultToEmpty(t reflect.StructField, v reflect.Value) error {
if v.Kind() == reflect.Struct {
for i := 0; i < v.NumField(); i++ {
if err := applyDefaultToEmpty(v.Type().Field(i), v.Field(i)); err != nil {
return err
}
}
return nil
}
if !isZero(v) {
return nil
}
value, ok := t.Tag.Lookup("default")
if !ok {
return nil
}
return setValue(v, value)
}