Skip to content

Commit

Permalink
gohcl: Fix docs about supported types for blocks.
Browse files Browse the repository at this point in the history
This commit fixes a clause in the `gohcl` package documentation which incorrectly
states that HCL blocks could be decoded into `hcl.Body` and `hcl.Block` types.

It also removes some code paths in `decodeBlockToValue()` that _appeared_ to
handled these cases. In practice, these paths were unreachable anyway due to
various reflection-based type checks made before `decodeBlockToValue()` is
called.
  • Loading branch information
jmalloc committed Mar 6, 2022
1 parent 633d41d commit 163105d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 29 deletions.
30 changes: 6 additions & 24 deletions gohcl/decode.go
Expand Up @@ -258,32 +258,14 @@ func decodeBodyToMap(body hcl.Body, ctx *hcl.EvalContext, v reflect.Value) hcl.D
}

func decodeBlockToValue(block *hcl.Block, ctx *hcl.EvalContext, v reflect.Value) hcl.Diagnostics {
var diags hcl.Diagnostics

ty := v.Type()

switch {
case blockType.AssignableTo(ty):
v.Elem().Set(reflect.ValueOf(block))
case bodyType.AssignableTo(ty):
v.Elem().Set(reflect.ValueOf(block.Body))
case attrsType.AssignableTo(ty):
attrs, attrsDiags := block.Body.JustAttributes()
if len(attrsDiags) > 0 {
diags = append(diags, attrsDiags...)
}
v.Elem().Set(reflect.ValueOf(attrs))
default:
diags = append(diags, decodeBodyToValue(block.Body, ctx, v)...)
diags := decodeBodyToValue(block.Body, ctx, v)

if len(block.Labels) > 0 {
blockTags := getFieldTags(ty)
for li, lv := range block.Labels {
lfieldIdx := blockTags.Labels[li].FieldIndex
v.Field(lfieldIdx).Set(reflect.ValueOf(lv))
}
if len(block.Labels) > 0 {
blockTags := getFieldTags(v.Type())
for li, lv := range block.Labels {
lfieldIdx := blockTags.Labels[li].FieldIndex
v.Field(lfieldIdx).Set(reflect.ValueOf(lv))
}

}

return diags
Expand Down
8 changes: 3 additions & 5 deletions gohcl/doc.go
Expand Up @@ -24,11 +24,9 @@
// expression is assigned, or of any type accepted by gocty, in which case
// gocty will be used to assign the value to a native Go type.
//
// "block" fields may be of type *hcl.Block or hcl.Body, in which case the
// corresponding raw value is assigned, or may be a struct that recursively
// uses the same tags. Block fields may also be slices of any of these types,
// in which case multiple blocks of the corresponding type are decoded into
// the slice.
// "block" fields may be a struct that recursively uses the same tags, or a
// slice of such structs, in which case multiple blocks of the corresponding
// type are decoded into the slice.
//
// "body" can be placed on a single field of type hcl.Body to capture
// the full hcl.Body that was decoded for a block. This does not allow leftover
Expand Down

0 comments on commit 163105d

Please sign in to comment.