/
iteration.go
103 lines (87 loc) · 2.01 KB
/
iteration.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package tfhcl
import (
"github.com/hashicorp/hcl/v2"
"github.com/zclconf/go-cty/cty"
)
type dynamicIteration struct {
IteratorName string
Key cty.Value
Value cty.Value
Inherited map[string]*dynamicIteration
}
func (i *dynamicIteration) Object() cty.Value {
return cty.ObjectVal(map[string]cty.Value{
"key": i.Key,
"value": i.Value,
})
}
func (i *dynamicIteration) EvalContext(base *hcl.EvalContext) *hcl.EvalContext {
new := base.NewChild()
if i != nil {
new.Variables = map[string]cty.Value{}
for name, otherIt := range i.Inherited {
new.Variables[name] = otherIt.Object()
}
new.Variables[i.IteratorName] = i.Object()
}
return new
}
func (i *dynamicIteration) MakeChild(iteratorName string, key, value cty.Value) *dynamicIteration {
if i == nil {
// Create entirely new root iteration, then
return &dynamicIteration{
IteratorName: iteratorName,
Key: key,
Value: value,
}
}
inherited := map[string]*dynamicIteration{}
for name, otherIt := range i.Inherited {
inherited[name] = otherIt
}
inherited[i.IteratorName] = i
return &dynamicIteration{
IteratorName: iteratorName,
Key: key,
Value: value,
Inherited: inherited,
}
}
type metaArgIteration struct {
Count bool
Index cty.Value
ForEach bool
Key cty.Value
Value cty.Value
}
func MakeCountIteration(index cty.Value) *metaArgIteration {
return &metaArgIteration{
Count: true,
Index: index,
}
}
func MakeForEachIteration(key, value cty.Value) *metaArgIteration {
return &metaArgIteration{
ForEach: true,
Key: key,
Value: value,
}
}
func (i *metaArgIteration) EvalContext(base *hcl.EvalContext) *hcl.EvalContext {
new := base.NewChild()
if i != nil {
new.Variables = map[string]cty.Value{}
if i.Count {
new.Variables["count"] = cty.ObjectVal(map[string]cty.Value{
"index": i.Index,
})
}
if i.ForEach {
new.Variables["each"] = cty.ObjectVal(map[string]cty.Value{
"key": i.Key,
"value": i.Value,
})
}
}
return new
}