-
Notifications
You must be signed in to change notification settings - Fork 10
/
expansion_mode.go
85 lines (71 loc) · 2.21 KB
/
expansion_mode.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package instances
import (
"fmt"
"sort"
"github.com/zclconf/go-cty/cty"
"github.com/snyk/policy-engine/pkg/internal/terraform/addrs"
)
// expansion is an internal interface used to represent the different
// ways expansion can operate depending on how repetition is configured for
// an object.
type expansion interface {
instanceKeys() []addrs.InstanceKey
repetitionData(addrs.InstanceKey) RepetitionData
}
// expansionSingle is the expansion corresponding to no repetition arguments
// at all, producing a single object with no key.
//
// expansionSingleVal is the only valid value of this type.
type expansionSingle uintptr
var singleKeys = []addrs.InstanceKey{addrs.NoKey}
var expansionSingleVal expansionSingle
func (e expansionSingle) instanceKeys() []addrs.InstanceKey {
return singleKeys
}
func (e expansionSingle) repetitionData(key addrs.InstanceKey) RepetitionData {
if key != addrs.NoKey {
panic("cannot use instance key with non-repeating object")
}
return RepetitionData{}
}
// expansionCount is the expansion corresponding to the "count" argument.
type expansionCount int
func (e expansionCount) instanceKeys() []addrs.InstanceKey {
ret := make([]addrs.InstanceKey, int(e))
for i := range ret {
ret[i] = addrs.IntKey(i)
}
return ret
}
func (e expansionCount) repetitionData(key addrs.InstanceKey) RepetitionData {
i := int(key.(addrs.IntKey))
if i < 0 || i >= int(e) {
panic(fmt.Sprintf("instance key %d out of range for count %d", i, e))
}
return RepetitionData{
CountIndex: cty.NumberIntVal(int64(i)),
}
}
// expansionForEach is the expansion corresponding to the "for_each" argument.
type expansionForEach map[string]cty.Value
func (e expansionForEach) instanceKeys() []addrs.InstanceKey {
ret := make([]addrs.InstanceKey, 0, len(e))
for k := range e {
ret = append(ret, addrs.StringKey(k))
}
sort.Slice(ret, func(i, j int) bool {
return ret[i].(addrs.StringKey) < ret[j].(addrs.StringKey)
})
return ret
}
func (e expansionForEach) repetitionData(key addrs.InstanceKey) RepetitionData {
k := string(key.(addrs.StringKey))
v, ok := e[k]
if !ok {
panic(fmt.Sprintf("instance key %q does not match any instance", k))
}
return RepetitionData{
EachKey: cty.StringVal(k),
EachValue: v,
}
}