/
rewrite_properties.go
69 lines (61 loc) 路 1.81 KB
/
rewrite_properties.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
package hcl2
import (
"bytes"
"fmt"
"github.com/hashicorp/hcl/v2"
"github.com/pulumi/pulumi/pkg/v2/codegen/hcl2/model"
"github.com/pulumi/pulumi/pkg/v2/codegen/hcl2/syntax"
"github.com/pulumi/pulumi/sdk/v2/go/common/util/contract"
"github.com/zclconf/go-cty/cty"
)
func RewritePropertyReferences(expr model.Expression) model.Expression {
rewriter := func(expr model.Expression) (model.Expression, hcl.Diagnostics) {
traversal, ok := expr.(*model.ScopeTraversalExpression)
if !ok {
return expr, nil
}
p, ok := traversal.Parts[len(traversal.Parts)-1].(*ResourceProperty)
if !ok {
return expr, nil
}
var buffer bytes.Buffer
for _, t := range p.Path {
var err error
switch t := t.(type) {
case hcl.TraverseRoot:
_, err = fmt.Fprint(&buffer, t.Name)
case hcl.TraverseAttr:
_, err = fmt.Fprintf(&buffer, ".%s", t.Name)
case hcl.TraverseIndex:
switch t.Key.Type() {
case cty.String:
_, err = fmt.Fprintf(&buffer, ".%s", t.Key.AsString())
case cty.Number:
idx, _ := t.Key.AsBigFloat().Int64()
_, err = fmt.Fprintf(&buffer, "[%d]", idx)
default:
contract.Failf("unexpected traversal index of type %v", t.Key.Type())
}
}
contract.IgnoreError(err)
}
// TODO: transfer internal trivia
propertyPath := cty.StringVal(buffer.String())
value := &model.TemplateExpression{
Parts: []model.Expression{
&model.LiteralValueExpression{
Tokens: syntax.NewLiteralValueTokens(propertyPath),
Value: propertyPath,
},
},
}
value.SetLeadingTrivia(expr.GetLeadingTrivia())
value.SetTrailingTrivia(expr.GetTrailingTrivia())
diags := value.Typecheck(false)
contract.Assert(len(diags) == 0)
return value, nil
}
expr, diags := model.VisitExpression(expr, model.IdentityVisitor, rewriter)
contract.Assert(len(diags) == 0)
return expr
}