-
Notifications
You must be signed in to change notification settings - Fork 7
/
gofigure.go
637 lines (572 loc) · 14.4 KB
/
gofigure.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
// Package gofigure simplifies configuration of Go applications.
//
// Define a struct and call Gofigure()
package gofigure
import (
"errors"
"fmt"
"log"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/ian-kent/gofigure/sources"
)
// Debug controls log output
var Debug = false
func init() {
env := os.Getenv("GOFIGURE_DEBUG")
if len(env) > 0 {
Debug, _ = strconv.ParseBool(env)
}
sources.Logger = printf
sources.Debug = Debug
return
}
func printf(message string, args ...interface{}) {
if !Debug {
return
}
log.Printf(message, args...)
}
/* TODO
* - Add file/http sources
* - Add "decoders", e.g. json/env/xml
* - Default value (if gofigure is func()*StructType)
* - Ignore lowercased "unexported" fields?
*/
// gofiguration represents a parsed struct
type gofiguration struct {
order []string
params map[string]map[string]string
fields map[string]*gofiguritem
flagged bool
parent *gofiguration
children []*gofiguration
s interface{}
}
func (gfg *gofiguration) printf(message string, args ...interface{}) {
printf(message, args...)
}
// gofiguritem represents a single struct field
type gofiguritem struct {
keys map[string]string
field string
goField reflect.StructField
goValue reflect.Value
inner *gofiguration
}
// Sources contains a map of struct field tag names to source implementation
var Sources = map[string]sources.Source{
"env": &sources.Environment{},
"flag": &sources.CommandLine{},
}
// DefaultOrder sets the default order used
var DefaultOrder = []string{"env", "flag"}
// ErrUnsupportedType is returned if the interface isn't a
// pointer to a struct
var ErrUnsupportedType = errors.New("Unsupported interface type")
// ErrInvalidOrder is returned if the "order" struct tag is invalid
var ErrInvalidOrder = errors.New("Invalid order")
// ErrUnsupportedFieldType is returned for unsupported field types,
// e.g. chan or func
var ErrUnsupportedFieldType = errors.New("Unsupported field type")
// ParseStruct creates a gofiguration from a struct.
//
// It returns ErrUnsupportedType if s is not a struct or a
// pointer to a struct.
func parseStruct(s interface{}) (*gofiguration, error) {
var v reflect.Value
if reflect.TypeOf(s) != reflect.TypeOf(v) {
v = reflect.ValueOf(s)
if v.Kind() == reflect.PtrTo(reflect.TypeOf(s)).Kind() {
v = reflect.Indirect(v)
}
} else {
v = s.(reflect.Value)
}
if v.Kind() != reflect.Struct {
return nil, ErrUnsupportedType
}
t := v.Type()
gfg := &gofiguration{
params: make(map[string]map[string]string),
order: DefaultOrder,
fields: make(map[string]*gofiguritem),
s: s,
}
err := gfg.parseGofigureField(t)
if err != nil {
return nil, err
}
gfg.parseFields(v, t)
return gfg, nil
}
func getStructTags(tag string) map[string]string {
// http://golang.org/src/pkg/reflect/type.go?s=20885:20906#L747
m := make(map[string]string)
for tag != "" {
// skip leading space
i := 0
for i < len(tag) && tag[i] == ' ' {
i++
}
tag = tag[i:]
if tag == "" {
break
}
// scan to colon.
// a space or a quote is a syntax error
i = 0
for i < len(tag) && tag[i] != ' ' && tag[i] != ':' && tag[i] != '"' {
i++
}
if i+1 >= len(tag) || tag[i] != ':' || tag[i+1] != '"' {
break
}
name := string(tag[:i])
tag = tag[i+1:]
// scan quoted string to find value
i = 1
for i < len(tag) && tag[i] != '"' {
if tag[i] == '\\' {
i++
}
i++
}
if i >= len(tag) {
break
}
qvalue := string(tag[:i+1])
tag = tag[i+1:]
value, _ := strconv.Unquote(qvalue)
m[name] = value
}
return m
}
var argRe = regexp.MustCompile("([a-z]+)([A-Z][a-z]+)")
func (gfg *gofiguration) parseGofigureField(t reflect.Type) error {
gf, ok := t.FieldByName("gofigure")
if ok {
tags := getStructTags(string(gf.Tag))
for name, value := range tags {
if name == "order" {
oParts := strings.Split(value, ",")
for _, p := range oParts {
if _, ok := Sources[p]; !ok {
return ErrInvalidOrder
}
}
gfg.order = oParts
continue
}
// Parse orderKey:"value" tags, e.g.
// envPrefix, which gets split into
// gfg.params["env"]["prefix"] = "value"
// gfg.params["env"] is then passed to
// source registered with that key
match := argRe.FindStringSubmatch(name)
if len(match) > 1 {
if _, ok := gfg.params[match[1]]; !ok {
gfg.params[match[1]] = make(map[string]string)
}
gfg.params[match[1]][strings.ToLower(match[2])] = value
}
}
}
return nil
}
func (gfg *gofiguration) parseFields(v reflect.Value, t reflect.Type) {
gfg.printf("Found %d fields", t.NumField())
for i := 0; i < t.NumField(); i++ {
f := t.Field(i).Name
if f == "gofigure" {
gfg.printf("Skipped field '%s'", f)
continue
}
gfg.printf("Parsed field '%s'", f)
gfi := &gofiguritem{
field: f,
goField: t.Field(i),
goValue: v.Field(i),
keys: make(map[string]string),
}
tag := t.Field(i).Tag
if len(tag) > 0 {
gfi.keys = getStructTags(string(tag))
}
gfg.fields[f] = gfi
}
}
func (gfg *gofiguration) cleanupSources() {
for _, o := range gfg.order {
Sources[o].Cleanup()
}
}
func (gfg *gofiguration) initSources() error {
for _, o := range gfg.order {
err := Sources[o].Init(gfg.params[o])
if err != nil {
return err
}
}
return nil
}
func (gfg *gofiguration) registerFields() error {
for _, gfi := range gfg.fields {
kn := gfi.field
var err error
switch gfi.goField.Type.Kind() {
case reflect.Struct:
gfg.printf("Registering as struct type")
// TODO do shit
sGfg, err := parseStruct(gfi.goValue)
if err != nil {
return err
}
sGfg.apply(gfg)
gfi.inner = sGfg
default:
gfg.printf("Registering as default type")
for _, o := range gfg.order {
if k, ok := gfi.keys[o]; ok {
kn = k
}
gfg.printf("Registering '%s' for source '%s' with key '%s'", gfi.field, o, kn)
err = Sources[o].Register(kn, "", gfi.keys, gfi.goField.Type)
}
}
if err != nil {
return err
}
}
return nil
}
func numVal(i string) string {
if len(i) == 0 {
return "0"
}
return i
}
func (gfi *gofiguritem) populateDefaultType(order []string) error {
// FIXME could just preserve types
var v string
switch gfi.goField.Type.Kind() {
case reflect.Bool:
v = fmt.Sprintf("%t", gfi.goValue.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v = fmt.Sprintf("%d", gfi.goValue.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v = fmt.Sprintf("%d", gfi.goValue.Uint())
case reflect.Float32, reflect.Float64:
v = fmt.Sprintf("%f", gfi.goValue.Float())
case reflect.String:
v = gfi.goValue.String()
}
var prevVal = &v
for _, source := range order {
kn := gfi.field
if k, ok := gfi.keys[source]; ok {
kn = k
}
val, err := Sources[source].Get(kn, prevVal)
if err != nil {
return err
}
prevVal = &val
printf("Got value '%s' from source '%s' for key '%s'", val, source, gfi.field)
switch gfi.goField.Type.Kind() {
case reflect.Bool:
if len(val) == 0 {
printf("Setting bool value to false")
val = "false"
}
b, err := strconv.ParseBool(val)
if err != nil {
return err
}
gfi.goValue.SetBool(b)
case reflect.Int:
i, err := strconv.ParseInt(numVal(val), 10, 64)
if err != nil {
return err
}
gfi.goValue.SetInt(i)
case reflect.Int8:
i, err := strconv.ParseInt(numVal(val), 10, 8)
if err != nil {
return err
}
gfi.goValue.SetInt(i)
case reflect.Int16:
i, err := strconv.ParseInt(numVal(val), 10, 16)
if err != nil {
return err
}
gfi.goValue.SetInt(i)
case reflect.Int32:
i, err := strconv.ParseInt(numVal(val), 10, 32)
if err != nil {
return err
}
gfi.goValue.SetInt(i)
case reflect.Int64:
i, err := strconv.ParseInt(numVal(val), 10, 64)
if err != nil {
return err
}
gfi.goValue.SetInt(i)
case reflect.Uint:
i, err := strconv.ParseUint(numVal(val), 10, 64)
if err != nil {
return err
}
gfi.goValue.SetUint(i)
case reflect.Uint8:
i, err := strconv.ParseUint(numVal(val), 10, 8)
if err != nil {
return err
}
gfi.goValue.SetUint(i)
case reflect.Uint16:
i, err := strconv.ParseUint(numVal(val), 10, 16)
if err != nil {
return err
}
gfi.goValue.SetUint(i)
case reflect.Uint32:
i, err := strconv.ParseUint(numVal(val), 10, 32)
if err != nil {
return err
}
gfi.goValue.SetUint(i)
case reflect.Uint64:
i, err := strconv.ParseUint(numVal(val), 10, 64)
if err != nil {
return err
}
gfi.goValue.SetUint(i)
case reflect.Float32:
f, err := strconv.ParseFloat(numVal(val), 32)
if err != nil {
return err
}
gfi.goValue.SetFloat(f)
case reflect.Float64:
f, err := strconv.ParseFloat(numVal(val), 64)
if err != nil {
return err
}
gfi.goValue.SetFloat(f)
case reflect.String:
gfi.goValue.SetString(val)
default:
return ErrUnsupportedFieldType
}
}
return nil
}
func (gfi *gofiguritem) populateSliceType(order []string) error {
var prevVal *[]string
for _, source := range order {
kn := gfi.field
if k, ok := gfi.keys[source]; ok {
kn = k
}
printf("Looking for field '%s' with key '%s' in source '%s'", gfi.field, kn, source)
val, err := Sources[source].GetArray(kn, prevVal)
if err != nil {
return err
}
// This causes duplication between array sources depending on order
//prevVal = &val
printf("Got value '%+v' from array source '%s' for key '%s'", val, source, gfi.field)
switch gfi.goField.Type.Kind() {
case reflect.Slice:
switch gfi.goField.Type.Elem().Kind() {
case reflect.String:
for _, s := range val {
printf("Appending string value '%s' to slice", s)
gfi.goValue.Set(reflect.Append(gfi.goValue, reflect.ValueOf(s)))
}
case reflect.Int:
for _, s := range val {
printf("Appending int value '%s' to slice", s)
i, err := strconv.ParseInt(numVal(s), 10, 64)
if err != nil {
return err
}
gfi.goValue.Set(reflect.Append(gfi.goValue, reflect.ValueOf(int(i))))
}
case reflect.Int8:
for _, s := range val {
printf("Appending int8 value '%s' to slice", s)
i, err := strconv.ParseInt(numVal(s), 10, 8)
if err != nil {
return err
}
gfi.goValue.Set(reflect.Append(gfi.goValue, reflect.ValueOf(int8(i))))
}
case reflect.Int16:
for _, s := range val {
printf("Appending int16 value '%s' to slice", s)
i, err := strconv.ParseInt(numVal(s), 10, 16)
if err != nil {
return err
}
gfi.goValue.Set(reflect.Append(gfi.goValue, reflect.ValueOf(int16(i))))
}
case reflect.Int32:
for _, s := range val {
printf("Appending int32 value '%s' to slice", s)
i, err := strconv.ParseInt(numVal(s), 10, 32)
if err != nil {
return err
}
gfi.goValue.Set(reflect.Append(gfi.goValue, reflect.ValueOf(int32(i))))
}
case reflect.Int64:
for _, s := range val {
printf("Appending int64 value '%s' to slice", s)
i, err := strconv.ParseInt(numVal(s), 10, 64)
if err != nil {
return err
}
gfi.goValue.Set(reflect.Append(gfi.goValue, reflect.ValueOf(int64(i))))
}
case reflect.Uint:
for _, s := range val {
printf("Appending uint value '%s' to slice", s)
i, err := strconv.ParseUint(numVal(s), 10, 64)
if err != nil {
return err
}
gfi.goValue.Set(reflect.Append(gfi.goValue, reflect.ValueOf(uint(i))))
}
case reflect.Uint8:
for _, s := range val {
printf("Appending uint8 value '%s' to slice", s)
i, err := strconv.ParseUint(numVal(s), 10, 8)
if err != nil {
return err
}
gfi.goValue.Set(reflect.Append(gfi.goValue, reflect.ValueOf(uint8(i))))
}
case reflect.Uint16:
for _, s := range val {
printf("Appending uint16 value '%s' to slice", s)
i, err := strconv.ParseUint(numVal(s), 10, 16)
if err != nil {
return err
}
gfi.goValue.Set(reflect.Append(gfi.goValue, reflect.ValueOf(uint16(i))))
}
case reflect.Uint32:
for _, s := range val {
printf("Appending uint32 value '%s' to slice", s)
i, err := strconv.ParseUint(numVal(s), 10, 32)
if err != nil {
return err
}
gfi.goValue.Set(reflect.Append(gfi.goValue, reflect.ValueOf(uint32(i))))
}
case reflect.Uint64:
for _, s := range val {
printf("Appending uint64 value '%s' to slice", s)
i, err := strconv.ParseUint(numVal(s), 10, 64)
if err != nil {
return err
}
gfi.goValue.Set(reflect.Append(gfi.goValue, reflect.ValueOf(uint64(i))))
}
// TODO floats
default:
//return ErrUnsupportedFieldType
}
}
}
return nil
}
func (gfi *gofiguritem) populateStructType(order []string) error {
return gfi.inner.populateStruct()
}
func (gfg *gofiguration) populateStruct() error {
if gfg == nil {
return nil
}
for _, gfi := range gfg.fields {
printf("Populating field %s", gfi.field)
switch gfi.goField.Type.Kind() {
case reflect.Invalid, reflect.Uintptr, reflect.Complex64,
reflect.Complex128, reflect.Chan, reflect.Func,
reflect.Ptr, reflect.UnsafePointer:
return ErrUnsupportedFieldType
case reflect.Interface:
// TODO
return ErrUnsupportedFieldType
case reflect.Map:
// TODO
return ErrUnsupportedFieldType
case reflect.Slice:
printf("Calling populateSliceType")
err := gfi.populateSliceType(gfg.order)
if err != nil {
return err
}
case reflect.Struct:
printf("Calling populateStructType")
err := gfi.populateStructType(gfg.order)
if err != nil {
return err
}
case reflect.Array:
// TODO
return ErrUnsupportedFieldType
default:
printf("Calling populateDefaultType")
err := gfi.populateDefaultType(gfg.order)
if err != nil {
return err
}
}
}
for _, c := range gfg.children {
err := c.populateStruct()
if err != nil {
return err
}
}
return nil
}
// Apply applies the gofiguration to the struct
func (gfg *gofiguration) apply(parent *gofiguration) error {
gfg.parent = parent
if parent == nil {
defer gfg.cleanupSources()
err := gfg.initSources()
if err != nil {
return err
}
} else {
parent.children = append(parent.children, gfg)
}
err := gfg.registerFields()
if err != nil {
return err
}
if parent == nil {
return gfg.populateStruct()
}
return nil
}
// Gofigure parses and applies the configuration defined by the struct.
//
// It returns ErrUnsupportedType if s is not a pointer to a struct.
func Gofigure(s interface{}) error {
gfg, err := parseStruct(s)
if err != nil {
return err
}
return gfg.apply(nil)
}