From bae322855727eae7618ff16b7f94bfa9eb11e911 Mon Sep 17 00:00:00 2001 From: Donny Xia Date: Fri, 11 Dec 2020 14:52:35 -0800 Subject: [PATCH] Add function to check is YNode zero --- kyaml/yaml/rnode.go | 3 ++- kyaml/yaml/rnode_test.go | 4 ++++ kyaml/yaml/types.go | 12 ++++++++++++ kyaml/yaml/types_test.go | 12 ++++++++++++ 4 files changed, 30 insertions(+), 1 deletion(-) diff --git a/kyaml/yaml/rnode.go b/kyaml/yaml/rnode.go index 5118c5f04..5e65436aa 100644 --- a/kyaml/yaml/rnode.go +++ b/kyaml/yaml/rnode.go @@ -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 diff --git a/kyaml/yaml/rnode_test.go b/kyaml/yaml/rnode_test.go index ecf67e1bc..48d83d190 100644 --- a/kyaml/yaml/rnode_test.go +++ b/kyaml/yaml/rnode_test.go @@ -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 = ` diff --git a/kyaml/yaml/types.go b/kyaml/yaml/types.go index 4adf0bda7..7954c1fa4 100644 --- a/kyaml/yaml/types.go +++ b/kyaml/yaml/types.go @@ -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"` diff --git a/kyaml/yaml/types_test.go b/kyaml/yaml/types_test.go index 6da832003..ac3553678 100644 --- a/kyaml/yaml/types_test.go +++ b/kyaml/yaml/types_test.go @@ -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") + } +}