/
finder.go
354 lines (302 loc) · 6.67 KB
/
finder.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
// Package finder Provides a simple and convenient filedir lookup function,
// supports filtering, excluding, matching, ignoring, etc.
// and with some commonly built-in matchers.
package finder
import (
"os"
"path/filepath"
"strings"
)
// FileFinder type alias.
type FileFinder = Finder
// Finder struct
type Finder struct {
// config for finder
c *Config
// last error
err error
// num - founded fs elem number
num int
// ch - founded fs elem chan
ch chan Elem
// caches - cache found fs elem. if config.CacheResult is true
caches []Elem
}
// New instance with source dir paths.
func New(dirs []string) *Finder {
c := NewConfig(dirs...)
return NewWithConfig(c)
}
// NewFinder new instance with source dir paths.
func NewFinder(dirPaths ...string) *Finder { return New(dirPaths) }
// NewWithConfig new instance with config.
func NewWithConfig(c *Config) *Finder {
return &Finder{c: c}
}
// NewEmpty new empty Finder instance
func NewEmpty() *Finder {
return &Finder{c: NewEmptyConfig()}
}
// EmptyFinder new empty Finder instance. alias of NewEmpty()
func EmptyFinder() *Finder { return NewEmpty() }
//
// --------- do finding ---------
//
// Find files in given dir paths. will return a channel, you can use it to get the result.
//
// Usage:
//
// f := NewFinder("/path/to/dir")
// for el := range f.Find() {
// fmt.Println(el.Path())
// }
func (f *Finder) Find() <-chan Elem {
f.find()
return f.ch
}
// Elems find and return founded file Elem. alias of Find()
func (f *Finder) Elems() <-chan Elem { return f.Find() }
// Results find and return founded file Elem. alias of Find()
func (f *Finder) Results() <-chan Elem { return f.Find() }
// FindNames find and return founded file/dir names.
func (f *Finder) FindNames() []string {
paths := make([]string, 0, 8*len(f.c.ScanDirs))
for el := range f.Find() {
paths = append(paths, el.Name())
}
return paths
}
// FindPaths find and return founded file/dir paths.
func (f *Finder) FindPaths() []string {
paths := make([]string, 0, 8*len(f.c.ScanDirs))
for el := range f.Find() {
paths = append(paths, el.Path())
}
return paths
}
// Each founded file or dir Elem.
func (f *Finder) Each(fn func(el Elem)) { f.EachElem(fn) }
// EachElem founded file or dir Elem.
func (f *Finder) EachElem(fn func(el Elem)) {
f.find()
for el := range f.ch {
fn(el)
}
}
// EachPath founded file paths.
func (f *Finder) EachPath(fn func(filePath string)) {
f.EachElem(func(el Elem) {
fn(el.Path())
})
}
// EachFile each file os.File
func (f *Finder) EachFile(fn func(file *os.File)) {
f.EachElem(func(el Elem) {
file, err := os.Open(el.Path())
if err == nil {
fn(file)
} else {
f.err = err
}
})
}
// EachStat each file os.FileInfo
func (f *Finder) EachStat(fn func(fi os.FileInfo, filePath string)) {
f.EachElem(func(el Elem) {
fi, err := el.Info()
if err == nil {
fn(fi, el.Path())
} else {
f.err = err
}
})
}
// EachContents handle each found file contents
func (f *Finder) EachContents(fn func(contents, filePath string)) {
f.EachElem(func(el Elem) {
bs, err := os.ReadFile(el.Path())
if err == nil {
fn(string(bs), el.Path())
} else {
f.err = err
}
})
}
// prepare for find.
func (f *Finder) prepare() {
f.err = nil
f.ch = make(chan Elem, 8)
if f.CacheNum() == 0 {
f.num = 0
}
if f.c == nil {
f.c = NewConfig()
} else {
f.c.Init()
}
}
// do finding
func (f *Finder) find() {
f.prepare()
go func() {
defer close(f.ch)
// read from caches
if f.c.CacheResult && len(f.caches) > 0 {
for _, el := range f.caches {
f.ch <- el
}
return
}
// do finding
var err error
for _, dirPath := range f.c.ScanDirs {
if f.c.UseAbsPath {
dirPath, err = filepath.Abs(dirPath)
if err != nil {
f.err = err
continue
}
}
f.c.depth = 0
f.findDir(dirPath, f.c)
}
}()
}
// code refer filepath.glob()
func (f *Finder) findDir(dirPath string, c *Config) {
des, err := os.ReadDir(dirPath)
if err != nil {
return // ignore I/O error
}
var ok bool
c.depth++
for _, ent := range des {
name := ent.Name()
isDir := ent.IsDir()
if name[0] == '.' {
if isDir {
if c.ExcludeDotDir {
continue
}
} else if c.ExcludeDotFile {
continue
}
}
fullPath := filepath.Join(dirPath, name)
el := NewElem(fullPath, ent)
// apply generic filters
if !applyExMatchers(el, c.ExMatchers) {
continue
}
// --- dir: apply dir filters
if isDir {
if !applyExMatchers(el, c.DirExMatchers) {
continue
}
if len(c.Matchers) > 0 {
ok = applyMatchers(el, c.Matchers)
if !ok && len(c.DirMatchers) > 0 {
ok = applyMatchers(el, c.DirMatchers)
}
} else {
ok = applyMatchers(el, c.DirMatchers)
}
if ok && c.FindFlags&FlagDir > 0 {
if c.CacheResult {
f.caches = append(f.caches, el)
}
f.num++
f.ch <- el
if c.FindFlags == FlagDir {
continue // only find subdir on ok=false
}
}
// find in sub dir.
if c.MaxDepth == 0 || c.depth < c.MaxDepth {
f.findDir(fullPath, c)
c.depth-- // restore depth
}
continue
}
// --- type: file
if c.FindFlags&FlagFile == 0 {
continue
}
// apply file filters
if !applyExMatchers(el, c.FileExMatchers) {
continue
}
if len(c.Matchers) > 0 {
ok = applyMatchers(el, c.Matchers)
if !ok && len(c.FileMatchers) > 0 {
ok = applyMatchers(el, c.FileMatchers)
}
} else {
ok = applyMatchers(el, c.FileMatchers)
}
// write to consumer
if ok && c.FindFlags&FlagFile > 0 {
if c.CacheResult {
f.caches = append(f.caches, el)
}
f.num++
f.ch <- el
}
}
}
func applyMatchers(el Elem, fls []Matcher) bool {
for _, f := range fls {
if f.Apply(el) {
return true
}
}
return len(fls) == 0
}
func applyExMatchers(el Elem, fls []Matcher) bool {
for _, f := range fls {
if f.Apply(el) {
return false
}
}
return true
}
// Reset filters config setting and results info.
func (f *Finder) Reset() {
c := NewConfig(f.c.ScanDirs...)
c.ExcludeDotDir = f.c.ExcludeDotDir
c.FindFlags = f.c.FindFlags
c.MaxDepth = f.c.MaxDepth
f.c = c
f.ResetResult()
}
// ResetResult reset result info.
func (f *Finder) ResetResult() {
f.num = 0
f.err = nil
f.ch = make(chan Elem, 8)
f.caches = []Elem{}
}
// Num get found elem num. only valid after finding.
func (f *Finder) Num() int {
return f.num
}
// Err get last error
func (f *Finder) Err() error {
return f.err
}
// Caches get cached results. only valid after finding.
func (f *Finder) Caches() []Elem {
return f.caches
}
// CacheNum get
func (f *Finder) CacheNum() int {
return len(f.caches)
}
// Config get
func (f *Finder) Config() Config {
return *f.c
}
// String all dir paths
func (f *Finder) String() string {
return strings.Join(f.c.ScanDirs, ";")
}