Skip to content

Commit

Permalink
hcl/printer: preserve list comment on first line
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchellh committed Jan 25, 2017
1 parent 4f21d59 commit efcf294
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 1 deletion.
17 changes: 16 additions & 1 deletion hcl/printer/nodes.go
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,10 @@ func (p *printer) list(l *ast.ListType) []byte {
}

// Output the item itself
buf.Write(p.output(item))
// also indent each line
val := p.output(item)
curLen := len(val)
buf.Write(val)

// If this is a heredoc item we always have to output a newline
// so that it parses properly.
Expand All @@ -592,6 +595,18 @@ func (p *printer) list(l *ast.ListType) []byte {
buf.WriteString(",")
insertSpaceBeforeItem = true
}

if lit, ok := item.(*ast.LiteralType); ok && lit.LineComment != nil {
// if the next item doesn't have any comments, do not align
buf.WriteByte(blank) // align one space
for i := 0; i < longestLine-curLen; i++ {
buf.WriteByte(blank)
}

for _, comment := range lit.LineComment.List {
buf.WriteString(comment.Text)
}
}
}

}
Expand Down
1 change: 1 addition & 0 deletions hcl/printer/printer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type entry struct {
var data = []entry{
{"complexhcl.input", "complexhcl.golden"},
{"list.input", "list.golden"},
{"list_comment.input", "list_comment.golden"},
{"comment.input", "comment.golden"},
{"comment_aligned.input", "comment_aligned.golden"},
{"comment_array.input", "comment_array.golden"},
Expand Down
7 changes: 7 additions & 0 deletions hcl/printer/testdata/list_comment.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
foo = [1, # Hello
2,
]

foo = [1, # Hello
2, # World
]
6 changes: 6 additions & 0 deletions hcl/printer/testdata/list_comment.input
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
foo = [1, # Hello
2]

foo = [1, # Hello
2, # World
]

0 comments on commit efcf294

Please sign in to comment.