Skip to content

Commit

Permalink
Merge pull request #276 from goccy/feature/fix-encoding-multiline-string
Browse files Browse the repository at this point in the history
Fix encoding of sequence with multiline string
  • Loading branch information
goccy authored Jan 11, 2022
2 parents 251b4db + 9bcbd0a commit c7fe9bf
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
6 changes: 6 additions & 0 deletions ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -1586,6 +1586,12 @@ func (n *SequenceNode) blockStyleString() string {
splittedValues := strings.Split(valueStr, "\n")
trimmedFirstValue := strings.TrimLeft(splittedValues[0], " ")
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.
for i := 1; i < len(splittedValues); i++ {
splittedValues[i] = strings.TrimLeft(splittedValues[i], " ")
}
}
newValues := []string{trimmedFirstValue}
for i := 1; i < len(splittedValues); i++ {
if len(splittedValues[i]) <= diffLength {
Expand Down
46 changes: 46 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1302,3 +1302,49 @@ func Example_MarshalYAML() {
//
// field: 13
}

func TestMarshalIndentWithMultipleText(t *testing.T) {
t.Run("depth1", func(t *testing.T) {
b, err := yaml.MarshalWithOptions(map[string]interface{}{
"key": []string{`line1
line2
line3`},
}, yaml.Indent(2))
if err != nil {
t.Fatal(err)
}
got := string(b)
expected := `key:
- |-
line1
line2
line3
`
if expected != got {
t.Fatalf("failed to encode.\nexpected:\n%s\nbut got:\n%s\n", expected, got)
}
})
t.Run("depth2", func(t *testing.T) {
b, err := yaml.MarshalWithOptions(map[string]interface{}{
"key": map[string]interface{}{
"key2": []string{`line1
line2
line3`},
},
}, yaml.Indent(2))
if err != nil {
t.Fatal(err)
}
got := string(b)
expected := `key:
key2:
- |-
line1
line2
line3
`
if expected != got {
t.Fatalf("failed to encode.\nexpected:\n%s\nbut got:\n%s\n", expected, got)
}
})
}

0 comments on commit c7fe9bf

Please sign in to comment.