-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenv.go
258 lines (208 loc) · 6.9 KB
/
env.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
package confy
import (
"encoding"
"os"
"reflect"
"strconv"
"strings"
)
type envParser[T any] struct {
o *options
}
func newEnvLoader[T any](o *options) *envParser[T] {
return &envParser[T]{
o: o,
}
}
// LoadEnv populates a configuration file T from environment variables
func LoadEnv[T any](delimiter string) (result T, err error) {
if reflect.TypeOf(result).Kind() != reflect.Struct {
panic("LoadEnv(...) only supports configs of Struct type")
}
result, _, err = Config[T](FromEnvs(delimiter))
return
}
// LoadEnvWithTransform populates a configuration file T from env variables and uses the transform to change the name of the environment variable
func LoadEnvWithTransform[T any](delimiter string, transform func(string) string) (result T, err error) {
if reflect.TypeOf(result).Kind() != reflect.Struct {
panic("LoadEnvWithTransform(...) only supports configs of Struct type")
}
result, _, err = Config[T](FromEnvs(delimiter), WithEnvTransform(transform))
return
}
// GetGeneratedEnv return list of auto generated environment variable names that LoadEnv/Config will check
func GetGeneratedEnv[T any](delimiter string) []string {
var a T
if reflect.TypeOf(a).Kind() != reflect.Struct {
panic("GetGeneratedEnv(...) only supports configs of Struct type")
}
o := options{}
FromEnvs(delimiter)(&o)
ep := newEnvLoader[T](&o)
var result []string
for _, field := range getFields(true, &a) {
envVariable, ok := determineVariableName(&a, ep.o.env.delimiter, nil, field)
if !ok {
continue
}
result = append(result, envVariable)
}
return result
}
// GetGeneratedEnvWithTransform return list of auto generated environment variable names that LoadEnv/Config will check
// it optionally also takes a transform func that you can use to change the env name
func GetGeneratedEnvWithTransform[T any](delimiter string, transformFunc Transform) []string {
var a T
if reflect.TypeOf(a).Kind() != reflect.Struct {
panic("GetGeneratedEnvWithTransform(...) only supports configs of Struct type")
}
envs := GetGeneratedEnv[T](delimiter)
for i := range envs {
if transformFunc != nil {
envs[i] = transformFunc(envs[i])
}
}
return envs
}
func (ep *envParser[T]) apply(result *T) (somethingSet bool, err error) {
for _, field := range getFields(true, result) {
envVariable, ok := determineVariableName(result, ep.o.env.delimiter, ep.o.env.transform, field)
if !ok {
continue
}
value, wasSet := os.LookupEnv(envVariable)
logger.Info("ENV", "was_set", wasSet, envVariable, maskSensitive(value, field.tag))
if wasSet {
somethingSet = true
ep.setBasicFieldFromString(result, field.path, value)
}
}
return somethingSet, nil
}
func (ep *envParser[T]) setBasicFieldFromString(v interface{}, fieldPath []string, value string) {
r := reflect.ValueOf(v).Elem()
flagName := strings.Join(resolvePath(v, fieldPath), ep.o.cli.delimiter)
isBlank := value == ""
outer:
for i, part := range fieldPath {
if i == len(fieldPath)-1 {
f := r.FieldByName(part)
if f.IsValid() {
switch f.Kind() {
case reflect.String:
f.SetString(value)
case reflect.Int, reflect.Int64:
if isBlank {
f.SetInt(0)
continue
}
reflectedVal, err := strconv.Atoi(value)
if err != nil {
logger.Error("field should be float", "err", err, "path", flagName)
continue
}
f.SetInt(int64(reflectedVal))
case reflect.Bool:
switch value {
case "true", "false", "":
f.SetBool(value == "true" && value != "")
default:
logger.Error("field should be bool", "value", value, "path", flagName)
continue
}
case reflect.Float64:
if isBlank {
f.SetFloat(0)
continue
}
reflectedVal, err := strconv.ParseFloat(value, 64)
if err != nil {
logger.Error("field should be float", "err", err, "path", flagName)
continue
}
f.SetFloat(reflectedVal)
case reflect.Slice:
sliceParts := strings.Split(value, ",")
sliceContentType := f.Type().Elem()
switch sliceContentType.Kind() {
case reflect.String:
f.Set(reflect.ValueOf(sliceParts))
case reflect.Int, reflect.Int64:
var resultingArray []int
for _, p := range sliceParts {
a, err := strconv.Atoi(p)
if err != nil {
logger.Error("expected int could not parse", "err", err, "value", p, "path", flagName)
continue outer
}
resultingArray = append(resultingArray, a)
}
f.Set(reflect.ValueOf(resultingArray))
case reflect.Float64:
var resultingArray []float64
for _, p := range sliceParts {
a, err := strconv.ParseFloat(p, 64)
if err != nil {
logger.Error("expected float could not parse", "err", err, "value", p, "path", flagName)
continue outer
}
resultingArray = append(resultingArray, a)
}
f.Set(reflect.ValueOf(resultingArray))
case reflect.Bool:
var resultingArray []bool
for _, p := range sliceParts {
switch p {
case "true", "false":
resultingArray = append(resultingArray, p == "true")
default:
logger.Error("expected bool could not parse", "value", p, "path", flagName)
continue outer
}
}
f.Set(reflect.ValueOf(resultingArray))
default:
inter := reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
if !reflect.PointerTo(sliceContentType).Implements(inter) {
logger.Warn("type inside of complex slice did not implement encoding.TextUnmarshaler", "flag", flagName, "path", flagName)
continue
}
sliceVal := reflect.MakeSlice(reflect.SliceOf(sliceContentType), 0, len(sliceParts))
for _, p := range sliceParts {
n := reflect.New(sliceContentType).Interface().(encoding.TextUnmarshaler)
err := n.UnmarshalText([]byte(p))
if err != nil {
logger.Error("could not unmarshal text for complex inner slice type", "err", err, "flag", flagName, "path", flagName)
continue outer
}
// Append to our slice - need to get the element value, not pointer
elemVal := reflect.ValueOf(n).Elem()
sliceVal = reflect.Append(sliceVal, elemVal)
}
f.Set(sliceVal)
}
case reflect.Struct:
_, ok := f.Addr().Interface().(encoding.TextUnmarshaler)
if !ok {
logger.Warn("structure doesnt implement encoding.TextUnmarshaler", "flag", flagName, "path", flagName)
continue
}
n := reflect.New(f.Type())
err := n.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value))
if err != nil {
logger.Error("unmarshaling struct (TextUnmarshaler) failed", "err", err, "path", flagName)
continue
}
f.Set(n.Elem())
default:
logger.Warn("unsupported type for env auto-addition", "type", f.Kind().String(), "path", flagName)
continue
}
} else {
logger.Error("Field not found", "path", flagName)
}
} else {
r = r.FieldByName(part)
}
}
}