From 1aa7a1e70972e586f5284ad23f91c8a3c8bdc838 Mon Sep 17 00:00:00 2001 From: Phani Teja Marupaka Date: Sun, 27 Jun 2021 16:55:16 -0700 Subject: [PATCH] Handle null values while formatting --- kyaml/kio/filters/fmtr_test.go | 49 ++++++++++++++++++++++++++++++++++ kyaml/yaml/compatibility.go | 8 ++++++ 2 files changed, 57 insertions(+) diff --git a/kyaml/kio/filters/fmtr_test.go b/kyaml/kio/filters/fmtr_test.go index 156bbcf643..5a59bd8fc4 100644 --- a/kyaml/kio/filters/fmtr_test.go +++ b/kyaml/kio/filters/fmtr_test.go @@ -1048,3 +1048,52 @@ metadata: }) } } + +func TestFormatInput_NullCases(t *testing.T) { + y := ` +apiVersion: v1 +kind: Service +metadata: + name: nginx + labels: + app: null +spec: + selector: + app: nginx + ports: + - name: http + port: 80 + targetPort: ~ + nodePort: null + allocateLoadBalancerNodePorts: null +` + + // keep the style on values that parse as non-string types + expected := `apiVersion: v1 +kind: Service +metadata: + name: nginx + labels: + app: null +spec: + selector: + app: nginx + ports: + - name: http + port: 80 + targetPort: ~ + nodePort: null + allocateLoadBalancerNodePorts: null +` + + buff := &bytes.Buffer{} + err := kio.Pipeline{ + Inputs: []kio.Reader{&kio.ByteReader{Reader: strings.NewReader(y)}}, + Filters: []kio.Filter{FormatFilter{ + UseSchema: true, + }}, + Outputs: []kio.Writer{kio.ByteWriter{Writer: buff}}, + }.Execute() + assert.NoError(t, err) + assert.Equal(t, expected, buff.String()) +} diff --git a/kyaml/yaml/compatibility.go b/kyaml/yaml/compatibility.go index 77b0f6db0d..545c527a94 100644 --- a/kyaml/yaml/compatibility.go +++ b/kyaml/yaml/compatibility.go @@ -45,6 +45,14 @@ func FormatNonStringStyle(node *Node, schema spec.Schema) { default: return } + + // if the node tag is null, make sure we don't add any non-null tags + // https://github.com/GoogleContainerTools/kpt/issues/2321 + if node.Tag == NodeTagNull { + // must NOT quote null values + node.Style = 0 + return + } if tag, found := typeToTag[t]; found { // make sure the right tag is set node.Tag = tag