Skip to content

Commit

Permalink
starlark/types: Attribute.Get, support for map attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
mcuadros committed Apr 13, 2020
1 parent 8b962d2 commit 6fc80cd
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
26 changes: 26 additions & 0 deletions starlark/types/attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,35 @@ func (c *Attribute) Index(i int) starlark.Value {
return NewAttributeWithPath(c.r, *c.t.ListElementType(), c.name, path)
}

if c.t.IsMapType() {
return NewAttributeWithPath(c.r, c.t, c.name, path)
}

return starlark.None
}

// Get honors the starlark.Mapping interface.
func (c *Attribute) Get(key starlark.Value) (v starlark.Value, found bool, err error) {
switch vKey := key.(type) {
case starlark.Int:
if !c.t.IsSetType() && !c.t.IsListType() && !c.t.IsMapType() {
return nil, false, fmt.Errorf("%s does not support index", c.name)
}

index, _ := vKey.Int64()
return c.Index(int(index)), true, nil
case starlark.String:
if !c.t.IsMapType() {
return nil, false, fmt.Errorf("%s it's not a dict", c.name)
}

path := fmt.Sprintf("%s.%s", c.path, vKey.GoString())
return NewAttributeWithPath(c.r, c.t, c.name, path), true, nil
default:
return nil, false, fmt.Errorf("%s: unexpected key type %s", c.name, key.Type())
}
}

// Len honors the starlark.Indexable interface.
func (c *Attribute) Len() int {
if !c.t.IsSetType() && !c.t.IsListType() {
Expand Down
8 changes: 7 additions & 1 deletion starlark/types/testdata/attribute.star
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@ assert.eq(str(cluster.master_auth.client_certificate), "${google_container_clust
# attr non-object
assert.fails(lambda: web.ami.foo, "Attribute<string> it's not a object")


# fn wrapping
assert.eq(str(fn("base64encode", web.ami)), "${base64encode(data.aws_ami.id_2.id)}")

# attribute of dict
k8s = tf.provider("kubernetes")

secret = k8s.data.secret("foo")
assert.eq(str(secret.data["qux"]), "${data.kubernetes_secret.foo.data.qux}")
assert.eq(str(secret.data["qux"][0]), "${data.kubernetes_secret.foo.data.qux.0}")

0 comments on commit 6fc80cd

Please sign in to comment.