hcl/printer: print lead comments for lists properly

This commit is contained in:
Mitchell Hashimoto 2016-10-08 14:47:58 +08:00
parent 8d4635e72c
commit 26fb5a83d4
No known key found for this signature in database
GPG Key ID: 744E147AA52F5B0A
4 changed files with 44 additions and 0 deletions

View File

@ -62,6 +62,14 @@ func (p *printer) collectComments(node ast.Node) {
ast.Walk(node, func(nn ast.Node) (ast.Node, bool) {
switch t := nn.(type) {
case *ast.LiteralType:
if t.LeadComment != nil {
for _, comment := range t.LeadComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
delete(standaloneComments, comment.Pos())
}
}
}
if t.LineComment != nil {
for _, comment := range t.LineComment.List {
if _, ok := standaloneComments[comment.Pos()]; ok {
@ -445,6 +453,17 @@ func (p *printer) list(l *ast.ListType) []byte {
// multiline list, add newline before we add each item
buf.WriteByte(newline)
insertSpaceBeforeItem = false
// If we have a lead comment, then we want to write that first
leadComment := false
if lit, ok := item.(*ast.LiteralType); ok && lit.LeadComment != nil {
leadComment = true
for _, comment := range lit.LeadComment.List {
buf.Write(p.indent([]byte(comment.Text)))
buf.WriteByte(newline)
}
}
// also indent each line
val := p.output(item)
curLen := len(val)
@ -466,6 +485,10 @@ func (p *printer) list(l *ast.ListType) []byte {
if i == len(l.List)-1 {
buf.WriteByte(newline)
}
if leadComment {
buf.WriteByte(newline)
}
} else {
if insertSpaceBeforeItem {
buf.WriteByte(blank)

View File

@ -33,6 +33,7 @@ var data = []entry{
{"list.input", "list.golden"},
{"comment.input", "comment.golden"},
{"comment_aligned.input", "comment_aligned.golden"},
{"comment_array.input", "comment_array.golden"},
{"comment_newline.input", "comment_newline.golden"},
{"comment_standalone.input", "comment_standalone.golden"},
{"empty_block.input", "empty_block.golden"},

View File

@ -0,0 +1,10 @@
banana = [
# I really want to comment this item in the array.
"a",
# This as well
"b",
"c", # And C
"d",
]

View File

@ -0,0 +1,10 @@
banana = [
# I really want to comment this item in the array.
"a",
# This as well
"b",
"c", # And C
"d",
]