forked from elastic/elastic-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast.go
1028 lines (884 loc) · 24.1 KB
/
ast.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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package transpiler
import (
"bytes"
"crypto/sha256"
"encoding/base64"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"github.com/elastic/elastic-agent/internal/pkg/eql"
)
const (
selectorSep = "."
// conditionKey is the name of the reserved key that will be computed using EQL to a boolean result.
//
// This makes the key "condition" inside of a dictionary a reserved name.
conditionKey = "condition"
)
// Selector defines a path to access an element in the Tree, currently selectors only works when the
// target is a Dictionary, accessing list values are not currently supported by any methods using
// selectors.
type Selector = string
var (
trueVal = []byte{1}
falseVal = []byte{0}
)
// Processors represent an attached list of processors.
type Processors []map[string]interface{}
// Node represents a node in the configuration Tree a Node can point to one or multiples children
// nodes.
type Node interface {
fmt.Stringer
// Find search a string in the current node.
Find(string) (Node, bool)
// Value returns the value of the node.
Value() interface{}
//Close clones the current node.
Clone() Node
// Hash compute a sha256 hash of the current node and recursively call any children.
Hash() []byte
// Apply apply the current vars, returning the new value for the node.
Apply(*Vars) (Node, error)
// Processors returns any attached processors, because of variable substitution.
Processors() Processors
}
// AST represents a raw configuration which is purely data, only primitives are currently supported,
// Int, float, string and bool. Complex are not taking into consideration. The Tree allow to define
// operation on the retrieves options in a more structured way. We are using this new structure to
// create filtering rules or manipulation rules to convert a configuration to another format.
type AST struct {
root Node
}
func (a *AST) String() string {
return "{AST:" + a.root.String() + "}"
}
// Dict represents a dictionary in the Tree, where each key is a entry into an array. The Dict will
// keep the ordering.
type Dict struct {
value []Node
processors []map[string]interface{}
}
// NewDict creates a new dict with provided nodes.
func NewDict(nodes []Node) *Dict {
return NewDictWithProcessors(nodes, nil)
}
// NewDictWithProcessors creates a new dict with provided nodes and attached processors.
func NewDictWithProcessors(nodes []Node, processors Processors) *Dict {
return &Dict{nodes, processors}
}
// Find takes a string which is a key and try to find the elements in the associated K/V.
func (d *Dict) Find(key string) (Node, bool) {
for _, i := range d.value {
if i.(*Key).name == key {
return i, true
}
}
return nil, false
}
// Insert inserts a value into a collection.
func (d *Dict) Insert(node Node) {
d.value = append(d.value, node)
}
func (d *Dict) String() string {
var sb strings.Builder
for i := 0; i < len(d.value); i++ {
sb.WriteString("{")
sb.WriteString(d.value[i].String())
sb.WriteString("}")
if i < len(d.value)-1 {
sb.WriteString(",")
}
}
return sb.String()
}
// Value returns the value of dict which is a slice of node.
func (d *Dict) Value() interface{} {
return d.value
}
// Clone clones the values and return a new dictionary.
func (d *Dict) Clone() Node {
nodes := make([]Node, 0, len(d.value))
for _, i := range d.value {
if i == nil {
continue
}
nodes = append(nodes, i.Clone())
}
return &Dict{value: nodes}
}
// Hash compute a sha256 hash of the current node and recursively call any children.
func (d *Dict) Hash() []byte {
h := sha256.New()
for _, v := range d.value {
h.Write(v.Hash())
}
return h.Sum(nil)
}
// Apply applies the vars to all the nodes in the dictionary.
func (d *Dict) Apply(vars *Vars) (Node, error) {
nodes := make([]Node, 0, len(d.value))
for _, v := range d.value {
k := v.(*Key)
n, err := k.Apply(vars)
if err != nil {
return nil, err
}
if n == nil {
continue
}
if k.name == conditionKey {
b := n.Value().(*BoolVal)
if !b.value {
// condition failed; whole dictionary should be removed
return nil, nil
}
// condition successful, but don't include condition in result
continue
}
nodes = append(nodes, n)
}
return &Dict{nodes, nil}, nil
}
// Processors returns any attached processors, because of variable substitution.
func (d *Dict) Processors() Processors {
if d.processors != nil {
return d.processors
}
for _, v := range d.value {
if p := v.Processors(); p != nil {
return p
}
}
return nil
}
// sort sorts the keys in the dictionary
func (d *Dict) sort() {
sort.Slice(d.value, func(i, j int) bool {
return d.value[i].(*Key).name < d.value[j].(*Key).name
})
}
// Key represents a Key / value pair in the dictionary.
type Key struct {
name string
value Node
}
// NewKey creates a new key with provided name node pair.
func NewKey(name string, val Node) *Key {
return &Key{name, val}
}
func (k *Key) String() string {
var sb strings.Builder
sb.WriteString(k.name)
sb.WriteString(":")
if k.value == nil {
sb.WriteString("nil")
} else {
sb.WriteString(k.value.String())
}
return sb.String()
}
// Find finds a key in a Dictionary or a list.
func (k *Key) Find(key string) (Node, bool) {
switch v := k.value.(type) {
case *Dict:
return v.Find(key)
case *List:
return v.Find(key)
default:
return nil, false
}
}
// Name returns the name for the key.
func (k *Key) Name() string {
return k.name
}
// Value returns the raw value.
func (k *Key) Value() interface{} {
return k.value
}
// Clone returns a clone of the current key and his embedded values.
func (k *Key) Clone() Node {
if k.value != nil {
return &Key{name: k.name, value: k.value.Clone()}
}
return &Key{name: k.name, value: nil}
}
// Hash compute a sha256 hash of the current node and recursively call any children.
func (k *Key) Hash() []byte {
h := sha256.New()
h.Write([]byte(k.name))
if k.value != nil {
h.Write(k.value.Hash())
}
return h.Sum(nil)
}
// Apply applies the vars to the value.
func (k *Key) Apply(vars *Vars) (Node, error) {
if k.value == nil {
return k, nil
}
if k.name == conditionKey {
switch v := k.value.(type) {
case *BoolVal:
return k, nil
case *StrVal:
cond, err := eql.Eval(v.value, vars, true)
if err != nil {
return nil, fmt.Errorf(`condition "%s" evaluation failed: %w`, v.value, err)
}
return &Key{k.name, NewBoolVal(cond)}, nil
}
return nil, fmt.Errorf("condition key's value must be a string; received %T", k.value)
}
v, err := k.value.Apply(vars)
if err != nil {
return nil, err
}
if v == nil {
return nil, nil
}
return &Key{k.name, v}, nil
}
// Processors returns any attached processors, because of variable substitution.
func (k *Key) Processors() Processors {
if k.value != nil {
return k.value.Processors()
}
return nil
}
// List represents a slice in our Tree.
type List struct {
value []Node
processors Processors
}
// NewList creates a new list with provided nodes.
func NewList(nodes []Node) *List {
return NewListWithProcessors(nodes, nil)
}
// NewListWithProcessors creates a new list with provided nodes with processors attached.
func NewListWithProcessors(nodes []Node, processors Processors) *List {
return &List{nodes, processors}
}
func (l *List) String() string {
var sb strings.Builder
sb.WriteString("[")
for i := 0; i < len(l.value); i++ {
sb.WriteString(l.value[i].String())
if i < len(l.value)-1 {
sb.WriteString(",")
}
}
sb.WriteString("]")
return sb.String()
}
// Hash compute a sha256 hash of the current node and recursively call any children.
func (l *List) Hash() []byte {
h := sha256.New()
for _, v := range l.value {
h.Write(v.Hash())
}
return h.Sum(nil)
}
// Find takes an index and return the values at that index.
func (l *List) Find(idx string) (Node, bool) {
i, err := strconv.Atoi(idx)
if err != nil {
return nil, false
}
if l.value == nil {
return nil, false
}
if i > len(l.value)-1 || i < 0 {
return nil, false
}
return l.value[i], true
}
// Value returns the raw value.
func (l *List) Value() interface{} {
return l.value
}
// Clone clones a new list and the clone items.
func (l *List) Clone() Node {
nodes := make([]Node, 0, len(l.value))
for _, i := range l.value {
if i == nil {
continue
}
nodes = append(nodes, i.Clone())
}
return &List{value: nodes}
}
// Apply applies the vars to all nodes in the list.
func (l *List) Apply(vars *Vars) (Node, error) {
nodes := make([]Node, 0, len(l.value))
for _, v := range l.value {
n, err := v.Apply(vars)
if err != nil {
return nil, err
}
if n == nil {
continue
}
nodes = append(nodes, n)
}
return NewList(nodes), nil
}
// Processors returns any attached processors, because of variable substitution.
func (l *List) Processors() Processors {
if l.processors != nil {
return l.processors
}
for _, v := range l.value {
if p := v.Processors(); p != nil {
return p
}
}
return nil
}
// StrVal represents a string.
type StrVal struct {
value string
processors Processors
}
// NewStrVal creates a new string value node with provided value.
func NewStrVal(val string) *StrVal {
return NewStrValWithProcessors(val, nil)
}
// NewStrValWithProcessors creates a new string value node with provided value and processors.
func NewStrValWithProcessors(val string, processors Processors) *StrVal {
return &StrVal{val, processors}
}
// Find receive a key and return false since the node is not a List or Dict.
func (s *StrVal) Find(key string) (Node, bool) {
return nil, false
}
func (s *StrVal) String() string {
return s.value
}
// Value returns the value.
func (s *StrVal) Value() interface{} {
return s.value
}
// Clone clone the value.
func (s *StrVal) Clone() Node {
k := *s
return &k
}
// Hash we return the byte slice of the string.
func (s *StrVal) Hash() []byte {
return []byte(s.value)
}
// Apply applies the vars to the string value.
func (s *StrVal) Apply(vars *Vars) (Node, error) {
return vars.Replace(s.value)
}
// Processors returns any linked processors that are now connected because of Apply.
func (s *StrVal) Processors() Processors {
return s.processors
}
// IntVal represents an int.
type IntVal struct {
value int
processors Processors
}
// NewIntVal creates a new int value node with provided value.
func NewIntVal(val int) *IntVal {
return NewIntValWithProcessors(val, nil)
}
// NewIntValWithProcessors creates a new int value node with provided value and attached processors.
func NewIntValWithProcessors(val int, processors Processors) *IntVal {
return &IntVal{val, processors}
}
// Find receive a key and return false since the node is not a List or Dict.
func (s *IntVal) Find(key string) (Node, bool) {
return nil, false
}
func (s *IntVal) String() string {
return strconv.Itoa(s.value)
}
// Value returns the value.
func (s *IntVal) Value() interface{} {
return s.value
}
// Clone clone the value.
func (s *IntVal) Clone() Node {
k := *s
return &k
}
// Apply does nothing.
func (s *IntVal) Apply(_ *Vars) (Node, error) {
return s, nil
}
// Hash we convert the value into a string and return the byte slice.
func (s *IntVal) Hash() []byte {
return []byte(s.String())
}
// Processors returns any linked processors that are now connected because of Apply.
func (s *IntVal) Processors() Processors {
return s.processors
}
// UIntVal represents an int.
type UIntVal struct {
value uint64
processors Processors
}
// NewUIntVal creates a new uint value node with provided value.
func NewUIntVal(val uint64) *UIntVal {
return NewUIntValWithProcessors(val, nil)
}
// NewUIntValWithProcessors creates a new uint value node with provided value with processors attached.
func NewUIntValWithProcessors(val uint64, processors Processors) *UIntVal {
return &UIntVal{val, processors}
}
// Find receive a key and return false since the node is not a List or Dict.
func (s *UIntVal) Find(key string) (Node, bool) {
return nil, false
}
func (s *UIntVal) String() string {
return strconv.FormatUint(s.value, 10)
}
// Value returns the value.
func (s *UIntVal) Value() interface{} {
return s.value
}
// Clone clone the value.
func (s *UIntVal) Clone() Node {
k := *s
return &k
}
// Hash we convert the value into a string and return the byte slice.
func (s *UIntVal) Hash() []byte {
return []byte(s.String())
}
// Apply does nothing.
func (s *UIntVal) Apply(_ *Vars) (Node, error) {
return s, nil
}
// Processors returns any linked processors that are now connected because of Apply.
func (s *UIntVal) Processors() Processors {
return s.processors
}
// FloatVal represents a float.
// NOTE: We will convert float32 to a float64.
type FloatVal struct {
value float64
processors Processors
}
// NewFloatVal creates a new float value node with provided value.
func NewFloatVal(val float64) *FloatVal {
return NewFloatValWithProcessors(val, nil)
}
// NewFloatValWithProcessors creates a new float value node with provided value with processors attached.
func NewFloatValWithProcessors(val float64, processors Processors) *FloatVal {
return &FloatVal{val, processors}
}
// Find receive a key and return false since the node is not a List or Dict.
func (s *FloatVal) Find(key string) (Node, bool) {
return nil, false
}
func (s *FloatVal) String() string {
return fmt.Sprintf("%f", s.value)
}
// Value return the raw value.
func (s *FloatVal) Value() interface{} {
return s.value
}
// Clone clones the value.
func (s *FloatVal) Clone() Node {
k := *s
return &k
}
// Hash return a string representation of the value, we try to return the minimal precision we can.
func (s *FloatVal) Hash() []byte {
return []byte(strconv.FormatFloat(s.value, 'f', -1, 64))
}
// Apply does nothing.
func (s *FloatVal) Apply(_ *Vars) (Node, error) {
return s, nil
}
// Processors returns any linked processors that are now connected because of Apply.
func (s *FloatVal) Processors() Processors {
return s.processors
}
// BoolVal represents a boolean in our Tree.
type BoolVal struct {
value bool
processors Processors
}
// NewBoolVal creates a new bool value node with provided value.
func NewBoolVal(val bool) *BoolVal {
return NewBoolValWithProcessors(val, nil)
}
// NewBoolValWithProcessors creates a new bool value node with provided value with processors attached.
func NewBoolValWithProcessors(val bool, processors Processors) *BoolVal {
return &BoolVal{val, processors}
}
// Find receive a key and return false since the node is not a List or Dict.
func (s *BoolVal) Find(key string) (Node, bool) {
return nil, false
}
func (s *BoolVal) String() string {
if s.value {
return "true"
}
return "false"
}
// Value returns the value.
func (s *BoolVal) Value() interface{} {
return s.value
}
// Clone clones the value.
func (s *BoolVal) Clone() Node {
k := *s
return &k
}
// Hash returns a single byte to represent the boolean value.
func (s *BoolVal) Hash() []byte {
if s.value {
return trueVal
}
return falseVal
}
// Apply does nothing.
func (s *BoolVal) Apply(_ *Vars) (Node, error) {
return s, nil
}
// Processors returns any linked processors that are now connected because of Apply.
func (s *BoolVal) Processors() Processors {
return s.processors
}
// NewAST takes a map and convert it to an internal Tree, allowing us to executes rules on the
// data to shape it in a different way or to filter some of the information.
func NewAST(m map[string]interface{}) (*AST, error) {
root, err := loadForNew(m)
if err != nil {
return nil, err
}
return &AST{root: root}, nil
}
func loadForNew(val interface{}) (Node, error) {
root, err := load(reflect.ValueOf(val))
if err != nil {
return nil, fmt.Errorf("could not parse configuration into a tree, error: %w", err)
}
return root, nil
}
func load(val reflect.Value) (Node, error) {
val = lookupVal(val)
switch val.Kind() {
case reflect.Map:
return loadMap(val)
case reflect.Slice, reflect.Array:
return loadSliceOrArray(val)
case reflect.String:
return &StrVal{value: val.Interface().(string)}, nil
case reflect.Int:
return &IntVal{value: val.Interface().(int)}, nil
case reflect.Int64:
return &IntVal{value: int(val.Interface().(int64))}, nil
case reflect.Uint:
return &UIntVal{value: uint64(val.Interface().(uint))}, nil
case reflect.Uint64:
return &UIntVal{value: val.Interface().(uint64)}, nil
case reflect.Float64:
return &FloatVal{value: val.Interface().(float64)}, nil
case reflect.Float32:
return &FloatVal{value: float64(val.Interface().(float32))}, nil
case reflect.Bool:
return &BoolVal{value: val.Interface().(bool)}, nil
default:
if val.IsNil() {
return nil, nil
}
return nil, fmt.Errorf("unknown type %T for %+v", val.Interface(), val)
}
}
// Accept takes a visitor and will visit each node of the Tree while calling the right methods on
// the visitor.
// NOTE(ph): Some operation could be refactored to use a visitor, I plan to add a checksum visitor.
func (a *AST) Accept(visitor Visitor) {
a.dispatch(a.root, visitor)
}
func (a *AST) dispatch(n Node, visitor Visitor) {
switch t := n.(type) {
case *Dict:
visitorDict := visitor.OnDict()
for _, child := range t.value {
key := child.(*Key)
visitorDict.OnKey(key.name)
subvisitor := visitorDict.Visitor()
a.dispatch(key.value, subvisitor)
visitorDict.OnValue(subvisitor)
}
visitorDict.OnComplete()
case *List:
visitorList := visitor.OnList()
for _, child := range t.value {
subvisitor := visitorList.Visitor()
a.dispatch(child, subvisitor)
visitorList.OnValue(subvisitor)
}
visitorList.OnComplete()
case *StrVal:
visitor.OnStr(t.value)
case *IntVal:
visitor.OnInt(t.value)
case *UIntVal:
visitor.OnUInt(t.value)
case *BoolVal:
visitor.OnBool(t.value)
case *FloatVal:
visitor.OnFloat(t.value)
}
}
// Clone clones the object.
func (a *AST) Clone() *AST {
return &AST{root: a.root.Clone()}
}
// Hash calculates a hash from all the included nodes in the tree.
func (a *AST) Hash() []byte {
return a.root.Hash()
}
// HashStr return the calculated hash as a base64 url encoded string.
func (a *AST) HashStr() string {
return base64.URLEncoding.EncodeToString(a.root.Hash())
}
// Equal check if two AST are equals by using the computed hash.
func (a *AST) Equal(other *AST) bool {
return bytes.Equal(a.Hash(), other.Hash())
}
// Lookup looks for a value from the AST.
//
// Return type is in the native form and not in the Node types from the AST.
func (a *AST) Lookup(name string) (interface{}, bool) {
node, ok := Lookup(a, name)
if !ok {
return nil, false
}
_, isKey := node.(*Key)
if isKey {
// matched on a key, return the value
node = node.Value().(Node)
}
m := &MapVisitor{}
a.dispatch(node, m)
return m.Content, true
}
func splitPath(s Selector) []string {
if s == "" {
return nil
}
return strings.Split(s, selectorSep)
}
func loadMap(val reflect.Value) (Node, error) {
node := &Dict{}
mapKeys := val.MapKeys()
names := make([]string, 0, len(mapKeys))
for _, aKey := range mapKeys {
names = append(names, aKey.Interface().(string))
}
sort.Strings(names)
for _, name := range names {
aValue, err := load(val.MapIndex(reflect.ValueOf(name)))
if err != nil {
return nil, err
}
keys := strings.Split(name, selectorSep)
if !isDictOrKey(aValue) {
node.value = append(node.value, &Key{name: name, value: aValue})
continue
}
// get last known existing node
var lastKnownKeyIdx int
var knownNode Node = node
for i, k := range keys {
n, isDict := knownNode.Find(k)
if !isDict {
break
}
lastKnownKeyIdx = i
knownNode = n
}
// Produce remainder
restKeys := keys[lastKnownKeyIdx+1:]
restDict := &Dict{}
if len(restKeys) == 0 {
if avd, ok := aValue.(*Dict); ok {
restDict.value = avd.value
} else if avd, ok := aValue.(*Key); ok {
restDict.value = []Node{avd.value}
} else {
restDict.value = append(restDict.value, aValue)
}
} else {
for i := len(restKeys) - 1; i >= 0; i-- {
if len(restDict.value) == 0 {
// this is the first one
restDict.value = []Node{&Key{name: restKeys[i], value: aValue}}
continue
}
restDict.value = []Node{&Key{name: restKeys[i], value: restDict.Clone()}}
}
}
// Attach remainder to last known node
restKey := &Key{name: keys[lastKnownKeyIdx], value: restDict}
if knownNodeDict, ok := knownNode.(*Dict); ok {
knownNodeDict.value = append(knownNodeDict.value, restKey)
} else if knownNodeKey, ok := knownNode.(*Key); ok {
dict, ok := knownNodeKey.value.(*Dict)
if ok {
dict.value = append(dict.value, restDict.value...)
}
}
}
return node, nil
}
func isDictOrKey(val Node) bool {
if _, ok := val.(*Key); ok {
return true
}
if _, ok := val.(*Dict); ok {
return true
}
return false
}
func loadSliceOrArray(val reflect.Value) (Node, error) {
node := &List{}
for i := 0; i < val.Len(); i++ {
aValue, err := load(val.Index(i))
if err != nil {
return nil, err
}
node.value = append(node.value, aValue)
}
return node, nil
}
func lookupVal(val reflect.Value) reflect.Value {
for (val.Kind() == reflect.Ptr || val.Kind() == reflect.Interface) && !val.IsNil() {
val = val.Elem()
}
return val
}
func attachProcessors(node Node, processors Processors) Node {
switch n := node.(type) {
case *Dict:
n.processors = processors
case *List:
n.processors = processors
case *StrVal:
n.processors = processors
case *IntVal:
n.processors = processors
case *UIntVal:
n.processors = processors
case *FloatVal:
n.processors = processors
case *BoolVal:
n.processors = processors
}
return node
}
// Lookup accept an AST and a selector and return the matching Node at that position.
func Lookup(a *AST, selector Selector) (Node, bool) {
// Run through the graph and find matching nodes.
current := a.root
for _, part := range splitPath(selector) {
n, ok := current.Find(part)
if !ok {
return nil, false
}
current = n
}
return current, true
}
// Insert inserts a node into an existing AST, will return and error if the target position cannot
// accept a new node.
func Insert(a *AST, node Node, to Selector) error {
current := a.root
for _, part := range splitPath(to) {
n, ok := current.Find(part)
if !ok {
switch t := current.(type) {
case *Key:
switch vt := t.value.(type) {
case *Dict:
newNode := &Key{name: part, value: &Dict{}}
vt.value = append(vt.value, newNode)
vt.sort()
current = newNode
continue
case *List:
// inserting at index but array empty
newNode := &Dict{}
vt.value = append(vt.value, newNode)
current = newNode
continue
default:
return fmt.Errorf("expecting collection and received %T for '%s'", to, to)
}
case *Dict:
newNode := &Key{name: part, value: &Dict{}}
t.value = append(t.value, newNode)
t.sort()
current = newNode
continue
default:
return fmt.Errorf("expecting Dict and received %T for '%s'", t, to)
}
}
current = n
}
// Apply the current node and replace any existing elements,
// that could exist after the selector.
d, ok := current.(*Key)
if !ok {
return fmt.Errorf("expecting Key and received %T for '%s'", current, to)
}
switch nt := node.(type) {
case *Dict:
d.value = node
case *List:
d.value = node
case *Key:
// adding key to existing dictionary
// should overwrite the current key if it exists
dValue, ok := d.value.(*Dict)
if !ok {
// not a dictionary (replace it all)
d.value = &Dict{[]Node{node}, nil}
} else {
// remove the duplicate key (if it exists)
for i, key := range dValue.value {
if k, ok := key.(*Key); ok {