From 44322f02484b851c13a8e1bb9a5fe4a485981257 Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Fri, 21 Feb 2020 11:02:10 +1100 Subject: [PATCH] Fixed writing to null document --- cmd/commands_test.go | 19 +++++++++++++++++++ cmd/utils.go | 10 +++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/cmd/commands_test.go b/cmd/commands_test.go index 27b4245c..d5267134 100644 --- a/cmd/commands_test.go +++ b/cmd/commands_test.go @@ -1245,6 +1245,25 @@ func TestWriteCmd(t *testing.T) { test.AssertResult(t, expectedOutput, result.Output) } +func TestWriteEmptyMultiDocCmd(t *testing.T) { + content := `# this is empty +--- +` + filename := test.WriteTempYamlFile(content) + defer test.RemoveTempYamlFile(filename) + + cmd := getRootCommand() + result := test.RunCmd(cmd, fmt.Sprintf("write %s c 7", filename)) + if result.Error != nil { + t.Error(result.Error) + } + expectedOutput := `c: 7 + +# this is empty +` + test.AssertResult(t, expectedOutput, result.Output) +} + func TestWriteFromFileCmd(t *testing.T) { content := `b: c: 3 diff --git a/cmd/utils.go b/cmd/utils.go index cb753056..5a5800ab 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -199,6 +199,11 @@ func parseDocumentIndex() (bool, int, error) { type updateDataFn func(dataBucket *yaml.Node, currentIndex int) error +func isNullDocument(dataBucket *yaml.Node) bool { + return dataBucket.Kind == yaml.DocumentNode && (len(dataBucket.Content) == 0 || + dataBucket.Content[0].Kind == yaml.ScalarNode && dataBucket.Content[0].Tag == "!!null") +} + func mapYamlDecoder(updateData updateDataFn, encoder yqlib.Encoder) yamlDecoderFn { return func(decoder *yaml.Decoder) error { var dataBucket yaml.Node @@ -218,8 +223,11 @@ func mapYamlDecoder(updateData updateDataFn, encoder yqlib.Encoder) yamlDecoderF if errorReading == io.EOF && docIndexInt == 0 && currentIndex == 0 { //empty document, lets just make one - child := yaml.Node{Kind: yaml.MappingNode} dataBucket = yaml.Node{Kind: yaml.DocumentNode, Content: make([]*yaml.Node, 1)} + child := yaml.Node{Kind: yaml.MappingNode} + dataBucket.Content[0] = &child + } else if isNullDocument(&dataBucket) { + child := yaml.Node{Kind: yaml.MappingNode} dataBucket.Content[0] = &child } else if errorReading == io.EOF { if !updateAll && currentIndex <= docIndexInt {