feat: kubesphere 4.0 (#6115)

* feat: kubesphere 4.0

Signed-off-by: ci-bot <ci-bot@kubesphere.io>

* feat: kubesphere 4.0

Signed-off-by: ci-bot <ci-bot@kubesphere.io>

---------

Signed-off-by: ci-bot <ci-bot@kubesphere.io>
Co-authored-by: ks-ci-bot <ks-ci-bot@example.com>
Co-authored-by: joyceliu <joyceliu@yunify.com>
This commit is contained in:
KubeSphere CI Bot
2024-09-06 11:05:52 +08:00
committed by GitHub
parent b5015ec7b9
commit 447a51f08b
8557 changed files with 546695 additions and 1146174 deletions

View File

@@ -87,6 +87,16 @@ var MappingNode yaml.Kind = yaml.MappingNode
var ScalarNode yaml.Kind = yaml.ScalarNode
var SequenceNode yaml.Kind = yaml.SequenceNode
func nodeKindString(k yaml.Kind) string {
return map[yaml.Kind]string{
yaml.SequenceNode: "SequenceNode",
yaml.MappingNode: "MappingNode",
yaml.ScalarNode: "ScalarNode",
yaml.DocumentNode: "DocumentNode",
yaml.AliasNode: "AliasNode",
}[k]
}
var DoubleQuotedStyle yaml.Style = yaml.DoubleQuotedStyle
var FlowStyle yaml.Style = yaml.FlowStyle
var FoldedStyle yaml.Style = yaml.FoldedStyle

View File

@@ -68,7 +68,7 @@ func (y *YFilter) UnmarshalYAML(unmarshal func(interface{}) error) error {
type YFilters []YFilter
func (y YFilters) Filters() []Filter {
var f []Filter
f := make([]Filter, 0, len(y))
for i := range y {
f = append(f, y[i].Filter)
}

View File

@@ -197,36 +197,37 @@ func (c FieldClearer) Filter(rn *RNode) (*RNode, error) {
return nil, err
}
for i := 0; i < len(rn.Content()); i += 2 {
// if name matches, remove these 2 elements from the list because
// they are treated as a fieldName/fieldValue pair.
if rn.Content()[i].Value == c.Name {
if c.IfEmpty {
if len(rn.Content()[i+1].Content) > 0 {
continue
}
}
// save the item we are about to remove
removed := NewRNode(rn.Content()[i+1])
if len(rn.YNode().Content) > i+2 {
l := len(rn.YNode().Content)
// remove from the middle of the list
rn.YNode().Content = rn.Content()[:i]
rn.YNode().Content = append(
rn.YNode().Content,
rn.Content()[i+2:l]...)
} else {
// remove from the end of the list
rn.YNode().Content = rn.Content()[:i]
}
// return the removed field name and value
return removed, nil
var removed *RNode
visitFieldsWhileTrue(rn.Content(), func(key, value *yaml.Node, keyIndex int) bool {
if key.Value != c.Name {
return true
}
}
// nothing removed
return nil, nil
// the name matches: remove these 2 elements from the list because
// they are treated as a fieldName/fieldValue pair.
if c.IfEmpty {
if len(value.Content) > 0 {
return true
}
}
// save the item we are about to remove
removed = NewRNode(value)
if len(rn.YNode().Content) > keyIndex+2 {
l := len(rn.YNode().Content)
// remove from the middle of the list
rn.YNode().Content = rn.Content()[:keyIndex]
rn.YNode().Content = append(
rn.YNode().Content,
rn.Content()[keyIndex+2:l]...)
} else {
// remove from the end of the list
rn.YNode().Content = rn.Content()[:keyIndex]
}
return false
})
return removed, nil
}
func MatchElement(field, value string) ElementMatcher {
@@ -402,14 +403,15 @@ func (f FieldMatcher) Filter(rn *RNode) (*RNode, error) {
return nil, err
}
for i := 0; i < len(rn.Content()); i = IncrementFieldIndex(i) {
isMatchingField := rn.Content()[i].Value == f.Name
if isMatchingField {
requireMatchFieldValue := f.Value != nil
if !requireMatchFieldValue || rn.Content()[i+1].Value == f.Value.YNode().Value {
return NewRNode(rn.Content()[i+1]), nil
}
var returnNode *RNode
requireMatchFieldValue := f.Value != nil
visitMappingNodeFields(rn.Content(), func(key, value *yaml.Node) {
if !requireMatchFieldValue || value.Value == f.Value.YNode().Value {
returnNode = NewRNode(value)
}
}, f.Name)
if returnNode != nil {
return returnNode, nil
}
if f.Create != nil {
@@ -550,7 +552,7 @@ func (l PathGetter) getFilter(part, nextPart string, fieldPath *[]string) (Filte
default:
// mapping node
*fieldPath = append(*fieldPath, part)
return l.fieldFilter(part, l.getKind(nextPart))
return l.fieldFilter(part, getPathPartKind(nextPart, l.Create))
}
}
@@ -590,15 +592,18 @@ func (l PathGetter) fieldFilter(
return FieldMatcher{Name: name, Create: &RNode{value: &yaml.Node{Kind: kind, Style: l.Style}}}, nil
}
func (l PathGetter) getKind(nextPart string) yaml.Kind {
func getPathPartKind(nextPart string, defaultKind yaml.Kind) yaml.Kind {
if IsListIndex(nextPart) {
// if nextPart is of the form [a=b], then it is an index into a Sequence
// so the current part must be a SequenceNode
return yaml.SequenceNode
}
if IsIdxNumber(nextPart) {
return yaml.SequenceNode
}
if nextPart == "" {
// final name in the path, use the l.Create defined Kind
return l.Create
// final name in the path, use the default kind provided
return defaultKind
}
// non-sequence intermediate Node
@@ -640,13 +645,19 @@ func (s MapEntrySetter) Filter(rn *RNode) (*RNode, error) {
if s.Name == "" {
s.Name = GetValue(s.Key)
}
for i := 0; i < len(rn.Content()); i = IncrementFieldIndex(i) {
isMatchingField := rn.Content()[i].Value == s.Name
if isMatchingField {
rn.Content()[i] = s.Key.YNode()
rn.Content()[i+1] = s.Value.YNode()
return rn, nil
content := rn.Content()
fieldStillNotFound := true
visitFieldsWhileTrue(content, func(key, value *yaml.Node, keyIndex int) bool {
if key.Value == s.Name {
content[keyIndex] = s.Key.YNode()
content[keyIndex+1] = s.Value.YNode()
fieldStillNotFound = false
}
return fieldStillNotFound
})
if !fieldStillNotFound {
return rn, nil
}
// create the field
@@ -794,12 +805,22 @@ func ErrorIfAnyInvalidAndNonNull(kind yaml.Kind, rn ...*RNode) error {
return nil
}
var nodeTypeIndex = map[yaml.Kind]string{
yaml.SequenceNode: "SequenceNode",
yaml.MappingNode: "MappingNode",
yaml.ScalarNode: "ScalarNode",
yaml.DocumentNode: "DocumentNode",
yaml.AliasNode: "AliasNode",
type InvalidNodeKindError struct {
expectedKind yaml.Kind
node *RNode
}
func (e *InvalidNodeKindError) Error() string {
msg := fmt.Sprintf("wrong node kind: expected %s but got %s",
nodeKindString(e.expectedKind), nodeKindString(e.node.YNode().Kind))
if content, err := e.node.String(); err == nil {
msg += fmt.Sprintf(": node contents:\n%s", content)
}
return msg
}
func (e *InvalidNodeKindError) ActualNodeKind() Kind {
return e.node.YNode().Kind
}
func ErrorIfInvalid(rn *RNode, kind yaml.Kind) error {
@@ -809,11 +830,7 @@ func ErrorIfInvalid(rn *RNode, kind yaml.Kind) error {
}
if rn.YNode().Kind != kind {
s, _ := rn.String()
return errors.Errorf(
"wrong Node Kind for %s expected: %v was %v: value: {%s}",
strings.Join(rn.FieldPath(), "."),
nodeTypeIndex[kind], nodeTypeIndex[rn.YNode().Kind], strings.TrimSpace(s))
return &InvalidNodeKindError{node: rn, expectedKind: kind}
}
if kind == yaml.MappingNode {
@@ -859,9 +876,3 @@ func SplitIndexNameValue(p string) (string, string, error) {
}
return parts[0], parts[1], nil
}
// IncrementFieldIndex increments i to point to the next field name element in
// a slice of Contents.
func IncrementFieldIndex(i int) int {
return i + 2
}

View File

@@ -4,9 +4,13 @@
package yaml
import (
"fmt"
"regexp"
"strconv"
"strings"
"sigs.k8s.io/kustomize/kyaml/errors"
"sigs.k8s.io/kustomize/kyaml/internal/forked/github.com/go-yaml/yaml"
)
// PathMatcher returns all RNodes matching the path wrapped in a SequenceNode.
@@ -21,7 +25,7 @@ type PathMatcher struct {
// Each path part may be one of:
// * FieldMatcher -- e.g. "spec"
// * Map Key -- e.g. "app.k8s.io/version"
// * List Entry -- e.g. "[name=nginx]" or "[=-jar]"
// * List Entry -- e.g. "[name=nginx]" or "[=-jar]" or "0"
//
// Map Keys and Fields are equivalent.
// See FieldMatcher for more on Fields and Map Keys.
@@ -43,10 +47,18 @@ type PathMatcher struct {
// This is useful for if the nodes are to be printed in FlowStyle.
StripComments bool
val *RNode
field string
matchRegex string
indexNumber int
// Create will cause missing path parts to be created as they are walked.
//
// * The leaf Node (final path) will be created with a Kind matching Create
// * Intermediary Nodes will be created as either a MappingNodes or
// SequenceNodes as appropriate for each's Path location.
// * Nodes identified by an index will only be created if the index indicates
// an append operation (i.e. index=len(list))
Create yaml.Kind `yaml:"create,omitempty"`
val *RNode
field string
matchRegex string
}
func (p *PathMatcher) stripComments(n *Node) {
@@ -109,7 +121,7 @@ func (p *PathMatcher) doMatchEvery(rn *RNode) (*RNode, error) {
func (p *PathMatcher) visitEveryElem(elem *RNode) error {
fieldName := p.Path[0]
// recurse on the matching element
pm := &PathMatcher{Path: p.Path[1:]}
pm := &PathMatcher{Path: p.Path[1:], Create: p.Create}
add, err := pm.filter(elem)
for k, v := range pm.Matches {
p.Matches[k] = v
@@ -125,13 +137,25 @@ func (p *PathMatcher) visitEveryElem(elem *RNode) error {
func (p *PathMatcher) doField(rn *RNode) (*RNode, error) {
// lookup the field
field, err := rn.Pipe(Get(p.Path[0]))
if err != nil || field == nil {
// if the field doesn't exist, return nil
if err != nil || (!IsCreate(p.Create) && field == nil) {
return nil, err
}
if IsCreate(p.Create) && field == nil {
var nextPart string
if len(p.Path) > 1 {
nextPart = p.Path[1]
}
nextPartKind := getPathPartKind(nextPart, p.Create)
field = &RNode{value: &yaml.Node{Kind: nextPartKind}}
err := rn.PipeE(SetField(p.Path[0], field))
if err != nil {
return nil, err
}
}
// recurse on the field, removing the first element of the path
pm := &PathMatcher{Path: p.Path[1:]}
pm := &PathMatcher{Path: p.Path[1:], Create: p.Create}
p.val, err = pm.filter(field)
p.Matches = pm.Matches
return p.val, err
@@ -144,18 +168,33 @@ func (p *PathMatcher) doIndexSeq(rn *RNode) (*RNode, error) {
if err != nil {
return nil, err
}
p.indexNumber = idx
elements, err := rn.Elements()
if err != nil {
return nil, err
}
if len(elements) == idx && IsCreate(p.Create) {
var nextPart string
if len(p.Path) > 1 {
nextPart = p.Path[1]
}
elem := &yaml.Node{Kind: getPathPartKind(nextPart, p.Create)}
err = rn.PipeE(Append(elem))
if err != nil {
return nil, errors.WrapPrefixf(err, "failed to append element for %q", p.Path[0])
}
elements = append(elements, NewRNode(elem))
}
if len(elements) < idx+1 {
return nil, fmt.Errorf("index %d specified but only %d elements found", idx, len(elements))
}
// get target element
element := elements[idx]
// recurse on the matching element
pm := &PathMatcher{Path: p.Path[1:]}
pm := &PathMatcher{Path: p.Path[1:], Create: p.Create}
add, err := pm.filter(element)
for k, v := range pm.Matches {
p.Matches[k] = v
@@ -176,16 +215,39 @@ func (p *PathMatcher) doSeq(rn *RNode) (*RNode, error) {
return nil, err
}
if p.field == "" {
primitiveElement := len(p.field) == 0
if primitiveElement {
err = rn.VisitElements(p.visitPrimitiveElem)
} else {
err = rn.VisitElements(p.visitElem)
}
if err != nil || p.val == nil || len(p.val.YNode().Content) == 0 {
if err != nil {
return nil, err
}
if !p.val.IsNil() && len(p.val.YNode().Content) == 0 {
p.val = nil
}
return p.val, nil
if !IsCreate(p.Create) || p.val != nil {
return p.val, nil
}
var elem *yaml.Node
valueNode := NewScalarRNode(p.matchRegex).YNode()
if primitiveElement {
elem = valueNode
} else {
elem = &yaml.Node{
Kind: yaml.MappingNode,
Content: []*yaml.Node{{Kind: yaml.ScalarNode, Value: p.field}, valueNode},
}
}
err = rn.PipeE(Append(elem))
if err != nil {
return nil, errors.WrapPrefixf(err, "failed to create element for %q", p.Path[0])
}
// re-do the sequence search; this time we'll find the element we just created
return p.doSeq(rn)
}
func (p *PathMatcher) visitPrimitiveElem(elem *RNode) error {
@@ -228,7 +290,7 @@ func (p *PathMatcher) visitElem(elem *RNode) error {
}
// recurse on the matching element
pm := &PathMatcher{Path: p.Path[1:]}
pm := &PathMatcher{Path: p.Path[1:], Create: p.Create}
add, err := pm.filter(elem)
for k, v := range pm.Matches {
p.Matches[k] = v

View File

@@ -1,7 +1,7 @@
// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
// Package merge contains libraries for merging fields from one RNode to another
// Package merge2 contains libraries for merging fields from one RNode to another
// RNode
package merge2
@@ -20,7 +20,7 @@ func Merge(src, dest *yaml.RNode, mergeOptions yaml.MergeOptions) (*yaml.RNode,
}.Walk()
}
// Merge parses the arguments, and merges fields from srcStr into destStr.
// MergeStrings parses the arguments, and merges fields from srcStr into destStr.
func MergeStrings(srcStr, destStr string, infer bool, mergeOptions yaml.MergeOptions) (string, error) {
src, err := yaml.Parse(srcStr)
if err != nil {
@@ -64,6 +64,12 @@ func (m Merger) VisitMap(nodes walk.Sources, s *openapi.ResourceSchema) (*yaml.R
return walk.ClearNode, nil
}
// If Origin is missing, preserve explicitly set null in Dest ("null", "~", etc)
if nodes.Origin().IsNil() && !nodes.Dest().IsNil() && len(nodes.Dest().YNode().Value) > 0 {
// Return a new node so that it won't have a "!!null" tag and therefore won't be cleared.
return yaml.NewScalarRNode(nodes.Dest().YNode().Value), nil
}
return nodes.Origin(), nil
}
if nodes.Origin().IsTaggedNull() {

View File

@@ -6,8 +6,8 @@ package yaml
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strconv"
"strings"
@@ -53,7 +53,7 @@ func Parse(value string) (*RNode, error) {
// 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 := ioutil.ReadFile(path)
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
@@ -66,7 +66,7 @@ func WriteFile(node *RNode, path string) error {
if err != nil {
return err
}
return ioutil.WriteFile(path, []byte(out), 0600)
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.
@@ -242,11 +242,7 @@ func (rn *RNode) IsTaggedNull() bool {
// 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() ||
IsYNodeTaggedNull(rn.YNode()) ||
IsYNodeEmptyMap(rn.YNode()) ||
IsYNodeEmptySeq(rn.YNode()) ||
IsYNodeZero(rn.YNode())
return rn.IsNil() || IsYNodeNilOrEmpty(rn.YNode())
}
// IsStringValue is true if the RNode is not nil and is scalar string node
@@ -420,12 +416,11 @@ func (rn *RNode) SetApiVersion(av string) {
// given field, so this function cannot be used to make distinctions
// between these cases.
func (rn *RNode) getMapFieldValue(field string) *yaml.Node {
for i := 0; i < len(rn.Content()); i = IncrementFieldIndex(i) {
if rn.Content()[i].Value == field {
return rn.Content()[i+1]
}
}
return nil
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
@@ -440,31 +435,33 @@ func (rn *RNode) getMetaStringField(fName string) string {
if md == nil {
return ""
}
f := md.Field(fName)
if f.IsNilOrEmpty() {
return ""
}
return GetValue(f.Value)
var result string
visitMappingNodeFields(md.Content, func(key, value *yaml.Node) {
if !IsYNodeNilOrEmpty(value) {
result = value.Value
}
}, fName)
return result
}
// getMetaData returns the RNode holding the value of the metadata field.
// getMetaData returns the *yaml.Node of the metadata field.
// Return nil if field not found (no error).
func (rn *RNode) getMetaData() *RNode {
func (rn *RNode) getMetaData() *yaml.Node {
if IsMissingOrNull(rn) {
return nil
}
var n *RNode
content := rn.Content()
if rn.YNode().Kind == DocumentNode {
// get the content if this is the document node
n = NewRNode(rn.Content()[0])
} else {
n = rn
content = content[0].Content
}
mf := n.Field(MetadataField)
if mf.IsNilOrEmpty() {
return nil
}
return mf.Value
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.
@@ -496,14 +493,14 @@ func (rn *RNode) SetNamespace(ns string) error {
}
// GetAnnotations gets the metadata annotations field.
// If the field is missing, returns an empty map.
// If the annotations field is missing, returns an empty map.
// Use another method to check for missing metadata.
func (rn *RNode) GetAnnotations() map[string]string {
meta := rn.getMetaData()
if meta == nil {
return make(map[string]string)
}
return rn.getMapFromMeta(meta, AnnotationsField)
// 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.
@@ -512,24 +509,45 @@ func (rn *RNode) SetAnnotations(m map[string]string) error {
}
// GetLabels gets the metadata labels field.
// If the field is missing, returns an empty map.
// If the labels field is missing, returns an empty map.
// Use another method to check for missing metadata.
func (rn *RNode) GetLabels() map[string]string {
// 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)
}
return rn.getMapFromMeta(meta, LabelsField)
}
// getMapFromMeta returns map, sometimes empty, from metadata.
func (rn *RNode) getMapFromMeta(meta *RNode, fName string) map[string]string {
result := make(map[string]string)
if f := meta.Field(fName); !f.IsNilOrEmpty() {
_ = f.Value.VisitFields(func(node *MapNode) error {
result[GetValue(node.Key)] = GetValue(node.Value)
return nil
})
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
}
@@ -696,9 +714,9 @@ func (rn *RNode) Fields() ([]string, error) {
return nil, errors.Wrap(err)
}
var fields []string
for i := 0; i < len(rn.Content()); i += 2 {
fields = append(fields, rn.Content()[i].Value)
}
visitMappingNodeFields(rn.Content(), func(key, value *yaml.Node) {
fields = append(fields, key.Value)
})
return fields, nil
}
@@ -709,13 +727,12 @@ func (rn *RNode) FieldRNodes() ([]*RNode, error) {
return nil, errors.Wrap(err)
}
var fields []*RNode
for i := 0; i < len(rn.Content()); i += 2 {
yNode := rn.Content()[i]
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(yNode)
rNode.SetYNode(key)
fields = append(fields, rNode)
}
})
return fields, nil
}
@@ -725,13 +742,11 @@ func (rn *RNode) Field(field string) *MapNode {
if rn.YNode().Kind != yaml.MappingNode {
return nil
}
for i := 0; i < len(rn.Content()); i = IncrementFieldIndex(i) {
isMatchingField := rn.Content()[i].Value == field
if isMatchingField {
return &MapNode{Key: NewRNode(rn.Content()[i]), Value: NewRNode(rn.Content()[i+1])}
}
}
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.
@@ -752,6 +767,59 @@ func (rn *RNode) VisitFields(fn func(node *MapNode) error) error {
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) {
@@ -937,7 +1005,11 @@ func deAnchor(yn *yaml.Node) (res *yaml.Node, err error) {
case yaml.ScalarNode:
return yn, nil
case yaml.AliasNode:
return deAnchor(yn.Alias)
result, err := deAnchor(yn.Alias)
if err != nil {
return nil, err
}
return CopyYNode(result), nil
case yaml.MappingNode:
toMerge, err := removeMergeTags(yn)
if err != nil {
@@ -1003,17 +1075,19 @@ func findMergeValues(yn *yaml.Node) ([]*yaml.Node, error) {
// it fails.
func getMergeTagValue(yn *yaml.Node) (*yaml.Node, error) {
var result *yaml.Node
for i := 0; i < len(yn.Content); i += 2 {
key := yn.Content[i]
value := yn.Content[i+1]
var err error
visitFieldsWhileTrue(yn.Content, func(key, value *yaml.Node, _ int) bool {
if isMerge(key) {
if result != nil {
return nil, fmt.Errorf("duplicate merge key")
err = fmt.Errorf("duplicate merge key")
result = nil
return false
}
result = value
}
}
return result, nil
return true
})
return result, err
}
// removeMergeTags removes all merge tags and returns a ordered list of yaml

View File

@@ -39,11 +39,20 @@ func IsYNodeEmptyMap(n *yaml.Node) bool {
return n != nil && n.Kind == yaml.MappingNode && len(n.Content) == 0
}
// IsYNodeEmptyMap is true if the Node is a non-nil empty sequence.
// IsYNodeEmptySeq is true if the Node is a non-nil empty sequence.
func IsYNodeEmptySeq(n *yaml.Node) bool {
return n != nil && n.Kind == yaml.SequenceNode && len(n.Content) == 0
}
// IsYNodeNilOrEmpty is true if the Node is nil or appears empty.
func IsYNodeNilOrEmpty(n *yaml.Node) bool {
return n == nil ||
IsYNodeTaggedNull(n) ||
IsYNodeEmptyMap(n) ||
IsYNodeEmptySeq(n) ||
IsYNodeZero(n)
}
// IsYNodeEmptyDoc is true if the node is a Document with no content.
// E.g.: "---\n---"
func IsYNodeEmptyDoc(n *yaml.Node) bool {
@@ -238,3 +247,53 @@ type MergeOptions struct {
// source list to destination or append.
ListIncreaseDirection MergeOptionsListIncreaseDirection
}
// Since ObjectMeta and TypeMeta are stable, we manually create DeepCopy funcs for ResourceMeta and ObjectMeta.
// For TypeMeta and NameMeta no DeepCopy funcs are required, as they only contain basic types.
// DeepCopyInto copies the receiver, writing into out. in must be non-nil.
func (in *ObjectMeta) DeepCopyInto(out *ObjectMeta) {
*out = *in
out.NameMeta = in.NameMeta
if in.Labels != nil {
in, out := &in.Labels, &out.Labels
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
if in.Annotations != nil {
in, out := &in.Annotations, &out.Annotations
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
}
// DeepCopy copies the receiver, creating a new ObjectMeta.
func (in *ObjectMeta) DeepCopy() *ObjectMeta {
if in == nil {
return nil
}
out := new(ObjectMeta)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto copies the receiver, writing into out. in must be non-nil.
func (in *ResourceMeta) DeepCopyInto(out *ResourceMeta) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
}
// DeepCopy copies the receiver, creating a new ResourceMeta.
func (in *ResourceMeta) DeepCopy() *ResourceMeta {
if in == nil {
return nil
}
out := new(ResourceMeta)
in.DeepCopyInto(out)
return out
}

View File

@@ -217,7 +217,7 @@ func (l *Walker) setAssociativeSequenceElements(valuesList [][]string, keys []st
// Add the val to the sequence. val will replace the item in the sequence if
// there is an item that matches all key-value pairs. Otherwise val will be appended
// the the sequence.
// the sequence.
_, err = itemsToBeAdded.Pipe(yaml.ElementSetter{
Element: val.YNode(),
Keys: validKeys,