diff --git a/hcl/printer/nodes.go b/hcl/printer/nodes.go index 708816b1..eea4f5cc 100644 --- a/hcl/printer/nodes.go +++ b/hcl/printer/nodes.go @@ -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. @@ -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) + } + } } } diff --git a/hcl/printer/printer_test.go b/hcl/printer/printer_test.go index fbcaa3cb..6189acb9 100644 --- a/hcl/printer/printer_test.go +++ b/hcl/printer/printer_test.go @@ -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"}, diff --git a/hcl/printer/testdata/list_comment.golden b/hcl/printer/testdata/list_comment.golden new file mode 100644 index 00000000..e5753c91 --- /dev/null +++ b/hcl/printer/testdata/list_comment.golden @@ -0,0 +1,7 @@ +foo = [1, # Hello + 2, +] + +foo = [1, # Hello + 2, # World +] diff --git a/hcl/printer/testdata/list_comment.input b/hcl/printer/testdata/list_comment.input new file mode 100644 index 00000000..1d636c88 --- /dev/null +++ b/hcl/printer/testdata/list_comment.input @@ -0,0 +1,6 @@ +foo = [1, # Hello +2] + +foo = [1, # Hello +2, # World +]