Example #1
0
        public void CanCancelCheckoutThroughNotifyCallback()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                string relativePath = "a.txt";
                Touch(repo.Info.WorkingDirectory, relativePath, "Hello\n");

                repo.Index.Stage(relativePath);
                repo.Commit("Initial commit", Constants.Signature, Constants.Signature);

                // Create 2nd branch
                repo.CreateBranch("branch2");

                // Update file in main
                Touch(repo.Info.WorkingDirectory, relativePath, "Hello from master!\n");
                repo.Index.Stage(relativePath);
                repo.Commit("2nd commit", Constants.Signature, Constants.Signature);

                // Checkout branch2
                repo.Checkout("branch2");

                // Update the context of a.txt - a.txt will then conflict between branch2 and master.
                Touch(repo.Info.WorkingDirectory, relativePath, "Hello From branch2!\n");

                // Verify that we get called for the notify conflict cb
                string conflictPath = string.Empty;
                CheckoutNotificationOptions checkoutNotifications = new CheckoutNotificationOptions((path, flags) => { conflictPath = path; return false; }, CheckoutNotifyFlags.Conflict);
                Assert.Throws<UserCancelledException>(() => repo.Checkout("master", CheckoutModifiers.None, null, checkoutNotifications));
                Assert.Equal(relativePath, conflictPath);
            }
        }
        public void CanCheckoutAnExistingBranch(string branchName)
        {
            TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo(StandardTestRepoWorkingDirPath);
            using (var repo = new Repository(path.RepositoryPath))
            {
                Branch master = repo.Branches["master"];
                Assert.True(master.IsCurrentRepositoryHead);

                // Set the working directory to the current head
                ResetAndCleanWorkingDirectory(repo);

                Assert.False(repo.Index.RetrieveStatus().IsDirty);

                Branch branch = repo.Branches[branchName];
                Assert.NotNull(branch);

                Branch test = repo.Checkout(branch);
                Assert.False(repo.Info.IsHeadDetached);

                Assert.False(test.IsRemote);
                Assert.True(test.IsCurrentRepositoryHead);
                Assert.Equal(repo.Head, test);

                Assert.False(master.IsCurrentRepositoryHead);

                // Working directory should not be dirty
                Assert.False(repo.Index.RetrieveStatus().IsDirty);
            }
        }
        public void CanCheckoutAnArbitraryCommit(string commitPointer)
        {
            TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo(StandardTestRepoWorkingDirPath);
            using (var repo = new Repository(path.RepositoryPath))
            {
                Branch master = repo.Branches["master"];
                Assert.True(master.IsCurrentRepositoryHead);

                // Set the working directory to the current head
                ResetAndCleanWorkingDirectory(repo);

                Assert.False(repo.Index.RetrieveStatus().IsDirty);

                Branch detachedHead = repo.Checkout(commitPointer);

                Assert.Equal(repo.Head, detachedHead);
                Assert.Equal(repo.Lookup(commitPointer).Sha, detachedHead.Tip.Sha);
                Assert.True(repo.Head.IsCurrentRepositoryHead);
                Assert.True(repo.Info.IsHeadDetached);
                Assert.False(repo.Index.RetrieveStatus().IsDirty);

                Assert.True(detachedHead.IsCurrentRepositoryHead);
                Assert.False(detachedHead.IsRemote);
                Assert.Equal(detachedHead.Name, detachedHead.CanonicalName);

                Assert.Equal("(no branch)", detachedHead.CanonicalName);

                Assert.False(master.IsCurrentRepositoryHead);
            }
        }
        public void CanCheckoutAnExistingBranchByName(string branchName)
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                Branch master = repo.Branches["master"];
                Assert.True(master.IsCurrentRepositoryHead);

                // Set the working directory to the current head
                ResetAndCleanWorkingDirectory(repo);

                Assert.False(repo.Index.RetrieveStatus().IsDirty);

                Branch test = repo.Checkout(branchName);
                Assert.False(repo.Info.IsHeadDetached);

                Assert.False(test.IsRemote);
                Assert.True(test.IsCurrentRepositoryHead);
                Assert.Equal(repo.Head, test);

                Assert.False(master.IsCurrentRepositoryHead);

                // Working directory should not be dirty
                Assert.False(repo.Index.RetrieveStatus().IsDirty);

                // Assert reflog entry is created
                var reflogEntry = repo.Refs.Log(repo.Refs.Head).First();
                Assert.Equal(master.Tip.Id, reflogEntry.From);
                Assert.Equal(repo.Branches[branchName].Tip.Id, reflogEntry.To);
                Assert.NotNull(reflogEntry.Commiter.Email);
                Assert.NotNull(reflogEntry.Commiter.Name);
                Assert.Equal(string.Format("checkout: moving from master to {0}", branchName), reflogEntry.Message);
            }
        }
Example #5
0
        public void CommitOnDetachedHeadShouldInsertReflogEntry()
        {
            string repoPath = CloneStandardTestRepo();

            using (var repo = new Repository(repoPath))
            {
                Assert.False(repo.Info.IsHeadDetached);

                var parentCommit = repo.Head.Tip.Parents.First();
                repo.Checkout(parentCommit.Sha);
                Assert.True(repo.Info.IsHeadDetached);

                const string relativeFilepath = "new.txt";
                string filePath = Path.Combine(repo.Info.WorkingDirectory, relativeFilepath);

                File.WriteAllText(filePath, "content\n");
                repo.Index.Stage(relativeFilepath);

                var author = DummySignature;
                const string commitMessage = "Commit on detached head";
                var commit = repo.Commit(commitMessage, author, author);

                // Assert a reflog entry is created on HEAD
                var reflogEntry = repo.Refs.Log("HEAD").First();
                Assert.Equal(author, reflogEntry.Commiter);
                Assert.Equal(commit.Id, reflogEntry.To);
                Assert.Equal(string.Format("commit: {0}", commitMessage), repo.Refs.Log("HEAD").First().Message);
            }
        }
Example #6
0
        public void CanCorrectlyCountCommitsWhenSwitchingToAnotherBranch()
        {
            string path = SandboxStandardTestRepo();
            using (var repo = new Repository(path))
            {
                // Hard reset and then remove untracked files
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                repo.Checkout("test");
                Assert.Equal(2, repo.Commits.Count());
                Assert.Equal("e90810b8df3e80c413d903f631643c716887138d", repo.Commits.First().Id.Sha);

                repo.Checkout("master");
                Assert.Equal(9, repo.Commits.Count());
                Assert.Equal("32eab9cb1f450b5fe7ab663462b77d7f4b703344", repo.Commits.First().Id.Sha);
            }
        }
        private static FileInfo CommitFileOnBranch(Repository repo, string branchName, String content)
        {
            var branch = repo.CreateBranch(branchName);

            repo.Checkout(branch.FriendlyName);

            FileInfo expectedPath = StageNewFile(repo, content);

            repo.Commit("Commit", Constants.Signature, Constants.Signature);
            return(expectedPath);
        }
Example #8
0
        public void CheckingOutAgainstAnUnbornBranchThrows()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                Assert.True(repo.Info.IsHeadOrphaned);

                Assert.Throws <OrphanedHeadException>(() => repo.Checkout(repo.Head));
            }
        }
Example #9
0
        public void CheckoutBranchByShortNameAttachesTheHead(string shortBranchName, string referenceName)
        {
            string path = CloneStandardTestRepo();

            using (var repo = new Repository(path))
            {
                // Set the working directory to the current head
                ResetAndCleanWorkingDirectory(repo);
                Assert.False(repo.Index.RetrieveStatus().IsDirty);

                repo.Checkout("6dcf9bf");
                Assert.True(repo.Info.IsHeadDetached);

                var branch = repo.Checkout(shortBranchName);

                Assert.False(repo.Info.IsHeadDetached);
                Assert.Equal(referenceName, repo.Head.CanonicalName);
                Assert.Equal(referenceName, branch.CanonicalName);
            }
        }
Example #10
0
 public void CheckOut(string branchName)
 {
     using (var r = new Repository(Path))
     {
         Branch b = r.Branches[branchName];
         r.Checkout(b, new CheckoutOptions()
         {
             CheckoutModifiers = CheckoutModifiers.Force
         });
     }
 }
Example #11
0
        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);
                }
            }
        }
Example #12
0
        public void QueryingTheRemoteForADetachedHeadBranchReturnsNull()
        {
            string path = CloneStandardTestRepo();

            using (var repo = new Repository(path))
            {
                repo.Checkout(repo.Head.Tip.Sha, CheckoutOptions.Force, null);
                Branch trackLocal = repo.Head;
                Assert.Null(trackLocal.Remote);
            }
        }
    public void BranchToFromTag(string branchName, string fromTag, string onBranch, string @as = null)
    {
        if (!participants.ContainsKey(branchName))
        {
            diagramBuilder.Append("create ");
            Participant(branchName, @as);
        }

        diagramBuilder.AppendLineFormat("{0} -> {1}: branch from tag ({2})", GetParticipant(onBranch), GetParticipant(branchName), fromTag);
        Repository.Checkout(Repository.CreateBranch(branchName));
    }
Example #14
0
        public void CanFollowFirstParent()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                var branch = repo.CreateBranch("branch");

                // Make an earlier tag on master
                repo.Commit("A", Constants.Signature, Constants.Signature, new CommitOptions {
                    AllowEmptyCommit = true
                });
                repo.ApplyTag("firstParentTag");

                // Make a later tag on branch
                repo.Checkout(branch);
                repo.Commit("B", Constants.Signature, Constants.Signature, new CommitOptions {
                    AllowEmptyCommit = true
                });
                repo.ApplyTag("mostRecentTag");

                repo.Checkout("master");
                repo.Commit("C", Constants.Signature, Constants.Signature, new CommitOptions {
                    AllowEmptyCommit = true
                });
                repo.Merge(branch, Constants.Signature, new MergeOptions()
                {
                    FastForwardStrategy = FastForwardStrategy.NoFastForward
                });

                // With OnlyFollowFirstParent = false, the most recent tag reachable should be returned
                Assert.Equal("mostRecentTag-3-gf17be71", repo.Describe(repo.Head.Tip, new DescribeOptions {
                    OnlyFollowFirstParent = false, Strategy = DescribeStrategy.Tags
                }));

                // With OnlyFollowFirstParent = true, the most recent tag on the current branch should be returned
                Assert.Equal("firstParentTag-2-gf17be71", repo.Describe(repo.Head.Tip, new DescribeOptions {
                    OnlyFollowFirstParent = true, Strategy = DescribeStrategy.Tags
                }));
            }
        }
Example #15
0
        public static string Update(string url, Log log, string directory)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                Utility.Log(LogStatus.Skipped, "Updater", string.Format("No Url specified - {0}", url), log);
            }
            else
            {
                try
                {
                    var dir = Path.Combine(directory, url.GetHashCode().ToString("X"), "trunk");

                    if (Repository.IsValid(dir))
                    {
                        using (var repo = new Repository(dir))
                        {
                            repo.Config.Set("user.name", Config.Instance.Username);
                            repo.Config.Set("user.email", Config.Instance.Username + "@joduska.me");
                            repo.Fetch("origin");
                            repo.Checkout("origin/master", new CheckoutOptions {
                                CheckoutModifiers = CheckoutModifiers.Force
                            });
                        }
                    }
                    else
                    {
                        var oldPath = Path.Combine(directory, url.GetHashCode().ToString("X"));

                        if (Directory.Exists(oldPath))
                        {
                            Directory.Delete(oldPath, true);
                        }

                        Repository.Clone(url, dir, new CloneOptions {
                            Checkout = true
                        });
                        using (var repo = new Repository(dir))
                        {
                            repo.Config.Set("user.name", Config.Instance.Username);
                            repo.Config.Set("user.email", Config.Instance.Username + "@joduska.me");
                        }
                    }

                    return(dir);
                }
                catch (Exception ex)
                {
                    Utility.Log(LogStatus.Error, "Updater", string.Format("{0} - {1}", ex.Message, url), log);
                }
            }

            return(string.Empty);
        }
Example #16
0
 internal static void DeleteBranch(Repository repo, Branch branch)
 {
     if (branch == null)
     {
         return;
     }
     if (branch.IsCurrentRepositoryHead)
     {
         repo.Checkout(repo.Branches[repo.Flow().GetPrefixByBranch(GitFlowSetting.Master)]);
     }
     repo.Branches.Remove(branch);
 }
    void SetupRepo(Action <IRepository> initialMasterAction)
    {
        var randomFile = Path.Combine(Repository.Info.WorkingDirectory, Guid.NewGuid().ToString());

        File.WriteAllText(randomFile, string.Empty);
        Repository.Stage(randomFile);

        initialMasterAction(Repository);

        Repository.Checkout(Repository.CreateBranch("develop"));
        Repository.MakeACommit();
    }
Example #18
0
        public void CheckoutPreviousCheckedOutBranch()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                // Set the working directory to the current head
                ResetAndCleanWorkingDirectory(repo);
                Assert.False(repo.RetrieveStatus().IsDirty);

                Branch previousHead = repo.Checkout("i-do-numbers");
                repo.Checkout("diff-test-cases");

                //Go back to previous branch checked out
                var branch = repo.Checkout(@"@{-1}");

                Assert.False(repo.Info.IsHeadDetached);
                Assert.Equal(previousHead.CanonicalName, repo.Head.CanonicalName);
                Assert.Equal(previousHead.CanonicalName, branch.CanonicalName);
            }
        }
 public bool Checkout(string commitish)
 {
     try
     {
         _repository.Checkout(commitish);
         return(true);
     }
     catch (MergeConflictException ex)
     {
         return(false);
     }
 }
        public void CorrectlyEncodesAndDecodesInput()
        {
            const string decodedInput = "This is a substitution cipher";
            const string encodedInput = "Guvf vf n fhofgvghgvba pvcure";

            var attributes = new List <FilterAttributeEntry> {
                new FilterAttributeEntry("rot13")
            };
            var filter             = new SubstitutionCipherFilter("cipher-filter", attributes);
            var filterRegistration = GlobalSettings.RegisterFilter(filter);

            string repoPath = InitNewRepository();
            string fileName = Guid.NewGuid() + ".rot13";

            using (var repo = new Repository(repoPath))
            {
                CreateConfigurationWithDummyUser(repo, Constants.Identity);
                CreateAttributesFile(repo, "*.rot13 filter=rot13");

                var blob         = CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);
                var textDetected = blob.GetContentText();

                Assert.Equal(encodedInput, textDetected);
                Assert.Equal(1, filter.CleanCalledCount);
                Assert.Equal(0, filter.SmudgeCalledCount);

                var branch = repo.CreateBranch("delete-files");
                repo.Checkout(branch.FriendlyName);

                DeleteFile(repo, fileName);

                repo.Checkout("master");

                var fileContents = ReadTextFromFile(repo, fileName);
                Assert.Equal(1, filter.SmudgeCalledCount);
                Assert.Equal(decodedInput, fileContents);
            }

            GlobalSettings.DeregisterFilter(filterRegistration);
        }
Example #21
0
        public void CanCheckoutAnArbitraryCommit(string commitPointer, bool checkoutByCommitOrBranchSpec, string expectedReflogTarget)
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                Branch master = repo.Branches["master"];
                Assert.True(master.IsCurrentRepositoryHead);

                // Set the working directory to the current head
                ResetAndCleanWorkingDirectory(repo);

                Assert.False(repo.Index.RetrieveStatus().IsDirty);

                var commit = repo.Lookup<Commit>(commitPointer);

                Branch detachedHead = checkoutByCommitOrBranchSpec ? repo.Checkout(commitPointer) : repo.Checkout(commit);

                Assert.Equal(repo.Head, detachedHead);
                Assert.Equal(commit.Sha, detachedHead.Tip.Sha);
                Assert.True(repo.Head.IsCurrentRepositoryHead);
                Assert.True(repo.Info.IsHeadDetached);
                Assert.False(repo.Index.RetrieveStatus().IsDirty);

                Assert.True(detachedHead.IsCurrentRepositoryHead);
                Assert.False(detachedHead.IsRemote);
                Assert.Equal(detachedHead.Name, detachedHead.CanonicalName);

                Assert.Equal("(no branch)", detachedHead.CanonicalName);

                Assert.False(master.IsCurrentRepositoryHead);

                // Assert reflog entry is created
                var reflogEntry = repo.Refs.Log(repo.Refs.Head).First();
                Assert.Equal(master.Tip.Id, reflogEntry.From);
                Assert.Equal(commit.Sha, reflogEntry.To.Sha);
                Assert.NotNull(reflogEntry.Commiter.Email);
                Assert.NotNull(reflogEntry.Commiter.Name);
                Assert.Equal(string.Format("checkout: moving from master to {0}", expectedReflogTarget), reflogEntry.Message);
            }
        }
Example #22
0
        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 = SandboxStandardTestRepo();

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

                // 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

                repo.Checkout(secondBranch);
                // 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);
            }
        }
Example #23
0
        public void CurrentStepInfoIsNullWhenNotRebasing()
        {
            SelfCleaningDirectory scd = BuildSelfCleaningDirectory();
            var path = Repository.Init(scd.DirectoryPath);

            using (Repository repo = new Repository(path))
            {
                ConstructRebaseTestRepository(repo);
                repo.Checkout(topicBranch1Name);

                Assert.Null(repo.Rebase.GetCurrentStepInfo());
            }
        }
        public void CheckoutBranchFromDetachedHead()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                // Set the working directory to the current head
                ResetAndCleanWorkingDirectory(repo);
                Assert.False(repo.RetrieveStatus().IsDirty);

                Branch initialHead = repo.Checkout("6dcf9bf");

                Assert.True(repo.Info.IsHeadDetached);

                Branch newHead = repo.Checkout(repo.Branches["master"], Constants.Signature);

                // Assert reflog entry is created
                AssertRefLogEntry(repo, "HEAD", newHead.Tip.Id,
                                  string.Format("checkout: moving from {0} to {1}", initialHead.Tip.Sha, newHead.Name),
                                  initialHead.Tip.Id, Constants.Signature);
            }
        }
Example #25
0
    public void BranchTo(string branchName, string @as = null)
    {
        if (!participants.ContainsKey(branchName))
        {
            diagramBuilder.Append("create ");
            Participant(branchName, @as);
        }

        var branch = Repository.Head.Name;

        diagramBuilder.AppendLineFormat("{0} -> {1}: branch from {2}", GetParticipant(branch), GetParticipant(branchName), branch);
        Repository.Checkout(Repository.CreateBranch(branchName));
    }
Example #26
0
        public void CanCancelCheckoutThroughNotifyCallback()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                const string relativePath = "a.txt";
                Touch(repo.Info.WorkingDirectory, relativePath, "Hello\n");

                repo.Stage(relativePath);
                repo.Commit("Initial commit", Constants.Signature, Constants.Signature);

                // Create 2nd branch
                repo.CreateBranch("branch2");

                // Update file in main
                Touch(repo.Info.WorkingDirectory, relativePath, "Hello from master!\n");
                repo.Stage(relativePath);
                repo.Commit("2nd commit", Constants.Signature, Constants.Signature);

                // Checkout branch2
                repo.Checkout("branch2");

                // Update the context of a.txt - a.txt will then conflict between branch2 and master.
                Touch(repo.Info.WorkingDirectory, relativePath, "Hello From branch2!\n");

                // Verify that we get called for the notify conflict cb
                string conflictPath = string.Empty;

                CheckoutOptions options = new CheckoutOptions()
                {
                    OnCheckoutNotify    = (path, flags) => { conflictPath = path; return(false); },
                    CheckoutNotifyFlags = CheckoutNotifyFlags.Conflict,
                };

                Assert.Throws <UserCancelledException>(() => repo.Checkout("master", options));
                Assert.Equal(relativePath, conflictPath);
            }
        }
        public void CherryPickWithConflictDoesNotCommit()
        {
            const string firstBranchFileName = "first branch file.txt";
            const string secondBranchFileName = "second branch file.txt";
            const string sharedBranchFileName = "first+second branch file.txt";

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

                // 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

                repo.Checkout(secondBranch);
                // 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

                CherryPickResult cherryPickResult = repo.CherryPick(repo.Branches["FirstBranch"].Tip, Constants.Signature);

                Assert.Equal(CherryPickStatus.Conflicts, cherryPickResult.Status);

                Assert.Null(cherryPickResult.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);
            }
        }
Example #28
0
        public void IsUpToDateMerge()
        {
            const string sharedBranchFileName = "first+second branch file.txt";

            string path = SandboxStandardTestRepo();

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

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

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

                repo.Checkout(secondBranch);

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

                Assert.Equal(MergeStatus.UpToDate, mergeResult.Status);
            }
        }
        public void RetrievingSubmoduleInBranchShouldWork()
        {
            var path = SandboxSubmoduleTestRepo();

            using (var repo = new Repository(path))
            {
                var submodule = repo.Submodules["sm_branch_only"];
                Assert.Null(submodule);

                repo.Checkout("dev", new CheckoutOptions {
                    CheckoutModifiers = CheckoutModifiers.Force
                });
                submodule = repo.Submodules["sm_branch_only"];
                Assert.NotNull(submodule);
                Assert.NotEqual(SubmoduleStatus.Unmodified, submodule.RetrieveStatus());

                repo.Checkout("master", new CheckoutOptions {
                    CheckoutModifiers = CheckoutModifiers.Force
                });
                submodule = repo.Submodules["sm_branch_only"];
                Assert.Null(submodule);
            }
        }
Example #30
0
        public void QueryingTheRemoteForADetachedHeadBranchReturnsNull()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                repo.Checkout(repo.Head.Tip.Sha, new CheckoutOptions()
                {
                    CheckoutModifiers = CheckoutModifiers.Force
                });
                Branch trackLocal = repo.Head;
                Assert.Null(trackLocal.Remote);
            }
        }
Example #31
0
        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);
                }
            }
        }
        protected void Checkout(string path, string url)
        {
            Repository _repo = GetRepo(path, url);

            _repo.Checkout(path, true, new NullProgressMonitor());
            if (Repo == null)
            {
                Repo = _repo;
            }
            else
            {
                Repo2 = _repo;
            }
        }
Example #33
0
        public void CheckingOutThroughRepositoryCallsCheckoutProgress()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                PopulateBasicRepository(repo);
                bool wasCalled = false;

                repo.Checkout(otherBranchName, CheckoutModifiers.None, (path, completed, total) => wasCalled = true, null);

                Assert.True(wasCalled);
            }
        }
Example #34
0
        private void InitializeRepo()
        {
            try
            {
                Repository.Init(_configurationPath);
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat("Error initializing repository in {0}. Error: {1}", _configurationPath, ex.Message);
            }

            _gitRepo = new Repository(_configurationPath);

            // if the repo was not created then log the situation and return, no reason to try to fetch/update from
            // uninitialized repo
            if (_gitRepo == null)
            {
                _logger.Error("Fatal error: Unable to create the GIT repository");
                return;
            }

            if (!_gitRepo.Network.Remotes.Any())
            {
                // Only add and fetch origin if we don't already have it
                _gitRepo.Network.Remotes.Add("origin", _remoteRepoUrl);
            }

            try
            {
                _gitRepo.Fetch("origin", new FetchOptions {
                    CredentialsProvider = (url, user, cred) => _credentials
                });

                // So, let's configure the local branch to track the remote one.
                _gitRepo.Branches.Update(LocalBranch, b => b.TrackedBranch = TrackedBranch.CanonicalName);

                Branch checkedOutBranch = _gitRepo.Checkout(LocalBranch, new CheckoutOptions {
                    CheckoutModifiers = CheckoutModifiers.Force
                });
                _gitRepo.Network.Pull(_signature, GetFastForwardPullOptions());

                _logger.DebugFormat("Branch checked out for repository '{0}' in '{1}' (branch: {2})",
                                    _remoteRepoUrl, _configurationPath, checkedOutBranch.Name);
            }
            catch (LibGit2SharpException ex)
            {
                _logger.ErrorFormat("Error fetching/pulling from origin ({0}). Error: {1} (credentials used: [{2}][{3}]. Password is encoded.",
                                    _remoteRepoUrl, ex.Message, _config.UserName, _config.PasswordEncoded);
            }
        }
Example #35
0
        public void SmudgeIsCalledIfAttributeEntryMatches(string filterAttribute, string attributeEntry, int smudgeCount)
        {
            const string decodedInput = "This is a substitution cipher";

            var filterForAttributes = new List <FilterAttributeEntry> {
                new FilterAttributeEntry(filterAttribute)
            };
            var filter = new SubstitutionCipherFilter("cipher-filter", filterForAttributes);

            var filterRegistration = GlobalSettings.RegisterFilter(filter);

            string repoPath = InitNewRepository();
            string fileName = Guid.NewGuid() + ".txt";

            string configPath        = CreateConfigurationWithDummyUser(Constants.Identity);
            var    repositoryOptions = new RepositoryOptions {
                GlobalConfigurationLocation = configPath
            };

            using (var repo = new Repository(repoPath, repositoryOptions))
            {
                CreateAttributesFile(repo, attributeEntry);

                CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);

                var branch = repo.CreateBranch("delete-files");
                repo.Checkout(branch.FriendlyName);

                DeleteFile(repo, fileName);

                repo.Checkout("master");

                Assert.Equal(smudgeCount, filter.SmudgeCalledCount);
            }

            GlobalSettings.DeregisterFilter(filterRegistration);
        }
    public void GivenARemoteWithATagOnMaster_AndAPullRequestWithTwoCommits_AndBuildIsRunningInTeamCity_VersionIsCalculatedProperly(string pullRequestRef)
    {
        using (var fixture = new EmptyRepositoryFixture())
        {
            var remoteRepositoryPath = PathHelper.GetTempPath();
            Repository.Init(remoteRepositoryPath);
            using (var remoteRepository = new Repository(remoteRepositoryPath))
            {
                remoteRepository.Config.Set("user.name", "Test");
                remoteRepository.Config.Set("user.email", "*****@*****.**");
                fixture.Repository.Network.Remotes.Add("origin", remoteRepositoryPath);
                Console.WriteLine("Created git repository at {0}", remoteRepositoryPath);
                remoteRepository.MakeATaggedCommit("1.0.3");

                var branch = remoteRepository.CreateBranch("FeatureBranch");
                remoteRepository.Checkout(branch);
                remoteRepository.MakeCommits(2);
                remoteRepository.Checkout(remoteRepository.Head.Tip.Sha);
                //Emulate merge commit
                var mergeCommitSha = remoteRepository.MakeACommit().Sha;
                remoteRepository.Checkout("master"); // HEAD cannot be pointing at the merge commit
                remoteRepository.Refs.Add(pullRequestRef, new ObjectId(mergeCommitSha));

                // Checkout PR commit
                Commands.Fetch((Repository)fixture.Repository, "origin", new string[0], new FetchOptions(), null);
                fixture.Repository.Checkout(mergeCommitSha);
            }

            var result = GitVersionHelper.ExecuteIn(fixture.RepositoryPath, isTeamCity: true);

            result.ExitCode.ShouldBe(0);
            result.OutputVariables.FullSemVer.ShouldBe("1.0.4-PullRequest0005.3");

            // Cleanup repository files
            DirectoryHelper.DeleteDirectory(remoteRepositoryPath);
        }
    }
Example #37
0
        private static void WalkIntoProjectHistory(string projectName, string localRepoPath
                                                   , string projectPath, string branchName, Action <LibGit2Sharp.Commit, string, string, string> CheckoutHandler)
        {
            using (var repo = new Repository(localRepoPath))
            {
                foreach (var commit in repo.Branches[branchName].Commits)
                {
                    var checkoutOptions = new CheckoutOptions();
                    checkoutOptions.CheckoutModifiers = CheckoutModifiers.Force;
                    repo.Checkout(commit, checkoutOptions);

                    CheckoutHandler(commit, projectName, projectPath, branchName);
                }
            }
        }
Example #38
0
        public void ContinuingRebaseWithUnstagedChangesThrows()
        {
            SelfCleaningDirectory scd = BuildSelfCleaningDirectory();
            var path = Repository.Init(scd.DirectoryPath);

            using (Repository repo = new Repository(path))
            {
                ConstructRebaseTestRepository(repo);

                repo.Checkout(topicBranch1Name);
                Assert.False(repo.RetrieveStatus().IsDirty);

                Branch branch   = repo.Branches[topicBranch1Name];
                Branch upstream = repo.Branches[conflictBranch1Name];
                Branch onto     = repo.Branches[conflictBranch1Name];

                RebaseResult rebaseResult = repo.Rebase.Start(branch, upstream, onto, Constants.Identity, null);

                // Verify that we have a conflict.
                Assert.Equal(CurrentOperation.RebaseMerge, repo.Info.CurrentOperation);
                Assert.Equal(RebaseStatus.Conflicts, rebaseResult.Status);
                Assert.True(repo.RetrieveStatus().IsDirty);
                Assert.False(repo.Index.IsFullyMerged);
                Assert.Equal(0, rebaseResult.CompletedStepCount);
                Assert.Equal(3, rebaseResult.TotalStepCount);

                Assert.Throws <UnmergedIndexEntriesException>(() =>
                                                              repo.Rebase.Continue(Constants.Identity, null));

                // Resolve the conflict
                foreach (Conflict conflict in repo.Index.Conflicts)
                {
                    Touch(repo.Info.WorkingDirectory,
                          conflict.Theirs.Path,
                          repo.Lookup <Blob>(conflict.Theirs.Id).GetContentText(new FilteringOptions(conflict.Theirs.Path)));
                    Commands.Stage(repo, conflict.Theirs.Path);
                }

                Touch(repo.Info.WorkingDirectory,
                      filePathA,
                      "Unstaged content");

                Assert.Throws <UnmergedIndexEntriesException>(() =>
                                                              repo.Rebase.Continue(Constants.Identity, null));

                Assert.True(repo.Index.IsFullyMerged);
            }
        }
    public void NServiceBusReleaseSpecificCommit()
    {
        using (var repository = new Repository(@"C:\Code\NServiceBus"))
        {
            var branch = repository.Branches.First(x => x.Name == "release-4.1.0");
            repository.Checkout("c0e0a5e13775552cd3e08e039f453e4cf1fd4235");

            var finder  = new GitVersionFinder();
            var version = finder.FindVersion(new GitVersionContext(repository, branch));
            Debug.WriteLine(version.Major);
            Debug.WriteLine(version.Minor);
            Debug.WriteLine(version.Patch);
            Debug.WriteLine(version.PreReleaseTag);
            Debug.WriteLine(version.BuildMetaData);
        }
    }
Example #40
0
        public void CanNotRevertAMergeCommitWithoutSpecifyingTheMainlineBranch()
        {
            const string revertBranchName = "refs/heads/revert_merge";
            const string commitIdToRevert = "2747045";

            string repoPath = CloneRevertTestRepo();
            using (var repo = new Repository(repoPath))
            {
                Branch branch = repo.Checkout(revertBranchName);
                Assert.NotNull(branch);

                var commitToRevert = repo.Lookup<Commit>(commitIdToRevert);
                Assert.NotNull(commitToRevert);

                Assert.Throws<LibGit2SharpException>(() => repo.Revert(commitToRevert, Constants.Signature));
            }
        }
        public void CanRevert()
        {
            // The branch name to perform the revert on,
            // and the file whose contents we expect to be reverted.
            const string revertBranchName = "refs/heads/revert";
            const string revertedFile = "a.txt";

            string path = CloneRevertTestRepo();
            using (var repo = new Repository(path))
            {
                // Checkout the revert branch.
                Branch branch = repo.Checkout(revertBranchName);
                Assert.NotNull(branch);

                // Revert tip commit.
                RevertResult result = repo.Revert(repo.Head.Tip, Constants.Signature);
                Assert.NotNull(result);
                Assert.Equal(RevertStatus.Reverted, result.Status);

                // Verify commit was made.
                Assert.NotNull(result.Commit);

                // Verify the expected commit ID.
                Assert.Equal("04746060fa753c9970d88a0b59151d7b212ac903", result.Commit.Id.Sha);

                // Verify workspace is clean.
                Assert.True(repo.Index.IsFullyMerged);
                Assert.False(repo.Index.RetrieveStatus().IsDirty);

                // Lookup the blob containing the expected reverted content of a.txt.
                Blob expectedBlob = repo.Lookup<Blob>("bc90ea420cf6c5ae3db7dcdffa0d79df567f219b");
                Assert.NotNull(expectedBlob);

                // Verify contents of Index.
                IndexEntry revertedIndexEntry = repo.Index[revertedFile];
                Assert.NotNull(revertedIndexEntry);

                // Verify the contents of the index.
                Assert.Equal(expectedBlob.Id, revertedIndexEntry.Id);

                // Verify contents of workspace.
                string fullPath = Path.Combine(repo.Info.WorkingDirectory, revertedFile);
                Assert.Equal(expectedBlob.GetContentText(new FilteringOptions(revertedFile)), File.ReadAllText(fullPath));
            }
        }
        public void CanRevertAndNotCommit()
        {
            // The branch name to perform the revert on,
            // and the file whose contents we expect to be reverted.
            const string revertBranchName = "refs/heads/revert";
            const string revertedFile = "a.txt";

            string path = CloneRevertTestRepo();
            using (var repo = new Repository(path))
            {
                string modifiedFileFullPath = Path.Combine(repo.Info.WorkingDirectory, revertedFile);

                // Checkout the revert branch.
                Branch branch = repo.Checkout(revertBranchName);
                Assert.NotNull(branch);

                // Revert tip commit.
                RevertResult result = repo.Revert(repo.Head.Tip, Constants.Signature, new RevertOptions() { CommitOnSuccess = false });
                Assert.NotNull(result);
                Assert.Equal(RevertStatus.Reverted, result.Status);

                // Verify the commit was made.
                Assert.Null(result.Commit);

                // Verify workspace is dirty.
                FileStatus fileStatus = repo.Index.RetrieveStatus(revertedFile);
                Assert.Equal(FileStatus.Staged, fileStatus);

                // This is the ID of the blob containing the expected content.
                Blob expectedBlob = repo.Lookup<Blob>("bc90ea420cf6c5ae3db7dcdffa0d79df567f219b");
                Assert.NotNull(expectedBlob);

                // Verify contents of Index.
                IndexEntry revertedIndexEntry = repo.Index[revertedFile];
                Assert.NotNull(revertedIndexEntry);

                Assert.Equal(expectedBlob.Id, revertedIndexEntry.Id);

                // Verify contents of workspace.
                string fullPath = Path.Combine(repo.Info.WorkingDirectory, revertedFile);
                Assert.Equal(expectedBlob.GetContentText(new FilteringOptions(revertedFile)), File.ReadAllText(fullPath));
            }
        }
Example #43
0
        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);
            }
        }
Example #44
0
        public void CanCheckoutAnExistingBranch(string name)
        {
            TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo();
            using (var repo = new Repository(path.RepositoryPath))
            {
                Branch master = repo.Branches["master"];
                Assert.True(master.IsCurrentRepositoryHead);

                Branch branch = repo.Branches[name];
                Assert.NotNull(branch);

                Branch test = repo.Checkout(branch);
                Assert.False(repo.Info.IsHeadDetached);

                Assert.False(test.IsRemote);
                Assert.True(test.IsCurrentRepositoryHead);
                Assert.Equal(repo.Head, test);

                Assert.False(master.IsCurrentRepositoryHead);
            }
        }
Example #45
0
        public void CanCheckoutAnExistingBranch(string name)
        {
            TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo();
            using (var repo = new Repository(path.RepositoryPath))
            {
                Branch master = repo.Branches["master"];
                master.IsCurrentRepositoryHead.ShouldBeTrue();

                Branch branch = repo.Branches[name];
                branch.ShouldNotBeNull();

                Branch test = repo.Checkout(branch);
                repo.Info.IsHeadDetached.ShouldBeFalse();

                test.IsRemote.ShouldBeFalse();
                test.IsCurrentRepositoryHead.ShouldBeTrue();
                test.ShouldEqual(repo.Head);

                master.IsCurrentRepositoryHead.ShouldBeFalse();
            }
        }
        public void CanCherryPick(bool fromDetachedHead)
        {
            string path = SandboxMergeTestRepo();
            using (var repo = new Repository(path))
            {
                if (fromDetachedHead)
                {
                    repo.Checkout(repo.Head.Tip.Id.Sha);
                }

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

                CherryPickResult result = repo.CherryPick(commitToMerge, Constants.Signature);

                Assert.Equal(CherryPickStatus.CherryPicked, result.Status);
                Assert.Equal(cherryPickedCommitId, result.Commit.Id.Sha);
                Assert.False(repo.RetrieveStatus().Any());
                Assert.Equal(fromDetachedHead, repo.Info.IsHeadDetached);
                Assert.Equal(commitToMerge.Author, result.Commit.Author);
                Assert.Equal(Constants.Signature, result.Commit.Committer);
            }
        }
Example #47
0
        public void CanCheckoutAnArbitraryCommit(string commitPointer)
        {
            TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo();
            using (var repo = new Repository(path.RepositoryPath))
            {
                Branch master = repo.Branches["master"];
                Assert.True(master.IsCurrentRepositoryHead);

                Branch detachedHead = repo.Checkout(commitPointer);

                Assert.True(repo.Info.IsHeadDetached);

                Assert.False(detachedHead.IsRemote);
                Assert.Equal(detachedHead.Name, detachedHead.CanonicalName);
                Assert.Equal("(no branch)", detachedHead.CanonicalName);
                Assert.Equal(repo.Lookup(commitPointer).Sha, detachedHead.Tip.Sha);

                Assert.Equal(repo.Head, detachedHead);

                Assert.False(master.IsCurrentRepositoryHead);
                Assert.True(detachedHead.IsCurrentRepositoryHead);
                Assert.True(repo.Head.IsCurrentRepositoryHead);
            }
        }
 public void QueryingTheRemoteForADetachedHeadBranchReturnsNull()
 {
     string path = SandboxStandardTestRepo();
     using (var repo = new Repository(path))
     {
         repo.Checkout(repo.Head.Tip.Sha, new CheckoutOptions() { CheckoutModifiers = CheckoutModifiers.Force });
         Branch trackLocal = repo.Head;
         Assert.Null(trackLocal.Remote);
     }
 }
Example #49
0
        public void CheckoutPreviousCheckedOutBranch()
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                // Set the working directory to the current head
                ResetAndCleanWorkingDirectory(repo);
                Assert.False(repo.RetrieveStatus().IsDirty);

                Branch previousHead = repo.Checkout("i-do-numbers");
                repo.Checkout("diff-test-cases");

                //Go back to previous branch checked out
                var branch = repo.Checkout(@"@{-1}");

                Assert.False(repo.Info.IsHeadDetached);
                Assert.Equal(previousHead.CanonicalName, repo.Head.CanonicalName);
                Assert.Equal(previousHead.CanonicalName, branch.CanonicalName);
            }
        }
Example #50
0
 public void CheckingOutANonExistingBranchThrows()
 {
     using (var repo = new Repository(BareTestRepoPath))
     {
         Assert.Throws<LibGit2Exception>(() => repo.Checkout("i-do-not-exist"));
     }
 }
Example #51
0
 public void CheckingOutABranchWithBadParamsThrows()
 {
     using (var repo = new Repository(BareTestRepoPath))
     {
         Assert.Throws<ArgumentException>(() => repo.Checkout(string.Empty));
         Assert.Throws<ArgumentNullException>(() => repo.Checkout(default(Branch)));
         Assert.Throws<ArgumentNullException>(() => repo.Checkout(default(string)));
     }
 }
Example #52
0
        public void CanCorrectlyCountCommitsWhenSwitchingToAnotherBranch()
        {
            using (var repo = new Repository(BareTestRepoPath))
            {
                repo.Checkout("test");
                Assert.Equal(2, repo.Commits.Count());
                Assert.Equal("e90810b8df3e80c413d903f631643c716887138d", repo.Commits.First().Id.Sha);

                repo.Checkout("master");
                Assert.Equal(7, repo.Commits.Count());
                Assert.Equal("4c062a6361ae6959e06292c1fa5e2822d9c96345", repo.Commits.First().Id.Sha);
            }
        }
Example #53
0
        public void CanEnumerateFromDetachedHead()
        {
            TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo();
            using (var repoClone = new Repository(path.RepositoryPath))
            {
                string headSha = repoClone.Head.Tip.Sha;
                repoClone.Checkout(headSha);

                AssertEnumerationOfCommitsInRepo(repoClone,
                    repo => new Filter { Since = repo.Head },
                    new[]
                        {
                            "4c062a6", "be3563a", "c47800c", "9fd738e",
                            "4a202b3", "5b5b025", "8496071",
                        });
            }
        }
Example #54
0
        public void CheckoutRetainsUntrackedChanges()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                PopulateBasicRepository(repo);

                // Generate an unstaged change.
                string fullPathFileB = Touch(repo.Info.WorkingDirectory, "b.txt", alternateFileContent);

                // Verify that there is an untracked entry.
                Assert.Equal(1, repo.RetrieveStatus().Untracked.Count());
                Assert.Equal(FileStatus.Untracked, repo.RetrieveStatus(fullPathFileB));

                repo.Checkout(otherBranchName);

                // Verify untracked entry still exists.
                Assert.Equal(1, repo.RetrieveStatus().Untracked.Count());
                Assert.Equal(FileStatus.Untracked, repo.RetrieveStatus(fullPathFileB));
            }
        }
Example #55
0
 public void CheckoutLowerCasedHeadThrows()
 {
     using (var repo = new Repository(StandardTestRepoWorkingDirPath))
     {
         Assert.Throws<LibGit2SharpException>(() => repo.Checkout("head"));
     }
 }
Example #56
0
        public void ForceCheckoutRetainsIgnoredChanges()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                PopulateBasicRepository(repo);

                // Create file in ignored bin directory.
                string ignoredFilePath = Touch(
                    repo.Info.WorkingDirectory,
                    "bin/some_ignored_file.txt",
                    "hello from this ignored file.");

                Assert.Equal(1, repo.RetrieveStatus().Ignored.Count());

                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(ignoredFilePath));

                repo.Checkout(otherBranchName, new CheckoutOptions() { CheckoutModifiers = CheckoutModifiers.Force });

                // Verify that the ignored file still exists.
                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(ignoredFilePath));
                Assert.True(File.Exists(ignoredFilePath));
            }
        }
Example #57
0
        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);
                }
            }
        }
Example #58
0
        public void CanEnumerateFromDetachedHead()
        {
            string path = CloneStandardTestRepo();
            using (var repoClone = new Repository(path))
            {
                // Hard reset and then remove untracked files
                repoClone.Reset(ResetOptions.Hard);
                repoClone.RemoveUntrackedFiles();

                string headSha = repoClone.Head.Tip.Sha;
                repoClone.Checkout(headSha);

                AssertEnumerationOfCommitsInRepo(repoClone,
                    repo => new Filter { Since = repo.Head },
                    new[]
                        {
                            "32eab9c", "592d3c8", "4c062a6",
                            "be3563a", "c47800c", "9fd738e",
                            "4a202b3", "5b5b025", "8496071",
                        });
            }
        }
Example #59
0
        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);
            }
        }
Example #60
0
        public void CheckoutFromDetachedHead(string commitPointer)
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                // Set the working directory to the current head
                ResetAndCleanWorkingDirectory(repo);
                Assert.False(repo.RetrieveStatus().IsDirty);

                var commitSha = repo.Lookup(commitPointer).Sha;

                Branch initialHead = repo.Checkout("6dcf9bf");

                repo.Checkout(commitPointer);

                // Assert reflog entry is created
                var reflogEntry = repo.Refs.Log(repo.Refs.Head).First();
                Assert.Equal(initialHead.Tip.Id, reflogEntry.From);
                Assert.Equal(commitSha, reflogEntry.To.Sha);
                Assert.NotNull(reflogEntry.Commiter.Email);
                Assert.NotNull(reflogEntry.Commiter.Name);
                Assert.Equal(string.Format("checkout: moving from {0} to {1}", initialHead.Tip.Sha, commitPointer), reflogEntry.Message);
            }
        }