Skip to content

Commit

Permalink
basic: Support formatting multi-document files (#19)
Browse files Browse the repository at this point in the history
Files with multiple documents are more common than I originally thought,
so it is best that I switch to Decode and Encode for this formatter that
will properly format all documents in multi-document files.
  • Loading branch information
braydonk committed Aug 23, 2022
1 parent fcac9d5 commit 79d0e08
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 7 deletions.
28 changes: 21 additions & 7 deletions formatters/basic/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ package basic

import (
"bytes"
"errors"
"io"

"gopkg.in/yaml.v3"
)
Expand All @@ -31,17 +33,29 @@ func (f *BasicFormatter) Type() string {
}

func (f *BasicFormatter) Format(yamlContent []byte) ([]byte, error) {
var unmarshalled yaml.Node
err := yaml.Unmarshal(yamlContent, &unmarshalled)
if err != nil {
return nil, err
decoder := yaml.NewDecoder(bytes.NewReader(yamlContent))
documents := []yaml.Node{}
for {
var docNode yaml.Node
err := decoder.Decode(&docNode)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, err
}
documents = append(documents, docNode)
}

var b bytes.Buffer
e := yaml.NewEncoder(&b)
e.SetIndent(f.Config.Indent)
err = e.Encode(&unmarshalled)
if err != nil {
return nil, err
for _, doc := range documents {
err := e.Encode(&doc)
if err != nil {
return nil, err
}
}

return b.Bytes(), nil
}
16 changes: 16 additions & 0 deletions formatters/basic/formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,19 @@ a:`
t.Fatalf("keys were reordered:\n%s", s)
}
}

func TestFormatterParsesMultipleDocuments(t *testing.T) {
f := &basic.BasicFormatter{Config: basic.DefaultConfig()}

yaml := `b:
---
a:
`
s, err := f.Format([]byte(yaml))
if err != nil {
t.Fatalf("expected formatting to pass, returned error: %v", err)
}
if len(s) != len([]byte(yaml)) {
t.Fatalf("expected yaml not to change, result: %s", string(s))
}
}

0 comments on commit 79d0e08

Please sign in to comment.