forked from CircleCI-Public/circleci-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filetree.go
216 lines (177 loc) · 4.56 KB
/
filetree.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package filetree
import (
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/mitchellh/mapstructure"
yaml "gopkg.in/yaml.v2"
)
// This is a quick hack of a function to convert interfaces
// into to map[string]interface{} and combine them.
func mergeTree(trees ...interface{}) map[string]interface{} {
result := make(map[string]interface{})
for _, tree := range trees {
kvp := make(map[string]interface{})
if err := mapstructure.Decode(tree, &kvp); err != nil {
panic(err)
}
for k, v := range kvp {
result[k] = v
}
}
return result
}
// SpecialCase is a function you can pass to NewTree
// in order to override the behavior when marshalling a node.
var SpecialCase func(path string) bool
// Node represents a leaf in the filetree
type Node struct {
FullPath string `json:"full_path"`
Info os.FileInfo `json:"-"`
Children []*Node `json:"-"`
Parent *Node `json:"-"`
}
// MarshalYAML serializes the tree into YAML
func (n Node) MarshalYAML() (interface{}, error) {
if len(n.Children) == 0 {
return n.marshalLeaf()
}
return n.marshalParent()
}
func (n Node) basename() string {
return n.Info.Name()
}
func (n Node) name() string {
return strings.TrimSuffix(n.basename(), filepath.Ext(n.basename()))
}
func (n Node) rootFile() bool {
return n.Info.Mode().IsRegular() && n.root() == n.Parent
}
func (n Node) specialCase() bool {
re := regexp.MustCompile(`^@.*\.(yml|yaml)$`)
return re.MatchString(n.basename())
}
func (n Node) marshalParent() (interface{}, error) {
subtree := map[string]interface{}{}
for _, child := range n.Children {
c, err := child.MarshalYAML()
if err != nil {
return subtree, err
}
if child.rootFile() {
merged := mergeTree(subtree, c)
subtree = merged
} else if child.specialCase() {
merged := mergeTree(subtree, subtree[child.Parent.name()], c)
subtree = merged
} else {
merged := mergeTree(subtree[child.name()], c)
subtree[child.name()] = merged
}
}
return subtree, nil
}
// Returns the root node
func (n Node) root() *Node {
root := n.Parent
for root.Parent != nil {
root = root.Parent
}
return root
}
func (n Node) marshalLeaf() (interface{}, error) {
var content interface{}
// TODO: this check may be unnecessary with the isYaml check
if n.Info.IsDir() {
return content, nil
}
if !isYaml(n.Info) {
return content, nil
}
buf, err := ioutil.ReadFile(n.FullPath)
if err != nil {
return content, err
}
err = yaml.Unmarshal(buf, &content)
return content, err
}
func dotfile(info os.FileInfo) bool {
re := regexp.MustCompile(`^\..+`)
return re.MatchString(info.Name())
}
func dotfolder(info os.FileInfo) bool {
return info.IsDir() && dotfile(info)
}
func isYaml(info os.FileInfo) bool {
re := regexp.MustCompile(`.+\.(yml|yaml)$`)
return re.MatchString(info.Name())
}
// PathNodes is a map of filepaths to tree nodes with ordered path keys.
type PathNodes struct {
Map map[string]*Node
Keys []string
}
func buildTree(absRootPath string, pathNodes PathNodes) *Node {
var rootNode *Node
for _, path := range pathNodes.Keys {
node := pathNodes.Map[path]
// skip dotfile nodes that aren't the root path
if absRootPath != path && node.Info.Mode().IsRegular() {
if dotfile(node.Info) || !isYaml(node.Info) {
continue
}
}
parentPath := filepath.Dir(path)
parent, exists := pathNodes.Map[parentPath]
if exists {
node.Parent = parent
parent.Children = append(parent.Children, node)
} else {
rootNode = node
}
}
return rootNode
}
func collectNodes(absRootPath string) (PathNodes, error) {
pathNodes := PathNodes{}
pathNodes.Map = make(map[string]*Node)
pathNodes.Keys = []string{}
err := filepath.Walk(absRootPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip any dotfolders that aren't the root path
if absRootPath != path && dotfolder(info) {
// Turn off logging to stdout in this package
//fmt.Printf("Skipping dotfolder: %+v\n", path)
return filepath.SkipDir
}
fp, err := filepath.Abs(path)
if err != nil {
return err
}
pathNodes.Keys = append(pathNodes.Keys, path)
pathNodes.Map[path] = &Node{
FullPath: fp,
Info: info,
Children: make([]*Node, 0),
}
return nil
})
return pathNodes, err
}
// NewTree creates a new filetree starting at the root
func NewTree(rootPath string) (*Node, error) {
absRootPath, err := filepath.Abs(rootPath)
if err != nil {
return nil, err
}
pathNodes, err := collectNodes(absRootPath)
if err != nil {
return nil, err
}
rootNode := buildTree(absRootPath, pathNodes)
return rootNode, err
}