Skip to content

Commit 6fc80cd

Browse files
committed
starlark/types: Attribute.Get, support for map attributes
1 parent 8b962d2 commit 6fc80cd

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

starlark/types/attribute.go

+26
Original file line numberDiff line numberDiff line change
@@ -155,9 +155,35 @@ func (c *Attribute) Index(i int) starlark.Value {
155155
return NewAttributeWithPath(c.r, *c.t.ListElementType(), c.name, path)
156156
}
157157

158+
if c.t.IsMapType() {
159+
return NewAttributeWithPath(c.r, c.t, c.name, path)
160+
}
161+
158162
return starlark.None
159163
}
160164

165+
// Get honors the starlark.Mapping interface.
166+
func (c *Attribute) Get(key starlark.Value) (v starlark.Value, found bool, err error) {
167+
switch vKey := key.(type) {
168+
case starlark.Int:
169+
if !c.t.IsSetType() && !c.t.IsListType() && !c.t.IsMapType() {
170+
return nil, false, fmt.Errorf("%s does not support index", c.name)
171+
}
172+
173+
index, _ := vKey.Int64()
174+
return c.Index(int(index)), true, nil
175+
case starlark.String:
176+
if !c.t.IsMapType() {
177+
return nil, false, fmt.Errorf("%s it's not a dict", c.name)
178+
}
179+
180+
path := fmt.Sprintf("%s.%s", c.path, vKey.GoString())
181+
return NewAttributeWithPath(c.r, c.t, c.name, path), true, nil
182+
default:
183+
return nil, false, fmt.Errorf("%s: unexpected key type %s", c.name, key.Type())
184+
}
185+
}
186+
161187
// Len honors the starlark.Indexable interface.
162188
func (c *Attribute) Len() int {
163189
if !c.t.IsSetType() && !c.t.IsListType() {

starlark/types/testdata/attribute.star

+7-1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,12 @@ assert.eq(str(cluster.master_auth.client_certificate), "${google_container_clust
4747
# attr non-object
4848
assert.fails(lambda: web.ami.foo, "Attribute<string> it's not a object")
4949

50-
5150
# fn wrapping
5251
assert.eq(str(fn("base64encode", web.ami)), "${base64encode(data.aws_ami.id_2.id)}")
52+
53+
# attribute of dict
54+
k8s = tf.provider("kubernetes")
55+
56+
secret = k8s.data.secret("foo")
57+
assert.eq(str(secret.data["qux"]), "${data.kubernetes_secret.foo.data.qux}")
58+
assert.eq(str(secret.data["qux"][0]), "${data.kubernetes_secret.foo.data.qux.0}")

0 commit comments

Comments
 (0)