-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathast.go
60 lines (48 loc) · 1.24 KB
/
ast.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
package tpp
import (
"fmt"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/zclconf/go-cty/cty"
"k8s.io/utils/ptr"
)
func (t *Terraform) iterModules(iter func(source string, bl *hclwrite.Block) error) error {
for _, bl := range t.fi.Body().Blocks() {
if !isModuleBlock(bl) {
continue
}
if len(bl.Labels()) == 0 {
return ErrNoModuleName
}
modName := bl.Labels()[0]
src := getAttrQuotedValue(bl.Body(), attrNameSource)
if src == nil {
return fmt.Errorf("could not parse source for module %q", modName)
}
if !t.isManagedModule(*src) {
continue
}
if err := iter(*src, bl); err != nil {
return fmt.Errorf("error for module %q: %w", modName, err)
}
}
return nil
}
func isModuleBlock(block *hclwrite.Block) bool {
return block.Type() == blockTypeModule
}
func getAttrQuotedValue(body *hclwrite.Body, attrName string) *string {
attrVal := body.GetAttribute(attrName)
if attrVal == nil {
return nil
}
for _, ident := range attrVal.BuildTokens(nil) {
if ident.Type == hclsyntax.TokenQuotedLit {
return ptr.To(string(ident.Bytes))
}
}
return nil
}
func setStringAttr(bl *hclwrite.Block, name, val string) {
bl.Body().SetAttributeValue(name, cty.StringVal(val))
}