Repository navigation
Expand file tree
/
Copy pathdiff_filter.go
More file actions
286 lines (253 loc) · 7.56 KB
/
Copy pathdiff_filter.go
File metadata and controls
286 lines (253 loc) · 7.56 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package git
import (
"bytes"
"fmt"
"io"
"regexp"
"unicode/utf8"
"github.com/sourcegraph/sourcegraph/pkg/pathmatch"
"sourcegraph.com/sourcegraph/go-diff/diff"
)
// compilePathMatcher compiles the path options into a PathMatcher.
func compilePathMatcher(options PathOptions) (pathmatch.PathMatcher, error) {
return pathmatch.CompilePathPatterns(
options.IncludePatterns, options.ExcludePattern,
pathmatch.CompileOptions{CaseSensitive: options.IsCaseSensitive, RegExp: options.IsRegExp},
)
}
// filterAndHighlightDiff returns the raw diff with query matches highlighted
// and only hunks that satisfy the query (if onlyMatchingHunks) and path matcher.
func filterAndHighlightDiff(rawDiff []byte, query *regexp.Regexp, onlyMatchingHunks bool, pathMatcher pathmatch.PathMatcher) ([]byte, []Highlight, error) {
const (
maxFiles = 5
maxHunksPerFile = 3
matchContextLines = 1
maxLinesPerHunk = 5
maxMatchesPerLine = 100
maxCharsPerLine = 200
)
dr := diff.NewMultiFileDiffReader(bytes.NewReader(rawDiff))
var matchingFileDiffs []*diff.FileDiff
for i := 0; ; i++ {
fileDiff, err := dr.ReadFile()
if err == io.EOF {
break
} else if err != nil {
return nil, nil, err
}
// Exclude files whose names don't match.
origNameMatches := fileDiff.OrigName != "/dev/null" && pathMatcher.MatchPath(fileDiff.OrigName)
newNameMatches := fileDiff.NewName != "/dev/null" && pathMatcher.MatchPath(fileDiff.NewName)
if !origNameMatches && !newNameMatches {
continue
}
// TODO(sqs): preserve the "no newline" message. We clear it out because our truncateLongLines
// and splitHunkMatches funcs don't properly adjust its offset as they modify hunk.Body. If
// the OrigNoNewlineAt points to an out-of-bounds offset, a panic will occur.
for _, hunk := range fileDiff.Hunks {
hunk.OrigNoNewlineAt = 0
}
// Truncate long lines, for perf.
for _, hunk := range fileDiff.Hunks {
hunk.Body = truncateLongLines(hunk.Body, maxCharsPerLine)
}
// Exclude hunks not matching the query.
if onlyMatchingHunks {
fileDiff.Hunks = splitHunkMatches(fileDiff.Hunks, query, matchContextLines, maxLinesPerHunk)
}
if len(fileDiff.Hunks) > 0 {
if len(fileDiff.Hunks) > maxHunksPerFile {
fileDiff.Hunks = fileDiff.Hunks[:maxHunksPerFile]
}
matchingFileDiffs = append(matchingFileDiffs, fileDiff)
}
}
if len(matchingFileDiffs) > maxFiles {
matchingFileDiffs = matchingFileDiffs[:maxFiles]
} else if len(matchingFileDiffs) == 0 {
return nil, nil, nil
}
var err error
rawDiff, err = diff.PrintMultiFileDiff(matchingFileDiffs)
if err != nil {
return nil, nil, err
}
// Highlight query matches in raw diff.
var highlights []Highlight
ignoreUntilAfterAtAt := false
for i, line := range bytes.Split(rawDiff, []byte("\n")) {
// Don't highlight matches that are not in the body (such as "+++ file1" or "--- file1").
if ignoreUntilAfterAtAt {
if atAt := bytes.HasPrefix(line, []byte("@@")); atAt {
ignoreUntilAfterAtAt = false
continue
}
}
if bytes.HasPrefix(line, []byte("diff ")) {
ignoreUntilAfterAtAt = true
continue
}
// Always ignore subsequent "@@" lines, which are hunk headers.
if bytes.HasPrefix(line, []byte("@@")) {
continue
}
if len(line) == 0 {
continue
}
if query != nil {
lineWithoutStatus := line[1:] // don't match '-' or '+' line status
for _, match := range query.FindAllIndex(lineWithoutStatus, maxMatchesPerLine) {
highlights = append(highlights, Highlight{
Line: i + 1,
Character: match[0] + 1,
Length: match[1] - match[0],
})
}
}
}
return rawDiff, highlights, nil
}
func truncateLongLines(data []byte, maxCharsPerLine int) []byte {
// We reuse data's storage to avoid allocation.
offset := 0
lineLength := 0
hasSeenTruncatedLine := false // avoid writing until we need to
r := bytes.NewReader(data)
for {
r, n, err := r.ReadRune()
if err != nil {
if err != io.EOF {
panic(err)
}
break
}
if r == '\n' {
lineLength = -1 // will be incremented immediately after to 0
}
if lineLength < maxCharsPerLine {
if hasSeenTruncatedLine {
utf8.EncodeRune(data[offset:], r)
}
offset += n
lineLength++
} else {
hasSeenTruncatedLine = true
}
}
return data[:offset]
}
func diffHunkLineStatus(line []byte) (added, removed bool) {
if len(line) >= 1 {
added = line[0] == '+'
removed = line[0] == '-'
}
return
}
type diffHunkLineInfo struct {
added bool // line starts with '+'
removed bool // line starts with '-'
matching bool // line matches query (only computed for changed lines)
context bool // include because it's context for a matching changed line
}
func (info diffHunkLineInfo) changed() bool { return info.added || info.removed }
func computeDiffHunkInfo(lines [][]byte, query *regexp.Regexp, matchContextLines int) []diffHunkLineInfo {
// Return context line numbers for a given line number.
contextLines := func(line int) (start, end int) {
start = line - matchContextLines
if start < 0 {
start = 0
}
end = line + matchContextLines
if end > len(lines)-1 {
end = len(lines) - 1
}
return
}
lineInfo := make([]diffHunkLineInfo, len(lines))
for i, line := range lines {
lineInfo[i].added, lineInfo[i].removed = diffHunkLineStatus(line)
if lineInfo[i].changed() {
lineInfo[i].matching = query == nil || query.Match(line)
if lineInfo[i].matching {
// Mark context lines before/after matching lines.
start, end := contextLines(i)
for j := start; j <= end; j++ {
if i == j {
continue
}
lineInfo[j].context = true
}
}
}
}
return lineInfo
}
// splitHunkMatches returns a list of hunks that are a subset of the input hunks,
// filtered down to only hunks that match the query. Non-matching context lines
// and non-matching changed lines are eliminated, and the hunk header (start/end
// lines) are adjusted accordingly.
func splitHunkMatches(hunks []*diff.Hunk, query *regexp.Regexp, matchContextLines, maxLinesPerHunk int) (results []*diff.Hunk) {
addExtraHunkMatchesSection := func(hunk *diff.Hunk, extraHunkMatches int) {
if extraHunkMatches > 0 {
if hunk.Section != "" {
hunk.Section += " "
}
hunk.Section += fmt.Sprintf("... +%d", extraHunkMatches)
}
}
for _, hunk := range hunks {
var cur *diff.Hunk
var curLines [][]byte
lines := bytes.SplitAfter(hunk.Body, []byte("\n"))
lineInfo := computeDiffHunkInfo(lines, query, matchContextLines)
extraHunkMatches := 0
var origLineOffset, newLineOffset int32
for i, line := range lines {
if len(line) == 0 {
break
}
lineInfo := lineInfo[i]
if lineInfo.matching || lineInfo.context {
if maxLinesPerHunk > 0 && len(curLines) == matchContextLines*2+maxLinesPerHunk {
if lineInfo.matching {
extraHunkMatches++
}
continue
}
if cur == nil {
cur = &diff.Hunk{
OrigStartLine: hunk.OrigStartLine + origLineOffset,
NewStartLine: hunk.NewStartLine + newLineOffset,
Section: hunk.Section,
}
}
if !lineInfo.added {
cur.OrigLines++
}
if !lineInfo.removed {
cur.NewLines++
}
curLines = append(curLines, line)
} else if cur != nil {
addExtraHunkMatchesSection(cur, extraHunkMatches)
cur.Body = bytes.Join(curLines, nil)
results = append(results, cur)
cur = nil
curLines = nil
extraHunkMatches = 0
}
if !lineInfo.added {
origLineOffset++
}
if !lineInfo.removed {
newLineOffset++
}
}
if cur != nil {
addExtraHunkMatchesSection(cur, extraHunkMatches)
cur.Body = bytes.Join(curLines, nil)
results = append(results, cur)
}
}
return results
}