forked from pivotal-cf/cred-alert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff_scanner.go
83 lines (69 loc) · 1.71 KB
/
diff_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
package diffscanner
import (
"bufio"
"cred-alert/scanners"
"io"
"regexp"
"strconv"
"code.cloudfoundry.org/lager"
)
const MaxLineSize = 1024 * 1024
var fileHeaderRegexp = regexp.MustCompile(`^\+\+\+\s(?:\w\/(.*)|/dev/null)$`)
var hunkHeaderRegexp = regexp.MustCompile(`^@@.*\+(\d+),?\d*\s@@`)
var addedOrExistingLineRegexp = regexp.MustCompile(`^([\s\+])(.*)`)
type DiffScanner struct {
scanner *bufio.Scanner
content []byte
currentPath string
currentLineNumber int
}
func NewDiffScanner(diff io.Reader) *DiffScanner {
buf := make([]byte, 0, 4096)
s := &DiffScanner{
scanner: bufio.NewScanner(diff),
}
s.scanner.Buffer(buf, MaxLineSize)
return s
}
func (d *DiffScanner) Scan(logger lager.Logger) bool {
logger = logger.Session("diff-scanner").Session("scan")
logger.Debug("starting")
defer logger.Debug("done")
for d.scanner.Scan() {
line := d.scanner.Text()
matches := fileHeaderRegexp.FindStringSubmatch(line)
if len(matches) == 2 {
d.currentPath = matches[1]
continue
}
matches = hunkHeaderRegexp.FindStringSubmatch(line)
if len(matches) == 2 {
startLine, err := strconv.Atoi(matches[1])
if err != nil {
logger.Error("failed", err)
break
}
d.currentLineNumber = startLine - 1
continue
}
matches = addedOrExistingLineRegexp.FindStringSubmatch(line)
if len(matches) == 3 {
d.currentLineNumber++
if matches[1] == "+" {
d.content = []byte(matches[2])
return true
}
}
}
return false
}
func (d *DiffScanner) Line(lager.Logger) *scanners.Line {
return &scanners.Line{
Content: d.content,
LineNumber: d.currentLineNumber,
Path: d.currentPath,
}
}
func (d *DiffScanner) Err() error {
return d.scanner.Err()
}