diff --git a/goyaml.v3/emitterc.go b/goyaml.v3/emitterc.go index 430591a..6ea0ae8 100644 --- a/goyaml.v3/emitterc.go +++ b/goyaml.v3/emitterc.go @@ -1160,8 +1160,15 @@ func yaml_emitter_process_head_comment(emitter *yaml_emitter_t) bool { } // Write an line comment. -func yaml_emitter_process_line_comment(emitter *yaml_emitter_t) bool { +func yaml_emitter_process_line_comment_linebreak(emitter *yaml_emitter_t, linebreak bool) bool { if len(emitter.line_comment) == 0 { + // The next 3 lines are needed to resolve an issue with leading newlines + // See https://github.com/go-yaml/yaml/issues/755 + // When linebreak is set to true, put_break will be called and will add + // the needed newline. + if linebreak && !put_break(emitter) { + return false + } return true } if !emitter.whitespace { @@ -1910,7 +1917,7 @@ func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bo if !yaml_emitter_write_block_scalar_hints(emitter, value) { return false } - if !yaml_emitter_process_line_comment(emitter) { + if !yaml_emitter_process_line_comment_linebreak(emitter, true) { return false } //emitter.indention = true @@ -1947,7 +1954,7 @@ func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) boo if !yaml_emitter_write_block_scalar_hints(emitter, value) { return false } - if !yaml_emitter_process_line_comment(emitter) { + if !yaml_emitter_process_line_comment_linebreak(emitter, true) { return false } diff --git a/goyaml.v3/patch.go b/goyaml.v3/patch.go index 208d8dd..b98c332 100644 --- a/goyaml.v3/patch.go +++ b/goyaml.v3/patch.go @@ -31,3 +31,9 @@ func (e *Encoder) CompactSeqIndent() { func (e *Encoder) DefaultSeqIndent() { e.encoder.emitter.compact_sequence_indent = false } + +// yaml_emitter_process_line_comment preserves the original signature and delegates to +// yaml_emitter_process_line_comment_linebreak passing false for linebreak +func yaml_emitter_process_line_comment(emitter *yaml_emitter_t) bool { + return yaml_emitter_process_line_comment_linebreak(emitter, false) +} diff --git a/goyaml.v3/patch_test.go b/goyaml.v3/patch_test.go index 08707dd..7220301 100644 --- a/goyaml.v3/patch_test.go +++ b/goyaml.v3/patch_test.go @@ -144,3 +144,17 @@ func (s *S) TestEncoderCompactIndents(c *C) { c.Assert(buf.String(), Equals, expected) } } + +func (s *S) TestNewLinePreserved(c *C) { + obj := &marshalerValue{} + obj.Field.value = "a:\n b:\n c: d\n" + data, err := yaml.Marshal(obj) + c.Assert(err, IsNil) + c.Assert(string(data), Equals, "_: |\n a:\n b:\n c: d\n") + + obj.Field.value = "\na:\n b:\n c: d\n" + data, err = yaml.Marshal(obj) + c.Assert(err, IsNil) + // the newline at the start of the file should be preserved + c.Assert(string(data), Equals, "_: |4\n\n a:\n b:\n c: d\n") +}