From e3e49cc099efaabe9713f5602e42bb87d1c46670 Mon Sep 17 00:00:00 2001 From: Mateusz Gozdek Date: Wed, 15 Jan 2020 13:30:47 +0100 Subject: [PATCH] gohcl/decode.go: fix decoding value slices Currently, if user tries to decode such scenario, it results in "slice index out of range". Fixes regression introduced in 42351b1d15716a53accce7144d13df5606d56b19. Signed-off-by: Mateusz Gozdek --- gohcl/decode.go | 3 +++ gohcl/decode_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/gohcl/decode.go b/gohcl/decode.go index f0d589d..6079a01 100644 --- a/gohcl/decode.go +++ b/gohcl/decode.go @@ -185,6 +185,9 @@ func decodeBodyToStruct(body hcl.Body, ctx *hcl.EvalContext, val reflect.Value) diags = append(diags, decodeBlockToValue(block, ctx, v.Elem())...) sli.Index(i).Set(v) } else { + if i >= sli.Len() { + sli = reflect.Append(sli, reflect.Indirect(reflect.New(ty))) + } diags = append(diags, decodeBlockToValue(block, ctx, sli.Index(i))...) } } diff --git a/gohcl/decode_test.go b/gohcl/decode_test.go index 8f065c4..5260a0e 100644 --- a/gohcl/decode_test.go +++ b/gohcl/decode_test.go @@ -37,6 +37,10 @@ func TestDecodeBody(t *testing.T) { Nested []*withTwoAttributes `hcl:"nested,block"` } + type withListofNestedBlocksNoPointers struct { + Nested []withTwoAttributes `hcl:"nested,block"` + } + tests := []struct { Body map[string]interface{} Target func() interface{} @@ -623,6 +627,33 @@ func TestDecodeBody(t *testing.T) { }, 0, }, + { + // Make sure decoding value slices works the same as pointer slices. + map[string]interface{}{ + "nested": []map[string]interface{}{ + { + "b": "bar", + }, + { + "b": "baz", + }, + }, + }, + func() interface{} { + return &withListofNestedBlocksNoPointers{ + Nested: []withTwoAttributes{ + { + B: "foo", + }, + }, + } + }, + func(gotI interface{}) bool { + n := gotI.(withListofNestedBlocksNoPointers) + return n.Nested[0].B == "bar" && len(n.Nested) == 2 + }, + 0, + }, } for i, test := range tests {