-
Notifications
You must be signed in to change notification settings - Fork 0
/
grep.go
53 lines (46 loc) · 999 Bytes
/
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
package main
import (
"bufio"
"io"
"regexp"
)
type grepMatch struct {
line string
lineno int64
}
type grepResults struct {
isBinary bool
matches []grepMatch
}
func grep(contents io.Reader, pattern *regexp.Regexp, limit int) (*grepResults, error) {
if contents == nil || pattern == nil {
return &grepResults{}, nil
}
reader := bufio.NewReader(contents)
chunk, _ := reader.Peek(256)
for i := 0; i < len(chunk); i++ {
if chunk[i] == 0 {
return &grepResults{isBinary: true}, nil // Skip if the contents is binary.
}
}
chunk = nil
var (
lineno int64
results = &grepResults{}
)
scanner := bufio.NewScanner(reader)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
if limit > 0 && len(results.matches) >= limit {
break
}
lineno++
if pattern.Match(scanner.Bytes()) {
results.matches = append(results.matches, grepMatch{line: scanner.Text(), lineno: lineno})
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return results, nil
}