-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsource_tree.go
52 lines (44 loc) · 998 Bytes
/
source_tree.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
package collections
import (
"path/filepath"
"strings"
)
type SourceTree struct {
nodeMap map[string]*SourceNode
root []*SourceNode
}
func NewSourceTree() *SourceTree {
return &SourceTree{
nodeMap: make(map[string]*SourceNode),
}
}
func (st *SourceTree) Root() []*SourceNode {
return st.root
}
func (st *SourceTree) Add(path string, key string) *SourceNode {
path = strings.Trim(filepath.ToSlash(path), "/")
n := st.nodeMap[path]
if n != nil {
return n
}
items := strings.Split(path, "/")
n = &SourceNode{
Title: items[len(items)-1],
Key: key,
}
if len(items) >= 2 {
pPath := strings.Join(items[0:len(items)-1], "/")
parent := st.Add(pPath, pPath)
parent.Children = append(parent.Children, n)
} else {
st.root = append(st.root, n)
}
st.nodeMap[path] = n
return n
}
type SourceNode struct {
Title string `json:"title"`
Key string `json:"key"`
Children []*SourceNode `json:"children"`
IsLeaf bool `json:"isLeaf"`
}