From 1a002005c1aed623f8adc83933a8e9f0e30c57c7 Mon Sep 17 00:00:00 2001 From: monopole Date: Sat, 9 Jan 2021 06:57:01 -0800 Subject: [PATCH] Add RNode.Map method and test to help decoding. --- kyaml/go.mod | 1 + kyaml/yaml/rnode.go | 13 +++++++++++++ kyaml/yaml/rnode_test.go | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/kyaml/go.mod b/kyaml/go.mod index fc5657db7..0efc5d9f7 100644 --- a/kyaml/go.mod +++ b/kyaml/go.mod @@ -8,6 +8,7 @@ require ( github.com/go-openapi/spec v0.19.5 github.com/go-openapi/strfmt v0.19.5 github.com/go-openapi/validate v0.19.8 + github.com/google/go-cmp v0.3.0 github.com/markbates/pkger v0.17.1 github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 github.com/qri-io/starlib v0.4.2-0.20200213133954-ff2e8cd5ef8d diff --git a/kyaml/yaml/rnode.go b/kyaml/yaml/rnode.go index 3165d723d..63e028b06 100644 --- a/kyaml/yaml/rnode.go +++ b/kyaml/yaml/rnode.go @@ -785,6 +785,19 @@ func FromMap(m map[string]interface{}) (*RNode, error) { return Parse(string(c)) } +func (rn *RNode) Map() map[string]interface{} { + if rn == nil || rn.value == nil { + return make(map[string]interface{}) + } + var result map[string]interface{} + if err := rn.value.Decode(&result); err != nil { + // Should not be able to create an RNode that cannot be decoded; + // this is an unrecoverable error. + log.Fatalf("failed to decode ynode: %v", err) + } + return result +} + // ConvertJSONToYamlNode parses input json string and returns equivalent yaml node func ConvertJSONToYamlNode(jsonStr string) (*RNode, error) { var body map[string]interface{} diff --git a/kyaml/yaml/rnode_test.go b/kyaml/yaml/rnode_test.go index b6b6cf580..57f0276ed 100644 --- a/kyaml/yaml/rnode_test.go +++ b/kyaml/yaml/rnode_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" ) @@ -384,6 +385,38 @@ func TestRNodeGetValidatedMetadata(t *testing.T) { } } +func TestRNodeMapEmpty(t *testing.T) { + assert.Equal(t, 0, len(NewRNode(nil).Map())) +} + +func TestRNodeMap(t *testing.T) { + wn := NewRNode(nil) + if err := wn.UnmarshalJSON([]byte(`{ + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": { + "name": "homer", + "namespace": "simpsons" + } +}`)); err != nil { + t.Fatalf("unexpected unmarshaljson err: %v", err) + } + + expected := map[string]interface{}{ + "apiVersion": "apps/v1", + "kind": "Deployment", + "metadata": map[string]interface{}{ + "name": "homer", + "namespace": "simpsons", + }, + } + + actual := wn.Map() + if diff := cmp.Diff(expected, actual); diff != "" { + t.Fatalf("actual map does not deep equal expected map:\n%v", diff) + } +} + func TestRNodeFromMap(t *testing.T) { testConfigMap := map[string]interface{}{ "apiVersion": "v1",