forked from alecthomas/hcl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
visitor.go
55 lines (50 loc) · 1.13 KB
/
visitor.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
package hcl
import (
"reflect"
)
// Visit nodes in the AST.
//
// "next" may be called to continue traversal of child nodes.
func Visit(node Node, visitor func(node Node, next func() error) error) error {
if reflect.ValueOf(node).IsNil() { // Workaround for Go's typed nil interfaces.
return nil
}
return visitor(node, func() error {
for _, child := range node.children() {
if err := Visit(child, visitor); err != nil {
return err
}
}
return nil
})
}
// Find and return blocks, attributes or map entries with the given key.
func Find(node Node, names ...string) (nodes []Node) {
_ = Visit(node, func(node Node, next func() error) error {
switch node := node.(type) {
case *Block:
for _, name := range names {
if node.Name == name {
nodes = append(nodes, node)
break
}
}
case *Attribute:
for _, name := range names {
if node.Key == name {
nodes = append(nodes, node)
break
}
}
case *MapEntry:
for _, name := range names {
if node.Key.Str != nil && *node.Key.Str == name {
nodes = append(nodes, node)
break
}
}
}
return next()
})
return
}