-
Notifications
You must be signed in to change notification settings - Fork 0
/
scanner.go
84 lines (72 loc) · 1.34 KB
/
scanner.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
package main
import (
"bufio"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
func NewScanner() *Scanner {
return &Scanner{
files: make([]string, 0),
Logger: log.New(ioutil.Discard, "", log.LstdFlags),
}
}
type Scanner struct {
files []string
*log.Logger
result []FileMatch
}
func (me *Scanner) Scan(expr string) error {
re, err := regexp.Compile(expr)
if err != nil {
return err
}
me.result = make([]FileMatch, 0)
for _, filename := range me.Files() {
me.Println("scan:", filename)
fh, err := os.Open(filename)
if err != nil {
return err
}
s := bufio.NewScanner(fh)
var line int
fm := FileMatch{
Filename: filename,
Result: make([]LineMatch, 0),
}
for s.Scan() {
line++ // lines start with 1
text := s.Text()
if re.MatchString(text) {
fm.Result = append(fm.Result, LineMatch{
Line: line,
Text: strings.TrimSpace(text),
})
}
}
fh.Close()
if len(fm.Result) > 0 {
me.result = append(me.result, fm)
}
}
return nil
}
func (me *Scanner) LastResult() []FileMatch {
return me.result
}
// Files returns a filtered list of files
func (me *Scanner) Files() []string {
return me.files
}
// SetFiles to scan
func (me *Scanner) SetFiles(v []string) { me.files = v }
type FileMatch struct {
Filename string
Result []LineMatch
}
type LineMatch struct {
Line int
Text string
}