-
Notifications
You must be signed in to change notification settings - Fork 142
/
find.go
116 lines (96 loc) · 2.46 KB
/
find.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
package the_platinum_searcher
import (
"path/filepath"
"regexp"
"strings"
"sync"
"github.com/monochromegane/go-gitignore"
)
type find struct {
out chan string
opts Option
}
func (f find) start(roots []string, regexp *regexp.Regexp) {
defer close(f.out)
if f.opts.SearchOption.SearchStream {
f.out <- ""
} else if len(roots) == 1 {
f.findFile(roots[0], regexp)
} else {
f.findFiles(roots, regexp)
}
}
func (f find) findFiles(roots []string, reg *regexp.Regexp) {
wg := &sync.WaitGroup{}
wg.Add(len(roots))
for _, r := range roots {
go func(root string, reg *regexp.Regexp, wg *sync.WaitGroup) {
defer wg.Done()
f.findFile(root, reg)
}(r, reg, wg)
}
wg.Wait()
}
func (f find) findFile(root string, regexp *regexp.Regexp) {
var ignores ignoreMatchers
// add ignores from ignore option.
if len(f.opts.SearchOption.Ignore) > 0 {
ignores = append(ignores, gitignore.NewGitIgnoreFromReader(
root,
strings.NewReader(strings.Join(f.opts.SearchOption.Ignore, "\n")),
))
}
// add global gitignore.
if f.opts.SearchOption.GlobalGitIgnore {
if ignore := globalGitIgnore(root); ignore != nil {
ignores = append(ignores, ignore)
}
}
// add home ptignore.
if f.opts.SearchOption.HomePtIgnore {
if ignore := homePtIgnore(root); ignore != nil {
ignores = append(ignores, ignore)
}
}
followed := f.opts.SearchOption.Follow
walkIn(root, ignores, followed, func(path string, info *fileInfo, depth int, ignores ignoreMatchers) (ignoreMatchers, error) {
if info.isDir(followed) {
if depth > f.opts.SearchOption.Depth+1 {
return ignores, filepath.SkipDir
}
if !f.opts.SearchOption.Hidden && isHidden(info.name) {
return ignores, filepath.SkipDir
}
if ignores.Match(path, true) {
return ignores, filepath.SkipDir
}
if !f.opts.SearchOption.SkipVcsIgnore {
ignores = append(ignores, newIgnoreMatchers(path, f.opts.SearchOption.VcsIgnore)...)
}
return ignores, nil
}
if !f.opts.SearchOption.Follow && info.isSymlink() {
return ignores, nil
}
if info.isNamedPipe() {
return ignores, nil
}
if !f.opts.SearchOption.Hidden && isHidden(info.name) {
return ignores, filepath.SkipDir
}
if ignores.Match(path, false) {
return ignores, nil
}
if regexp != nil && !regexp.MatchString(path) {
return ignores, nil
}
f.out <- path
return ignores, nil
})
}
func isHidden(name string) bool {
if name == "." || name == ".." {
return false
}
return len(name) > 1 && name[0] == '.'
}