hcl icon indicating copy to clipboard operation
hcl copied to clipboard

Prevent hidden blocks from causing an error in hcl.Body.JustAttributes

Open Andrew-Morozko opened this issue 1 year ago • 1 comments

Currently hcl.Body.JustAttributes produces an error if there are any blocks in the hcl.Body. It seems to me that this is incorrect: we should produce an error only if there are non-hidden blocks in the body.

Motivating example
package main

import (
	"fmt"
	"os"

	"github.com/hashicorp/hcl/v2"
	"github.com/hashicorp/hcl/v2/gohcl"
	"github.com/hashicorp/hcl/v2/hclsyntax"
)

func dieOnError(diags hcl.Diagnostics) {
	if diags.HasErrors() {
		fmt.Println("Error:", diags)
		os.Exit(1)
	}
}

type Inner struct {
	Foo string `hcl:"foo"`
}

type Example struct {
	Inner Inner    `hcl:"inner,block"`
	Rest  hcl.Body `hcl:",remain"`
}

func main() {
	f, diag := hclsyntax.ParseConfig(
		[]byte(`
inner {
	foo = "foo"
}
bar = "bar"
`),
		"example.hcl",
		hcl.InitialPos,
	)
	dieOnError(diag)

	var ex Example
	diag = gohcl.DecodeBody(f.Body, nil, &ex)
	dieOnError(diag)

	attrs, diag := ex.Rest.JustAttributes()
	fmt.Printf("attrs are correct: %+v\n", attrs)
	dieOnError(diag)
}

Expected output:

attrs are correct: map[bar:0xc0000ea320]

Current output:

attrs are correct: map[bar:0xc0000ea320]
Error: example.hcl:2,1-6: Unexpected "inner" block; Blocks are not allowed here.

I'm not that experienced with HCL, but it seems like a bug in JustAttributes implementation

Andrew-Morozko avatar Dec 20 '23 11:12 Andrew-Morozko

CLA assistant check
All committers have signed the CLA.

hashicorp-cla avatar Dec 20 '23 11:12 hashicorp-cla