-
Notifications
You must be signed in to change notification settings - Fork 128
/
diff.go
558 lines (477 loc) · 12.4 KB
/
diff.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
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
// Copyright 2020 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package git
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"strconv"
"strings"
)
// DiffLineType is the line type in diff.
type DiffLineType uint8
// A list of different line types.
const (
DiffLinePlain DiffLineType = iota + 1
DiffLineAdd
DiffLineDelete
DiffLineSection
)
// DiffFileType is the file status in diff.
type DiffFileType uint8
// A list of different file statuses.
const (
DiffFileAdd DiffFileType = iota + 1
DiffFileChange
DiffFileDelete
DiffFileRename
)
// DiffLine represents a line in diff.
type DiffLine struct {
Type DiffLineType // The type of the line
Content string // The content of the line
LeftLine int // The left line number
RightLine int // The right line number
}
// DiffSection represents a section in diff.
type DiffSection struct {
Lines []*DiffLine // lines in the section
numAdditions int
numDeletions int
}
// NumLines returns the number of lines in the section.
func (s *DiffSection) NumLines() int {
return len(s.Lines)
}
// Line returns a specific line by given type and line number in a section.
func (s *DiffSection) Line(typ DiffLineType, line int) *DiffLine {
var (
difference = 0
addCount = 0
delCount = 0
matchedDiffLine *DiffLine
)
loop:
for _, diffLine := range s.Lines {
switch diffLine.Type {
case DiffLineAdd:
addCount++
case DiffLineDelete:
delCount++
default:
if matchedDiffLine != nil {
break loop
}
difference = diffLine.RightLine - diffLine.LeftLine
addCount = 0
delCount = 0
}
switch typ {
case DiffLineDelete:
if diffLine.RightLine == 0 && diffLine.LeftLine == line-difference {
matchedDiffLine = diffLine
}
case DiffLineAdd:
if diffLine.LeftLine == 0 && diffLine.RightLine == line+difference {
matchedDiffLine = diffLine
}
}
}
if addCount == delCount {
return matchedDiffLine
}
return nil
}
// DiffFile represents a file in diff.
type DiffFile struct {
// The name of the file.
Name string
// The type of the file.
Type DiffFileType
// The index (SHA1 hash) of the file. For a changed/new file, it is the new SHA,
// and for a deleted file it becomes "000000".
Index string
// OldIndex is the old index (SHA1 hash) of the file.
OldIndex string
// The sections in the file.
Sections []*DiffSection
numAdditions int
numDeletions int
oldName string
mode EntryMode
oldMode EntryMode
isBinary bool
isSubmodule bool
isIncomplete bool
}
// NumSections returns the number of sections in the file.
func (f *DiffFile) NumSections() int {
return len(f.Sections)
}
// NumAdditions returns the number of additions in the file.
func (f *DiffFile) NumAdditions() int {
return f.numAdditions
}
// NumDeletions returns the number of deletions in the file.
func (f *DiffFile) NumDeletions() int {
return f.numDeletions
}
// IsCreated returns true if the file is newly created.
func (f *DiffFile) IsCreated() bool {
return f.Type == DiffFileAdd
}
// IsDeleted returns true if the file has been deleted.
func (f *DiffFile) IsDeleted() bool {
return f.Type == DiffFileDelete
}
// IsRenamed returns true if the file has been renamed.
func (f *DiffFile) IsRenamed() bool {
return f.Type == DiffFileRename
}
// OldName returns previous name before renaming.
func (f *DiffFile) OldName() string {
return f.oldName
}
// Mode returns the mode of the file.
func (f *DiffFile) Mode() EntryMode {
return f.mode
}
// OldMode returns the old mode of the file if it's changed.
func (f *DiffFile) OldMode() EntryMode {
return f.oldMode
}
// IsBinary returns true if the file is in binary format.
func (f *DiffFile) IsBinary() bool {
return f.isBinary
}
// IsSubmodule returns true if the file contains information of a submodule.
func (f *DiffFile) IsSubmodule() bool {
return f.isSubmodule
}
// IsIncomplete returns true if the file is incomplete to the file diff.
func (f *DiffFile) IsIncomplete() bool {
return f.isIncomplete
}
// Diff represents a Git diff.
type Diff struct {
Files []*DiffFile // The files in the diff
totalAdditions int
totalDeletions int
isIncomplete bool
}
// NumFiles returns the number of files in the diff.
func (d *Diff) NumFiles() int {
return len(d.Files)
}
// TotalAdditions returns the total additions in the diff.
func (d *Diff) TotalAdditions() int {
return d.totalAdditions
}
// TotalDeletions returns the total deletions in the diff.
func (d *Diff) TotalDeletions() int {
return d.totalDeletions
}
// IsIncomplete returns true if the file is incomplete to the entire diff.
func (d *Diff) IsIncomplete() bool {
return d.isIncomplete
}
// SteamParseDiffResult contains results of streaming parsing a diff.
type SteamParseDiffResult struct {
Diff *Diff
Err error
}
type diffParser struct {
*bufio.Reader
maxFiles int
maxFileLines int
maxLineChars int
// The next line that hasn't been processed. It is used to determine what kind
// of process should go in.
buffer []byte
isEOF bool
}
func (p *diffParser) readLine() error {
if p.buffer != nil {
return nil
}
var err error
p.buffer, err = p.ReadBytes('\n')
if err != nil {
if err != io.EOF {
return fmt.Errorf("read string: %v", err)
}
p.isEOF = true
}
// Remove line break
if len(p.buffer) > 0 && p.buffer[len(p.buffer)-1] == '\n' {
p.buffer = p.buffer[:len(p.buffer)-1]
}
return nil
}
var diffHead = []byte("diff --git ")
func (p *diffParser) parseFileHeader() (*DiffFile, error) {
line := string(p.buffer)
p.buffer = nil
// NOTE: In case file name is surrounded by double quotes (it happens only in
// git-shell). e.g. diff --git "a/xxx" "b/xxx"
var middle int
hasQuote := line[len(diffHead)] == '"'
if hasQuote {
middle = strings.Index(line, ` "b/`)
} else {
middle = strings.Index(line, ` b/`)
}
beg := len(diffHead)
a := line[beg+2 : middle]
b := line[middle+3:]
if hasQuote {
a = string(UnescapeChars([]byte(a[1 : len(a)-1])))
b = string(UnescapeChars([]byte(b[1 : len(b)-1])))
}
file := &DiffFile{
Name: a,
oldName: b,
Type: DiffFileChange,
}
// Check file diff type and submodule
var err error
checkType:
for !p.isEOF {
if err = p.readLine(); err != nil {
return nil, err
}
line := string(p.buffer)
p.buffer = nil
if len(line) == 0 {
continue
}
switch {
case strings.HasPrefix(line, "new file"):
file.Type = DiffFileAdd
file.isSubmodule = strings.HasSuffix(line, " 160000")
fields := strings.Fields(line)
if len(fields) > 0 {
mode, _ := strconv.ParseUint(fields[len(fields)-1], 8, 64)
file.mode = EntryMode(mode)
if file.oldMode == 0 {
file.oldMode = file.mode
}
}
case strings.HasPrefix(line, "deleted"):
file.Type = DiffFileDelete
file.isSubmodule = strings.HasSuffix(line, " 160000")
fields := strings.Fields(line)
if len(fields) > 0 {
mode, _ := strconv.ParseUint(fields[len(fields)-1], 8, 64)
file.mode = EntryMode(mode)
if file.oldMode == 0 {
file.oldMode = file.mode
}
}
case strings.HasPrefix(line, "index"): // e.g. index ee791be..9997571 100644
fields := strings.Fields(line[6:])
shas := strings.Split(fields[0], "..")
if len(shas) != 2 {
return nil, errors.New("malformed index: expect two SHAs in the form of <old>..<new>")
}
file.OldIndex = shas[0]
file.Index = shas[1]
if len(fields) > 1 {
mode, _ := strconv.ParseUint(fields[1], 8, 64)
file.mode = EntryMode(mode)
file.oldMode = EntryMode(mode)
}
break checkType
case strings.HasPrefix(line, "similarity index "):
file.Type = DiffFileRename
file.oldName = a
file.Name = b
// No need to look for index if it's a pure rename
if strings.HasSuffix(line, "100%") {
break checkType
}
case strings.HasPrefix(line, "new mode"):
fields := strings.Fields(line)
if len(fields) > 0 {
mode, _ := strconv.ParseUint(fields[len(fields)-1], 8, 64)
file.mode = EntryMode(mode)
}
case strings.HasPrefix(line, "old mode"):
fields := strings.Fields(line)
if len(fields) > 0 {
mode, _ := strconv.ParseUint(fields[len(fields)-1], 8, 64)
file.oldMode = EntryMode(mode)
}
}
}
return file, nil
}
func (p *diffParser) parseSection() (_ *DiffSection, isIncomplete bool, _ error) {
line := string(p.buffer)
p.buffer = nil
section := &DiffSection{
Lines: []*DiffLine{
{
Type: DiffLineSection,
Content: line,
},
},
}
// Parse line number, e.g. @@ -0,0 +1,3 @@
var leftLine, rightLine int
ss := strings.Split(line, "@@")
ranges := strings.Split(ss[1][1:], " ")
leftLine, _ = strconv.Atoi(strings.Split(ranges[0], ",")[0][1:])
if len(ranges) > 1 {
rightLine, _ = strconv.Atoi(strings.Split(ranges[1], ",")[0])
} else {
rightLine = leftLine
}
var err error
for !p.isEOF {
if err = p.readLine(); err != nil {
return nil, false, err
}
if len(p.buffer) == 0 {
p.buffer = nil
continue
}
// Make sure we're still in the section. If not, we're done with this section.
if p.buffer[0] != ' ' &&
p.buffer[0] != '+' &&
p.buffer[0] != '-' {
// No new line indicator
if p.buffer[0] == '\\' &&
bytes.HasPrefix(p.buffer, []byte(`\ No newline at end of file`)) {
p.buffer = nil
continue
}
return section, false, nil
}
line := string(p.buffer)
p.buffer = nil
// Too many characters in a single diff line
if p.maxLineChars > 0 && len(line) > p.maxLineChars {
return section, true, nil
}
switch line[0] {
case ' ':
section.Lines = append(section.Lines, &DiffLine{
Type: DiffLinePlain,
Content: line,
LeftLine: leftLine,
RightLine: rightLine,
})
leftLine++
rightLine++
case '+':
section.Lines = append(section.Lines, &DiffLine{
Type: DiffLineAdd,
Content: line,
RightLine: rightLine,
})
section.numAdditions++
rightLine++
case '-':
section.Lines = append(section.Lines, &DiffLine{
Type: DiffLineDelete,
Content: line,
LeftLine: leftLine,
})
section.numDeletions++
if leftLine > 0 {
leftLine++
}
}
}
return section, false, nil
}
func (p *diffParser) parse() (*Diff, error) {
diff := new(Diff)
file := new(DiffFile)
currentFileLines := 0
var err error
for !p.isEOF {
if err = p.readLine(); err != nil {
return nil, err
}
if len(p.buffer) == 0 ||
bytes.HasPrefix(p.buffer, []byte("+++ ")) ||
bytes.HasPrefix(p.buffer, []byte("--- ")) {
p.buffer = nil
continue
}
// Found new file
if bytes.HasPrefix(p.buffer, diffHead) {
// Check if reached maximum number of files
if p.maxFiles > 0 && len(diff.Files) >= p.maxFiles {
diff.isIncomplete = true
_, _ = io.Copy(ioutil.Discard, p)
break
}
file, err = p.parseFileHeader()
if err != nil {
return nil, err
}
diff.Files = append(diff.Files, file)
currentFileLines = 0
continue
}
if file == nil || file.isIncomplete {
p.buffer = nil
continue
}
if bytes.HasPrefix(p.buffer, []byte("Binary")) {
p.buffer = nil
file.isBinary = true
continue
}
// Loop until we found section header
if p.buffer[0] != '@' {
p.buffer = nil
continue
}
// Too many diff lines for the file
if p.maxFileLines > 0 && currentFileLines > p.maxFileLines {
file.isIncomplete = true
diff.isIncomplete = true
continue
}
section, isIncomplete, err := p.parseSection()
if err != nil {
return nil, err
}
file.Sections = append(file.Sections, section)
file.numAdditions += section.numAdditions
file.numDeletions += section.numDeletions
diff.totalAdditions += section.numAdditions
diff.totalDeletions += section.numDeletions
currentFileLines += section.NumLines()
if isIncomplete {
file.isIncomplete = true
diff.isIncomplete = true
}
}
return diff, nil
}
// StreamParseDiff parses the diff read from the given io.Reader. It does
// parse-on-read to minimize the time spent on huge diffs. It accepts a channel
// to notify and send error (if any) to the caller when the process is done.
// Therefore, this method should be called in a goroutine asynchronously.
func StreamParseDiff(r io.Reader, done chan<- SteamParseDiffResult, maxFiles, maxFileLines, maxLineChars int) {
p := &diffParser{
Reader: bufio.NewReader(r),
maxFiles: maxFiles,
maxFileLines: maxFileLines,
maxLineChars: maxLineChars,
}
diff, err := p.parse()
done <- SteamParseDiffResult{
Diff: diff,
Err: err,
}
}