Skip to content

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

Open
Andrew-Morozko wants to merge 1 commit into
hashicorp:mainfrom
Andrew-Morozko:main
Open

Prevent hidden blocks from causing an error in hcl.Body.JustAttributes#646
Andrew-Morozko wants to merge 1 commit into
hashicorp:mainfrom
Andrew-Morozko:main

Conversation

@Andrew-Morozko

Copy link
Copy Markdown

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

Take into account the hidden status of the blocks while producing
diagnostics in JustAttributes
@hashicorp-cla

hashicorp-cla commented Dec 20, 2023

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants