forked from phR0ze/n
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap_string.go
817 lines (738 loc) · 19.8 KB
/
map_string.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
package n
import (
"github.com/phR0ze/n/pkg/enc/json"
yaml_enc "github.com/phR0ze/n/pkg/enc/yaml"
yaml "github.com/phR0ze/yaml/v2"
"github.com/pkg/errors"
)
// StringMap implements the IMap interface providing a generic way to work with map types
// including convenience methods on par with rapid development languages. This type is
// also specifically designed to handle ordered YAML constructs to work with YAML files
// with minimal structural changes i.e. no mass sorting changes.
type StringMap yaml.MapSlice
// M is an alias to NewStringMap
func M() *StringMap {
return &StringMap{}
}
// MV is an alias to NewStringMapV
func MV(m ...interface{}) *StringMap {
return NewStringMapV(m...)
}
// NewStringMap converts the given interface{} into a StringMap
func NewStringMap(obj interface{}) *StringMap {
return ToStringMap(obj)
}
// NewStringMapV creates a new empty StringMap if nothing given else
// converts the given value into a StringMap.
func NewStringMapV(m ...interface{}) *StringMap {
var new *StringMap
if len(m) == 0 {
new = &StringMap{}
} else {
new = ToStringMap(m[0])
}
return new
}
// Any tests if this Map is not empty or optionally if it contains any of the given variadic keys.
func (p *StringMap) Any(keys ...interface{}) bool {
if p == nil || len(*p) == 0 {
return false
}
ks := ToStrs(keys)
if len(ks) == 0 {
return true
}
for _, k := range ks {
if p.Exists(k) {
return true
}
}
return false
}
// Add the value to the map if it doesn't exist or update value if it does
func (p *StringMap) Add(key, val interface{}) *StringMap {
p.Set(key, val)
return p
}
// At gets the key value pair for the given index location
func (p *StringMap) At(i int) (key string, val *Object) {
val = &Object{}
if p == nil {
return
}
if i = absIndex(len(*p), i); i == -1 {
return
}
key = ToString((*p)[i].Key)
val.o = (*p)[i].Value
return
}
// Clear modifies this Map to clear out all key-value pairs and returns a reference to this Map.
func (p *StringMap) Clear() IMap {
if p == nil {
p = NewStringMapV()
} else if len(*p) > 0 {
*p = *NewStringMapV()
}
return p
}
// Copy returns a new Map with the indicated key-value pairs copied from this Map or all if not given.
func (p *StringMap) Copy(keys ...interface{}) (new IMap) {
val := NewStringMapV()
if p == nil || len(*p) == 0 {
return val
}
// Copy target keys or all keys
ks := ToStrs(keys)
if len(ks) == 0 {
(*val) = append(*val, (*p)...)
} else {
for _, k := range ks {
for i := 0; i < len(*p); i++ {
if k == ToString((*p)[i].Key) {
(*val) = append(*val, (*p)[i])
break
}
}
}
}
return val
}
// Delete modifies this Map to delete the indicated key-value pair and returns the value from the Map.
func (p *StringMap) Delete(key interface{}) (val *Object) {
val = &Object{}
if p == nil {
return
}
k := ToString(key)
for i := 0; i < len(*p); i++ {
if k == ToString((*p)[i].Key) {
val.o = (*p)[i].Value
if i+1 < len(*p) {
*p = append((*p)[:i], (*p)[i+1:]...)
} else {
*p = (*p)[:i]
}
break
}
}
return
}
// DeleteM modifies this Map to delete the indicated key-value pair and returns a reference to this Map rather than the key-value pair.
func (p *StringMap) DeleteM(key interface{}) IMap {
p.Delete(key)
return p
}
// Dump convert the StringMap into a pretty printed yaml string
func (p *StringMap) Dump() (pretty string) {
if p == nil {
return
}
if yml, err := yaml.Marshal(yaml.MapSlice(*p)); err == nil {
pretty = string(yml)
}
return
}
// Exists checks if the given key exists in this Map.
func (p *StringMap) Exists(key interface{}) bool {
if p == nil {
return false
}
k := ToString(key)
for i := 0; i < len(*p); i++ {
if k == ToString((*p)[i].Key) {
return true
}
}
return false
}
// G returns the underlying data structure as a Go type.
func (p *StringMap) G() map[string]interface{} {
val, _ := p.GE()
return val
}
// GE returns the underlying data structure as a Go type
func (p *StringMap) GE() (val map[string]interface{}, err error) {
val = map[string]interface{}{}
if p == nil {
return
}
for _, o := range *p {
k := ToString(o.Key)
v := DeReference(o.Value)
switch x := v.(type) {
case StringMap, yaml.MapSlice:
var m map[string]interface{}
if m, err = ToStringMap(x).GE(); err != nil {
return
}
val[k] = m
case []interface{}:
for i := 0; i < len(x); i++ {
switch x2 := x[i].(type) {
case StringMap, yaml.MapSlice:
var m map[string]interface{}
if m, err = ToStringMap(x2).GE(); err != nil {
return
}
x[i] = m
}
}
val[k] = x
default:
val[k] = v
}
}
return
}
// Generic returns true if the underlying implementation uses reflection
func (p *StringMap) Generic() bool {
return false
}
// Get returns the value at the given key location. Returns empty *Object if not found.
func (p *StringMap) Get(key interface{}) (val *Object) {
val = &Object{}
if p == nil {
return
}
k := ToString(key)
for i := 0; i < len(*p); i++ {
if k == ToString((*p)[i].Key) {
val.o = (*p)[i].Value
break
}
}
return
}
// Update sets the value for the given selector, using jq type selectors. Returns a reference to this Map.
func (p *StringMap) Update(selector string, val interface{}) IMap {
m, _ := p.UpdateE(selector, val)
return m
}
// UpdateE sets the value for the given selector, using jq type selectors. Returns a reference to this Map.
func (p *StringMap) UpdateE(selector string, val interface{}) (m IMap, err error) {
if p == nil {
p = NewStringMapV()
}
m = p
val = convertValue(val)
// Process keys from left to right
var keys *StringSlice
if keys, err = KeysFromSelector(selector); err != nil {
return
}
// Merge at root as no keys were given
if !keys.Any() {
if x, e := ToStringMapE(val); e == nil {
for i := 0; i < len(*x); i++ {
found := false
for j := 0; j < len(*p); j++ {
if ToString((*x)[i].Key) == ToString((*p)[j].Key) {
(*p)[j].Value = (*x)[i].Value
found = true
break
}
}
if !found {
p.Set((*x)[i].Key, (*x)[i].Value)
}
}
} else {
err = errors.Errorf("invalid selector for the type of value given, '%T'", val)
return
}
}
var pk interface{}
var m1, m2 *StringMap
cx, px := interface{}(p), interface{}(p)
for ko := keys.Shift(); !ko.Nil(); ko = keys.Shift() {
key := ko.ToStr()
switch x := cx.(type) {
// Identifier Index: .foo, .foo.bar
case map[string]interface{}, *StringMap, StringMap, yaml.MapSlice:
if m1, err = ToStringMapE(x); err != nil {
return
}
// Continue to drill or update and done
addOrReplace := false
if keys.Any() {
if v := m1.Get(key); !v.Nil() {
if YAMLCont(v.O()) {
cx = v.O()
pk, px = key, m1
} else {
addOrReplace = true
}
} else {
addOrReplace = true
}
} else {
m1.Set(key, val)
if px != nil && pk != nil {
if v, ok := px.([]interface{}); ok {
v[ToInt(pk)] = yaml.MapSlice(*m1)
} else {
if m2, err = ToStringMapE(px); err != nil {
return
}
m2.Set(pk, m1)
}
}
}
if addOrReplace {
m1.Set(key, M())
cx = m1.Get(key).O()
pk, px = key, m1
}
// Array Index/Iterator: .[2], .[-1], .[], .[key==val]
case []interface{}:
// Get array selectors
var i int
var k, v string
if i, k, v, err = IdxFromSelector(key.A(), len(x)); err != nil {
err = errors.Errorf("invalid array index selector %v", key.A())
cx = nil
return
}
// Select single element by key==value or index, e.g. .[k==v], [i]
if (k != "" && v != "") || i != -1 {
// Determine index
if k != "" && v != "" {
for j := 0; j < len(x); j++ {
if m1, err = ToStringMapE(x[j]); err != nil {
return
}
if m1.Get(k).A() == v {
i = j
break
}
}
}
// Move through or update index
if keys.Any() {
cx = x[i]
pk, px = i, x
} else {
x[i] = val
if px != nil && pk != nil {
if v, ok := px.([]interface{}); ok {
v[ToInt(pk)] = x
} else {
if m2, err = ToStringMapE(px); err != nil {
return
}
m2.Set(pk, x)
}
}
}
}
// Select all elements by .[] and translated to a -1 at this level
if i == -1 {
if keys.Any() {
for j := 0; j < len(x); j++ {
var o IMap
if o, err = ToStringMap(x[j]).UpdateE(keys.Join(".").A(), val); err != nil {
return
}
if m1, err = ToStringMapE(o); err != nil {
return
}
x[j] = yaml.MapSlice(*m1)
}
keys.Clear()
} else {
for j := 0; j < len(x); j++ {
x[j] = val
}
}
}
}
}
if err != nil {
m = nil
}
return
}
// Keys returns all the keys in this Map as a ISlice of the key type.
func (p *StringMap) Keys() ISlice {
keys := NewStringSliceV()
if p != nil {
for i := 0; i < len(*p); i++ {
*keys = append(*keys, ToString((*p)[i].Key))
}
}
return keys
}
// Len returns the number of elements in this Map.
func (p *StringMap) Len() int {
if p == nil {
return 0
}
return len(*p)
}
// M is an alias to ToStringMap
func (p *StringMap) M() (m *StringMap) {
return ToStringMap(p)
}
// MG is an alias ToStringMapG
func (p *StringMap) MG() (m map[string]interface{}) {
return p.G()
}
// Merge modifies this Map by overriding its values at selector with the given map
// where they both exist and returns a reference to this Map. Converting all string
// maps into *StringMap instances.
// Note: this function is unable to traverse through lists
func (p *StringMap) Merge(m IMap, selector ...string) IMap {
x1 := p
// 1. Select target if given
var pk1, px1 interface{}
if len(selector) > 0 {
key := selector[0]
cx1 := interface{}(*p)
// Process keys from left to right
keys, err := KeysFromSelector(key)
if err == nil {
for ko := keys.Shift(); !ko.Nil(); ko = keys.Shift() {
key := ko.ToString()
m := ToStringMap(cx1)
// Set a new map as the value if not a map
v := m.Get(key)
if v.Nil() || !YAMLMap(v.O()) {
m.Set(key, M())
v = m.Get(key)
if pk1 != nil && px1 != nil {
ToStringMap(px1).Set(pk1, m)
}
}
pk1, px1 = key, cx1
cx1 = v.O()
}
}
x1 = ToStringMap(cx1)
}
// 2. Merge at selection or root
x2, err := ToStringMapE(m)
switch {
case x1 == nil && (err != nil || m == nil):
return M()
case x1 == nil:
return x2
case err != nil || m == nil:
return x1
}
for _, o := range *x2 {
k := o.Key
v2 := DeReference(o.Value)
// x1 doesn't have the key so just set x2's value
v1 := x1.Get(k)
if v1.Nil() {
x1.Set(k, v2)
} else {
if YAMLMap(v1.o) && YAMLMap(v2) {
// x1 and x2 both contain the key and are both map types so recurse
x1.Set(k, ToStringMap(v1.o).Merge(ToStringMap(v2)))
} else {
// x1 or x2 is not a map so just override
x1.Set(k, v2)
}
}
}
if len(selector) > 0 {
p.Update(selector[0], x1)
}
return p
}
// Merge modifies this Map by overriding its values at selector with the given map
// where they both exist and returns a reference to this Map. Converting all string
// maps into *StringMap instances.
// Note: this function is unable to traverse through lists
func (p *StringMap) MergeG(m IMap, selector ...string) map[string]interface{} {
return p.Merge(m, selector...).MG()
}
// O returns the underlying data structure as is.
func (p *StringMap) O() interface{} {
return p.G()
}
// Query returns the value for the given selector, using jq type selectors. Returns empty *Object if not found.
// - `selector` supports dot notation similar to https://stedolan.github.io/jq/manual/#Basicfilters with some caveats
// - `params` are the string interpolation paramaters similar to fmt.Sprintf()
// - use the \\ character to escape periods that don't separate keys e.g. "[version=1\\.2\\.3]"
func (p *StringMap) Query(selector string, params ...interface{}) (val *Object) {
val, _ = p.QueryE(selector, params...)
return val
}
// QueryE returns the value for the given selector, using jq type selectors. Returns empty *Object if not found.
// - `selector` supports dot notation similar to https://stedolan.github.io/jq/manual/#Basicfilters with some caveats
// - `params` are the string interpolation paramaters similar to fmt.Sprintf()
// - use the \\ character to escape periods that don't separate keys e.g. "[version=1\\.2\\.3]"
func (p *StringMap) QueryE(selector string, params ...interface{}) (val *Object, err error) {
if p == nil || len(*p) == 0 {
err = errors.Errorf("failed to query empty map")
return
}
// Default object is self for identity case: .
val = &Object{o: p}
// Process keys from left to right
var keys *StringSlice
if keys, err = KeysFromSelector(selector, params...); err != nil {
return
}
for ko := keys.Shift(); !ko.Nil(); ko = keys.Shift() {
key := ko.ToStr()
switch x := val.o.(type) {
// Identifier Index: .foo, .foo.bar
case map[string]interface{}, *StringMap, StringMap, yaml.MapSlice:
m := ToStringMap(x)
val.o = m.Get(key).O()
// Array Index/Iterator: .[2], .[-1], .[], .[key==val]
case []interface{}:
// Get array selectors
var i int
var k, v string
if i, k, v, err = IdxFromSelector(key.A(), len(x)); err != nil {
err = errors.Errorf("invalid array index selector %v", key.A())
val.o = nil
return
}
// Select by key==value, e.g. .[k==v]
if k != "" && v != "" {
selected := false
for j := 0; j < len(x); j++ {
m := ToStringMap(x[j])
if m.Get(k).A() == v {
selected = true
val.o = m
}
}
if !selected {
err = errors.Errorf("invalid array element selection %v", key.A())
val.o = nil
return
}
}
// Index in if the value is a valid integer
if i != -1 {
val.o = x[i]
}
}
}
return
}
// Remove modifies this Map to delete the given key location, using jq type selectors
// and returns a reference to this Map rather than the deleted value.
// - `selector` supports dot notation similar to https://stedolan.github.io/jq/manual/#Basicfilters with some caveats
// - `params` are the string interpolation paramaters similar to fmt.Sprintf()
// - use the \\ character to escape periods that don't separate keys e.g. "[version=1\\.2\\.3]"
func (p *StringMap) Remove(selector string, params ...interface{}) IMap {
_, _ = p.RemoveE(selector, params...)
return p
}
// RemoveE modifies this Map to delete the given key location, using jq type selectors
// and returns a reference to this Map rather than the deleted value.
// - `selector` supports dot notation similar to https://stedolan.github.io/jq/manual/#Basicfilters with some caveats
// - `params` are the string interpolation paramaters similar to fmt.Sprintf()
// - use the \\ character to escape periods that don't separate keys e.g. "[version=1\\.2\\.3]"
func (p *StringMap) RemoveE(selector string, params ...interface{}) (m IMap, err error) {
if p == nil {
p = NewStringMapV()
}
m = p
// Process keys from left to right
var keys *StringSlice
if keys, err = KeysFromSelector(selector, params...); err != nil {
return
}
var pk interface{}
var m1, m2 *StringMap
cx, px := interface{}(p), interface{}(p)
for ko := keys.Shift(); !ko.Nil(); ko = keys.Shift() {
key := ko.ToStr()
switch x := cx.(type) {
// Identifier Index: .foo, .foo.bar
case map[string]interface{}, *StringMap, StringMap, yaml.MapSlice:
if m1, err = ToStringMapE(x); err != nil {
return
}
// Continue to drill or remove and done
if keys.Any() {
cx = m1.Get(key).O()
pk = key
px = m1
} else {
m1.DeleteM(key)
if px != nil && pk != nil {
if v, ok := px.([]interface{}); ok {
v[ToInt(pk)] = yaml.MapSlice(*m1)
} else {
if m2, err = ToStringMapE(px); err != nil {
return
}
m2.Set(pk, m1)
}
}
}
// Array Index/Iterator: .[2], .[-1], .[], .[key==val]
case []interface{}:
// Get array selectors
var i int
var k, v string
if i, k, v, err = IdxFromSelector(key.A(), len(x)); err != nil {
err = errors.Errorf("invalid array index selector %v", key.A())
cx = nil
return
}
// Select single element by key==value or index, e.g. .[k==v], [i]
if (k != "" && v != "") || i != -1 {
// Determine index
if k != "" && v != "" {
for j := 0; j < len(x); j++ {
if m1, err = ToStringMapE(x[j]); err != nil {
return
}
if m1.Get(k).A() == v {
i = j
break
}
}
}
// Move through or remove index
if keys.Any() {
cx = x[i]
pk = i
px = x
} else {
if i+1 < len(x) {
x = append(x[:i], x[i+1:]...)
} else {
x = x[:i]
}
if px != nil && pk != nil {
if v, ok := px.([]interface{}); ok {
v[ToInt(pk)] = x
} else {
if m2, err = ToStringMapE(px); err != nil {
return
}
m2.Set(pk, x)
}
}
}
}
// Select all elements by .[] and translated to a -1 at this level
if i == -1 {
if keys.Any() {
for j := 0; j < len(x); j++ {
var o IMap
if o, err = ToStringMap(x[j]).RemoveE(keys.Join(".").A()); err != nil {
return
}
if m1, err = ToStringMapE(o); err != nil {
return
}
x[j] = yaml.MapSlice(*m1)
}
keys.Clear()
} else {
if px != nil && pk != nil {
if v, ok := px.([]interface{}); ok {
v[ToInt(pk)] = []interface{}{}
} else {
if m2, err = ToStringMapE(px); err != nil {
return
}
m2.Set(pk, []interface{}{})
}
}
}
}
}
}
if err != nil {
m = nil
}
return
}
// Set the value for the given key to the given val. Returns true if the key did not yet exist in this Map.
func (p *StringMap) Set(key, val interface{}) (new bool) {
if p == nil {
return
}
new = true
k := ToString(key)
for i := 0; i < len(*p); i++ {
if k == ToString((*p)[i].Key) {
new = false
(*p)[i].Value = convertValue(val)
break
}
}
if new {
*p = append(*p, yaml.MapItem{Key: k, Value: convertValue(val)})
}
return
}
// Convert known types
func convertValue(in interface{}) (out interface{}) {
v1 := DeReference(in)
switch x1 := v1.(type) {
case StringMap, map[string]interface{}, map[interface{}]interface{}:
out = yaml.MapSlice(*ToStringMap(x1))
case []interface{}:
for j := 0; j < len(x1); j++ {
v2 := DeReference(x1[j])
switch x2 := v2.(type) {
case StringMap, map[string]interface{}, map[interface{}]interface{}:
x1[j] = yaml.MapSlice(*ToStringMap(x2))
}
}
out = x1
default:
out = in
}
return
}
// SetM the value for the given key to the given val creating map if necessary. Returns a reference to this Map.
func (p *StringMap) SetM(key, val interface{}) IMap {
if p == nil {
p = NewStringMapV()
}
p.Set(key, val)
return p
}
// ToStringMap converts the map to a *StringMap
func (p *StringMap) ToStringMap() (m *StringMap) {
return ToStringMap(p)
}
// ToStringMapG converts the map to a Golang map[string]interface{}
func (p *StringMap) ToStringMapG() (m map[string]interface{}) {
return p.O().(map[string]interface{})
}
// YAML converts the Map into a YAML string
func (p *StringMap) YAML() (data string) {
_data, err := yaml.Marshal(yaml.MapSlice(*p))
if err != nil {
return
}
data = string(_data)
return
}
// YAMLE converts the Map into a YAML string
func (p *StringMap) YAMLE() (data string, err error) {
var _data []byte
if _data, err = yaml.Marshal(yaml.MapSlice(*p)); err != nil {
err = errors.Wrapf(err, "failed to marshal map[string]interface{}")
return
}
data = string(_data)
return
}
// WriteJSON converts the *StringMap into a map[string]interface{} then calls
// json.WriteJSON on it to write it out to disk.
func (p *StringMap) WriteJSON(filename string) (err error) {
return json.WriteJSON(filename, p.G())
}
// WriteYAML converts the *StringMap into a map[string]interface{} then calls
// yaml.WriteYAML on it to write it out to disk.
func (p *StringMap) WriteYAML(filename string) (err error) {
return yaml_enc.WriteYAML(filename, yaml.MapSlice(*p))
}