hashicorp / hcl2

Former temporary home for experimental new version of HCL
https://github.com/hashicorp/hcl
Mozilla Public License 2.0
373 stars 66 forks source link

Format doesn't correct handle block content after newline #83

Closed nathkn closed 5 years ago

nathkn commented 5 years ago

My apologies if this is a known issue.

using github.com/hashicorp/hcl2 v0.0.0-20190130225218-89dbc5eb3d9e

Given the following HCL

service "foo"
{
    content = "bar"
}

hclwrite.format does not correctly move the bracket '{' to the same line as the block, making the following example fail:

func main() {
    testContent := []byte(`service "foo"
{
    content = "bar"
}`)

    formattedContent := hclwrite.Format(testContent)
    p := hclparse.NewParser()
    _, diags := p.ParseHCL(formattedContent, "test-file.hcl")
    if diags.HasErrors() {
        fmt.Printf("error parsing hcl file: %v", diags.Error())
    }
}

result:

error parsing hcl file: test-file.hcl:1,14-2,1: Invalid block definition; A block definition must have block content delimited by "{" and "}", starting on the same line as the block header.

Using HCL v1, this works with

formattedContent, _ := printer.Format(testContent)
apparentlymart commented 5 years ago

Hi @nathkn,

In HCL 2 the input you gave here is considered a syntax error, not a style decision: the brace is always required to be on the same line as the header it belongs to, as the error message suggests.

The formatter only produces defined results for valid input, so this behavior is expected... you should always test the input for valid syntax using the parser before calling hclwrite.Format on it.

nathkn commented 5 years ago

Good to know!

I had thought that it was the kind of syntax error that the formatter would pick up (since in v1 I was using github.com/hashicorp/hcl/hcl/printer, which does fix the syntax error). I'll make sure to verify accordingly.