Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gohcl/decode.go: fix decoding value slices #335

Merged
merged 1 commit into from
Nov 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 42351b1.

Signed-off-by: Mateusz Gozdek <[email protected]>
  • Loading branch information
invidian committed Jan 15, 2020
commit e3e49cc099efaabe9713f5602e42bb87d1c46670
3 changes: 3 additions & 0 deletions gohcl/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))...)
}
}
Expand Down
31 changes: 31 additions & 0 deletions gohcl/decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down Expand Up @@ -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 {
Expand Down