-
Notifications
You must be signed in to change notification settings - Fork 10
/
node.go
656 lines (528 loc) · 12.1 KB
/
node.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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
package conf
import (
"bytes"
"encoding"
"flag"
"fmt"
"reflect"
"sort"
"time"
"github.com/segmentio/objconv"
"github.com/segmentio/objconv/json"
"github.com/segmentio/objconv/yaml"
)
// NodeKind is an enumeration which describes the different types of nodes that
// are supported in a configuration.
type NodeKind int
const (
// ScalarNode represents configuration nodes of type Scalar.
ScalarNode NodeKind = iota
// ArrayNode represents configuration nodes of type Array.
ArrayNode
// MapNode represents configuration nodes of type Map.
MapNode
)
// The Node interface defines the common interface supported by the different
// types of configuration nodes supported by the conf package.
type Node interface {
flag.Value
objconv.ValueEncoder
objconv.ValueDecoder
// Kind returns the NodeKind of the configuration node.
Kind() NodeKind
// Value returns the underlying value wrapped by the configuration node.
Value() interface{}
}
// EqualNode compares n1 and n2, returning true if they are deeply equal.
func EqualNode(n1 Node, n2 Node) bool {
if n1 == nil || n2 == nil {
return n1 == n2
}
k1 := n1.Kind()
k2 := n2.Kind()
if k1 != k2 {
return false
}
switch k1 {
case ArrayNode:
return equalNodeArray(n1.(Array), n2.(Array))
case MapNode:
return equalNodeMap(n1.(Map), n2.(Map))
default:
return equalNodeScalar(n1.(Scalar), n2.(Scalar))
}
}
func equalNodeArray(a1 Array, a2 Array) bool {
n1 := a1.Len()
n2 := a2.Len()
if n1 != n2 {
return false
}
for i := 0; i != n1; i++ {
if !EqualNode(a1.Item(i), a2.Item(i)) {
return false
}
}
return true
}
func equalNodeMap(m1 Map, m2 Map) bool {
n1 := m1.Len()
n2 := m2.Len()
if n1 != n2 {
return false
}
for _, item := range m1.Items() {
if !EqualNode(item.Value, m2.Item(item.Name)) {
return false
}
}
return true
}
func equalNodeScalar(s1 Scalar, s2 Scalar) bool {
v1 := s1.value.IsValid()
v2 := s2.value.IsValid()
if !v1 || !v2 {
return v1 == v2
}
t1 := s1.value.Type()
t2 := s2.value.Type()
if t1 != t2 {
return false
}
switch t1 {
case timeTimeType:
return s1.Value().(time.Time).Equal(s2.Value().(time.Time))
}
return reflect.DeepEqual(s1.Value(), s2.Value())
}
// MakeNode builds a Node from the value v.
//
// The function panics if v contains unrepresentable values.
func MakeNode(v interface{}) Node {
return makeNode(reflect.ValueOf(v))
}
func makeNode(v reflect.Value) Node {
if !v.IsValid() {
return makeNodeScalar(v)
}
t := v.Type()
switch t {
case timeTimeType, timeDurationType:
return makeNodeScalar(v)
}
if _, ok := objconv.AdapterOf(t); ok {
return makeNodeScalar(v)
}
switch {
case
t.Implements(objconvValueDecoderInterface),
t.Implements(textUnmarshalerInterface):
return makeNodeScalar(v)
}
switch t.Kind() {
case reflect.Array, reflect.Chan, reflect.Func, reflect.UnsafePointer, reflect.Interface:
panic("unsupported type found in configuration: " + t.String())
case reflect.Struct:
return makeNodeStruct(v, t)
case reflect.Map:
return makeNodeMap(v, t)
case reflect.Slice:
return makeNodeSlice(v, t)
case reflect.Ptr:
return makeNodePtr(v, t)
default:
return makeNodeScalar(v)
}
}
func makeNodeStruct(v reflect.Value, t reflect.Type) (m Map) {
m.value = v
m.items = newMapItems()
populateNodeStruct(t, t.Name(), v, t, m)
// if using the "_" notation to embed structs, it's possible that names are no longer unique.
props := make(map[string]struct{})
for _, item := range m.Items() {
if _, ok := props[item.Name]; ok {
panic("duplicate name '" + item.Name + "' found after collapsing embedded structs in configuration: " + t.String())
}
props[item.Name] = struct{}{}
}
return
}
// populateNodeStruct is the mutually recursive helper of makeNodeStruct to create the node struct with potentially
// embedded types. It will populate m with the struct fields from v. The original type and path of the current field
// are passed in order to create decent panic strings if an invalid configuration is detected.
func populateNodeStruct(originalT reflect.Type, path string, v reflect.Value, t reflect.Type, m Map) {
for i, n := 0, v.NumField(); i != n; i++ {
fv := v.Field(i)
ft := t.Field(i)
if !isExported(ft) {
continue
}
name, help := ft.Tag.Get("conf"), ft.Tag.Get("help")
switch name {
case "-":
continue
case "_":
path = path + "." + ft.Name
if ft.Type.Kind() != reflect.Struct || !ft.Anonymous {
panic("found \"_\" on invalid type at path " + path + " in configuration: " + originalT.Name())
}
populateNodeStruct(originalT, path, fv, ft.Type, m)
continue
case "":
name = ft.Name
}
m.items.push(MapItem{
Name: name,
Help: help,
Value: makeNode(fv),
})
}
}
func makeNodeMap(v reflect.Value, t reflect.Type) (m Map) {
if v.IsNil() && v.CanSet() {
v.Set(reflect.MakeMap(v.Type()))
}
m.value = v
m.items = newMapItems()
for _, key := range v.MapKeys() {
m.items.push(MapItem{
Name: key.String(), // only string keys are supported for now
Value: makeNode(v.MapIndex(key)),
})
}
sort.Sort(m.items)
return
}
func makeNodeSlice(v reflect.Value, t reflect.Type) (a Array) {
n := v.Len()
a.value = v
a.items = newArrayItems()
for i := 0; i != n; i++ {
a.items.push(makeNode(v.Index(i)))
}
return
}
func makeNodePtr(v reflect.Value, t reflect.Type) Node {
if v.IsNil() {
p := reflect.New(t.Elem())
if v.CanSet() {
v.Set(p)
}
v = p
}
return makeNode(v.Elem())
}
func makeNodeScalar(value reflect.Value) (s Scalar) {
s.value = value
return
}
func isExported(f reflect.StructField) bool {
return len(f.PkgPath) == 0
}
// A Scalar is a node type that wraps a basic value.
type Scalar struct {
value reflect.Value
}
func (s Scalar) Kind() NodeKind {
return ScalarNode
}
func (s Scalar) Value() interface{} {
if !s.value.IsValid() {
return nil
}
return s.value.Interface()
}
func (s Scalar) String() string {
b, _ := yaml.Marshal(s)
return string(bytes.TrimSpace(b))
}
func (s Scalar) Set(str string) (err error) {
defer func() {
if x := recover(); x != nil {
err = fmt.Errorf("%s", x)
}
}()
if s.value.Kind() == reflect.String {
s.value.SetString(str)
return
}
ptr := s.value.Addr().Interface()
if err = yaml.Unmarshal([]byte(str), ptr); err != nil {
if b, _ := json.Marshal(str); b != nil {
if json.Unmarshal(b, ptr) == nil {
err = nil
}
}
}
return
}
func (s Scalar) EncodeValue(e objconv.Encoder) error {
return e.Encode(s.Value())
}
func (s Scalar) DecodeValue(d objconv.Decoder) error {
return d.Decode(s.value.Addr().Interface())
}
func (s Scalar) IsBoolFlag() bool {
return s.value.IsValid() && s.value.Kind() == reflect.Bool
}
// Array is a node type that wraps a slice value.
type Array struct {
value reflect.Value
items *arrayItems
}
func (a Array) Kind() NodeKind {
return ArrayNode
}
func (a Array) Value() interface{} {
if !a.value.IsValid() {
return nil
}
return a.value.Interface()
}
func (a Array) Items() []Node {
if a.items == nil {
return nil
}
return a.items.items()
}
func (a Array) Item(i int) Node {
return a.items.index(i)
}
func (a Array) Len() int {
if a.items == nil {
return 0
}
return a.items.len()
}
func (a Array) String() string {
if a.Len() == 0 {
return "[ ]"
}
b := &bytes.Buffer{}
b.WriteByte('[')
for i, item := range a.Items() {
if i != 0 {
b.WriteString(", ")
}
b.WriteString(item.String())
}
b.WriteByte(']')
return b.String()
}
func (a Array) Set(s string) error {
return yaml.Unmarshal([]byte(s), a)
}
func (a Array) EncodeValue(e objconv.Encoder) (err error) {
i := 0
return e.EncodeArray(a.Len(), func(e objconv.Encoder) (err error) {
if err = a.Item(i).EncodeValue(e); err != nil {
return
}
i++
return
})
}
func (a Array) DecodeValue(d objconv.Decoder) (err error) {
a.pop(a.Len())
return d.DecodeArray(func(d objconv.Decoder) (err error) {
if err = a.push().DecodeValue(d); err != nil {
a.pop(1)
}
return
})
}
func (a Array) push() Node {
i := a.Len()
a.value.Set(reflect.Append(a.value, reflect.Zero(a.value.Type().Elem())))
a.items.push(makeNode(a.value.Index(i)))
return a.items.index(i)
}
func (a Array) pop(n int) {
if n != 0 {
a.value.Set(a.value.Slice(0, a.Len()-n))
a.items.pop(n)
}
}
// Map is a map type that wraps a map or struct value.
type Map struct {
value reflect.Value
items *mapItems
}
// MapItem is the type of elements stored in a Map.
type MapItem struct {
Name string
Help string
Value Node
}
func (m Map) Kind() NodeKind {
return MapNode
}
func (m Map) Value() interface{} {
if !m.value.IsValid() {
return nil
}
return m.value.Interface()
}
func (m Map) Items() []MapItem {
if m.items == nil {
return nil
}
return m.items.items()
}
func (m Map) Item(name string) Node {
if m.items == nil {
return nil
}
return m.items.get(name)
}
func (m Map) Len() int {
if m.items == nil {
return 0
}
return m.items.len()
}
func (m Map) String() string {
if m.Len() == 0 {
return "{ }"
}
b := &bytes.Buffer{}
b.WriteString("{ ")
for i, item := range m.Items() {
if i != 0 {
b.WriteString(", ")
}
fmt.Fprintf(b, "%s: %s", item.Name, item.Value)
if len(item.Help) != 0 {
fmt.Fprintf(b, " (%s)", item.Help)
}
}
b.WriteString(" }")
return b.String()
}
func (m Map) Set(s string) error {
return yaml.Unmarshal([]byte(s), m)
}
func (m Map) EncodeValue(e objconv.Encoder) error {
i := 0
return e.EncodeMap(m.Len(), func(ke objconv.Encoder, ve objconv.Encoder) (err error) {
item := &m.items.nodes[i]
if err = ke.Encode(item.Name); err != nil {
return
}
if err = item.Value.EncodeValue(ve); err != nil {
return
}
i++
return
})
}
func (m Map) DecodeValue(d objconv.Decoder) error {
return d.DecodeMap(func(kd objconv.Decoder, vd objconv.Decoder) (err error) {
var key string
if err = kd.Decode(&key); err != nil {
return
}
if m.value.Kind() == reflect.Struct {
if item := m.Item(key); item != nil {
return item.DecodeValue(vd)
}
return vd.Decode(nil) // discard
}
name := reflect.ValueOf(key)
node := makeNode(reflect.New(m.value.Type().Elem()))
if err = node.DecodeValue(vd); err != nil {
return
}
m.value.SetMapIndex(name, reflect.ValueOf(node.Value()))
m.items.put(MapItem{
Name: key,
Value: makeNode(m.value.MapIndex(name)),
})
return
})
}
func (m Map) Scan(do func([]string, MapItem)) {
m.scan(make([]string, 0, 10), do)
}
func (m Map) scan(path []string, do func([]string, MapItem)) {
for _, item := range m.Items() {
do(path, item)
switch v := item.Value.(type) {
case Map:
v.scan(append(path, item.Name), do)
}
}
}
type arrayItems struct {
nodes []Node
}
func newArrayItems(nodes ...Node) *arrayItems {
return &arrayItems{nodes}
}
func (a *arrayItems) push(n Node) {
a.nodes = append(a.nodes, n)
}
func (a *arrayItems) pop(n int) {
a.nodes = a.nodes[:len(a.nodes)-n]
}
func (a *arrayItems) len() int {
return len(a.nodes)
}
func (a *arrayItems) index(i int) Node {
return a.nodes[i]
}
func (a *arrayItems) items() []Node {
return a.nodes
}
type mapItems struct {
nodes []MapItem
}
func newMapItems(nodes ...MapItem) *mapItems {
return &mapItems{nodes}
}
func (m *mapItems) get(name string) Node {
if i := m.index(name); i >= 0 {
return m.nodes[i].Value
}
return nil
}
func (m *mapItems) index(name string) int {
for i, node := range m.nodes {
if node.Name == name {
return i
}
}
return -1
}
func (m *mapItems) len() int {
return len(m.nodes)
}
func (m *mapItems) items() []MapItem {
return m.nodes
}
func (m *mapItems) push(item MapItem) {
m.nodes = append(m.nodes, item)
}
func (m *mapItems) put(item MapItem) {
if i := m.index(item.Name); i >= 0 {
m.nodes[i] = item
} else {
m.push(item)
}
}
func (m *mapItems) Less(i int, j int) bool {
return m.nodes[i].Name < m.nodes[j].Name
}
func (m *mapItems) Swap(i int, j int) {
m.nodes[i], m.nodes[j] = m.nodes[j], m.nodes[i]
}
func (m *mapItems) Len() int {
return len(m.nodes)
}
var (
timeTimeType = reflect.TypeOf(time.Time{})
timeDurationType = reflect.TypeOf(time.Duration(0))
objconvValueDecoderInterface = reflect.TypeOf((*objconv.ValueDecoder)(nil)).Elem()
textUnmarshalerInterface = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
)