From 314ea6f332adda5d78045e80a1ef69f2c9064800 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Sat, 14 Jul 2018 15:01:27 -0700 Subject: [PATCH] hclwrite: Allow format to be called on fragment of tokens --- hclwrite/format.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/hclwrite/format.go b/hclwrite/format.go index 178cb2a..d9235ec 100644 --- a/hclwrite/format.go +++ b/hclwrite/format.go @@ -296,8 +296,6 @@ func spaceAfterToken(subject, before, after *Token) bool { func linesForFormat(tokens Tokens) []formatLine { if len(tokens) == 0 { - // should never happen, since we should always have EOF, but let's - // not crash anyway. return make([]formatLine, 0) } @@ -331,6 +329,16 @@ func linesForFormat(tokens Tokens) []formatLine { } } + // If a set of tokens doesn't end in TokenEOF (e.g. because it's a + // fragment of tokens from the middle of a file) then we might fall + // out here with a line still pending. + if lineStart < len(tokens) { + lines[li].lead = tokens[lineStart:] + if lines[li].lead[len(lines[li].lead)-1].Type == hclsyntax.TokenEOF { + lines[li].lead = lines[li].lead[:len(lines[li].lead)-1] + } + } + // Now we'll pick off any trailing comments and attribute assignments // to shuffle off into the "comment" and "assign" cells. for i := range lines {