forked from libgit2/git2go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff_test.go
690 lines (547 loc) · 16.6 KB
/
diff_test.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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
package git
import (
"errors"
"fmt"
"io/ioutil"
"path"
"reflect"
"strings"
"testing"
)
func TestFindSimilar(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
originalTree, newTree := createTestTrees(t, repo)
diffOpt, _ := DefaultDiffOptions()
diff, err := repo.DiffTreeToTree(originalTree, newTree, &diffOpt)
checkFatal(t, err)
if diff == nil {
t.Fatal("no diff returned")
}
findOpts, err := DefaultDiffFindOptions()
checkFatal(t, err)
findOpts.Flags = DiffFindBreakRewrites
err = diff.FindSimilar(&findOpts)
checkFatal(t, err)
numDiffs := 0
numAdded := 0
numDeleted := 0
err = diff.ForEach(func(file DiffDelta, progress float64) (DiffForEachHunkCallback, error) {
numDiffs++
switch file.Status {
case DeltaAdded:
numAdded++
case DeltaDeleted:
numDeleted++
}
return func(hunk DiffHunk) (DiffForEachLineCallback, error) {
return func(line DiffLine) error {
return nil
}, nil
}, nil
}, DiffDetailLines)
if numDiffs != 2 {
t.Fatal("Incorrect number of files in diff")
}
if numAdded != 1 {
t.Fatal("Incorrect number of new files in diff")
}
if numDeleted != 1 {
t.Fatal("Incorrect number of deleted files in diff")
}
}
func TestDiffTreeToTree(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
originalTree, newTree := createTestTrees(t, repo)
callbackInvoked := false
opts := DiffOptions{
NotifyCallback: func(diffSoFar *Diff, delta DiffDelta, matchedPathSpec string) error {
callbackInvoked = true
return nil
},
OldPrefix: "x1/",
NewPrefix: "y1/",
}
diff, err := repo.DiffTreeToTree(originalTree, newTree, &opts)
checkFatal(t, err)
if !callbackInvoked {
t.Fatal("callback not invoked")
}
if diff == nil {
t.Fatal("no diff returned")
}
files := make([]string, 0)
hunks := make([]DiffHunk, 0)
lines := make([]DiffLine, 0)
patches := make([]string, 0)
err = diff.ForEach(func(file DiffDelta, progress float64) (DiffForEachHunkCallback, error) {
patch, err := diff.Patch(len(patches))
if err != nil {
return nil, err
}
defer patch.Free()
patchStr, err := patch.String()
if err != nil {
return nil, err
}
patches = append(patches, patchStr)
files = append(files, file.OldFile.Path)
return func(hunk DiffHunk) (DiffForEachLineCallback, error) {
hunks = append(hunks, hunk)
return func(line DiffLine) error {
lines = append(lines, line)
return nil
}, nil
}, nil
}, DiffDetailLines)
checkFatal(t, err)
if len(files) != 1 {
t.Fatal("Incorrect number of files in diff")
}
if files[0] != "README" {
t.Fatal("File in diff was expected to be README")
}
if len(hunks) != 1 {
t.Fatal("Incorrect number of hunks in diff")
}
if hunks[0].OldStart != 1 || hunks[0].NewStart != 1 {
t.Fatal("Incorrect hunk")
}
if len(lines) != 2 {
t.Fatal("Incorrect number of lines in diff")
}
if lines[0].Content != "foo\n" {
t.Fatal("Incorrect lines in diff")
}
if lines[1].Content != "file changed\n" {
t.Fatal("Incorrect lines in diff")
}
if want1, want2 := "x1/README", "y1/README"; !strings.Contains(patches[0], want1) || !strings.Contains(patches[0], want2) {
t.Errorf("Diff patch doesn't contain %q or %q\n\n%s", want1, want2, patches[0])
}
stats, err := diff.Stats()
checkFatal(t, err)
if stats.Insertions() != 1 {
t.Fatal("Incorrect number of insertions in diff")
}
if stats.Deletions() != 1 {
t.Fatal("Incorrect number of deletions in diff")
}
if stats.FilesChanged() != 1 {
t.Fatal("Incorrect number of changed files in diff")
}
errTest := errors.New("test error")
err = diff.ForEach(func(file DiffDelta, progress float64) (DiffForEachHunkCallback, error) {
return nil, errTest
}, DiffDetailLines)
if err != errTest {
t.Fatal("Expected custom error to be returned")
}
}
func createTestTrees(t *testing.T, repo *Repository) (originalTree *Tree, newTree *Tree) {
var err error
_, originalTreeId := seedTestRepo(t, repo)
originalTree, err = repo.LookupTree(originalTreeId)
checkFatal(t, err)
_, newTreeId := updateReadme(t, repo, "file changed\n")
newTree, err = repo.LookupTree(newTreeId)
checkFatal(t, err)
return originalTree, newTree
}
func TestDiffBlobs(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
odb, err := repo.Odb()
checkFatal(t, err)
id1, err := odb.Write([]byte("hello\nhello\n"), ObjectBlob)
checkFatal(t, err)
id2, err := odb.Write([]byte("hallo\nhallo\n"), ObjectBlob)
checkFatal(t, err)
blob1, err := repo.LookupBlob(id1)
checkFatal(t, err)
blob2, err := repo.LookupBlob(id2)
checkFatal(t, err)
var files, hunks, lines int
err = DiffBlobs(blob1, "hi", blob2, "hi", nil,
func(delta DiffDelta, progress float64) (DiffForEachHunkCallback, error) {
files++
return func(hunk DiffHunk) (DiffForEachLineCallback, error) {
hunks++
return func(line DiffLine) error {
lines++
return nil
}, nil
}, nil
},
DiffDetailLines)
if files != 1 {
t.Fatal("Bad number of files iterated")
}
if hunks != 1 {
t.Fatal("Bad number of hunks iterated")
}
// two removals, two additions
if lines != 4 {
t.Fatalf("Bad number of lines iterated")
}
}
func TestApplyDiffAddfile(t *testing.T) {
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
seedTestRepo(t, repo)
addFirstFileCommit, addFirstFileTree := addAndGetTree(t, repo, "file1", `hello`)
defer addFirstFileCommit.Free()
defer addFirstFileTree.Free()
addSecondFileCommit, addSecondFileTree := addAndGetTree(t, repo, "file2", `hello2`)
defer addSecondFileCommit.Free()
defer addSecondFileTree.Free()
diff, err := repo.DiffTreeToTree(addFirstFileTree, addSecondFileTree, nil)
checkFatal(t, err)
defer diff.Free()
t.Run("check does not apply to current tree because file exists", func(t *testing.T) {
err = repo.ResetToCommit(addSecondFileCommit, ResetHard, &CheckoutOpts{})
checkFatal(t, err)
err = repo.ApplyDiff(diff, ApplyLocationBoth, nil)
if err == nil {
t.Error("expecting applying patch to current repo to fail")
}
})
t.Run("check apply to correct commit", func(t *testing.T) {
err = repo.ResetToCommit(addFirstFileCommit, ResetHard, &CheckoutOpts{})
checkFatal(t, err)
err = repo.ApplyDiff(diff, ApplyLocationBoth, nil)
checkFatal(t, err)
t.Run("Check that diff only changed one file", func(t *testing.T) {
checkSecondFileStaged(t, repo)
index, err := repo.Index()
checkFatal(t, err)
defer index.Free()
newTreeOID, err := index.WriteTreeTo(repo)
checkFatal(t, err)
newTree, err := repo.LookupTree(newTreeOID)
checkFatal(t, err)
defer newTree.Free()
_, err = repo.CreateCommit("HEAD", signature(), signature(), fmt.Sprintf("patch apply"), newTree, addFirstFileCommit)
checkFatal(t, err)
})
t.Run("test applying patch produced the same diff", func(t *testing.T) {
head, err := repo.Head()
checkFatal(t, err)
commit, err := repo.LookupCommit(head.Target())
checkFatal(t, err)
defer commit.Free()
tree, err := commit.Tree()
checkFatal(t, err)
defer tree.Free()
newDiff, err := repo.DiffTreeToTree(addFirstFileTree, tree, nil)
checkFatal(t, err)
defer newDiff.Free()
raw1b, err := diff.ToBuf(DiffFormatPatch)
checkFatal(t, err)
raw2b, err := newDiff.ToBuf(DiffFormatPatch)
checkFatal(t, err)
raw1 := string(raw1b)
raw2 := string(raw2b)
if raw1 != raw2 {
t.Error("diffs should be the same")
}
})
})
t.Run("check convert to raw buffer and apply", func(t *testing.T) {
err = repo.ResetToCommit(addFirstFileCommit, ResetHard, &CheckoutOpts{})
checkFatal(t, err)
raw, err := diff.ToBuf(DiffFormatPatch)
checkFatal(t, err)
if len(raw) == 0 {
t.Error("empty diff created")
}
diff2, err := DiffFromBuffer(raw, repo)
checkFatal(t, err)
defer diff2.Free()
err = repo.ApplyDiff(diff2, ApplyLocationBoth, nil)
checkFatal(t, err)
})
t.Run("check apply callbacks work", func(t *testing.T) {
// reset the state and get new default options for test
resetAndGetOpts := func(t *testing.T) *ApplyOptions {
err = repo.ResetToCommit(addFirstFileCommit, ResetHard, &CheckoutOpts{})
checkFatal(t, err)
opts, err := DefaultApplyOptions()
checkFatal(t, err)
return opts
}
t.Run("Check hunk callback working applies patch", func(t *testing.T) {
opts := resetAndGetOpts(t)
called := false
opts.ApplyHunkCallback = func(hunk *DiffHunk) (apply bool, err error) {
called = true
return true, nil
}
err = repo.ApplyDiff(diff, ApplyLocationBoth, opts)
checkFatal(t, err)
if called == false {
t.Error("apply hunk callback was not called")
}
checkSecondFileStaged(t, repo)
})
t.Run("Check delta callback working applies patch", func(t *testing.T) {
opts := resetAndGetOpts(t)
called := false
opts.ApplyDeltaCallback = func(hunk *DiffDelta) (apply bool, err error) {
if hunk.NewFile.Path != "file2" {
t.Error("Unexpected delta in diff application")
}
called = true
return true, nil
}
err = repo.ApplyDiff(diff, ApplyLocationBoth, opts)
checkFatal(t, err)
if called == false {
t.Error("apply hunk callback was not called")
}
checkSecondFileStaged(t, repo)
})
t.Run("Check delta callback returning false does not apply patch", func(t *testing.T) {
opts := resetAndGetOpts(t)
called := false
opts.ApplyDeltaCallback = func(hunk *DiffDelta) (apply bool, err error) {
if hunk.NewFile.Path != "file2" {
t.Error("Unexpected hunk in diff application")
}
called = true
return false, nil
}
err = repo.ApplyDiff(diff, ApplyLocationBoth, opts)
checkFatal(t, err)
if called == false {
t.Error("apply hunk callback was not called")
}
checkNoFilesStaged(t, repo)
})
t.Run("Check hunk callback returning causes application to fail", func(t *testing.T) {
opts := resetAndGetOpts(t)
called := false
opts.ApplyHunkCallback = func(hunk *DiffHunk) (apply bool, err error) {
called = true
return false, errors.New("something happened")
}
err = repo.ApplyDiff(diff, ApplyLocationBoth, opts)
if err == nil {
t.Error("expected an error after trying to apply")
}
if called == false {
t.Error("apply hunk callback was not called")
}
checkNoFilesStaged(t, repo)
})
t.Run("Check delta callback returning causes application to fail", func(t *testing.T) {
opts := resetAndGetOpts(t)
called := false
opts.ApplyDeltaCallback = func(hunk *DiffDelta) (apply bool, err error) {
if hunk.NewFile.Path != "file2" {
t.Error("Unexpected delta in diff application")
}
called = true
return false, errors.New("something happened")
}
err = repo.ApplyDiff(diff, ApplyLocationBoth, opts)
if err == nil {
t.Error("expected an error after trying to apply")
}
if called == false {
t.Error("apply hunk callback was not called")
}
checkNoFilesStaged(t, repo)
})
})
}
func TestApplyToTree(t *testing.T) {
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
seedTestRepo(t, repo)
commitA, treeA := addAndGetTree(t, repo, "file", "a")
defer commitA.Free()
defer treeA.Free()
commitB, treeB := addAndGetTree(t, repo, "file", "b")
defer commitB.Free()
defer treeB.Free()
commitC, treeC := addAndGetTree(t, repo, "file", "c")
defer commitC.Free()
defer treeC.Free()
diffAB, err := repo.DiffTreeToTree(treeA, treeB, nil)
checkFatal(t, err)
diffAC, err := repo.DiffTreeToTree(treeA, treeC, nil)
checkFatal(t, err)
for _, tc := range []struct {
name string
tree *Tree
diff *Diff
applyHunkCallback ApplyHunkCallback
applyDeltaCallback ApplyDeltaCallback
error error
expectedDiff *Diff
}{
{
name: "applying patch produces the same diff",
tree: treeA,
diff: diffAB,
expectedDiff: diffAB,
},
{
name: "applying a conflicting patch errors",
tree: treeB,
diff: diffAC,
error: &GitError{
Message: "hunk at line 1 did not apply",
Code: ErrApplyFail,
Class: ErrClassPatch,
},
},
{
name: "callbacks succeeding apply the diff",
tree: treeA,
diff: diffAB,
applyHunkCallback: func(*DiffHunk) (bool, error) { return true, nil },
applyDeltaCallback: func(*DiffDelta) (bool, error) { return true, nil },
expectedDiff: diffAB,
},
{
name: "hunk callback returning false does not apply",
tree: treeA,
diff: diffAB,
applyHunkCallback: func(*DiffHunk) (bool, error) { return false, nil },
},
{
name: "hunk callback erroring fails the call",
tree: treeA,
diff: diffAB,
applyHunkCallback: func(*DiffHunk) (bool, error) { return true, errors.New("message dropped") },
error: &GitError{
Code: ErrGeneric,
Class: ErrClassInvalid,
},
},
{
name: "delta callback returning false does not apply",
tree: treeA,
diff: diffAB,
applyDeltaCallback: func(*DiffDelta) (bool, error) { return false, nil },
},
{
name: "delta callback erroring fails the call",
tree: treeA,
diff: diffAB,
applyDeltaCallback: func(*DiffDelta) (bool, error) { return true, errors.New("message dropped") },
error: &GitError{
Code: ErrGeneric,
Class: ErrClassInvalid,
},
},
} {
t.Run(tc.name, func(t *testing.T) {
opts, err := DefaultApplyOptions()
checkFatal(t, err)
opts.ApplyHunkCallback = tc.applyHunkCallback
opts.ApplyDeltaCallback = tc.applyDeltaCallback
index, err := repo.ApplyToTree(tc.diff, tc.tree, opts)
if tc.error != nil {
if !reflect.DeepEqual(err, tc.error) {
t.Fatalf("expected error %q but got %q", tc.error, err)
}
return
}
checkFatal(t, err)
patchedTreeOID, err := index.WriteTreeTo(repo)
checkFatal(t, err)
patchedTree, err := repo.LookupTree(patchedTreeOID)
checkFatal(t, err)
patchedDiff, err := repo.DiffTreeToTree(tc.tree, patchedTree, nil)
checkFatal(t, err)
appliedRaw, err := patchedDiff.ToBuf(DiffFormatPatch)
checkFatal(t, err)
if tc.expectedDiff == nil {
if len(appliedRaw) > 0 {
t.Fatalf("expected no diff but got: %s", appliedRaw)
}
return
}
expectedDiff, err := tc.expectedDiff.ToBuf(DiffFormatPatch)
checkFatal(t, err)
if string(expectedDiff) != string(appliedRaw) {
t.Fatalf("diffs do not match:\nexpected: %s\n\nactual: %s", expectedDiff, appliedRaw)
}
})
}
}
// checkSecondFileStaged checks that there is a single file called "file2" uncommitted in the repo
func checkSecondFileStaged(t *testing.T, repo *Repository) {
opts := StatusOptions{
Show: StatusShowIndexAndWorkdir,
Flags: StatusOptIncludeUntracked,
}
statuses, err := repo.StatusList(&opts)
checkFatal(t, err)
count, err := statuses.EntryCount()
checkFatal(t, err)
if count != 1 {
t.Error("diff should affect exactly one file")
}
if count == 0 {
t.Fatal("no statuses, cannot continue test")
}
entry, err := statuses.ByIndex(0)
checkFatal(t, err)
if entry.Status != StatusIndexNew {
t.Error("status should be 'new' as file has been added between commits")
}
if entry.HeadToIndex.NewFile.Path != "file2" {
t.Error("new file should be 'file2")
}
return
}
// checkNoFilesStaged checks that there is a single file called "file2" uncommitted in the repo
func checkNoFilesStaged(t *testing.T, repo *Repository) {
opts := StatusOptions{
Show: StatusShowIndexAndWorkdir,
Flags: StatusOptIncludeUntracked,
}
statuses, err := repo.StatusList(&opts)
checkFatal(t, err)
count, err := statuses.EntryCount()
checkFatal(t, err)
if count != 0 {
t.Error("files changed unexpectedly")
}
}
// addAndGetTree creates a file and commits it, returning the commit and tree
func addAndGetTree(t *testing.T, repo *Repository, filename string, content string) (*Commit, *Tree) {
headCommit, err := headCommit(repo)
checkFatal(t, err)
defer headCommit.Free()
p := repo.Path()
p = strings.TrimSuffix(p, ".git")
p = strings.TrimSuffix(p, ".git/")
err = ioutil.WriteFile(path.Join(p, filename), []byte((content)), 0777)
checkFatal(t, err)
index, err := repo.Index()
checkFatal(t, err)
defer index.Free()
err = index.AddByPath(filename)
checkFatal(t, err)
newTreeOID, err := index.WriteTreeTo(repo)
checkFatal(t, err)
newTree, err := repo.LookupTree(newTreeOID)
checkFatal(t, err)
defer newTree.Free()
commitId, err := repo.CreateCommit("HEAD", signature(), signature(), fmt.Sprintf("add %s", filename), newTree, headCommit)
checkFatal(t, err)
commit, err := repo.LookupCommit(commitId)
checkFatal(t, err)
tree, err := commit.Tree()
checkFatal(t, err)
return commit, tree
}