forked from joeshaw/envdecode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
envdecode.go
367 lines (310 loc) · 8.42 KB
/
envdecode.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
// Package envdecode is a package for populating structs from environment
// variables, using struct tags.
package envdecode
import (
"errors"
"fmt"
"log"
"net/url"
"os"
"reflect"
"sort"
"strconv"
"strings"
"time"
)
// ErrInvalidTarget indicates that the target value passed to
// Decode is invalid. Target must be a non-nil pointer to a struct.
var ErrInvalidTarget = errors.New("target must be non-nil pointer to struct that has at least one exported field with a valid env tag.")
// FailureFunc is called when an error is encountered during a MustDecode
// operation. It prints the error and terminates the process.
//
// This variable can be assigned to another function of the user-programmer's
// design, allowing for graceful recovery of the problem, such as loading
// from a backup configuration file.
var FailureFunc = func(err error) {
log.Fatalf("envdecode: an error was encountered while decoding: %v\n", err)
}
// Decoder is the interface implemented by an object that can decode an
// environment variable string representation of itself.
type Decoder interface {
Decode(string) error
}
// Decode environment variables into the provided target. The target
// must be a non-nil pointer to a struct. Fields in the struct must
// be exported, and tagged with an "env" struct tag with a value
// containing the name of the environment variable. An error is
// returned if there are no exported members tagged.
//
// Default values may be provided by appending ",default=value" to the
// struct tag. Required values may be marked by appending ",required"
// to the struct tag. It is an error to provide both "default" and
// "required".
//
// All primitive types are supported, including bool, floating point,
// signed and unsigned integers, and string. Boolean and numeric
// types are decoded using the standard strconv Parse functions for
// those types. Structs and pointers to structs are decoded
// recursively. time.Duration is supported via the
// time.ParseDuration() function and *url.URL is supported via the
// url.Parse() function. Slices are supported for all above mentioned
// primitive types. Semicolon is used as delimiter in environment variables.
func Decode(target interface{}) error {
nFields, err := decode(target)
if err != nil {
return err
}
// if we didn't do anything - the user probably did something
// wrong like leave all fields unexported.
if nFields == 0 {
return ErrInvalidTarget
}
return nil
}
func decode(target interface{}) (int, error) {
s := reflect.ValueOf(target)
if s.Kind() != reflect.Ptr || s.IsNil() {
return 0, ErrInvalidTarget
}
s = s.Elem()
if s.Kind() != reflect.Struct {
return 0, ErrInvalidTarget
}
t := s.Type()
setFieldCount := 0
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
switch f.Kind() {
case reflect.Ptr:
if f.Elem().Kind() != reflect.Struct {
break
}
f = f.Elem()
fallthrough
case reflect.Struct:
ss := f.Addr().Interface()
_, custom := ss.(Decoder)
if custom {
break
}
n, err := decode(ss)
if err != nil {
return 0, err
}
setFieldCount += n
}
if !f.CanSet() {
continue
}
tag := t.Field(i).Tag.Get("env")
if tag == "" {
continue
}
parts := strings.Split(tag, ",")
env := os.Getenv(parts[0])
required := false
hasDefault := false
defaultValue := ""
for _, o := range parts[1:] {
if !required {
required = strings.HasPrefix(o, "required")
}
if strings.HasPrefix(o, "default=") {
hasDefault = true
defaultValue = o[8:]
}
}
if required && hasDefault {
panic(`envdecode: "default" and "required" may not be specified in the same annotation`)
}
if env == "" && required {
return 0, fmt.Errorf("the environment variable \"%s\" is missing", parts[0])
}
if env == "" {
env = defaultValue
}
if env == "" {
continue
}
setFieldCount++
decoder, custom := f.Addr().Interface().(Decoder)
if custom {
decoder.Decode(env)
} else if f.Kind() == reflect.Slice {
decodeSlice(&f, env)
} else {
decodePrimitiveType(&f, env)
}
}
return setFieldCount, nil
}
func decodeSlice(f *reflect.Value, env string) {
parts := strings.Split(env, ";")
values := parts[:0]
for _, x := range parts {
if x != "" {
values = append(values, strings.TrimSpace(x))
}
}
valuesCount := len(values)
slice := reflect.MakeSlice(f.Type(), valuesCount, valuesCount)
if valuesCount > 0 {
for i := 0; i < valuesCount; i++ {
e := slice.Index(i)
decodePrimitiveType(&e, values[i])
}
}
f.Set(slice)
}
func decodePrimitiveType(f *reflect.Value, env string) {
switch f.Kind() {
case reflect.Bool:
v, err := strconv.ParseBool(env)
if err == nil {
f.SetBool(v)
}
case reflect.Float32, reflect.Float64:
bits := f.Type().Bits()
v, err := strconv.ParseFloat(env, bits)
if err == nil {
f.SetFloat(v)
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if t := f.Type(); t.PkgPath() == "time" && t.Name() == "Duration" {
v, err := time.ParseDuration(env)
if err == nil {
f.SetInt(int64(v))
}
} else {
bits := f.Type().Bits()
v, err := strconv.ParseInt(env, 0, bits)
if err == nil {
f.SetInt(v)
}
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
bits := f.Type().Bits()
v, err := strconv.ParseUint(env, 0, bits)
if err == nil {
f.SetUint(v)
}
case reflect.String:
f.SetString(env)
case reflect.Ptr:
if t := f.Type().Elem(); t.Kind() == reflect.Struct && t.PkgPath() == "net/url" && t.Name() == "URL" {
v, err := url.Parse(env)
if err == nil {
f.Set(reflect.ValueOf(v))
}
}
}
}
// MustDecode calls Decode and terminates the process if any errors
// are encountered.
func MustDecode(target interface{}) {
err := Decode(target)
if err != nil {
FailureFunc(err)
}
}
//// Configuration info for Export
type ConfigInfo struct {
Field string
EnvVar string
Value string
DefaultValue string
HasDefault bool
Required bool
UsesEnv bool
}
type ConfigInfoSlice []*ConfigInfo
func (c ConfigInfoSlice) Less(i, j int) bool {
return c[i].EnvVar < c[j].EnvVar
}
func (c ConfigInfoSlice) Len() int {
return len(c)
}
func (c ConfigInfoSlice) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}
// Returns a list of final configuration metadata sorted by envvar name
func Export(target interface{}) ([]*ConfigInfo, error) {
s := reflect.ValueOf(target)
if s.Kind() != reflect.Ptr || s.IsNil() {
return nil, ErrInvalidTarget
}
cfg := []*ConfigInfo{}
s = s.Elem()
if s.Kind() != reflect.Struct {
return nil, ErrInvalidTarget
}
t := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fName := t.Field(i).Name
fElem := f
if f.Kind() == reflect.Ptr {
fElem = f.Elem()
}
if fElem.Kind() == reflect.Struct {
ss := fElem.Addr().Interface()
subCfg, err := Export(ss)
if err != ErrInvalidTarget {
f = fElem
for _, v := range subCfg {
v.Field = fmt.Sprintf("%s.%s", fName, v.Field)
cfg = append(cfg, v)
}
}
}
tag := t.Field(i).Tag.Get("env")
if tag == "" {
continue
}
parts := strings.Split(tag, ",")
ci := &ConfigInfo{
Field: fName,
EnvVar: parts[0],
UsesEnv: os.Getenv(parts[0]) != "",
}
for _, o := range parts[1:] {
if strings.HasPrefix(o, "default=") {
ci.HasDefault = true
ci.DefaultValue = o[8:]
} else if strings.HasPrefix(o, "required") {
ci.Required = true
}
}
if f.Kind() == reflect.Ptr && f.IsNil() {
ci.Value = ""
} else if stringer, ok := f.Interface().(fmt.Stringer); ok {
ci.Value = stringer.String()
} else {
switch f.Kind() {
case reflect.Bool:
ci.Value = strconv.FormatBool(f.Bool())
case reflect.Float32, reflect.Float64:
bits := f.Type().Bits()
ci.Value = strconv.FormatFloat(f.Float(), 'f', -1, bits)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
ci.Value = strconv.FormatInt(f.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
ci.Value = strconv.FormatUint(f.Uint(), 10)
case reflect.String:
ci.Value = f.String()
case reflect.Slice:
ci.Value = fmt.Sprintf("%v", f.Interface())
default:
// Unable to determine string format for value
return nil, ErrInvalidTarget
}
}
cfg = append(cfg, ci)
}
// No configuration tags found, assume invalid input
if len(cfg) == 0 {
return nil, ErrInvalidTarget
}
sort.Sort(ConfigInfoSlice(cfg))
return cfg, nil
}