diff --git a/command/fmt_test.go b/command/fmt_test.go index 7d9f3b11979..36497bc80dd 100644 --- a/command/fmt_test.go +++ b/command/fmt_test.go @@ -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") + } +} diff --git a/command/test-fixtures/fmt_errs/malformed.pkr.hcl b/command/test-fixtures/fmt_errs/malformed.pkr.hcl new file mode 100644 index 00000000000..78bff46e974 --- /dev/null +++ b/command/test-fixtures/fmt_errs/malformed.pkr.hcl @@ -0,0 +1,14 @@ +variable "region" { + type =string +} + +invalid + +source "amazon-ebs" "example" { + region = var.region +} + +build { + sources = ["source.amazon-ebs.example"] +} + diff --git a/hcl2template/formatter.go b/hcl2template/formatter.go index c04bb114748..3835aea8b55 100644 --- a/hcl2template/formatter.go +++ b/hcl2template/formatter.go @@ -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" @@ -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)