-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathgrep.go
80 lines (72 loc) · 1.42 KB
/
grep.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
package the_platinum_searcher
import (
"math"
"runtime"
"sync"
)
var newLine = []byte("\n")
type grep struct {
in chan string
done chan struct{}
grepper grepper
printer printer
opts Option
}
func newGrep(pattern pattern, in chan string, done chan struct{}, opts Option, printer printer) grep {
return grep{
in: in,
done: done,
grepper: newGrepper(
pattern,
printer,
opts,
),
printer: printer,
opts: opts,
}
}
func (g grep) start() {
wg := &sync.WaitGroup{}
worker := func() {
defer wg.Done()
buf := make([]byte, 16384)
for path := range g.in {
g.grepper.grep(path, buf)
}
}
num := int(math.Max(float64(runtime.NumCPU()), 2.0))
for i := 0; i < num; i++ {
wg.Add(1)
go worker()
}
wg.Wait()
close(g.printer.in)
g.done <- <-g.printer.done
}
type grepper interface {
grep(path string, buf []byte)
}
func newGrepper(pattern pattern, printer printer, opts Option) grepper {
if opts.SearchOption.EnableFilesWithRegexp {
return passthroughGrep{
printer: printer,
}
} else if opts.SearchOption.Regexp {
return extendedGrep{
pattern: pattern,
lineGrep: newLineGrep(printer, opts),
}
} else {
if opts.OutputOption.Before > 0 || opts.OutputOption.After > 0 {
return fixedGrep{
pattern: pattern,
lineGrep: newLineGrep(printer, opts),
}
}
return bufferGrep{
pattern: pattern,
printer: printer,
column: opts.OutputOption.Column,
}
}
}