-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
rnode.go
1385 lines (1251 loc) · 37 KB
/
rnode.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 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package yaml
import (
"encoding/json"
"fmt"
"log"
"os"
"regexp"
"strconv"
"strings"
"sigs.k8s.io/kustomize/kyaml/errors"
"sigs.k8s.io/kustomize/kyaml/sliceutil"
"sigs.k8s.io/kustomize/kyaml/utils"
"sigs.k8s.io/kustomize/kyaml/yaml/internal/k8sgen/pkg/labels"
yaml "sigs.k8s.io/yaml/goyaml.v3"
)
// MakeNullNode returns an RNode that represents an empty document.
func MakeNullNode() *RNode {
return NewRNode(&Node{Tag: NodeTagNull})
}
// MakePersistentNullNode returns an RNode that should be persisted,
// even when merging
func MakePersistentNullNode(value string) *RNode {
n := NewRNode(
&Node{
Tag: NodeTagNull,
Value: value,
Kind: yaml.ScalarNode,
},
)
n.ShouldKeep = true
return n
}
// IsMissingOrNull is true if the RNode is nil or explicitly tagged null.
// TODO: make this a method on RNode.
func IsMissingOrNull(node *RNode) bool {
return node.IsNil() || node.YNode().Tag == NodeTagNull
}
// IsEmptyMap returns true if the RNode is an empty node or an empty map.
// TODO: make this a method on RNode.
func IsEmptyMap(node *RNode) bool {
return IsMissingOrNull(node) || IsYNodeEmptyMap(node.YNode())
}
// GetValue returns underlying yaml.Node Value field
func GetValue(node *RNode) string {
if IsMissingOrNull(node) {
return ""
}
return node.YNode().Value
}
// Parse parses a yaml string into an *RNode.
// To parse multiple resources, consider a kio.ByteReader
func Parse(value string) (*RNode, error) {
return Parser{Value: value}.Filter(nil)
}
// ReadFile parses a single Resource from a yaml file.
// To parse multiple resources, consider a kio.ByteReader
func ReadFile(path string) (*RNode, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return Parse(string(b))
}
// WriteFile writes a single Resource to a yaml file
func WriteFile(node *RNode, path string) error {
out, err := node.String()
if err != nil {
return err
}
return errors.WrapPrefixf(os.WriteFile(path, []byte(out), 0600), "writing RNode to file")
}
// UpdateFile reads the file at path, applies the filter to it, and write the result back.
// path must contain a exactly 1 resource (YAML).
func UpdateFile(filter Filter, path string) error {
// Read the yaml
y, err := ReadFile(path)
if err != nil {
return err
}
// Update the yaml
if err := y.PipeE(filter); err != nil {
return err
}
// Write the yaml
return WriteFile(y, path)
}
// MustParse parses a yaml string into an *RNode and panics if there is an error
func MustParse(value string) *RNode {
v, err := Parser{Value: value}.Filter(nil)
if err != nil {
panic(err)
}
return v
}
// NewScalarRNode returns a new Scalar *RNode containing the provided scalar value.
func NewScalarRNode(value string) *RNode {
return &RNode{
value: &yaml.Node{
Kind: yaml.ScalarNode,
Value: value,
}}
}
// NewStringRNode returns a new Scalar *RNode containing the provided string.
// If the string is non-utf8, it will be base64 encoded, and the tag
// will indicate binary data.
func NewStringRNode(value string) *RNode {
n := yaml.Node{Kind: yaml.ScalarNode}
n.SetString(value)
return NewRNode(&n)
}
// NewListRNode returns a new List *RNode containing the provided scalar values.
func NewListRNode(values ...string) *RNode {
seq := &RNode{value: &yaml.Node{Kind: yaml.SequenceNode}}
for _, v := range values {
seq.value.Content = append(seq.value.Content, &yaml.Node{
Kind: yaml.ScalarNode,
Value: v,
})
}
return seq
}
// NewMapRNode returns a new Map *RNode containing the provided values
func NewMapRNode(values *map[string]string) *RNode {
m := &RNode{value: &yaml.Node{
Kind: yaml.MappingNode,
}}
if values == nil {
return m
}
for k, v := range *values {
m.value.Content = append(m.value.Content, &yaml.Node{
Kind: yaml.ScalarNode,
Value: k,
}, &yaml.Node{
Kind: yaml.ScalarNode,
Value: v,
})
}
return m
}
// SyncMapNodesOrder sorts the map node keys in 'to' node to match the order of
// map node keys in 'from' node, additional keys are moved to the end
func SyncMapNodesOrder(from, to *RNode) {
to.Copy()
res := &RNode{value: &yaml.Node{
Kind: to.YNode().Kind,
Style: to.YNode().Style,
Tag: to.YNode().Tag,
Anchor: to.YNode().Anchor,
Alias: to.YNode().Alias,
HeadComment: to.YNode().HeadComment,
LineComment: to.YNode().LineComment,
FootComment: to.YNode().FootComment,
Line: to.YNode().Line,
Column: to.YNode().Column,
}}
fromFieldNames, err := from.Fields()
if err != nil {
return
}
toFieldNames, err := to.Fields()
if err != nil {
return
}
for _, fieldName := range fromFieldNames {
if !sliceutil.Contains(toFieldNames, fieldName) {
continue
}
// append the common nodes in the order defined in 'from' node
res.value.Content = append(res.value.Content, to.Field(fieldName).Key.YNode(), to.Field(fieldName).Value.YNode())
toFieldNames = sliceutil.Remove(toFieldNames, fieldName)
}
for _, fieldName := range toFieldNames {
// append the residual nodes which are not present in 'from' node
res.value.Content = append(res.value.Content, to.Field(fieldName).Key.YNode(), to.Field(fieldName).Value.YNode())
}
to.SetYNode(res.YNode())
}
// NewRNode returns a new RNode pointer containing the provided Node.
func NewRNode(value *yaml.Node) *RNode {
return &RNode{value: value}
}
// RNode provides functions for manipulating Kubernetes Resources
// Objects unmarshalled into *yaml.Nodes
type RNode struct {
// fieldPath contains the path from the root of the KubernetesObject to
// this field.
// Only field names are captured in the path.
// e.g. a image field in a Deployment would be
// 'spec.template.spec.containers.image'
fieldPath []string
// FieldValue contains the value.
// FieldValue is always set:
// field: field value
// list entry: list entry value
// object root: object root
value *yaml.Node
// Whether we should keep this node, even if otherwise we would clear it
ShouldKeep bool
Match []string
}
// Copy returns a distinct copy.
func (rn *RNode) Copy() *RNode {
if rn == nil {
return nil
}
result := *rn
result.value = CopyYNode(rn.value)
return &result
}
var ErrMissingMetadata = fmt.Errorf("missing Resource metadata")
// IsNil is true if the node is nil, or its underlying YNode is nil.
func (rn *RNode) IsNil() bool {
return rn == nil || rn.YNode() == nil
}
// IsTaggedNull is true if a non-nil node is explicitly tagged Null.
func (rn *RNode) IsTaggedNull() bool {
return !rn.IsNil() && IsYNodeTaggedNull(rn.YNode())
}
// IsNilOrEmpty is true if the node is nil,
// has no YNode, or has YNode that appears empty.
func (rn *RNode) IsNilOrEmpty() bool {
return rn.IsNil() || IsYNodeNilOrEmpty(rn.YNode())
}
// IsStringValue is true if the RNode is not nil and is scalar string node
func (rn *RNode) IsStringValue() bool {
return !rn.IsNil() && IsYNodeString(rn.YNode())
}
// GetMeta returns the ResourceMeta for an RNode
func (rn *RNode) GetMeta() (ResourceMeta, error) {
if IsMissingOrNull(rn) {
return ResourceMeta{}, nil
}
missingMeta := true
n := rn
if n.YNode().Kind == DocumentNode {
// get the content is this is the document node
n = NewRNode(n.Content()[0])
}
// don't decode into the struct directly or it will fail on UTF-8 issues
// which appear in comments
m := ResourceMeta{}
// TODO: consider optimizing this parsing
if f := n.Field(APIVersionField); !f.IsNilOrEmpty() {
m.APIVersion = GetValue(f.Value)
missingMeta = false
}
if f := n.Field(KindField); !f.IsNilOrEmpty() {
m.Kind = GetValue(f.Value)
missingMeta = false
}
mf := n.Field(MetadataField)
if mf.IsNilOrEmpty() {
if missingMeta {
return m, ErrMissingMetadata
}
return m, nil
}
meta := mf.Value
if f := meta.Field(NameField); !f.IsNilOrEmpty() {
m.Name = f.Value.YNode().Value
missingMeta = false
}
if f := meta.Field(NamespaceField); !f.IsNilOrEmpty() {
m.Namespace = GetValue(f.Value)
missingMeta = false
}
if f := meta.Field(LabelsField); !f.IsNilOrEmpty() {
m.Labels = map[string]string{}
_ = f.Value.VisitFields(func(node *MapNode) error {
m.Labels[GetValue(node.Key)] = GetValue(node.Value)
return nil
})
missingMeta = false
}
if f := meta.Field(AnnotationsField); !f.IsNilOrEmpty() {
m.Annotations = map[string]string{}
_ = f.Value.VisitFields(func(node *MapNode) error {
m.Annotations[GetValue(node.Key)] = GetValue(node.Value)
return nil
})
missingMeta = false
}
if missingMeta {
return m, ErrMissingMetadata
}
return m, nil
}
// Pipe sequentially invokes each Filter, and passes the result to the next
// Filter.
//
// Analogous to http://www.linfo.org/pipes.html
//
// * rn is provided as input to the first Filter.
// * if any Filter returns an error, immediately return the error
// * if any Filter returns a nil RNode, immediately return nil, nil
// * if all Filters succeed with non-empty results, return the final result
func (rn *RNode) Pipe(functions ...Filter) (*RNode, error) {
// check if rn is nil to make chaining Pipe calls easier
if rn == nil {
return nil, nil
}
var v *RNode
var err error
if rn.value != nil && rn.value.Kind == yaml.DocumentNode {
// the first node may be a DocumentNode containing a single MappingNode
v = &RNode{value: rn.value.Content[0]}
} else {
v = rn
}
// return each fn in sequence until encountering an error or missing value
for _, c := range functions {
v, err = c.Filter(v)
if err != nil || v == nil {
return v, errors.Wrap(err)
}
}
return v, err
}
// PipeE runs Pipe, dropping the *RNode return value.
// Useful for directly returning the Pipe error value from functions.
func (rn *RNode) PipeE(functions ...Filter) error {
_, err := rn.Pipe(functions...)
return errors.Wrap(err)
}
// Document returns the Node for the value.
func (rn *RNode) Document() *yaml.Node {
return rn.value
}
// YNode returns the yaml.Node value. If the yaml.Node value is a DocumentNode,
// YNode will return the DocumentNode Content entry instead of the DocumentNode.
func (rn *RNode) YNode() *yaml.Node {
if rn == nil || rn.value == nil {
return nil
}
if rn.value.Kind == yaml.DocumentNode {
return rn.value.Content[0]
}
return rn.value
}
// SetYNode sets the yaml.Node value on an RNode.
func (rn *RNode) SetYNode(node *yaml.Node) {
if rn.value == nil || node == nil {
rn.value = node
return
}
*rn.value = *node
}
// GetKind returns the kind, if it exists, else empty string.
func (rn *RNode) GetKind() string {
if node := rn.getMapFieldValue(KindField); node != nil {
return node.Value
}
return ""
}
// SetKind sets the kind.
func (rn *RNode) SetKind(k string) {
rn.SetMapField(NewScalarRNode(k), KindField)
}
// GetApiVersion returns the apiversion, if it exists, else empty string.
func (rn *RNode) GetApiVersion() string {
if node := rn.getMapFieldValue(APIVersionField); node != nil {
return node.Value
}
return ""
}
// SetApiVersion sets the apiVersion.
func (rn *RNode) SetApiVersion(av string) {
rn.SetMapField(NewScalarRNode(av), APIVersionField)
}
// getMapFieldValue returns the value (*yaml.Node) of a mapping field.
// The value might be nil. Also, the function returns nil, not an error,
// if this node is not a mapping node, or if this node does not have the
// given field, so this function cannot be used to make distinctions
// between these cases.
func (rn *RNode) getMapFieldValue(field string) *yaml.Node {
var result *yaml.Node
visitMappingNodeFields(rn.Content(), func(key, value *yaml.Node) {
result = value
}, field)
return result
}
// GetName returns the name, or empty string if
// field not found. The setter is more restrictive.
func (rn *RNode) GetName() string {
return rn.getMetaStringField(NameField)
}
// getMetaStringField returns the value of a string field in metadata.
func (rn *RNode) getMetaStringField(fName string) string {
md := rn.getMetaData()
if md == nil {
return ""
}
var result string
visitMappingNodeFields(md.Content, func(key, value *yaml.Node) {
if !IsYNodeNilOrEmpty(value) {
result = value.Value
}
}, fName)
return result
}
// getMetaData returns the *yaml.Node of the metadata field.
// Return nil if field not found (no error).
func (rn *RNode) getMetaData() *yaml.Node {
if IsMissingOrNull(rn) {
return nil
}
content := rn.Content()
if rn.YNode().Kind == DocumentNode {
// get the content if this is the document node
content = content[0].Content
}
var mf *yaml.Node
visitMappingNodeFields(content, func(key, value *yaml.Node) {
if !IsYNodeNilOrEmpty(value) {
mf = value
}
}, MetadataField)
return mf
}
// SetName sets the metadata name field.
func (rn *RNode) SetName(name string) error {
return rn.SetMapField(NewScalarRNode(name), MetadataField, NameField)
}
// GetNamespace gets the metadata namespace field, or empty string if
// field not found. The setter is more restrictive.
func (rn *RNode) GetNamespace() string {
return rn.getMetaStringField(NamespaceField)
}
// SetNamespace tries to set the metadata namespace field. If the argument
// is empty, the field is dropped.
func (rn *RNode) SetNamespace(ns string) error {
meta, err := rn.Pipe(Lookup(MetadataField))
if err != nil {
return err
}
if ns == "" {
if rn == nil {
return nil
}
return meta.PipeE(Clear(NamespaceField))
}
return rn.SetMapField(
NewScalarRNode(ns), MetadataField, NamespaceField)
}
// GetAnnotations gets the metadata annotations field.
// If the annotations field is missing, returns an empty map.
// Use another method to check for missing metadata.
// If specific annotations are provided, then the map is
// restricted to only those entries with keys that match
// one of the specific annotations. If no annotations are
// provided, then the map will contain all entries.
func (rn *RNode) GetAnnotations(annotations ...string) map[string]string {
return rn.getMapFromMeta(AnnotationsField, annotations...)
}
// SetAnnotations tries to set the metadata annotations field.
func (rn *RNode) SetAnnotations(m map[string]string) error {
return rn.setMapInMetadata(m, AnnotationsField)
}
// GetLabels gets the metadata labels field.
// If the labels field is missing, returns an empty map.
// Use another method to check for missing metadata.
// If specific labels are provided, then the map is
// restricted to only those entries with keys that match
// one of the specific labels. If no labels are
// provided, then the map will contain all entries.
func (rn *RNode) GetLabels(labels ...string) map[string]string {
return rn.getMapFromMeta(LabelsField, labels...)
}
// getMapFromMeta returns a map, sometimes empty, from the fName
// field in the node's metadata field.
// If specific fields are provided, then the map is
// restricted to only those entries with keys that match
// one of the specific fields. If no fields are
// provided, then the map will contain all entries.
func (rn *RNode) getMapFromMeta(fName string, fields ...string) map[string]string {
meta := rn.getMetaData()
if meta == nil {
return make(map[string]string)
}
var result map[string]string
visitMappingNodeFields(meta.Content, func(_, fNameValue *yaml.Node) {
// fName is found in metadata; create the map from its content
expectedSize := len(fields)
if expectedSize == 0 {
expectedSize = len(fNameValue.Content) / 2 //nolint: gomnd
}
result = make(map[string]string, expectedSize)
visitMappingNodeFields(fNameValue.Content, func(key, value *yaml.Node) {
result[key.Value] = value.Value
}, fields...)
}, fName)
if result == nil {
return make(map[string]string)
}
return result
}
// SetLabels sets the metadata labels field.
func (rn *RNode) SetLabels(m map[string]string) error {
return rn.setMapInMetadata(m, LabelsField)
}
// This established proper quoting on string values, and sorts by key.
func (rn *RNode) setMapInMetadata(m map[string]string, field string) error {
meta, err := rn.Pipe(LookupCreate(MappingNode, MetadataField))
if err != nil {
return err
}
if err = meta.PipeE(Clear(field)); err != nil {
return err
}
if len(m) == 0 {
return nil
}
mapNode, err := meta.Pipe(LookupCreate(MappingNode, field))
if err != nil {
return err
}
for _, k := range SortedMapKeys(m) {
if _, err := mapNode.Pipe(
SetField(k, NewStringRNode(m[k]))); err != nil {
return err
}
}
return nil
}
func (rn *RNode) SetMapField(value *RNode, path ...string) error {
return rn.PipeE(
LookupCreate(yaml.MappingNode, path[0:len(path)-1]...),
SetField(path[len(path)-1], value),
)
}
func (rn *RNode) GetDataMap() map[string]string {
n, err := rn.Pipe(Lookup(DataField))
if err != nil {
return nil
}
result := map[string]string{}
_ = n.VisitFields(func(node *MapNode) error {
result[GetValue(node.Key)] = GetValue(node.Value)
return nil
})
return result
}
func (rn *RNode) GetBinaryDataMap() map[string]string {
n, err := rn.Pipe(Lookup(BinaryDataField))
if err != nil {
return nil
}
result := map[string]string{}
_ = n.VisitFields(func(node *MapNode) error {
result[GetValue(node.Key)] = GetValue(node.Value)
return nil
})
return result
}
// GetValidatedDataMap retrieves the data map and returns an error if the data
// map contains entries which are not included in the expectedKeys set.
func (rn *RNode) GetValidatedDataMap(expectedKeys []string) (map[string]string, error) {
dataMap := rn.GetDataMap()
err := rn.validateDataMap(dataMap, expectedKeys)
return dataMap, err
}
func (rn *RNode) validateDataMap(dataMap map[string]string, expectedKeys []string) error {
if dataMap == nil {
return fmt.Errorf("The datamap is unassigned")
}
for key := range dataMap {
found := false
for _, expected := range expectedKeys {
if expected == key {
found = true
}
}
if !found {
return fmt.Errorf("an unexpected key (%v) was found", key)
}
}
return nil
}
func (rn *RNode) SetDataMap(m map[string]string) {
if rn == nil {
log.Fatal("cannot set data map on nil Rnode")
}
if err := rn.PipeE(Clear(DataField)); err != nil {
log.Fatal(err)
}
if len(m) == 0 {
return
}
if err := rn.LoadMapIntoConfigMapData(m); err != nil {
log.Fatal(err)
}
}
func (rn *RNode) SetBinaryDataMap(m map[string]string) {
if rn == nil {
log.Fatal("cannot set binaryData map on nil Rnode")
}
if err := rn.PipeE(Clear(BinaryDataField)); err != nil {
log.Fatal(err)
}
if len(m) == 0 {
return
}
if err := rn.LoadMapIntoConfigMapBinaryData(m); err != nil {
log.Fatal(err)
}
}
// AppendToFieldPath appends a field name to the FieldPath.
func (rn *RNode) AppendToFieldPath(parts ...string) {
rn.fieldPath = append(rn.fieldPath, parts...)
}
// FieldPath returns the field path from the Resource root node, to rn.
// Does not include list indexes.
func (rn *RNode) FieldPath() []string {
return rn.fieldPath
}
// String returns string representation of the RNode
func (rn *RNode) String() (string, error) {
if rn == nil {
return "", nil
}
return String(rn.value)
}
// MustString returns string representation of the RNode or panics if there is an error
func (rn *RNode) MustString() string {
s, err := rn.String()
if err != nil {
panic(err)
}
return s
}
// Content returns Node Content field.
func (rn *RNode) Content() []*yaml.Node {
if rn == nil {
return nil
}
return rn.YNode().Content
}
// Fields returns the list of field names for a MappingNode.
// Returns an error for non-MappingNodes.
func (rn *RNode) Fields() ([]string, error) {
if err := ErrorIfInvalid(rn, yaml.MappingNode); err != nil {
return nil, errors.Wrap(err)
}
var fields []string
visitMappingNodeFields(rn.Content(), func(key, value *yaml.Node) {
fields = append(fields, key.Value)
})
return fields, nil
}
// FieldRNodes returns the list of field key RNodes for a MappingNode.
// Returns an error for non-MappingNodes.
func (rn *RNode) FieldRNodes() ([]*RNode, error) {
if err := ErrorIfInvalid(rn, yaml.MappingNode); err != nil {
return nil, errors.Wrap(err)
}
var fields []*RNode
visitMappingNodeFields(rn.Content(), func(key, value *yaml.Node) {
// for each key node in the input mapping node contents create equivalent rNode
rNode := &RNode{}
rNode.SetYNode(key)
fields = append(fields, rNode)
})
return fields, nil
}
// Field returns a fieldName, fieldValue pair for MappingNodes.
// Returns nil for non-MappingNodes.
func (rn *RNode) Field(field string) *MapNode {
if rn.YNode().Kind != yaml.MappingNode {
return nil
}
var result *MapNode
visitMappingNodeFields(rn.Content(), func(key, value *yaml.Node) {
result = &MapNode{Key: NewRNode(key), Value: NewRNode(value)}
}, field)
return result
}
// VisitFields calls fn for each field in the RNode.
// Returns an error for non-MappingNodes.
func (rn *RNode) VisitFields(fn func(node *MapNode) error) error {
// get the list of srcFieldNames
srcFieldNames, err := rn.Fields()
if err != nil {
return errors.Wrap(err)
}
// visit each field
for _, fieldName := range srcFieldNames {
if err := fn(rn.Field(fieldName)); err != nil {
return errors.Wrap(err)
}
}
return nil
}
// visitMappingNodeFields calls fn for fields in the content, in content order.
// The caller is responsible to ensure the node is a mapping node. If fieldNames
// are specified, then fn is called only for the fields that match the given
// fieldNames.
func visitMappingNodeFields(content []*yaml.Node, fn func(key, value *yaml.Node), fieldNames ...string) {
switch len(fieldNames) {
case 0: // visit all fields
visitFieldsWhileTrue(content, func(key, value *yaml.Node, _ int) bool {
fn(key, value)
return true
})
case 1: // visit single field
visitFieldsWhileTrue(content, func(key, value *yaml.Node, _ int) bool {
if key == nil {
return true
}
if fieldNames[0] == key.Value {
fn(key, value)
return false
}
return true
})
default: // visit specified fields
fieldsStillToVisit := make(map[string]bool, len(fieldNames))
for _, fieldName := range fieldNames {
fieldsStillToVisit[fieldName] = true
}
visitFieldsWhileTrue(content, func(key, value *yaml.Node, _ int) bool {
if key == nil {
return true
}
if fieldsStillToVisit[key.Value] {
fn(key, value)
delete(fieldsStillToVisit, key.Value)
}
return len(fieldsStillToVisit) > 0
})
}
}
// visitFieldsWhileTrue calls fn for the fields in content, in content order,
// until either fn returns false or all fields have been visited. The caller
// should ensure that content is from a mapping node, or fits the same expected
// pattern (consecutive key/value entries in the slice).
func visitFieldsWhileTrue(content []*yaml.Node, fn func(key, value *yaml.Node, keyIndex int) bool) {
for i := 0; i < len(content); i += 2 {
continueVisiting := fn(content[i], content[i+1], i)
if !continueVisiting {
return
}
}
}
// Elements returns the list of elements in the RNode.
// Returns an error for non-SequenceNodes.
func (rn *RNode) Elements() ([]*RNode, error) {
if err := ErrorIfInvalid(rn, yaml.SequenceNode); err != nil {
return nil, errors.Wrap(err)
}
var elements []*RNode
for i := 0; i < len(rn.Content()); i++ {
elements = append(elements, NewRNode(rn.Content()[i]))
}
return elements, nil
}
// ElementValues returns a list of all observed values for a given field name
// in a list of elements.
// Returns error for non-SequenceNodes.
func (rn *RNode) ElementValues(key string) ([]string, error) {
if err := ErrorIfInvalid(rn, yaml.SequenceNode); err != nil {
return nil, errors.Wrap(err)
}
var elements []string
for i := 0; i < len(rn.Content()); i++ {
field := NewRNode(rn.Content()[i]).Field(key)
if !field.IsNilOrEmpty() {
elements = append(elements, field.Value.YNode().Value)
}
}
return elements, nil
}
// ElementValuesList returns a list of lists, where each list is a set of
// values corresponding to each key in keys.
// Returns error for non-SequenceNodes.
func (rn *RNode) ElementValuesList(keys []string) ([][]string, error) {
if err := ErrorIfInvalid(rn, yaml.SequenceNode); err != nil {
return nil, errors.Wrap(err)
}
elements := make([][]string, len(rn.Content()))
for i := 0; i < len(rn.Content()); i++ {
for _, key := range keys {
field := NewRNode(rn.Content()[i]).Field(key)
if field.IsNilOrEmpty() {
elements[i] = append(elements[i], "")
} else {
elements[i] = append(elements[i], field.Value.YNode().Value)
}
}
}
return elements, nil
}
// Element returns the element in the list which contains the field matching the value.
// Returns nil for non-SequenceNodes or if no Element matches.
func (rn *RNode) Element(key, value string) *RNode {
if rn.YNode().Kind != yaml.SequenceNode {
return nil
}
elem, err := rn.Pipe(MatchElement(key, value))
if err != nil {
return nil
}
return elem
}
// ElementList returns the element in the list in which all fields keys[i] matches all
// corresponding values[i].
// Returns nil for non-SequenceNodes or if no Element matches.
func (rn *RNode) ElementList(keys []string, values []string) *RNode {
if rn.YNode().Kind != yaml.SequenceNode {
return nil
}
elem, err := rn.Pipe(MatchElementList(keys, values))
if err != nil {
return nil
}
return elem
}
// VisitElements calls fn for each element in a SequenceNode.
// Returns an error for non-SequenceNodes
func (rn *RNode) VisitElements(fn func(node *RNode) error) error {
elements, err := rn.Elements()
if err != nil {
return errors.Wrap(err)
}
for i := range elements {
if err := fn(elements[i]); err != nil {
return errors.Wrap(err)
}
}
return nil
}
// AssociativeSequenceKeys is a map of paths to sequences that have associative keys.
// The order sets the precedence of the merge keys -- if multiple keys are present
// in Resources in a list, then the FIRST key which ALL elements in the list have is used as the
// associative key for merging that list.
// Only infer name as a merge key.
var AssociativeSequenceKeys = []string{"name"}
// IsAssociative returns true if the RNode contains an AssociativeSequenceKey as a field.
func (rn *RNode) IsAssociative() bool {
return rn.GetAssociativeKey() != ""
}
// GetAssociativeKey returns the AssociativeSequenceKey used to merge the elements in the
// SequenceNode, or "" if the list is not associative.
func (rn *RNode) GetAssociativeKey() string {
// look for any associative keys in the first element
for _, key := range AssociativeSequenceKeys {
if checkKey(key, rn.Content()) {
return key
}
}
// element doesn't have an associative keys
return ""
}
// MarshalJSON creates a byte slice from the RNode.
func (rn *RNode) MarshalJSON() ([]byte, error) {
s, err := rn.String()
if err != nil {
return nil, err
}
if rn.YNode().Kind == SequenceNode {
var a []interface{}
if err := Unmarshal([]byte(s), &a); err != nil {
return nil, err
}
return json.Marshal(a)
}
m := map[string]interface{}{}
if err := Unmarshal([]byte(s), &m); err != nil {
return nil, err
}
return json.Marshal(m)
}
// UnmarshalJSON overwrites this RNode with data from []byte.
func (rn *RNode) UnmarshalJSON(b []byte) error {
m := map[string]interface{}{}
if err := json.Unmarshal(b, &m); err != nil {
return err
}
r, err := FromMap(m)
if err != nil {
return err
}
rn.value = r.value
return nil
}
// DeAnchor inflates all YAML aliases with their anchor values.
// All YAML anchor data is permanently removed (feel free to call Copy first).
func (rn *RNode) DeAnchor() (err error) {
rn.value, err = deAnchor(rn.value)