Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix encoding of sequence with multiline string #276

Merged
merged 1 commit into from
Jan 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
})
}