Skip to content

Commit

Permalink
Don't trim all space characters in SequenceNode.blockStyleString
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
martin-sucha committed Mar 13, 2023
1 parent 11ad39b commit 921b006
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
3 changes: 2 additions & 1 deletion ast/ast.go
Original file line number Diff line number Diff line change
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
19 changes: 19 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
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,24 @@ func Example_MarshalYAML() {
// field: 13
}

func TestIssue356(t *testing.T) {
in := `args:
- |
key:
nest1: something
nest2:
nest2a: b
`
f, err := parser.ParseBytes([]byte(in), 0)
if err != nil {
t.Fatalf("parse: %v", err)
}
got := f.String()
if in != got {
t.Fatalf("failed to encode.\nexpected:\n%s\nbut got:\n%s\n", 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 921b006

Please sign in to comment.