From e5948c4f167e5dda5c90b6f79bc0657f87d2d24e Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Sun, 13 Sep 2020 12:14:20 +1000 Subject: [PATCH] Fixed potential npe --- cmd/read_test.go | 21 +++++++++++++++++++++ cmd/utils.go | 17 +++++++++++------ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/cmd/read_test.go b/cmd/read_test.go index 96d4121b..d68547d8 100644 --- a/cmd/read_test.go +++ b/cmd/read_test.go @@ -617,6 +617,27 @@ pointer: *value-pointer` test.AssertResult(t, expectedOutput, result.Output) } +func TestReadMergeAnchorsExplodeMissingCmd(t *testing.T) { + content := `a: + <<: &anchor + c: d + e: f +` + filename := test.WriteTempYamlFile(content) + defer test.RemoveTempYamlFile(filename) + + cmd := getRootCommand() + result := test.RunCmd(cmd, fmt.Sprintf("read -X %s", filename)) + if result.Error != nil { + t.Error(result.Error) + } + expectedOutput := `a: + c: d + e: f +` + test.AssertResult(t, expectedOutput, result.Output) +} + func TestReadMergeAnchorsExplodeKeyCmd(t *testing.T) { content := `name: &nameField Mike *nameField: Great Guy` diff --git a/cmd/utils.go b/cmd/utils.go index cfc006be..9b1ca726 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -163,6 +163,9 @@ func setIfNotThere(node *yaml.Node, key string, value *yaml.Node) { } func applyAlias(node *yaml.Node, alias *yaml.Node) { + if alias == nil { + return + } for index := 0; index < len(alias.Content); index = index + 2 { keyNode := alias.Content[index] log.Debugf("applying alias key %v", keyNode.Value) @@ -185,12 +188,14 @@ func explodeNode(node *yaml.Node) error { return nil case yaml.AliasNode: log.Debugf("its an alias!") - node.Kind = node.Alias.Kind - node.Style = node.Alias.Style - node.Tag = node.Alias.Tag - node.Content = node.Alias.Content - node.Value = node.Alias.Value - node.Alias = nil + if node.Alias != nil { + node.Kind = node.Alias.Kind + node.Style = node.Alias.Style + node.Tag = node.Alias.Tag + node.Content = node.Alias.Content + node.Value = node.Alias.Value + node.Alias = nil + } return nil case yaml.MappingNode: for index := 0; index < len(node.Content); index = index + 2 {