diff --git a/encode.go b/encode.go index 8a5db9d0..8282c10e 100644 --- a/encode.go +++ b/encode.go @@ -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 diff --git a/encode_test.go b/encode_test.go index 3d8bfa49..8d3f4a9f 100644 --- a/encode_test.go +++ b/encode_test.go @@ -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{