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

Encode: fix multiline comment #775

Merged
merged 1 commit into from May 10, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 11 additions & 2 deletions marshaler.go
Expand Up @@ -652,10 +652,19 @@ func (enc *Encoder) encodeStruct(b []byte, ctx encoderCtx, v reflect.Value) ([]b
}

func (enc *Encoder) encodeComment(indent int, comment string, b []byte) []byte {
if comment != "" {
for len(comment) > 0 {
var line string
idx := strings.IndexByte(comment, '\n')
if idx >= 0 {
line = comment[:idx]
comment = comment[idx+1:]
} else {
line = comment
comment = ""
}
b = enc.indent(indent, b)
b = append(b, "# "...)
b = append(b, comment...)
b = append(b, line...)
b = append(b, '\n')
}
return b
Expand Down
16 changes: 16 additions & 0 deletions marshaler_test.go
Expand Up @@ -1004,6 +1004,22 @@ func TestIssue752(t *testing.T) {
require.Equal(t, "", string(out))
}

func TestIssue768(t *testing.T) {
type cfg struct {
Name string `comment:"This is a multiline comment.\nThis is line 2."`
}

out, err := toml.Marshal(&cfg{})
require.NoError(t, err)

expected := `# This is a multiline comment.
# This is line 2.
Name = ''
`

require.Equal(t, expected, string(out))
}

func TestMarshalNestedAnonymousStructs(t *testing.T) {
type Embedded struct {
Value string `toml:"value" json:"value"`
Expand Down