forked from alecthomas/hcl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
108 lines (94 loc) · 1.97 KB
/
util.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
104
105
106
107
108
package hcl
import (
"fmt"
"strings"
"unicode"
)
// StripComments recursively from an AST node.
func StripComments(node Node) error {
return Visit(node, func(node Node, next func() error) error {
switch node := node.(type) {
case *Attribute:
node.Comments = nil
case *Block:
node.Comments = nil
case *MapEntry:
node.Comments = nil
}
return next()
})
}
// AddParentRefs recursively updates an AST's parent references.
//
// This is called automatically during Parse*(), but can be called on a manually constructed AST.
func AddParentRefs(node Node) error {
addParentRefs(nil, node)
return nil
}
func addParentRefs(parent, node Node) {
switch node := node.(type) {
case *AST:
for _, entry := range node.Entries {
addParentRefs(node, entry)
}
case *Block:
node.Parent = parent
for _, entry := range node.Body {
addParentRefs(node, entry)
}
case *Entry:
node.Parent = parent
if node.Attribute != nil {
addParentRefs(node, node.Attribute)
} else {
addParentRefs(node, node.Block)
}
case *MapEntry:
node.Parent = parent
case *Value:
if node == nil {
return
}
node.Parent = parent
switch {
case node.HaveList:
for _, entry := range node.List {
addParentRefs(node, entry)
}
case node.HaveMap:
for _, entry := range node.Map {
addParentRefs(node, entry)
}
}
case *Attribute:
node.Parent = parent
addParentRefs(node, node.Value)
default:
panic(fmt.Sprintf("%T", node))
}
}
func dedent(s string) string {
lines := strings.Split(s, "\n")
indent := whitespacePrefix(lines[0])
for _, line := range lines[1:] {
candidate := whitespacePrefix(line)
if len(candidate) < len(indent) {
indent = candidate
}
}
for i, line := range lines {
lines[i] = strings.TrimPrefix(line, indent)
}
return strings.Join(lines, "\n")
}
func whitespacePrefix(s string) string {
indent := ""
for _, rn := range s {
if unicode.IsSpace(rn) {
indent += string(rn)
} else {
break
}
}
return indent
}