-
Notifications
You must be signed in to change notification settings - Fork 141
/
extended_grep.go
57 lines (48 loc) · 1.02 KB
/
extended_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
package the_platinum_searcher
import (
"io"
"log"
"os"
)
type extendedGrep struct {
lineGrep
pattern pattern
}
func (g extendedGrep) grep(path string, buf []byte) {
f, err := getFileHandler(path)
if err != nil {
log.Fatalf("open: %s\n", err)
}
defer f.Close()
if f == os.Stdin {
// TODO: File type is fixed in ASCII because it can not determine the character code.
g.grepEachLines(f, ASCII, func(b []byte) bool {
return g.pattern.regexp.Match(b)
}, func(b []byte) int {
return g.pattern.regexp.FindIndex(b)[0] + 1
})
return
}
c, err := f.Read(buf)
if err != nil && err != io.EOF {
log.Fatalf("read: %s\n", err)
}
if err == io.EOF {
return
}
// detect encoding.
limit := c
if limit > 512 {
limit = 512
}
encoding := detectEncoding(buf[:limit])
if encoding == ERROR || encoding == BINARY {
return
}
// grep each lines.
g.grepEachLines(f, encoding, func(b []byte) bool {
return g.pattern.regexp.Match(b)
}, func(b []byte) int {
return g.pattern.regexp.FindIndex(b)[0] + 1
})
}