-
Notifications
You must be signed in to change notification settings - Fork 2
/
walk.go
129 lines (111 loc) · 2.3 KB
/
walk.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
package lib
import (
"context"
"errors"
"io/fs"
"github.com/Files-com/files-sdk-go/v2/file/manager"
"github.com/zenthangplus/goccm"
)
type Walk[T any] struct {
fs.FS
Queue[string]
IterChan[T]
goccm.ConcurrencyManager
Root string
WalkFile func(d fs.DirEntry, path string) (T, error)
ListDirectories bool
}
type DirEntry struct {
fs.DirEntry
fs.FileInfo
path string
error
}
func (d DirEntry) Error() error {
return d.error
}
func (d DirEntry) Path() string {
return d.path
}
func (w *Walk[T]) Walk(ctx context.Context) *IterChan[T] {
w.Queue.Init(1)
it := (&IterChan[T]{}).Init()
if w.Root == "" {
w.Queue.Push(".")
} else {
w.Queue.Push(w.Root)
}
waitGroup := manager.WithWaitGroup(w.ConcurrencyManager)
go func() {
for {
if ctx.Err() != nil {
return
}
if dir := w.Queue.Pop(); dir != "" {
waitGroup.Add()
go func() {
err := w.walkDir(ctx, dir, it)
if err != nil {
it.SendError <- err
}
waitGroup.Done()
}()
}
if w.Len() == 0 {
waitGroup.Wait()
if w.Len() == 0 {
break
}
}
}
it.Stop <- true
}()
return it
}
func (w *Walk[T]) walkDir(ctx context.Context, dir string, it *IterChan[T]) error {
return fs.WalkDir(w.FS, dir, func(path string, d fs.DirEntry, err error) error {
if ctx.Err() != nil {
return ctx.Err()
}
if err != nil {
if errors.Is(err, fs.ErrPermission) {
it.Send <- DirEntry{d, nil, path, err}
return fs.SkipDir
}
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
if NormalizeForComparison(path) == NormalizeForComparison(dir) && d.IsDir() {
if NormalizeForComparison(path) == NormalizeForComparison(w.Root) && w.ListDirectories {
w.send(d, path, it)
}
return nil
}
if d.IsDir() && path != "." {
if w.ListDirectories {
w.send(d, path, it)
}
w.Queue.Push(path)
return fs.SkipDir
}
if !d.Type().IsRegular() {
return nil
}
w.send(d, path, it)
return nil
})
}
func (w *Walk[T]) send(d fs.DirEntry, path string, it *IterChan[T]) {
toSend, err := w.WalkFile(d, path)
if err != nil {
it.SendError <- err
} else {
it.Send <- toSend
}
}
func DirEntryWalkFile(d fs.DirEntry, path string) (DirEntry, error) {
info, err := d.Info()
return DirEntry{DirEntry: d, FileInfo: info, path: path, error: err}, err
}