Skip to content

Commit df1465d

Browse files
authored
formatters/basic: fix just comments edge case (google#259)
When `yaml.v3` parses a document that's just comments, it ends up parsing no actual nodes and thus loses the comment information. This will now be treated as an edge case and return the original content, in essence not modifying it if the yaml parsed successfully but no nodes are parsed out.
1 parent a11f0e0 commit df1465d

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

formatters/basic/formatter.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,10 @@ func (f *BasicFormatter) Format(input []byte) ([]byte, error) {
6464
documents = append(documents, docNode)
6565
}
6666

67+
if len(documents) == 0 {
68+
return input, nil
69+
}
70+
6771
// Run all YAML features.
6872
for _, d := range documents {
6973
if err := f.YAMLFeatures.ApplyFeatures(d); err != nil {

formatters/basic/formatter_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,3 +455,17 @@ b:
455455
t.Fatalf("expected: '%s', got: '%s'", expectedYml, result)
456456
}
457457
}
458+
459+
func TestJustComments(t *testing.T) {
460+
config := basic.DefaultConfig()
461+
f := newFormatter(config)
462+
463+
yml := `# hi`
464+
expectedYml := `# hi`
465+
result, err := f.Format([]byte(yml))
466+
assert.NilErr(t, err)
467+
resultStr := string(result)
468+
if resultStr != expectedYml {
469+
t.Fatalf("expected: '%s', got: '%s'", expectedYml, result)
470+
}
471+
}

0 commit comments

Comments
 (0)