-
Notifications
You must be signed in to change notification settings - Fork 4
/
rf_iterate.go
63 lines (58 loc) · 1.2 KB
/
rf_iterate.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
package golden
import (
"fmt"
"strings"
"github.com/hashicorp/hcl/v2"
)
type refIterator func(t []hcl.Traverser, i int) []string
// iterator return a refIterator that travel a list of tokens, and return referenced block's address inside this expression
func iterator(keyword string, addressLength int) refIterator {
return func(ts []hcl.Traverser, i int) []string {
var r []string
if len(ts) == 0 {
return nil
}
if name(ts[i]) != keyword {
return nil
}
if len(ts) < i+addressLength {
return nil
}
remain := addressLength
sb := strings.Builder{}
// data.xyz.abc
for j := i; remain > 0; j++ {
sb.WriteString(name(ts[j]))
remain--
if remain > 0 {
sb.WriteString(".")
}
}
r = []string{sb.String()}
//potential index, like data.xyz.abc["foo"]
if len(ts) > i+addressLength+1 {
index, ok := ts[i+addressLength].(hcl.TraverseIndex)
if ok {
sb.WriteString(fmt.Sprintf(`[%s]`, CtyValueToString(index.Key)))
r = append(r, sb.String())
}
}
return r
}
}
func name(t hcl.Traverser) string {
switch tp := t.(type) {
case hcl.TraverseRoot:
{
return tp.Name
}
case hcl.TraverseAttr:
{
return tp.Name
}
default:
{
return ""
}
}
}