From b51a96373503f50594df5c18a07ad6e6a7395517 Mon Sep 17 00:00:00 2001 From: alstephenclaypool <41022275+alstephenclaypool@users.noreply.github.com> Date: Wed, 20 Sep 2023 19:01:11 -0400 Subject: [PATCH] fix empty yaml on documents with comment only sections (#166) * fix empty yaml when running vals eval on documents with comment only sections Signed-off-by: Stephen Claypool * add tests for nodesFromReader Signed-off-by: Stephen Claypool --------- Signed-off-by: Stephen Claypool --- io.go | 4 +++- io_test.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/io.go b/io.go index 5e0519e..cf73e89 100644 --- a/io.go +++ b/io.go @@ -69,7 +69,9 @@ func nodesFromReader(reader io.Reader) ([]yaml.Node, error) { } break } - nodes = append(nodes, node) + if len(node.Content[0].Content) > 0 { + nodes = append(nodes, node) + } } return nodes, nil } diff --git a/io_test.go b/io_test.go index 2e6d981..9f9e1e0 100644 --- a/io_test.go +++ b/io_test.go @@ -77,3 +77,53 @@ func Test_InputOutput(t *testing.T) { }) } } + +func Test_NodesFromReader(t *testing.T) { + simpleDocument := "---\nfoo: bar\n" + commentDocument := "---\n# comment\n" + + tests := []struct { + name string + input string + nodes int + }{ + { + name: "single document", + input: simpleDocument, + nodes: 1, + }, + { + name: "multi document", + input: simpleDocument + simpleDocument, + nodes: 2, + }, + { + name: "single comment document", + input: commentDocument, + nodes: 0, + }, + { + name: "multiple comment document", + input: commentDocument + commentDocument, + nodes: 0, + }, + { + name: "mixed documents", + input: simpleDocument + commentDocument, + nodes: 1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + nodes, err := nodesFromReader(strings.NewReader(tt.input)) + if err != nil { + t.Fatal(err) + } + + if len(nodes) != tt.nodes { + t.Errorf("Expected %v nodes, got %v", tt.nodes, len(nodes)) + } + }) + } +}