Skip to content

Commit

Permalink
Don't trim all space characters in SequenceNode.blockStyleString (#361)
Browse files Browse the repository at this point in the history
* Don't trim all space characters in SequenceNode.blockStyleString

This fixes #356.
The code would have removed more spaces than it added.

A better solution long-term would probably be to add a specialized
method to StringNode to not add the prefix in the first place.

* Add issue 356 test case for block with first empty line

The indentation level in a block scalar is determined by the first
non-empty line.
  • Loading branch information
martin-sucha committed Mar 21, 2023
1 parent 7a084f4 commit 3ca6a75
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
3 changes: 2 additions & 1 deletion ast/ast.go
Expand Up @@ -1570,8 +1570,9 @@ func (n *SequenceNode) blockStyleString() string {
diffLength := len(splittedValues[0]) - len(trimmedFirstValue)
if len(splittedValues) > 1 && value.Type() == StringType || value.Type() == LiteralType {
// If multi-line string, the space characters for indent have already been added, so delete them.
prefix := space + " "
for i := 1; i < len(splittedValues); i++ {
splittedValues[i] = strings.TrimLeft(splittedValues[i], " ")
splittedValues[i] = strings.TrimPrefix(splittedValues[i], prefix)
}
}
newValues := []string{trimmedFirstValue}
Expand Down
41 changes: 41 additions & 0 deletions encode_test.go
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"fmt"
"github.com/goccy/go-yaml/parser"
"math"
"reflect"
"strconv"
Expand Down Expand Up @@ -1399,6 +1400,46 @@ func Example_MarshalYAML() {
// field: 13
}

func TestIssue356(t *testing.T) {
tests := map[string]struct {
in string
}{
"content on first line": {
in: `args:
- |
key:
nest1: something
nest2:
nest2a: b
`,
},
"empty first line": {
in: `args:
- |
key:
nest1: something
nest2:
nest2a: b
`,
},
}

for name, test := range tests {
t.Run(name, func(t *testing.T) {
f, err := parser.ParseBytes([]byte(test.in), 0)
if err != nil {
t.Fatalf("parse: %v", err)
}
got := f.String()
if test.in != got {
t.Fatalf("failed to encode.\nexpected:\n%s\nbut got:\n%s\n", test.in, got)
}
})
}
}

func TestMarshalIndentWithMultipleText(t *testing.T) {
t.Run("depth1", func(t *testing.T) {
b, err := yaml.MarshalWithOptions(map[string]interface{}{
Expand Down

0 comments on commit 3ca6a75

Please sign in to comment.