Skip to content

Commit

Permalink
fmt: print parse errors on error
Browse files Browse the repository at this point in the history
The fmt command reformats HCL2 templates, provided it can parse the file
and reformat its contents according to the standards set by the HCL
library's formatters.

However, if the file is malformed for some reason, the command will fail
with a parse error, but while the parse error message is shown, the
actual errors in the template(s) are not forwarded, making it hard for
users to understand what went wrong with the contents of the file
they're trying to format.

In order to be more helpful with those errors, we now forward those
parsing errors to the UI.
  • Loading branch information
lbajolet-hashicorp committed Mar 7, 2024
1 parent e3c8d9b commit ea1e798
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
15 changes: 15 additions & 0 deletions command/fmt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,18 @@ func Test_fmt_pipe(t *testing.T) {
})
}
}

const malformedTemplate = "test-fixtures/fmt_errs/malformed.pkr.hcl"

func TestFmtParseError(t *testing.T) {
p := helperCommand(t, "fmt", malformedTemplate)
outs, err := p.CombinedOutput()
if err == nil {
t.Errorf("Expected failure to format file, but command did not fail")
}
strLogs := string(outs)

if !strings.Contains(strLogs, "An argument or block definition is required here.") {
t.Errorf("Expected some diags about parse error, found none")
}
}
14 changes: 14 additions & 0 deletions command/test-fixtures/fmt_errs/malformed.pkr.hcl
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
variable "region" {
type =string
}

invalid

source "amazon-ebs" "example" {
region = var.region
}

build {
sources = ["source.amazon-ebs.example"]
}

3 changes: 2 additions & 1 deletion hcl2template/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"path/filepath"
"strings"

"github.com/hashicorp/go-multierror"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/hashicorp/hcl/v2/hclwrite"
Expand Down Expand Up @@ -135,7 +136,7 @@ func (f *HCL2Formatter) processFile(filename string) ([]byte, error) {

_, diags := f.parser.ParseHCL(inSrc, filename)
if diags.HasErrors() {
return nil, fmt.Errorf("failed to parse HCL %s", filename)
return nil, multierror.Append(nil, diags.Errs()...)
}

outSrc := hclwrite.Format(inSrc)
Expand Down

0 comments on commit ea1e798

Please sign in to comment.