Skip to content

Commit

Permalink
Merge pull request #318 from zoncoen/fix-encode
Browse files Browse the repository at this point in the history
fix: insert a separator between each encoded document
  • Loading branch information
goccy committed Oct 26, 2022
2 parents ecececd + 548aa05 commit 48a606c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
7 changes: 7 additions & 0 deletions encode.go
Expand Up @@ -39,6 +39,7 @@ type Encoder struct {
anchorPtrToNameMap map[uintptr]string
useLiteralStyleIfMultiline bool
commentMap map[*Path]*Comment
written bool

line int
column int
Expand Down Expand Up @@ -86,6 +87,12 @@ func (e *Encoder) EncodeContext(ctx context.Context, v interface{}) error {
if err := e.setCommentByCommentMap(node); err != nil {
return errors.Wrapf(err, "failed to set comment by comment map")
}
if !e.written {
e.written = true
} else {
// write document separator
e.writer.Write([]byte("---\n"))
}
var p printer.Printer
e.writer.Write(p.PrintNode(node))
return nil
Expand Down
14 changes: 14 additions & 0 deletions encode_test.go
Expand Up @@ -1094,6 +1094,20 @@ a:
}
}

func TestEncoder_MultipleDocuments(t *testing.T) {
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf)
if err := enc.Encode(1); err != nil {
t.Fatalf("failed to encode: %s", err)
}
if err := enc.Encode(2); err != nil {
t.Fatalf("failed to encode: %s", err)
}
if actual, expect := buf.String(), "1\n---\n2\n"; actual != expect {
t.Errorf("expect:\n%s\nactual\n%s\n", expect, actual)
}
}

func Example_Marshal_Node() {
type T struct {
Text ast.Node `yaml:"text"`
Expand Down

0 comments on commit 48a606c

Please sign in to comment.