Merge pull request #3346 from Shell32-Natsu/ynode-iszero

Add function to check is YNode zero
This commit is contained in:
Kubernetes Prow Robot
2020-12-15 09:43:48 -08:00
committed by GitHub
4 changed files with 30 additions and 1 deletions

View File

@@ -197,7 +197,8 @@ func (rn *RNode) IsNilOrEmpty() bool {
return rn.IsNil() ||
IsYNodeTaggedNull(rn.YNode()) ||
IsYNodeEmptyMap(rn.YNode()) ||
IsYNodeEmptySeq(rn.YNode())
IsYNodeEmptySeq(rn.YNode()) ||
IsYNodeZero(rn.YNode())
}
// GetMeta returns the ResourceMeta for an RNode

View File

@@ -750,6 +750,10 @@ func TestRNodeIsNilOrEmpty(t *testing.T) {
if NewListRNode("foo").IsNilOrEmpty() {
t.Fatalf("non-empty list should not be empty")
}
if !NewRNode(&Node{}).IsNilOrEmpty() {
t.Fatalf("zero YNode should be empty")
}
}
const deploymentJSON = `

View File

@@ -54,6 +54,18 @@ func IsYNodeString(n *yaml.Node) bool {
return n.Kind == yaml.ScalarNode && n.Tag == NodeTagString
}
// IsYNodeZero is true if all the public fields in the Node are empty.
// Which means it's not initialized and should be omitted when marshal.
// The Node itself has a method IsZero but it is not released
// in yaml.v3. https://pkg.go.dev/gopkg.in/yaml.v3#Node.IsZero
func IsYNodeZero(n *yaml.Node) bool {
// TODO: Change this to use IsZero when it's avaialable.
return n != nil && n.Kind == 0 && n.Style == 0 && n.Tag == "" && n.Value == "" &&
n.Anchor == "" && n.Alias == nil && n.Content == nil &&
n.HeadComment == "" && n.LineComment == "" && n.FootComment == "" &&
n.Line == 0 && n.Column == 0
}
// Parser parses values into configuration.
type Parser struct {
Kind string `yaml:"kind,omitempty"`

View File

@@ -112,3 +112,15 @@ func TestIsYNodeEmptySeq(t *testing.T) {
t.Fatalf("a node with content isn't empty")
}
}
func TestIsYNodeZero(t *testing.T) {
if IsYNodeZero(nil) {
t.Fatalf("nil node should not be zero")
}
if !IsYNodeZero(&Node{}) {
t.Fatalf("node is zero")
}
if IsYNodeZero(&Node{Kind: MappingNode}) {
t.Fatalf("node is not zero")
}
}