Skip to content

Commit

Permalink
🐛 Fix corruption when map or seq templating changes the style
Browse files Browse the repository at this point in the history
  • Loading branch information
gabe565 committed Sep 2, 2022
1 parent 67cbd8b commit 1ed90ce
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
25 changes: 25 additions & 0 deletions internal/node/has_comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,3 +61,28 @@ func GetCommentTmpl(prefix string, n *yaml.Node) (string, TmplTag) {
}
return "", DynamicTag
}

// MoveComment moves a comment between yaml.Node entries after a style change.
// When a yaml.MappingNode or yaml.SequenceNode has an inline comment,
// the decoder will set LineComment differently according to the node's style.
//
// When value(s) are on a single line (flow style), LineComment will be set on the value.
// When value(s) are on multiple lines (block style), LineComment will be set on the key.
//
// If templating changes the node's style, the comment needs to move or else
// encoding errors will occur.
func MoveComment(key, val *yaml.Node) {
if val.Kind != yaml.SequenceNode && val.Kind != yaml.MappingNode {
return
}

if len(val.Content) > 0 && val.LineComment != "" && key.LineComment == "" {
// Flow to block style: move comment from value to key.
key.LineComment = val.LineComment
val.LineComment = ""
} else if len(val.Content) == 0 && key.LineComment != "" && val.LineComment == "" {
// Block to flow style: move comment from key to value.
val.LineComment = key.LineComment
key.LineComment = ""
}
}
5 changes: 4 additions & 1 deletion internal/visitor/template_comments.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,17 @@ func (t TemplateComments) Run(n *yaml.Node) error {
}
} else {
// Current node was templated, do not need to traverse children
node.MoveComment(key, val)
continue
}
}

// Key did not have comment, run again with value.
// Key did not have comment, traversing children.
if err := t.Run(val); err != nil {
return err
}

node.MoveComment(key, val)
}
default:
for _, n := range n.Content {
Expand Down

0 comments on commit 1ed90ce

Please sign in to comment.