Welcome to mirror list, hosted at ThFree Co, Russian Federation.

MergeFixture.cs « LibGit2Sharp.Tests - github.com/mono/libgit2sharp.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 7801de7189e8106a122330090741ba0aeeeafb80 (plain)
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;

namespace LibGit2Sharp.Tests
{
    public class MergeFixture : BaseFixture
    {
        [Fact]
        public void ANewRepoIsFullyMerged()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                Assert.Equal(true, repo.Index.IsFullyMerged);
            }
        }

        [Fact]
        public void AFullyMergedRepoOnlyContainsStagedIndexEntries()
        {
            using (var repo = new Repository(StandardTestRepoWorkingDirPath))
            {
                Assert.Equal(true, repo.Index.IsFullyMerged);

                foreach (var entry in repo.Index)
                {
                    Assert.Equal(StageLevel.Staged, entry.StageLevel);
                }
            }
        }

        [Fact]
        public void SoftResetARepoWithUnmergedEntriesThrows()
        {
            using (var repo = new Repository(MergedTestRepoWorkingDirPath))
            {
                Assert.Equal(false, repo.Index.IsFullyMerged);

                var headCommit = repo.Head.Tip;
                var firstCommitParent = headCommit.Parents.First();
                Assert.Throws<UnmergedIndexEntriesException>(
                    () => repo.Reset(ResetMode.Soft, firstCommitParent));
            }
        }

        [Fact]
        public void CommitAgainARepoWithUnmergedEntriesThrows()
        {
            using (var repo = new Repository(MergedTestRepoWorkingDirPath))
            {
                Assert.Equal(false, repo.Index.IsFullyMerged);

                var author = Constants.Signature;
                Assert.Throws<UnmergedIndexEntriesException>(
                    () => repo.Commit("Try commit unmerged entries", author, author));
            }
        }

        [Fact]
        public void CanRetrieveTheBranchBeingMerged()
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                const string firstBranch = "9fd738e8f7967c078dceed8190330fc8648ee56a";
                const string secondBranch = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";

                Touch(repo.Info.Path, "MERGE_HEAD", string.Format("{0}{1}{2}{1}", firstBranch, "\n", secondBranch));

                Assert.Equal(CurrentOperation.Merge, repo.Info.CurrentOperation);
            }
        }

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void CanMergeRepoNonFastForward(bool shouldMergeOccurInDetachedHeadState)
        {
            const string firstBranchFileName = "first branch file.txt";
            const string secondBranchFileName = "second branch file.txt";
            const string sharedBranchFileName = "first+second branch file.txt";

            string path = CloneStandardTestRepo();

            using (var repo = new Repository(path))
            {
                var firstBranch = repo.CreateBranch("FirstBranch");
                firstBranch.Checkout();
                var originalTreeCount = firstBranch.Tip.Tree.Count;

                // Commit with ONE new file to both first & second branch (SecondBranch is created on this commit).
                AddFileCommitToRepo(repo, sharedBranchFileName);

                var secondBranch = repo.CreateBranch("SecondBranch");
                // Commit with ONE new file to first branch (FirstBranch moves forward as it is checked out, SecondBranch stays back one).
                AddFileCommitToRepo(repo, firstBranchFileName);

                if (shouldMergeOccurInDetachedHeadState)
                {
                    // Detaches HEAD
                    repo.Checkout(secondBranch.Tip);
                }
                else
                {
                    secondBranch.Checkout();
                }

                // Commit with ONE new file to second branch (FirstBranch and SecondBranch now point to separate commits that both have the same parent commit).
                AddFileCommitToRepo(repo, secondBranchFileName);

                MergeResult mergeResult = repo.Merge(repo.Branches["FirstBranch"].Tip, Constants.Signature);

                Assert.Equal(MergeStatus.NonFastForward, mergeResult.Status);

                Assert.Equal(repo.Head.Tip, mergeResult.Commit);
                Assert.Equal(originalTreeCount + 3, mergeResult.Commit.Tree.Count);    // Expecting original tree count plussed by the 3 added files.
                Assert.Equal(2, mergeResult.Commit.Parents.Count());   // Merge commit should have 2 parents
                Assert.Equal(shouldMergeOccurInDetachedHeadState, repo.Info.IsHeadDetached);

                if (!shouldMergeOccurInDetachedHeadState)
                {
                    // Ensure HEAD is still attached and points to SecondBranch
                    Assert.Equal(repo.Refs.Head.TargetIdentifier, secondBranch.CanonicalName);
                }
            }
        }

        [Fact]
        public void IsUpToDateMerge()
        {
            const string sharedBranchFileName = "first+second branch file.txt";

            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                var firstBranch = repo.CreateBranch("FirstBranch");
                firstBranch.Checkout();

                // Commit with ONE new file to both first & second branch (SecondBranch is created on this commit).
                AddFileCommitToRepo(repo, sharedBranchFileName);

                var secondBranch = repo.CreateBranch("SecondBranch");

                secondBranch.Checkout();

                MergeResult mergeResult = repo.Merge(repo.Branches["FirstBranch"].Tip, Constants.Signature);

                Assert.Equal(MergeStatus.UpToDate, mergeResult.Status);
            }
        }

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void CanFastForwardRepos(bool shouldMergeOccurInDetachedHeadState)
        {
            const string firstBranchFileName = "first branch file.txt";
            const string sharedBranchFileName = "first+second branch file.txt";

            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                // Reset the index and the working tree.
                repo.Reset(ResetMode.Hard);

                // Clean the working directory.
                repo.RemoveUntrackedFiles();

                var firstBranch = repo.CreateBranch("FirstBranch");
                firstBranch.Checkout();

                // Commit with ONE new file to both first & second branch (SecondBranch is created on this commit).
                AddFileCommitToRepo(repo, sharedBranchFileName);

                var secondBranch = repo.CreateBranch("SecondBranch");

                // Commit with ONE new file to first branch (FirstBranch moves forward as it is checked out, SecondBranch stays back one).
                AddFileCommitToRepo(repo, firstBranchFileName);

                if (shouldMergeOccurInDetachedHeadState)
                {
                    // Detaches HEAD
                    repo.Checkout(secondBranch.Tip);
                }
                else
                {
                    secondBranch.Checkout();
                }

                Assert.Equal(shouldMergeOccurInDetachedHeadState, repo.Info.IsHeadDetached);

                MergeResult mergeResult = repo.Merge(repo.Branches["FirstBranch"].Tip, Constants.Signature);

                Assert.Equal(MergeStatus.FastForward, mergeResult.Status);
                Assert.Equal(repo.Branches["FirstBranch"].Tip, mergeResult.Commit);
                Assert.Equal(repo.Branches["FirstBranch"].Tip, repo.Head.Tip);
                Assert.Equal(repo.Head.Tip, mergeResult.Commit);

                Assert.Equal(0, repo.Index.RetrieveStatus().Count());
                Assert.Equal(shouldMergeOccurInDetachedHeadState, repo.Info.IsHeadDetached);

                if (!shouldMergeOccurInDetachedHeadState)
                {
                    // Ensure HEAD is still attached and points to SecondBranch
                    Assert.Equal(repo.Refs.Head.TargetIdentifier, secondBranch.CanonicalName);
                }
            }
        }

        [Fact]
        public void ConflictingMergeRepos()
        {
            const string firstBranchFileName = "first branch file.txt";
            const string secondBranchFileName = "second branch file.txt";
            const string sharedBranchFileName = "first+second branch file.txt";

            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                var firstBranch = repo.CreateBranch("FirstBranch");
                firstBranch.Checkout();

                // Commit with ONE new file to both first & second branch (SecondBranch is created on this commit).
                AddFileCommitToRepo(repo, sharedBranchFileName);

                var secondBranch = repo.CreateBranch("SecondBranch");
                // Commit with ONE new file to first branch (FirstBranch moves forward as it is checked out, SecondBranch stays back one).
                AddFileCommitToRepo(repo, firstBranchFileName);
                AddFileCommitToRepo(repo, sharedBranchFileName, "The first branches comment");  // Change file in first branch

                secondBranch.Checkout();
                // Commit with ONE new file to second branch (FirstBranch and SecondBranch now point to separate commits that both have the same parent commit).
                AddFileCommitToRepo(repo, secondBranchFileName);
                AddFileCommitToRepo(repo, sharedBranchFileName, "The second branches comment");  // Change file in second branch

                MergeResult mergeResult = repo.Merge(repo.Branches["FirstBranch"].Tip, Constants.Signature);

                Assert.Equal(MergeStatus.Conflicts, mergeResult.Status);

                Assert.Null(mergeResult.Commit);
                Assert.Equal(1, repo.Index.Conflicts.Count());

                var conflict = repo.Index.Conflicts.First();
                var changes = repo.Diff.Compare(repo.Lookup<Blob>(conflict.Theirs.Id), repo.Lookup<Blob>(conflict.Ours.Id));

                Assert.False(changes.IsBinaryComparison);
            }
        }

        [Fact]
        public void ConflictingMergeReposBinary()
        {
            const string firstBranchFileName = "first branch file.bin";
            const string secondBranchFileName = "second branch file.bin";
            const string sharedBranchFileName = "first+second branch file.bin";

            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                var firstBranch = repo.CreateBranch("FirstBranch");
                firstBranch.Checkout();

                // Commit with ONE new file to both first & second branch (SecondBranch is created on this commit).
                AddFileCommitToRepo(repo, sharedBranchFileName);

                var secondBranch = repo.CreateBranch("SecondBranch");
                // Commit with ONE new file to first branch (FirstBranch moves forward as it is checked out, SecondBranch stays back one).
                AddFileCommitToRepo(repo, firstBranchFileName);
                AddFileCommitToRepo(repo, sharedBranchFileName, "\0The first branches comment\0");  // Change file in first branch

                secondBranch.Checkout();
                // Commit with ONE new file to second branch (FirstBranch and SecondBranch now point to separate commits that both have the same parent commit).
                AddFileCommitToRepo(repo, secondBranchFileName);
                AddFileCommitToRepo(repo, sharedBranchFileName, "\0The second branches comment\0");  // Change file in second branch

                MergeResult mergeResult = repo.Merge(repo.Branches["FirstBranch"].Tip, Constants.Signature);

                Assert.Equal(MergeStatus.Conflicts, mergeResult.Status);

                Assert.Equal(1, repo.Index.Conflicts.Count());

                Conflict conflict = repo.Index.Conflicts.First();

                var changes = repo.Diff.Compare(repo.Lookup<Blob>(conflict.Theirs.Id), repo.Lookup<Blob>(conflict.Ours.Id));

                Assert.True(changes.IsBinaryComparison);
            }
        }

        [Theory]
        [InlineData(true, FastForwardStrategy.Default, fastForwardBranchInitialId, MergeStatus.FastForward)]
        [InlineData(true, FastForwardStrategy.FastForwardOnly, fastForwardBranchInitialId, MergeStatus.FastForward)]
        [InlineData(false, FastForwardStrategy.Default, fastForwardBranchInitialId, MergeStatus.FastForward)]
        [InlineData(false, FastForwardStrategy.FastForwardOnly, fastForwardBranchInitialId, MergeStatus.FastForward)]
        public void CanFastForwardCommit(bool fromDetachedHead, FastForwardStrategy fastForwardStrategy, string expectedCommitId, MergeStatus expectedMergeStatus)
        {
            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                if(fromDetachedHead)
                {
                    repo.Checkout(repo.Head.Tip.Id.Sha);
                }

                Commit commitToMerge = repo.Branches["fast_forward"].Tip;

                MergeResult result = repo.Merge(commitToMerge, Constants.Signature, new MergeOptions() { FastForwardStrategy = fastForwardStrategy });

                Assert.Equal(expectedMergeStatus, result.Status);
                Assert.Equal(expectedCommitId, result.Commit.Id.Sha);
                Assert.False(repo.Index.RetrieveStatus().Any());
                Assert.Equal(fromDetachedHead, repo.Info.IsHeadDetached);
            }
        }

        [Theory]
        [InlineData(true, FastForwardStrategy.Default, MergeStatus.NonFastForward)]
        [InlineData(true, FastForwardStrategy.NoFastFoward, MergeStatus.NonFastForward)]
        [InlineData(false, FastForwardStrategy.Default, MergeStatus.NonFastForward)]
        [InlineData(false, FastForwardStrategy.NoFastFoward, MergeStatus.NonFastForward)]
        public void CanNonFastForwardMergeCommit(bool fromDetachedHead, FastForwardStrategy fastForwardStrategy, MergeStatus expectedMergeStatus)
        {
            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                if (fromDetachedHead)
                {
                    repo.Checkout(repo.Head.Tip.Id.Sha);
                }

                Commit commitToMerge = repo.Branches["normal_merge"].Tip;

                MergeResult result = repo.Merge(commitToMerge, Constants.Signature, new MergeOptions() { FastForwardStrategy = fastForwardStrategy });

                Assert.Equal(expectedMergeStatus, result.Status);
                Assert.False(repo.Index.RetrieveStatus().Any());
                Assert.Equal(fromDetachedHead, repo.Info.IsHeadDetached);
            }
        }

        [Fact]
        public void MergeReportsCheckoutProgress()
        {
            string repoPath = CloneMergeTestRepo();
            using (var repo = new Repository(repoPath))
            {
                Commit commitToMerge = repo.Branches["normal_merge"].Tip;

                bool wasCalled = false;

                MergeOptions options = new MergeOptions()
                {
                    OnCheckoutProgress = (path, completed, total) => wasCalled = true,
                };

                MergeResult result = repo.Merge(commitToMerge, Constants.Signature, options);

                Assert.True(wasCalled);
            }
        }

        [Fact]
        public void MergeReportsCheckoutNotifications()
        {
            string repoPath = CloneMergeTestRepo();
            using (var repo = new Repository(repoPath))
            {
                Commit commitToMerge = repo.Branches["normal_merge"].Tip;

                bool wasCalled = false;
                CheckoutNotifyFlags actualNotifyFlags = CheckoutNotifyFlags.None;

                MergeOptions options = new MergeOptions()
                {
                    OnCheckoutNotify = (path, notificationType) => { wasCalled = true; actualNotifyFlags = notificationType; return true; },
                    CheckoutNotifyFlags = CheckoutNotifyFlags.Updated,
                };

                MergeResult result = repo.Merge(commitToMerge, Constants.Signature, options);

                Assert.True(wasCalled);
                Assert.Equal(CheckoutNotifyFlags.Updated, actualNotifyFlags);
            }
        }

        [Fact]
        public void FastForwardMergeReportsCheckoutProgress()
        {
            string repoPath = CloneMergeTestRepo();
            using (var repo = new Repository(repoPath))
            {
                Commit commitToMerge = repo.Branches["fast_forward"].Tip;

                bool wasCalled = false;

                MergeOptions options = new MergeOptions()
                {
                    OnCheckoutProgress = (path, completed, total) => wasCalled = true,
                };

                MergeResult result = repo.Merge(commitToMerge, Constants.Signature, options);

                Assert.True(wasCalled);
            }
        }

        [Fact]
        public void FastForwardMergeReportsCheckoutNotifications()
        {
            string repoPath = CloneMergeTestRepo();
            using (var repo = new Repository(repoPath))
            {
                Commit commitToMerge = repo.Branches["fast_forward"].Tip;

                bool wasCalled = false;
                CheckoutNotifyFlags actualNotifyFlags = CheckoutNotifyFlags.None;

                MergeOptions options = new MergeOptions()
                {
                    OnCheckoutNotify = (path, notificationType) => { wasCalled = true; actualNotifyFlags = notificationType; return true; },
                    CheckoutNotifyFlags = CheckoutNotifyFlags.Updated,
                };

                MergeResult result = repo.Merge(commitToMerge, Constants.Signature, options);

                Assert.True(wasCalled);
                Assert.Equal(CheckoutNotifyFlags.Updated, actualNotifyFlags);
            }
        }

        [Fact]
        public void MergeCanDetectRenames()
        {
            // The environment is set up such that:
            // file b.txt is edited in the "rename" branch and
            // edited and renamed in the "rename_source" branch.
            // The edits are automergable.
            // We can rename "rename_source" into "rename"
            // if rename detection is enabled,
            // but the merge will fail with conflicts if this
            // change is not detected as a rename.

            string repoPath = CloneMergeTestRepo();
            using (var repo = new Repository(repoPath))
            {
                Branch currentBranch = repo.Checkout("rename_source");
                Assert.NotNull(currentBranch);

                Branch branchToMerge = repo.Branches["rename"];

                MergeResult result = repo.Merge(branchToMerge, Constants.Signature);

                Assert.Equal(MergeStatus.NonFastForward, result.Status);
            }
        }

        [Fact]
        public void FastForwardNonFastForwardableMergeThrows()
        {
            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                Commit commitToMerge = repo.Branches["normal_merge"].Tip;
                Assert.Throws<NonFastForwardException>(() => repo.Merge(commitToMerge, Constants.Signature, new MergeOptions() { FastForwardStrategy = FastForwardStrategy.FastForwardOnly }));
            }
        }

        [Fact]
        public void CanForceFastForwardMergeThroughConfig()
        {
            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                repo.Config.Set("merge.ff", "only");

                Commit commitToMerge = repo.Branches["normal_merge"].Tip;
                Assert.Throws<NonFastForwardException>(() => repo.Merge(commitToMerge, Constants.Signature, new MergeOptions()));
            }
        }

        [Fact]
        public void CanMergeAndNotCommit()
        {
            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                Commit commitToMerge = repo.Branches["normal_merge"].Tip;

                MergeResult result = repo.Merge(commitToMerge, Constants.Signature, new MergeOptions() { CommitOnSuccess = false});

                Assert.Equal(MergeStatus.NonFastForward, result.Status);
                Assert.Equal(null, result.Commit);

                RepositoryStatus repoStatus = repo.Index.RetrieveStatus();

                // Verify that there is a staged entry.
                Assert.Equal(1, repoStatus.Count());
                Assert.Equal(FileStatus.Staged, repo.Index.RetrieveStatus("b.txt"));
            }
        }

        [Fact]
        public void CanForceNonFastForwardMerge()
        {
            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                Commit commitToMerge = repo.Branches["fast_forward"].Tip;

                MergeResult result = repo.Merge(commitToMerge, Constants.Signature, new MergeOptions() { FastForwardStrategy = FastForwardStrategy.NoFastFoward });

                Assert.Equal(MergeStatus.NonFastForward, result.Status);
                Assert.Equal("f58f780d5a0ae392efd4a924450b1bbdc0577d32", result.Commit.Id.Sha);
                Assert.False(repo.Index.RetrieveStatus().Any());
            }
        }

        [Fact]
        public void CanForceNonFastForwardMergeThroughConfig()
        {
            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                repo.Config.Set("merge.ff", "false");

                Commit commitToMerge = repo.Branches["fast_forward"].Tip;

                MergeResult result = repo.Merge(commitToMerge, Constants.Signature, new MergeOptions());

                Assert.Equal(MergeStatus.NonFastForward, result.Status);
                Assert.Equal("f58f780d5a0ae392efd4a924450b1bbdc0577d32", result.Commit.Id.Sha);
                Assert.False(repo.Index.RetrieveStatus().Any());
            }
        }

        [Fact]
        public void VerifyUpToDateMerge()
        {
            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                Commit commitToMerge = repo.Branches["master"].Tip;

                MergeResult result = repo.Merge(commitToMerge, Constants.Signature, new MergeOptions() { FastForwardStrategy = FastForwardStrategy.NoFastFoward });

                Assert.Equal(MergeStatus.UpToDate, result.Status);
                Assert.Equal(null, result.Commit);
                Assert.False(repo.Index.RetrieveStatus().Any());
            }
        }

        [Theory]
        [InlineData("refs/heads/normal_merge", FastForwardStrategy.Default, MergeStatus.NonFastForward)]
        [InlineData("normal_merge", FastForwardStrategy.Default, MergeStatus.NonFastForward)]
        [InlineData("625186280ed2a6ec9b65d250ed90cf2e4acef957", FastForwardStrategy.Default, MergeStatus.NonFastForward)]
        [InlineData("fast_forward", FastForwardStrategy.Default, MergeStatus.FastForward)]
        public void CanMergeCommittish(string committish, FastForwardStrategy strategy, MergeStatus expectedMergeStatus)
        {
            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                MergeResult result = repo.Merge(committish, Constants.Signature, new MergeOptions() { FastForwardStrategy = strategy });

                Assert.Equal(expectedMergeStatus, result.Status);
                Assert.False(repo.Index.RetrieveStatus().Any());
            }
        }

        [Theory]
        [InlineData(true, FastForwardStrategy.FastForwardOnly)]
        [InlineData(false, FastForwardStrategy.FastForwardOnly)]
        [InlineData(true, FastForwardStrategy.NoFastFoward)]
        [InlineData(false, FastForwardStrategy.NoFastFoward)]
        public void MergeWithWorkDirConflictsThrows(bool shouldStage, FastForwardStrategy strategy)
        {
            // Merging the fast_forward branch results in a change to file
            // b.txt. In this test we modify the file in the working directory
            // and then attempt to perform a merge. We expect the merge to fail
            // due to merge conflicts.
            string committishToMerge = "fast_forward";

            using (var repo = new Repository(CloneMergeTestRepo()))
            {
                Touch(repo.Info.WorkingDirectory, "b.txt", "this is an alternate change");

                if (shouldStage)
                {
                    repo.Index.Stage("b.txt");
                }

                Assert.Throws<MergeConflictException>(() => repo.Merge(committishToMerge, Constants.Signature, new MergeOptions() { FastForwardStrategy = strategy }));
            }
        }

        [Theory]
        [InlineData(CheckoutFileConflictStrategy.Ours)]
        [InlineData(CheckoutFileConflictStrategy.Theirs)]
        public void CanSpecifyConflictFileStrategy(CheckoutFileConflictStrategy conflictStrategy)
        {
            const string conflictFile = "a.txt";
            const string conflictBranchName = "conflicts";

            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                Branch branch = repo.Branches[conflictBranchName];
                Assert.NotNull(branch);

                MergeOptions mergeOptions = new MergeOptions()
                {
                    FileConflictStrategy = conflictStrategy,
                };

                MergeResult result = repo.Merge(branch, Constants.Signature, mergeOptions);
                Assert.Equal(MergeStatus.Conflicts, result.Status);

                // Get the information on the conflict.
                Conflict conflict = repo.Index.Conflicts[conflictFile];

                Assert.NotNull(conflict);
                Assert.NotNull(conflict.Theirs);
                Assert.NotNull(conflict.Ours);

                // Get the blob containing the expected content.
                Blob expectedBlob = null;
                switch(conflictStrategy)
                {
                    case CheckoutFileConflictStrategy.Theirs:
                        expectedBlob = repo.Lookup<Blob>(conflict.Theirs.Id);
                        break;
                    case CheckoutFileConflictStrategy.Ours:
                        expectedBlob = repo.Lookup<Blob>(conflict.Ours.Id);
                        break;
                    default:
                        throw new Exception("Unexpected FileConflictStrategy");
                }

                Assert.NotNull(expectedBlob);

                // Check the content of the file on disk matches what is expected.
                string expectedContent = expectedBlob.GetContentText(new FilteringOptions(conflictFile));
                Assert.Equal(expectedContent, File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, conflictFile)));
            }
        }

        [Theory]
        [InlineData(MergeFileFavor.Ours)]
        [InlineData(MergeFileFavor.Theirs)]
        public void MergeCanSpecifyMergeFileFavorOption(MergeFileFavor fileFavorFlag)
        {
            const string conflictFile = "a.txt";
            const string conflictBranchName = "conflicts";

            string path = CloneMergeTestRepo();
            using (var repo = InitIsolatedRepository(path))
            {
                Branch branch = repo.Branches[conflictBranchName];
                Assert.NotNull(branch);

                var status = repo.Index.RetrieveStatus();
                MergeOptions mergeOptions = new MergeOptions()
                {
                    MergeFileFavor = fileFavorFlag,
                };

                MergeResult result = repo.Merge(branch, Constants.Signature, mergeOptions);

                Assert.Equal(MergeStatus.NonFastForward, result.Status);

                // Verify that the index and working directory are clean
                Assert.True(repo.Index.IsFullyMerged);
                Assert.False(repo.Index.RetrieveStatus().IsDirty);

                // Get the blob containing the expected content.
                Blob expectedBlob = null;
                switch (fileFavorFlag)
                {
                    case MergeFileFavor.Theirs:
                        expectedBlob = repo.Lookup<Blob>("3dd9738af654bbf1c363f6c3bbc323bacdefa179");
                        break;
                    case MergeFileFavor.Ours:
                        expectedBlob = repo.Lookup<Blob>("610b16886ca829cebd2767d9196f3c4378fe60b5");
                        break;
                    default:
                        throw new Exception("Unexpected MergeFileFavor");
                }

                Assert.NotNull(expectedBlob);

                // Verify the index has the expected contents
                IndexEntry entry = repo.Index[conflictFile];
                Assert.NotNull(entry);
                Assert.Equal(expectedBlob.Id, entry.Id);

                // Verify the content of the file on disk matches what is expected.
                string expectedContent = expectedBlob.GetContentText(new FilteringOptions(conflictFile));
                Assert.Equal(expectedContent, File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, conflictFile)));
            }
        }

        [Theory]
        [InlineData("refs/heads/normal_merge", FastForwardStrategy.Default, MergeStatus.NonFastForward)]
        [InlineData("fast_forward", FastForwardStrategy.Default, MergeStatus.FastForward)]
        public void CanMergeBranch(string branchName, FastForwardStrategy strategy, MergeStatus expectedMergeStatus)
        {
            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                Branch branch = repo. Branches[branchName];
                MergeResult result = repo.Merge(branch, Constants.Signature, new MergeOptions() { FastForwardStrategy = strategy });

                Assert.Equal(expectedMergeStatus, result.Status);
                Assert.False(repo.Index.RetrieveStatus().Any());
            }
        }

        [Fact]
        public void CanMergeIntoOrphanedBranch()
        {
            string path = CloneMergeTestRepo();
            using (var repo = new Repository(path))
            {
                repo.Refs.Add("HEAD", "refs/heads/orphan", true);

                // Remove entries from the working directory
                foreach(var entry in repo.Index.RetrieveStatus())
                {
                    repo.Index.Unstage(entry.FilePath);
                    repo.Index.Remove(entry.FilePath, true);
                }

                // Assert that we have an empty working directory.
                Assert.False(repo.Index.RetrieveStatus().Any());

                MergeResult result = repo.Merge("master", Constants.Signature);

                Assert.Equal(MergeStatus.FastForward, result.Status);
                Assert.Equal(masterBranchInitialId, result.Commit.Id.Sha);
                Assert.False(repo.Index.RetrieveStatus().Any());
            }
        }

        private Commit AddFileCommitToRepo(IRepository repository, string filename, string content = null)
        {
            Touch(repository.Info.WorkingDirectory, filename, content);

            repository.Index.Stage(filename);

            return repository.Commit("New commit", Constants.Signature, Constants.Signature);
        }

        // Commit IDs of the checked in merge_testrepo
        private const string masterBranchInitialId = "83cebf5389a4adbcb80bda6b68513caee4559802";
        private const string fastForwardBranchInitialId = "4dfaa1500526214ae7b33f9b2c1144ca8b6b1f53";
    }
}