1
1
mirror of https://github.com/mcuadros/ascode synced 2024-11-26 06:01:08 +01:00

starlark/types: Value and Type support for dicts/maps

Signed-off-by: Máximo Cuadros <mcuadros@gmail.com>
This commit is contained in:
Máximo Cuadros 2019-07-27 20:50:26 +02:00
parent a32599f413
commit 8d842717ce
4 changed files with 38 additions and 2 deletions

@ -44,7 +44,7 @@ func NewTypeFromStarlark(typ string) (*Type, error) {
t.cty = cty.String
case "list", "ResourceCollection":
t.cty = cty.List(cty.NilType)
case "dictaa", "Resource":
case "dict", "Resource":
t.cty = cty.Map(cty.NilType)
case "Computed":
t.cty = cty.String
@ -80,7 +80,7 @@ func NewTypeFromCty(typ cty.Type) (*Type, error) {
}
if typ.IsMapType() {
t.typ = "dicaat"
t.typ = "dict"
}
if typ.IsListType() {
@ -134,6 +134,10 @@ func (t *Type) Validate(v starlark.Value) error {
if t.cty.IsListType() || t.cty.IsSetType() {
return t.validateListType(v.(*starlark.List), t.cty.ElementType())
}
case *starlark.Dict:
if t.cty.IsMapType() {
return nil
}
}
return fmt.Errorf("expected %s, got %s", t.typ, v.Type())

@ -30,6 +30,9 @@ func TestNewTypeFromStarlark_NonScalar(t *testing.T) {
typ := MustTypeFromStarlark("list")
assert.True(t, typ.Cty().IsListType())
typ = MustTypeFromStarlark("dict")
assert.True(t, typ.Cty().IsMapType())
typ = MustTypeFromStarlark("ResourceCollection<bar>")
assert.True(t, typ.Cty().IsListType())
@ -46,6 +49,7 @@ func TestNewTypeFromCty(t *testing.T) {
{"int", cty.Number},
{"bool", cty.Bool},
{"list", cty.List(cty.String)},
{"dict", cty.Map(cty.String)},
{"set", cty.Set(cty.String)},
{"tuple", cty.Tuple([]cty.Type{})},
}

@ -68,6 +68,15 @@ func (v *Value) Cty() cty.Value {
}
return cty.ListVal(values)
case "dict":
dict := v.v.(*starlark.Dict)
values := make(map[string]cty.Value)
for _, t := range dict.Items() {
key := fmt.Sprintf("%s", MustValue(t.Index(0)).Interface())
values[key] = MustValue(t.Index(1)).Cty()
}
return cty.MapVal(values)
case "Computed":
return cty.StringVal(v.v.(*Computed).GoString())
default:
@ -96,6 +105,15 @@ func (v *Value) Interface() interface{} {
}
return out
case *starlark.Dict:
values := make(map[string]interface{})
for _, t := range cast.Items() {
key := fmt.Sprintf("%s", MustValue(t.Index(0)).Interface())
values[key] = MustValue(t.Index(1)).Interface()
}
return values
default:
return v
}

@ -10,6 +10,10 @@ import (
)
func TestMustValue(t *testing.T) {
dict := starlark.NewDict(1)
dict.SetKey(starlark.String("foo"), starlark.MakeInt(42))
testCases := []struct {
v starlark.Value
cty cty.Type
@ -46,6 +50,12 @@ func TestMustValue(t *testing.T) {
cty.ListVal([]cty.Value{cty.StringVal("foo")}),
[]interface{}{"foo"},
},
{
dict,
cty.Map(cty.NilType),
cty.MapVal(map[string]cty.Value{"foo": cty.NumberIntVal(42)}),
map[string]interface{}{"foo": int64(42)},
},
}
for _, tc := range testCases {