-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtree.go
600 lines (489 loc) · 11.6 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
package explorer
import (
"errors"
"fmt"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
)
type NodeKind uint8
const (
FileNode NodeKind = iota
FolderNode
)
// A filter is used to decide which files/folders are retained when
// buiding a EntryNode's children. Returning false will remove the current
// entry from from the children.
type EntryFilter func(info fs.FileInfo) bool
type EntryNode struct {
Path string
fs.FileInfo
// parent must be of folder kind.
Parent *EntryNode
children []*EntryNode
}
var isWindows = runtime.GOOS == "windows"
func hiddenFileFilter(info fs.FileInfo) bool {
name := info.Name()
if isWindows {
return !strings.HasPrefix(name, "$") && !strings.HasSuffix(name, ".sys")
} else {
return !strings.HasPrefix(name, ".")
}
}
func searchFilter(query string) func(info fs.FileInfo) bool {
return func(info fs.FileInfo) bool {
return strings.Contains(info.Name(), query)
}
}
func AggregatedFilters(filters ...EntryFilter) EntryFilter {
if len(filters) <= 0 {
return nil
}
return func(info fs.FileInfo) bool {
for _, filter := range filters {
if filter == nil {
continue
}
if !filter(info) {
return false
}
}
return true
}
}
// Create a new file tree with a relative or absolute rootDir. A filter is used
// to decide which files/folders are retained.
func NewFileTree(rootDir string) (*EntryNode, error) {
rootDir, err := filepath.Abs(rootDir)
if err != nil {
log.Fatalln(err)
}
st, err := os.Stat(rootDir)
if err != nil {
return nil, err
}
root := &EntryNode{
Path: rootDir,
Parent: nil,
FileInfo: st,
}
return root, nil
}
// Load build the tree.
func loadTree(rootDir string) (*EntryNode, error) {
var root *EntryNode
// current parent during walk.
var parent *EntryNode
err := filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Println("file/folder skipped: ", path)
return filepath.SkipDir
}
// if info.IsDir() {
// for _, prefix := range skipPatterns {
// if strings.HasPrefix(info.Name(), prefix) || strings.HasPrefix(path, prefix) {
// return filepath.SkipDir
// }
// }
// }
entry := &EntryNode{
Path: filepath.Clean(path),
FileInfo: info,
}
if info.IsDir() {
if entry.Path == rootDir {
root = entry
}
}
// find the parent of the current entry:
if p := findParent(parent, entry); p != nil {
p.children = append(p.children, entry)
entry.Parent = p
}
if entry.IsDir() {
// update the current parent to this folder
parent = entry
}
return nil
})
if err != nil {
return nil, err
}
return root, nil
}
func (n *EntryNode) Kind() NodeKind {
if n.IsDir() {
return FolderNode
}
return FileNode
}
func (n *EntryNode) Children() []*EntryNode {
if !n.IsDir() {
return nil
}
if n.children == nil {
n.Refresh(hiddenFileFilter)
}
return n.children
}
// Add new file or folder.
func (n *EntryNode) AddChild(name string, kind NodeKind) error {
if !n.IsDir() {
return nil
}
if name == "" {
return errors.New("empty file/folder name")
}
if n.exists(name) {
return errors.New("duplicated file/folder name")
}
path := filepath.Join(n.Path, name)
if kind == FileNode {
file, err := os.Create(path)
if err != nil {
return err
}
file.Close()
} else if kind == FolderNode {
if err := os.Mkdir(path, 0755); err != nil {
return err
}
}
st, _ := os.Stat(path)
child := &EntryNode{
Path: filepath.Clean(path),
Parent: n,
FileInfo: st,
}
// insert at the beginning of the children.
n.children = slices.Insert(n.children, 0, child)
return nil
}
// Copy copies the file at nodePath to the current folder.
// Copy does not replace existing files/folders, instead it returns
// an error indicating that case.
func (n *EntryNode) Copy(nodePath string) error {
if !n.IsDir() {
return nil
}
if nodePath == "" || !entryExists(nodePath) {
return errors.New("not a valid entry path")
}
if n.exists(filepath.Base(nodePath)) {
return errors.New("duplicated file/folder name: " + nodePath)
}
nodeInfo, _ := os.Stat(nodePath)
switch nodeInfo.Mode() & os.ModeType {
case os.ModeDir:
err := copyDirectory(nodePath, n.Path)
if err != nil {
return err
}
case os.ModeSymlink:
if err := copySymLink(nodePath, filepath.Join(n.Path, filepath.Base(nodePath))); err != nil {
return err
}
default:
if err := copyFile(nodePath, filepath.Join(n.Path, filepath.Base(nodePath))); err != nil {
return err
}
}
return n.Refresh(hiddenFileFilter)
}
// Move moves the file at nodePath to the current folder.
// Move does not replace existing files/folders, instead it returns
// an error indicating that case.
func (n *EntryNode) Move(nodePath string) error {
if !n.IsDir() {
return nil
}
if nodePath == "" || !entryExists(nodePath) {
return errors.New("not a valid entry path")
}
if n.exists(filepath.Base(nodePath)) {
return errors.New("duplicated file/folder name")
}
err := os.Rename(nodePath, filepath.Join(n.Path, filepath.Base(nodePath)))
if err != nil {
return err
}
// if nodePath is a descendant of the root tree, refresh its parent to clean dirty nodes.
parent := findNodeInTree(n, filepath.Dir(nodePath))
if parent != nil && parent != n {
parent.Refresh(hiddenFileFilter)
}
return n.Refresh(hiddenFileFilter)
}
func (n *EntryNode) exists(name string) bool {
filename := filepath.Join(n.Path, name)
return entryExists(filename)
}
// Update set a new name for the current file/folder.
func (n *EntryNode) UpdateName(newName string) error {
if n.Parent == nil {
return errors.New("cannot update name of root dir")
}
if n.Name() == newName || newName == "" {
return nil
}
if n.Parent.exists(newName) {
return errors.New("duplicated file/folder name")
}
newPath := filepath.Join(filepath.Dir(n.Path), newName)
defer func() {
n.Path = filepath.Clean(newPath)
st, _ := os.Stat(n.Path)
n.FileInfo = st
if len(n.children) > 0 {
n.Refresh(hiddenFileFilter)
}
}()
return os.Rename(n.Path, newPath)
}
// Delete removes the current file/folders to the system Trash bin.
func (n *EntryNode) Delete() error {
if n.Parent == nil {
return errors.New("cannot update name of root dir")
}
err := throwToTrash(n.Path)
if err != nil {
return err
}
n.Parent.children = slices.DeleteFunc(n.Parent.children, func(en *EntryNode) bool {
return en.Path == n.Path
})
return nil
}
// Print the entire tree in console.
func (n *EntryNode) Print() {
n.printTree(0)
}
// what type of the file, e.g, pdf, png。 This is for
// file nodes only
func (n *EntryNode) FileType() string {
return filepath.Ext(n.Name())
}
// Refresh reload child entries of the current entry node
func (n *EntryNode) Refresh(filterFunc EntryFilter) error {
if !n.IsDir() {
return nil
}
n.children = n.children[:0]
err := filepath.Walk(n.Path, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Println("file/folder skipped: ", path, err)
return filepath.SkipDir
}
if path == n.Path {
return nil
}
// only direct children dir is walked.
if filepath.Dir(path) != n.Path {
return filepath.SkipDir
}
if filterFunc != nil && filterFunc(info) {
entry := &EntryNode{
Path: filepath.Clean(path),
FileInfo: info,
Parent: n,
}
n.children = append(n.children, entry)
}
return nil
})
if err != nil {
return err
}
return nil
}
// for test purpose
func (n *EntryNode) printTree(depth int) {
if !n.IsDir() {
fmt.Printf("+--%s %s\n", strings.Repeat("-", depth), n.Path)
} else {
fmt.Printf("|%s \\--- %s\n", strings.Repeat(" ", depth), n.Path)
}
for _, child := range n.Children() {
child.printTree(depth + 1)
}
}
func findParent(root *EntryNode, child *EntryNode) *EntryNode {
if root == nil {
return nil
}
if filepath.Dir(child.Path) == root.Path {
return root
}
// trace back to parent's parent
grandparent := root.Parent
if grandparent == nil {
return nil
}
return findParent(grandparent, child)
}
func entryExists(path string) bool {
_, err := os.Stat(path)
return !errors.Is(err, os.ErrNotExist)
}
// copyDirectory copies src dir to dest dir, preserving permissions and ownership.
func copyDirectory(src, dst string) error {
subdir := filepath.Join(dst, filepath.Base(src))
if err := createDir(subdir, 0755); err != nil {
return err
}
entries, err := os.ReadDir(src)
if err != nil {
return err
}
for _, entry := range entries {
sourcePath := filepath.Join(src, entry.Name())
destPath := filepath.Join(subdir, entry.Name())
fileInfo, err := os.Stat(sourcePath)
if err != nil {
return err
}
switch fileInfo.Mode() & os.ModeType {
case os.ModeDir:
if err := copyDirectory(sourcePath, destPath); err != nil {
return err
}
case os.ModeSymlink:
if err := copySymLink(sourcePath, destPath); err != nil {
return err
}
default:
if err := copyFile(sourcePath, destPath); err != nil {
return err
}
}
err = chown(sourcePath, destPath, fileInfo)
if err != nil {
return err
}
isSymlink := fileInfo.Mode()&os.ModeSymlink != 0
if !isSymlink {
if err := os.Chmod(destPath, fileInfo.Mode()); err != nil {
return err
}
}
}
return nil
}
// copyFile copies a src file to a dst file where src and dst are regular files.
func copyFile(src, dst string) error {
srcStat, err := os.Stat(src)
if err != nil {
return err
}
if !srcStat.Mode().IsRegular() {
return fmt.Errorf("%s is not a regular file", src)
}
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
destFile, err := os.Create(dst)
if err != nil {
return err
}
defer destFile.Close()
_, err = io.Copy(destFile, srcFile)
return err
}
func createDir(dir string, perm os.FileMode) error {
if entryExists(dir) {
return nil
}
if err := os.MkdirAll(dir, perm); err != nil {
return fmt.Errorf("failed to create directory: '%s', error: '%s'", dir, err.Error())
}
return nil
}
// copySymLink copies a symbolic link from src to dst.
func copySymLink(src, dst string) error {
link, err := os.Readlink(src)
if err != nil {
return err
}
return os.Symlink(link, dst)
}
// find longest common path for path1 and path2. path1 and path2 must be
// absolute paths.
func longestCommonPath(path1, path2 string) string {
if path1 == path2 {
return path1
}
lastSeq := -1
idx := 0
for i := 0; i < min(len(path1), len(path2)); i++ {
if path1[i] != path2[i] {
break
}
idx = i
if path1[i] == os.PathSeparator {
lastSeq = i
}
}
if lastSeq < 0 {
return ""
}
if idx > lastSeq && idx == min(len(path1), len(path2))-1 {
if len(path1) > len(path2) && path1[idx+1] == os.PathSeparator {
return path1[:idx+1]
} else if len(path2) > len(path1) && path2[idx+1] == os.PathSeparator {
return path2[:idx+1]
}
}
// without the trailing seqarator.
return path1[:lastSeq]
}
// find the node that has its Path equals path.
// The node is an artitary node of a tree.
func findNodeInTree(node *EntryNode, path string) *EntryNode {
if path == node.Path {
return node
}
commonPath := longestCommonPath(node.Path, path)
if commonPath == "" {
return nil
}
commonNode := node
for {
if commonNode.Path == commonPath {
break
}
commonNode = commonNode.Parent
if commonNode == nil {
return nil
}
}
if commonNode.Path == path {
return commonNode
}
// search decencents
children := commonNode.children
LOOP:
for len(children) > 0 {
for _, child := range children {
if child.Path == path {
return child
}
if child.Path == node.Path {
continue
}
if len(child.children) > 0 {
children = child.children
goto LOOP
}
}
break
}
return nil
}