Skip to content

Commit

Permalink
ext/typeexpr: Convert defaults for optional attrs
Browse files Browse the repository at this point in the history
When parsing optional object attribute defaults, we previously verified
that the default value was convertible to the attribute type. However,
we did not keep this converted value.

This commit uses the converted default value, rather than delaying
conversion until later. In turn this prevents crashes when transforming
collections which contain objects with optional attributes, caused by
incompatible object types at the time of defaults application.
  • Loading branch information
alisdair committed Sep 22, 2022
1 parent 85e45c5 commit b857322
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
4 changes: 3 additions & 1 deletion ext/typeexpr/get_type.go
Expand Up @@ -249,7 +249,7 @@ func getType(expr hcl.Expression, constraint, withDefaults bool) (cty.Type, *Def
// If a default is set for an optional attribute, verify that it is
// convertible to the attribute type.
if defaultVal, ok := defaultValues[attrName]; ok {
_, err := convert.Convert(defaultVal, aty)
convertedDefaultVal, err := convert.Convert(defaultVal, aty)
if err != nil {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Expand All @@ -258,6 +258,8 @@ func getType(expr hcl.Expression, constraint, withDefaults bool) (cty.Type, *Def
Subject: defaultExpr.Range().Ptr(),
})
delete(defaultValues, attrName)
} else {
defaultValues[attrName] = convertedDefaultVal
}
}

Expand Down
4 changes: 3 additions & 1 deletion ext/typeexpr/get_type_test.go
Expand Up @@ -504,7 +504,9 @@ func TestGetTypeDefaults(t *testing.T) {
}, []string{"b"}),
}, []string{"a"}),
DefaultValues: map[string]cty.Value{
"a": cty.EmptyObjectVal,
"a": cty.ObjectVal(map[string]cty.Value{
"b": cty.NullVal(cty.Number),
}),
},
Children: map[string]*Defaults{
"a": {
Expand Down

0 comments on commit b857322

Please sign in to comment.