Support rejecting unknown key feature
I think it would be nice to support the rejecting unknown key feature like DisallowUnknownFields() of encoding/json as below:
err := hcl.hasUnknownKey(structure, input)
If you don't plan to support this feature, I would like to know if there is a way to reject unknown key using current features.
Hi @ryysud!
I think you're asking this about HCL v1 and so I've labelled it as such.
HCL v2 already has such a feature and this is in fact the default behavior in package hclsimple. For that API, the opt-in to allow arguments that are not covered by the target type is to add a new field to capture them:
type Example struct {
// (any attributes you specifically want to capture)
Remain hcl.Body `"hcl:,remain"`
}
The hcl.Body written into Remain can then be used for additional decoding of the leftover parts.
HCL v1 is largely feature-frozen at this point, because new development is happening in v2. Therefore if it isn't already available in that version then it's unlikely to be added in future. I'm not sure if such a feature is available in v1 or not, though. I think you could work around it by adding a []string field with a tag like "hcl:,unusedKeys" and then raising an error if it's not empty after decoding succeeds, but I'm not too familiar with that feature.
HCL v2 already has such a feature and this is in fact the default behavior in package hclsimple.
That's great! I will use HCL v2.
I think you could work around it by adding a []string field with a tag like "hcl:,unusedKeys" and then raising an error if it's not empty after decoding succeeds, but I'm not too familiar with that feature.
Thank you for the workaround.
I think you could work around it by adding a []string field with a tag like "hcl:,unusedKeys" and then raising an error if it's not empty after decoding succeeds, but I'm not too familiar with that feature.
For what it's worth, it looks like the unused keys feature incorrectly interprets map shorthand as unused keys. For example, the following results in item1 and name1 being set as unused keys:
item1 "name1" {
...
}
But the following syntax, which IIUC is functionally identical, does not:
item1 {
name1 {
...
}
}
HCL 1 historically made claims about treating certain constructs as equivalent to others, but in practice those claims do not hold consistently. HCL 1's decoding model is flawed, and that is why we redesigned it completely for HCL 2.