From 7951a6db0d852a5a0773e14245af889638372e51 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Fri, 25 Sep 2020 16:12:51 -0700 Subject: [PATCH] command/fmt: Format using the full hclwrite syntax tree Previously we were just using hclwrite.Format, a token-only formatting pass. Now we'll do that via the full hclwrite parser, getting the formatting as a side-effect of the parsing and re-serialization. This should have no change in observable behavior as-is, but in a future commit we'll add some additional processing rules that modify the syntax tree before re-serializing it. --- command/fmt.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/command/fmt.go b/command/fmt.go index b95b57a19..b31b025c7 100644 --- a/command/fmt.go +++ b/command/fmt.go @@ -176,7 +176,7 @@ func (c *FmtCommand) processFile(path string, r io.Reader, w io.Writer, isStdout return diags } - result := c.formatSourceCode(src) + result := c.formatSourceCode(src, path) if !bytes.Equal(src, result) { // Something was changed @@ -268,8 +268,16 @@ func (c *FmtCommand) processDir(path string, stdout io.Writer) tfdiags.Diagnosti // formatSourceCode is the formatting logic itself, applied to each file that // is selected (directly or indirectly) on the command line. -func (c *FmtCommand) formatSourceCode(src []byte) []byte { - return hclwrite.Format(src) +func (c *FmtCommand) formatSourceCode(src []byte, filename string) []byte { + f, diags := hclwrite.ParseConfig(src, filename, hcl.InitialPos) + if diags.HasErrors() { + // It would be weird to get here because the caller should already have + // checked for syntax errors and returned them. We'll just do nothing + // in this case, returning the input exactly as given. + return src + } + + return f.Bytes() } func (c *FmtCommand) Help() string {