-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtree.go
333 lines (294 loc) · 6.54 KB
/
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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package fsearch
import (
"encoding/json"
"errors"
"fmt"
"path/filepath"
"strings"
"sync"
)
var (
ErrInvalidPath = errors.New("path is invalid")
ErrNotFound = errors.New("path not found")
)
type Node struct {
id int64
name string
parent *Node
children map[string]*Node
}
type Tree struct {
root *Node
lock *sync.RWMutex
MaxId int64 `json:"maxId"`
PathSeparator string `json:"pathSeparator"`
err error
}
func NewTree(pathSeparator string) *Tree {
return &Tree{
root: &Node{
// parent is nil
id: 0,
name: "",
children: map[string]*Node{},
},
lock: &sync.RWMutex{},
MaxId: 1,
PathSeparator: pathSeparator,
}
}
// AddPath adds pathname to the tree and return new node ids
func (t *Tree) AddPath(pathname string) ([]*Node, error) {
pathname = filepath.Clean(pathname)
parts := strings.Split(pathname, t.PathSeparator)
if len(parts) == 0 {
return nil, ErrInvalidPath
}
t.lock.Lock()
defer t.lock.Unlock()
// TODO: remove base
node := t.root
createdNodes := []*Node{}
for _, part := range parts {
child, ok := node.children[part]
if !ok {
newNode := &Node{
id: t.MaxId,
name: part,
parent: node,
children: map[string]*Node{},
}
node.children[part] = newNode
createdNodes = append(createdNodes, newNode)
node = newNode
t.MaxId++
} else {
node = child
}
}
return createdNodes, nil
}
// DelPath deletes pathname from the tree
func (t *Tree) DelPath(pathname string) (*Node, error) {
pathname = filepath.Clean(pathname)
parts := strings.Split(pathname, t.PathSeparator)
if len(parts) == 0 {
return nil, ErrInvalidPath
}
t.lock.Lock()
defer t.lock.Unlock()
parent := t.root
var deletedNode *Node
for i, part := range parts {
child, ok := parent.children[part]
if !ok {
return nil, ErrNotFound
}
if i == len(parts)-1 {
deletedNode = child
child.parent = nil
delete(parent.children, part)
break
}
parent = child
}
return deletedNode, nil
}
// Rename rename the file/folder name
func (t *Tree) Rename(pathname, newName string) (*Node, error) {
if strings.Contains(newName, t.PathSeparator) {
return nil, ErrInvalidPath
}
pathname = filepath.Clean(pathname)
parts := strings.Split(pathname, t.PathSeparator)
if len(parts) == 0 {
return nil, ErrInvalidPath
}
t.lock.Lock()
defer t.lock.Unlock()
parent := t.root
var renamedNode *Node
for i, part := range parts {
child, ok := parent.children[part]
fmt.Println("rename", parent.name, part, ok)
if !ok {
return nil, ErrNotFound
}
if i == len(parts)-1 {
renamedNode = child
child.name = newName
delete(parent.children, part)
parent.children[newName] = child
break
}
parent = child
}
return renamedNode, nil
}
// MovePath moves pathname under dstParentPath
func (t *Tree) MovePath(pathname, dstParentPath string) error {
pathname = filepath.Clean(pathname)
parts := strings.Split(pathname, t.PathSeparator)
if len(parts) == 0 {
return ErrInvalidPath
}
dstPath := filepath.Clean(dstParentPath)
dstParts := strings.Split(dstPath, t.PathSeparator)
if len(dstParts) == 0 {
return ErrInvalidPath
}
t.lock.Lock()
defer t.lock.Unlock()
// find targetNode
parent := t.root
var targetNode *Node
for i, part := range parts {
child, ok := parent.children[part]
if !ok {
return ErrNotFound
}
if i == len(parts)-1 {
targetNode = child
delete(parent.children, part)
break
}
parent = child
}
// assign the targetNode to dstParent
itemName := parts[len(parts)-1]
parent = t.root
for i, part := range dstParts {
child, ok := parent.children[part]
if !ok {
return ErrNotFound
}
if i == len(dstParts)-1 {
child.children[itemName] = targetNode
targetNode.parent = child
break
}
parent = child
}
return nil
}
// GetPath traverses the path which is from the targetNode to root, and construct the pathname
func (t *Tree) GetPath(targetNode *Node) (string, error) {
node := targetNode
parts := []string{}
for node != nil {
parts = append(parts, node.name)
node = node.parent
}
if parts[len(parts)-1] != "" {
// the path is already deleted so it can not reach to root
return "", ErrNotFound
}
parts = parts[:len(parts)-1]
for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
parts[i], parts[j] = parts[j], parts[i]
}
return strings.Join(parts, t.PathSeparator), nil
}
type Row struct {
Id int64
ParentId int64
Name string
}
// Marshal marshals the tree into string rows
func (t *Tree) Marshal() chan string {
c := make(chan string, 1024)
// marshal tree
treeBytes, err := json.Marshal(t)
if err != nil {
t.err = err
close(c)
return c
}
c <- string(treeBytes)
worker := func() {
defer close(c)
queue := []*Node{
t.root,
}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
for childName, child := range node.children {
queue = append(queue, child)
row := &Row{
Id: child.id,
ParentId: node.id,
Name: childName,
}
rowBytes, err := json.Marshal(row)
if err != nil {
t.err = err
return
}
c <- string(rowBytes)
}
}
}
go worker()
return c
}
// Unmarshal restores the tree from rows
func (t *Tree) Unmarshal(rows chan string) {
// restore tree
rowStr := <-rows
tmpTree := &Tree{}
err := json.Unmarshal([]byte(rowStr), tmpTree)
if err != nil {
t.err = err
return
}
t.MaxId = tmpTree.MaxId
t.PathSeparator = tmpTree.PathSeparator
// restore nodes
row := &Row{}
// TODO: currently all nodes are saved in mem
// since each node only saves 2 integers
createdNodes := map[int64]*Node{
int64(0): t.root,
}
for rowStr := range rows {
err = json.Unmarshal([]byte(rowStr), row)
if err != nil {
t.err = err
return
}
parentNode := createdNodes[row.ParentId]
newNode := &Node{
id: row.Id,
name: row.Name,
parent: parentNode,
children: map[string]*Node{},
}
parentNode.children[row.Name] = newNode
createdNodes[row.Id] = newNode
}
}
// Err returns the last err (if it exists)
func (t *Tree) Err() error {
err := t.err
t.err = nil
return err
}
func (t *Tree) String() string {
result := ""
queue := []*Node{t.root}
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
if node == nil {
result += fmt.Sprintln("node not found")
continue
}
result += fmt.Sprintf("id(%d) name(%s)\n", node.id, node.name)
for key, child := range node.children {
queue = append(queue, child)
result += fmt.Sprintf("\tchild key(%s): id(%d) name(%s)\n", key, child.id, child.name)
}
}
return result
}