/
configo.go
401 lines (333 loc) · 8.8 KB
/
configo.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
// Package configo provides functions to handle configuration items.
//
// Example:
// type Config struct {
// SomeThing *SomeThing
// Mysql MysqlConfig `toml:"mysql"`
// Port *Int `default:"8080"`
// }
//
// type MysqlConfig struct {
// Dsn *string
// }
//
// mydb := "/mydb"
//
// config := Config{
// Mysql: MysqlConfig{
// Dsn: &mydb,
// },
// }
//
// err := configo.UnmarshalFile("/path/to/config.toml", &config)
// // error check
//
// fmt.Printf("Listening on port %d", *config.Port)
package configo
import (
"fmt"
"os"
"reflect"
"strconv"
"github.com/BurntSushi/toml"
)
// UnmarshalFile decodes the contents of the file `f` in TOML format into a pointer `v`. If `v` contains data, that data will be used as "defaults".
//
// A field's value will be determined based on the following order:
//
// 1. If an "env" tag exists for a field and an environment variable matching the tag's value exists, the environment variable's value will be used, subject to type casting.
// 2. If the field exists in the file, its value will be used. The `toml` tag may be used to map TOML keys to fields that don't match the key name exactly.
// 3. If `v` already contains a value for the field, it will be used.
// 4. If a "default" tag exists for a field, its value will be used, subject to type casting.
// 5. The field will be initialized to its zero value (i.e., "" for string, 0 for int, etc).
func UnmarshalFile(f string, v interface{}) error {
var err error
rv := reflect.ValueOf(v).Elem()
err = setDefaults(&rv)
if err != nil {
return err
}
// Unmarshalling TOML onto a non-zero struct is inconsistent.
// One time the value might be the pre-existing value, another time
// it might be from the TOML. Instead we unmarshal onto a new struct
// then walk the struct copying non-zero values.
nv := reflect.New(rv.Type())
ni := nv.Interface()
_, err = toml.DecodeFile(f, ni)
if err != nil {
return err
}
err = setToml(&rv, nv.Elem())
if err != nil {
return err
}
err = setEnv(&rv)
if err != nil {
return err
}
return nil
}
// FromDefaults sets pointer `v` based on default values of `v`.
//
// A field's value will be determined based on the following order:
//
// 1. If `v` already contains a value for the field, it will be used.
// 2. If a "default" tag exists for a field, its value will be used, subject to type casting.
// 3. The field will be initialized to its zero value (i.e., "" for string, 0 for int, etc).
func FromDefaults(v interface{}) error {
rv := reflect.ValueOf(v).Elem()
return setDefaults(&rv)
}
// FromEnv sets pointer `v` based on the environment.
//
// A field's value will be determined based on the following order:
//
// 1. If an "env" tag exists for a field and an environment variable matching the tag's value exists, the environment variable's value will be used, subject to type casting.
// 2. If `v` already contains a value for the field, it will be used.
func FromEnv(v interface{}) error {
rv := reflect.ValueOf(v).Elem()
return setEnv(&rv)
}
// FromTOML decodes the contents of the file `f` in TOML format into a pointer `v`.
//
// A field's value will be determined based on the following order:
//
// 1. If the field exists in the file, its value will be used. The `toml` tag may be used to map TOML keys to fields that don't match the key name exactly.
// 2. If `v` already contains a value for the field, it will be used.
func FromTOML(f string, v interface{}) error {
rv := reflect.ValueOf(v).Elem()
// Unmarshalling TOML onto a non-zero struct is inconsistent.
// One time the value might be the pre-existing value, another time
// it might be from the TOML. Instead we unmarshal onto a new struct
// then walk the struct copying non-zero values.
nv := reflect.New(rv.Type())
ni := nv.Interface()
_, err := toml.DecodeFile(f, ni)
if err != nil {
return err
}
return setToml(&rv, nv.Elem())
}
func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.String:
return v.Interface() == reflect.Zero(v.Type()).Interface()
case reflect.Ptr:
if !v.Elem().IsValid() {
return true
}
if v.Elem().Interface() == nil {
return true
}
}
return false
}
func set(v *reflect.Value, s string) error {
switch v.Kind() {
case reflect.Bool:
b, err := strconv.ParseBool(s)
if err != nil {
return err
}
v.SetBool(b)
return nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if s == "" {
s = "0"
}
n, err := strconv.ParseInt(s, 10, v.Type().Bits())
if err != nil {
return err
}
v.SetInt(n)
return nil
case reflect.Ptr:
if !v.Elem().IsValid() {
v.Set(reflect.New(v.Type().Elem()))
}
switch v.Interface().(type) {
case *bool:
b, err := strconv.ParseBool(s)
if err != nil {
return err
}
v.Elem().SetBool(b)
return nil
case *int, *int8, *int16, *int32, *int64:
n, err := strconv.ParseInt(s, 10, v.Elem().Type().Bits())
if err != nil {
return err
}
v.Elem().SetInt(n)
return nil
case *string:
v.Elem().SetString(s)
return nil
default:
// TODO: Do something with unknown pointer types
}
case reflect.String:
v.SetString(s)
return nil
default:
// TODO: Do something with unknown reflect types
}
return nil
}
func setDefaults(v *reflect.Value) error {
var err error
// TODO: Properly initialize struct pointers
// e.g. given "type Foo struct { Bar *OtherStruct }" set Bar's fields
// to their zero-value.
switch v.Kind() {
case reflect.Ptr:
if isZero(*v) {
v.Set(reflect.New(v.Type().Elem()))
}
nv := v.Elem()
err = setDefaults(&nv)
if err != nil {
return err
}
v = &nv
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
val := v.Field(i)
typ := v.Type().Field(i)
kind := val.Kind()
if kind == reflect.Struct {
err = setDefaults(&val)
if err != nil {
return err
}
continue
}
if kind == reflect.Ptr && val.Elem().Kind() == reflect.Struct {
err = setDefaults(&val)
if err != nil {
return err
}
continue
}
if isZero(val) {
switch val.Kind() {
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.String:
val.Set(reflect.ValueOf(val.Interface()))
case reflect.Ptr:
val.Set(reflect.New(val.Type().Elem()))
default:
// TODO: Do something with unknown types
}
tag := typ.Tag.Get("default")
if tag != "" {
err = set(&val, tag)
if err != nil {
err = fmt.Errorf("default %s: %s", typ.Name, err)
return err
}
}
}
}
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.String:
if isZero(*v) {
v.Set(reflect.ValueOf(v.Interface()))
}
default:
// TODO: Do something with unknown value types
}
return nil
}
func setEnv(v *reflect.Value) error {
var err error
switch v.Kind() {
case reflect.Ptr:
nv := v.Elem()
err = setEnv(&nv)
if err != nil {
return err
}
v = &nv
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
val := v.Field(i)
typ := v.Type().Field(i)
kind := val.Kind()
if kind == reflect.Struct {
err = setEnv(&val)
if err != nil {
return err
}
continue
}
if kind == reflect.Ptr && val.Elem().Kind() == reflect.Struct {
err = setEnv(&val)
if err != nil {
return err
}
continue
}
tag := typ.Tag.Get("env")
if tag == "" {
continue
}
getenv := os.Getenv(tag)
if getenv == "" {
continue
}
err = set(&val, getenv)
if err != nil {
err = fmt.Errorf("default %s: %s", typ.Name, err)
return err
}
}
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.String:
v.Set(reflect.ValueOf(v.Interface()))
default:
// TODO: Do something with unknown value types
}
return nil
}
func setToml(dst *reflect.Value, src reflect.Value) error {
var err error
// TODO: Don't assume src and dst are the same
switch dst.Kind() {
case reflect.Ptr:
dnv := dst.Elem()
snv := src.Elem()
err = setToml(&dnv, snv)
if err != nil {
return err
}
dst = &dnv
case reflect.Struct:
for i := 0; i < dst.NumField(); i++ {
dval := dst.Field(i)
sval := src.Field(i)
kind := dval.Kind()
if kind == reflect.Struct {
err = setToml(&dval, sval)
if err != nil {
return err
}
continue
}
if kind == reflect.Ptr && dval.Elem().Kind() == reflect.Struct {
err = setToml(&dval, sval)
if err != nil {
return err
}
continue
}
if !isZero(sval) {
dval.Set(sval)
}
}
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.String:
if !isZero(src) {
dst.Set(src)
}
default:
// TODO: Do something with unknown value types
}
return nil
}