Skip to content
This repository has been archived by the owner on Apr 27, 2021. It is now read-only.

Commit

Permalink
Merge pull request #5 from r6min/fix-comment-marshalling
Browse files Browse the repository at this point in the history
Fix marshalling for comments preceding sequenced items with keys
  • Loading branch information
nschhina authored May 28, 2019
2 parents 1aafb9d + 99c50ba commit 4d5fdf9
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
20 changes: 20 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,26 @@ func (e *encoder) sequenceitemv(tag string, in reflect.Value) {
continue
}

// Check if the value is a MapSlice
if reflect.TypeOf(item.Value) == reflect.TypeOf(MapSlice{}) {
itemSlice := item.Value.(MapSlice)
endIndex := 0

for index, subItem := range itemSlice {
endIndex = index

// check if the value is a comment
if subItem.Value == nil && len(subItem.Comment) > 0 {
// If the subitem is a comment, add it before beginning the sequence
e.commentv([]byte(subItem.Comment))
} else {
break
}
}
// remove all comments to avoid double printing
item.Value = itemSlice[endIndex:len(itemSlice)]
}

e.marshal("", reflect.ValueOf(item.Value))

// Note that empty end-of-line comments are ignored
Expand Down
21 changes: 21 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,27 @@ var marshalTests = []struct {
},
"a:\n b:\n # my comment\n - 3\n # my comment 2\n - 8\n",
},
{ // sequence containing mapitems preceded by comments
&yaml.MapSlice{
{Key: "a", Value: yaml.MapSlice{
{Key: "b", Value: []yaml.SequenceItem{
{Value: yaml.MapSlice{
{Key: nil, Value: nil, Comment: " my comment"},
{Key: nil, Value: nil, Comment: " my comment 2"},
{Key: "a", Value: 3, Comment: ""},
{Key: "b", Value: 7, Comment: ""},
{Key: nil, Value: nil, Comment: " my comment 3"},
}, Comment: ""},
{Value: yaml.MapSlice{
{Key: nil, Value: nil, Comment: " my comment 4"},
{Key: "a", Value: 9, Comment: ""},
{Key: "b", Value: 2, Comment: ""},
}, Comment: ""},
}, Comment: ""},
}, Comment: ""},
},
"a:\n b:\n # my comment\n # my comment 2\n - a: 3\n b: 7\n # my comment 3\n # my comment 4\n - a: 9\n b: 2\n",
},
{ // key comment (non-primitive value)
&yaml.MapSlice{
{Key: "a", Value: yaml.MapSlice{
Expand Down

0 comments on commit 4d5fdf9

Please sign in to comment.