From 548aa0527d111fc8e1e6d3c23cfd51eb589d305a Mon Sep 17 00:00:00 2001 From: zoncoen Date: Tue, 25 Oct 2022 00:51:54 +0900 Subject: [PATCH] fix: insert a separator between each encoded document Fix the behavior as the comment. --- encode.go | 7 +++++++ encode_test.go | 14 ++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/encode.go b/encode.go index f582b48..221706b 100644 --- a/encode.go +++ b/encode.go @@ -39,6 +39,7 @@ type Encoder struct { anchorPtrToNameMap map[uintptr]string useLiteralStyleIfMultiline bool commentMap map[*Path]*Comment + written bool line int column int @@ -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 diff --git a/encode_test.go b/encode_test.go index 2edb9a2..3720d41 100644 --- a/encode_test.go +++ b/encode_test.go @@ -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"`