public void CanCheckoutAnExistingBranchByName(string branchName)
        {
            string path = SandboxStandardTestRepo();
            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.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.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 #2
0
        public void CanRemoveAnUnalteredFileFromTheIndexWithoutRemovingItFromTheWorkingDirectory(
            bool removeFromWorkdir, string filename, bool throws, FileStatus initialStatus, bool existsBeforeRemove, bool existsAfterRemove, FileStatus lastStatus)
        {
            string path = SandboxStandardTestRepo();
            using (var repo = new Repository(path))
            {
                int count = repo.Index.Count;

                string fullpath = Path.Combine(repo.Info.WorkingDirectory, filename);

                Assert.Equal(initialStatus, repo.RetrieveStatus(filename));
                Assert.Equal(existsBeforeRemove, File.Exists(fullpath));

                if (throws)
                {
                    Assert.Throws<RemoveFromIndexException>(() => repo.Remove(filename, removeFromWorkdir));
                    Assert.Equal(count, repo.Index.Count);
                }
                else
                {
                    repo.Remove(filename, removeFromWorkdir);

                    Assert.Equal(count - 1, repo.Index.Count);
                    Assert.Equal(existsAfterRemove, File.Exists(fullpath));
                    Assert.Equal(lastStatus, repo.RetrieveStatus(filename));
                }
            }
        }
Example #3
0
        public void HonorDeeplyNestedGitIgnoreFile()
        {
            string path = InitNewRepository();
            using (var repo = new Repository(path))
            {
                char pd = Path.DirectorySeparatorChar;

                var gitIgnoreFile = string.Format("deeply{0}nested{0}.gitignore", pd);
                Touch(repo.Info.WorkingDirectory, gitIgnoreFile, "SmtCounters.h");

                Commands.Stage(repo, gitIgnoreFile);
                repo.Commit("Add .gitignore", Constants.Signature, Constants.Signature);

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

                var ignoredFile = string.Format("deeply{0}nested{0}SmtCounters.h", pd);
                Touch(repo.Info.WorkingDirectory, ignoredFile, "Content");
                Assert.False(repo.RetrieveStatus().IsDirty);

                var file = string.Format("deeply{0}nested{0}file.txt", pd);
                Touch(repo.Info.WorkingDirectory, file, "Yeah!");

                var repositoryStatus = repo.RetrieveStatus();
                Assert.True(repositoryStatus.IsDirty);

                Assert.Equal(FileStatus.Ignored, repositoryStatus[ignoredFile].State);
                Assert.Equal(FileStatus.NewInWorkdir, repositoryStatus[file].State);

                Assert.True(repo.Ignore.IsPathIgnored(ignoredFile));
                Assert.False(repo.Ignore.IsPathIgnored(file));
            }
        }
Example #4
0
        public void CanAddAndRemoveStash()
        {
            string path = SandboxStandardTestRepo();
            using (var repo = new Repository(path))
            {
                var stasher = Constants.Signature;

                Assert.True(repo.RetrieveStatus().IsDirty);

                Stash stash = repo.Stashes.Add(stasher, "My very first stash", StashModifiers.IncludeUntracked);

                // Check that untracked files are deleted from working directory
                string untrackedFilename = "new_untracked_file.txt";
                Assert.False(File.Exists(Path.Combine(repo.Info.WorkingDirectory, untrackedFilename)));
                Assert.NotNull(stash.Untracked[untrackedFilename]);

                Assert.NotNull(stash);
                Assert.Equal("stash@{0}", stash.CanonicalName);
                Assert.Contains("My very first stash", stash.Message);

                var stashRef = repo.Refs["refs/stash"];
                Assert.Equal(stash.WorkTree.Sha, stashRef.TargetIdentifier);

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

                // Create extra file
                untrackedFilename = "stash_candidate.txt";
                Touch(repo.Info.WorkingDirectory, untrackedFilename, "Oh, I'm going to be stashed!\n");

                Stash secondStash = repo.Stashes.Add(stasher, "My second stash", StashModifiers.IncludeUntracked);

                Assert.NotNull(stash);
                Assert.Equal("stash@{0}", stash.CanonicalName);
                Assert.Contains("My second stash", secondStash.Message);

                Assert.Equal(2, repo.Stashes.Count());
                Assert.Equal("stash@{0}", repo.Stashes.First().CanonicalName);
                Assert.Equal("stash@{1}", repo.Stashes.Last().CanonicalName);

                Assert.NotNull(secondStash.Untracked[untrackedFilename]);

                // Stash history has been shifted
                Assert.Equal(repo.Lookup<Commit>("stash@{0}").Sha, secondStash.WorkTree.Sha);
                Assert.Equal(repo.Lookup<Commit>("stash@{1}").Sha, stash.WorkTree.Sha);

                //Remove one stash
                repo.Stashes.Remove(0);
                Assert.Equal(1, repo.Stashes.Count());
                Stash newTopStash = repo.Stashes.First();
                Assert.Equal("stash@{0}", newTopStash.CanonicalName);
                Assert.Equal(stash.WorkTree.Sha, newTopStash.WorkTree.Sha);

                // Stash history has been shifted
                Assert.Equal(stash.WorkTree.Sha, repo.Lookup<Commit>("stash").Sha);
                Assert.Equal(stash.WorkTree.Sha, repo.Lookup<Commit>("stash@{0}").Sha);
            }
        }
Example #5
0
        public void CanIgnoreIgnoredPaths(string path)
        {
            using (var repo = new Repository(SandboxStandardTestRepo()))
            {
                Touch(repo.Info.WorkingDirectory, ".gitignore", "ignored_file.txt\nignored_folder/\n");
                Touch(repo.Info.WorkingDirectory, path, "This file is ignored.");

                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(path));
                Commands.Stage(repo, "*");
                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(path));
            }
        }
Example #6
0
        public void CanAddAnEntryToTheIndexFromAFileInTheWorkdir(string pathInTheWorkdir, FileStatus expectedBeforeStatus, FileStatus expectedAfterStatus)
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                var before = repo.RetrieveStatus(pathInTheWorkdir);
                Assert.Equal(expectedBeforeStatus, before);

                repo.Index.Add(pathInTheWorkdir);

                var after = repo.RetrieveStatus(pathInTheWorkdir);
                Assert.Equal(expectedAfterStatus, after);
            }
        }
        public void MixedResetRefreshesTheIndex()
        {
            string repoPath = InitNewRepository();

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

                var oldHeadId = repo.Head.Tip.Id;

                Tag tag = repo.Tags["mytag"];

                repo.Reset(ResetMode.Mixed, tag.CanonicalName);

                Assert.Equal(FileStatus.Modified, repo.RetrieveStatus("a.txt"));

                AssertRefLogEntry(repo, "HEAD",
                                  tag.Target.Id,
                                  string.Format("reset: moving to {0}", tag.Target.Sha),
                                  oldHeadId);

                AssertRefLogEntry(repo, "refs/heads/mybranch",
                                  tag.Target.Id,
                                  string.Format("reset: moving to {0}", tag.Target.Sha),
                                  oldHeadId);
            }
        }
Example #8
0
        public void CanStage(string relativePath, FileStatus currentStatus, bool doesCurrentlyExistInTheIndex, FileStatus expectedStatusOnceStaged, bool doesExistInTheIndexOnceStaged, int expectedIndexCountVariation)
        {
            string path = SandboxStandardTestRepo();
            using (var repo = new Repository(path))
            {
                int count = repo.Index.Count;
                Assert.Equal(doesCurrentlyExistInTheIndex, (repo.Index[relativePath] != null));
                Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath));

                repo.Stage(relativePath);

                Assert.Equal(count + expectedIndexCountVariation, repo.Index.Count);
                Assert.Equal(doesExistInTheIndexOnceStaged, (repo.Index[relativePath] != null));
                Assert.Equal(expectedStatusOnceStaged, repo.RetrieveStatus(relativePath));
            }
        }
Example #9
0
        public void CanCleanWorkingDirectory()
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                // Verify that there are the expected number of entries and untracked files
                Assert.Equal(6, repo.RetrieveStatus().Count());
                Assert.Equal(1, repo.RetrieveStatus().Untracked.Count());

                repo.RemoveUntrackedFiles();

                // Verify that there are the expected number of entries and 0 untracked files
                Assert.Equal(5, repo.RetrieveStatus().Count());
                Assert.Equal(0, repo.RetrieveStatus().Untracked.Count());
            }
        }
Example #10
0
        public void CanResolveConflictsByRemovingFromTheIndex(
            bool removeFromWorkdir, string filename, bool existsBeforeRemove, bool existsAfterRemove, FileStatus lastStatus, int removedIndexEntries)
        {
            var path = SandboxMergedTestRepo();
            using (var repo = new Repository(path))
            {
                int count = repo.Index.Count;

                string fullpath = Path.Combine(repo.Info.WorkingDirectory, filename);

                Assert.Equal(existsBeforeRemove, File.Exists(fullpath));
                Assert.NotNull(repo.Index.Conflicts[filename]);
                Assert.Equal(0, repo.Index.Conflicts.ResolvedConflicts.Count());

                repo.Remove(filename, removeFromWorkdir);

                Assert.Null(repo.Index.Conflicts[filename]);
                Assert.Equal(count - removedIndexEntries, repo.Index.Count);
                Assert.Equal(existsAfterRemove, File.Exists(fullpath));
                Assert.Equal(lastStatus, repo.RetrieveStatus(filename));

                Assert.Equal(1, repo.Index.Conflicts.ResolvedConflicts.Count());
                Assert.NotNull(repo.Index.Conflicts.ResolvedConflicts[filename]);
            }
        }
Example #11
0
        public void MixedResetRefreshesTheIndex()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath, new RepositoryOptions { Identity = Constants.Identity }))
            {
                FeedTheRepository(repo);

                var oldHeadId = repo.Head.Tip.Id;

                Tag tag = repo.Tags["mytag"];

                var before = DateTimeOffset.Now.TruncateMilliseconds();

                repo.Reset(ResetMode.Mixed, tag.CanonicalName);

                Assert.Equal(FileStatus.ModifiedInWorkdir, repo.RetrieveStatus("a.txt"));

                AssertRefLogEntry(repo, "HEAD",
                                  string.Format("reset: moving to {0}", tag.Target.Sha),
                                  oldHeadId,
                                  tag.Target.Id,
                                  Constants.Identity, before);

                AssertRefLogEntry(repo, "refs/heads/mybranch",
                                  string.Format("reset: moving to {0}", tag.Target.Sha),
                                  oldHeadId,
                                  tag.Target.Id,
                                  Constants.Identity, before);
            }
        }
Example #12
0
        public void CanCopeWithExternalChangesToTheIndex()
        {
            SelfCleaningDirectory scd = BuildSelfCleaningDirectory();

            Touch(scd.DirectoryPath, "a.txt", "a\n");
            Touch(scd.DirectoryPath, "b.txt", "b\n");

            string path = Repository.Init(scd.DirectoryPath);

            using (var repoWrite = new Repository(path))
            using (var repoRead = new Repository(path))
            {
                var writeStatus = repoWrite.RetrieveStatus();
                Assert.True(writeStatus.IsDirty);
                Assert.Equal(0, repoWrite.Index.Count);

                var readStatus = repoRead.RetrieveStatus();
                Assert.True(readStatus.IsDirty);
                Assert.Equal(0, repoRead.Index.Count);

                repoWrite.Stage("*");
                repoWrite.Commit("message", Constants.Signature, Constants.Signature);

                writeStatus = repoWrite.RetrieveStatus();
                Assert.False(writeStatus.IsDirty);
                Assert.Equal(2, repoWrite.Index.Count);

                readStatus = repoRead.RetrieveStatus();
                Assert.False(readStatus.IsDirty);
                Assert.Equal(2, repoRead.Index.Count);
            }
        }
Example #13
0
        public void CanAddAnEntryToTheIndexFromABlob()
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                const string targetIndexEntryPath = "1.txt";
                var before = repo.RetrieveStatus(targetIndexEntryPath);
                Assert.Equal(FileStatus.Unaltered, before);

                var blob = repo.Lookup<Blob>("a8233120f6ad708f843d861ce2b7228ec4e3dec6");

                repo.Index.Add(blob, targetIndexEntryPath, Mode.NonExecutableFile);

                var after = repo.RetrieveStatus(targetIndexEntryPath);
                Assert.Equal(FileStatus.ModifiedInIndex | FileStatus.ModifiedInWorkdir, after);
            }
        }
Example #14
0
        public void TemporaryRulesShouldApplyUntilCleared()
        {
            string path = SandboxStandardTestRepo();
            using (var repo = new Repository(path))
            {
                Touch(repo.Info.WorkingDirectory, "Foo.cs", "Bar");

                Assert.True(repo.RetrieveStatus().Untracked.Select(s => s.FilePath).Contains("Foo.cs"));

                repo.Ignore.AddTemporaryRules(new[] { "*.cs" });

                Assert.False(repo.RetrieveStatus().Untracked.Select(s => s.FilePath).Contains("Foo.cs"));

                repo.Ignore.ResetAllTemporaryRules();

                Assert.True(repo.RetrieveStatus().Untracked.Select(s => s.FilePath).Contains("Foo.cs"));
            }
        }
Example #15
0
 public void CanRetrieveTheStatusOfAFile()
 {
     var path = SandboxStandardTestRepoGitDir();
     using (var repo = new Repository(path))
     {
         FileStatus status = repo.RetrieveStatus("new_tracked_file.txt");
         Assert.Equal(FileStatus.Added, status);
     }
 }
        public void CanResetTargetOfARenameInIndex()
        {
            using (var repo = new Repository(CloneStandardTestRepo()))
            {
                repo.Move("branch_file.txt", "renamed_branch_file.txt");

                RepositoryStatus oldStatus = repo.RetrieveStatus();
                Assert.Equal(1, oldStatus.RenamedInIndex.Count());
                Assert.Equal(FileStatus.RenamedInIndex, oldStatus["renamed_branch_file.txt"].State);

                repo.Reset(repo.Lookup<Commit>("32eab9c"), new string[] { "renamed_branch_file.txt" });

                RepositoryStatus newStatus = repo.RetrieveStatus();
                Assert.Equal(0, newStatus.RenamedInIndex.Count());
                Assert.Equal(FileStatus.Untracked, newStatus["renamed_branch_file.txt"].State);
                Assert.Equal(FileStatus.Removed, newStatus["branch_file.txt"].State);
            }
        }
Example #17
0
        public void CanResetTargetOfARenameInIndex()
        {
            using (var repo = new Repository(SandboxStandardTestRepo()))
            {
                Commands.Move(repo, "branch_file.txt", "renamed_branch_file.txt");

                RepositoryStatus oldStatus = repo.RetrieveStatus();
                Assert.Equal(1, oldStatus.RenamedInIndex.Count());
                Assert.Equal(FileStatus.RenamedInIndex, oldStatus["renamed_branch_file.txt"].State);

                repo.Index.Replace(repo.Lookup<Commit>("32eab9c"), new string[] { "renamed_branch_file.txt" });

                RepositoryStatus newStatus = repo.RetrieveStatus();
                Assert.Equal(0, newStatus.RenamedInIndex.Count());
                Assert.Equal(FileStatus.NewInWorkdir, newStatus["renamed_branch_file.txt"].State);
                Assert.Equal(FileStatus.DeletedFromIndex, newStatus["branch_file.txt"].State);
            }
        }
Example #18
0
        public void CanDetectedVariousKindsOfRenaming()
        {
            string path = InitNewRepository();
            using (var repo = new Repository(path))
            {
                Touch(repo.Info.WorkingDirectory, "file.txt",
                    "This is a file with enough data to trigger similarity matching.\r\n" +
                    "This is a file with enough data to trigger similarity matching.\r\n" +
                    "This is a file with enough data to trigger similarity matching.\r\n" +
                    "This is a file with enough data to trigger similarity matching.\r\n");

                Commands.Stage(repo, "file.txt");
                repo.Commit("Initial commit", Constants.Signature, Constants.Signature);

                File.Move(Path.Combine(repo.Info.WorkingDirectory, "file.txt"),
                    Path.Combine(repo.Info.WorkingDirectory, "renamed.txt"));

                var opts = new StatusOptions
                {
                    DetectRenamesInIndex = true,
                    DetectRenamesInWorkDir = true
                };

                RepositoryStatus status = repo.RetrieveStatus(opts);

                // This passes as expected
                Assert.Equal(FileStatus.RenamedInWorkdir, status.Single().State);

                Commands.Stage(repo, "file.txt");
                Commands.Stage(repo, "renamed.txt");

                status = repo.RetrieveStatus(opts);

                Assert.Equal(FileStatus.RenamedInIndex, status.Single().State);

                File.Move(Path.Combine(repo.Info.WorkingDirectory, "renamed.txt"),
                    Path.Combine(repo.Info.WorkingDirectory, "renamed_again.txt"));

                status = repo.RetrieveStatus(opts);

                Assert.Equal(FileStatus.RenamedInWorkdir | FileStatus.RenamedInIndex,
                    status.Single().State);
            }
        }
        public void ResetTheIndexWithTheHeadUnstagesEverything()
        {
            string path = SandboxStandardTestRepo();
            using (var repo = new Repository(path))
            {
                RepositoryStatus oldStatus = repo.RetrieveStatus();
                Assert.Equal(3, oldStatus.Where(IsStaged).Count());

                var reflogEntriesCount = repo.Refs.Log(repo.Refs.Head).Count();

                repo.Reset();

                RepositoryStatus newStatus = repo.RetrieveStatus();
                Assert.Equal(0, newStatus.Where(IsStaged).Count());

                // Assert that no reflog entry is created
                Assert.Equal(reflogEntriesCount, repo.Refs.Log(repo.Refs.Head).Count());
            }
        }
        public void CanOpenABareRepoAsIfItWasAStandardOneWithANonExisitingIndexFile()
        {
            var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex };

            using (var repo = new Repository(BareTestRepoPath, options))
            {
                var st = repo.RetrieveStatus("1/branch_file.txt");
                Assert.Equal(FileStatus.Removed, st);
            }
        }
Example #21
0
        public void CanStageAndUnstageAnIgnoredFile()
        {
            string path = SandboxStandardTestRepo();
            using (var repo = new Repository(path))
            {
                Touch(repo.Info.WorkingDirectory, ".gitignore", "*.ign" + Environment.NewLine);

                const string relativePath = "Champa.ign";
                Touch(repo.Info.WorkingDirectory, relativePath, "On stage!" + Environment.NewLine);

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

                Commands.Stage(repo, relativePath, new StageOptions { IncludeIgnored = true });
                Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(relativePath));

                Commands.Unstage(repo, relativePath);
                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(relativePath));
            }
        }
        public void ComparingTheWorkDirAgainstTheIndexWithStrictUnmatchedExplicitPathsValidationAndANonExistentPathspecThrows(string relativePath, FileStatus currentStatus)
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath));

                Assert.Throws<UnmatchedPathException>(() => repo.Diff.Compare<TreeChanges>(new[] { relativePath }, false, new ExplicitPathsOptions()));
            }
        }
Example #23
0
        public void StagingAnUnknownFileThrowsIfExplicitPath(string relativePath, FileStatus status)
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                Assert.Null(repo.Index[relativePath]);
                Assert.Equal(status, repo.RetrieveStatus(relativePath));

                Assert.Throws<UnmatchedPathException>(() => repo.Stage(relativePath, new StageOptions { ExplicitPathsOptions = new ExplicitPathsOptions() }));
            }
        }
Example #24
0
        public void AddingAnEntryToTheIndexFromAUnknwonFileInTheWorkdirThrows()
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                const string filePath = "i_dont_exist.txt";
                var before = repo.RetrieveStatus(filePath);
                Assert.Equal(FileStatus.Nonexistent, before);

                Assert.Throws<NotFoundException>(() => repo.Index.Add(filePath));
            }
        }
Example #25
0
        public void CanUnstageBothSidesOfARename()
        {
            using (var repo = new Repository(SandboxStandardTestRepo()))
            {
                repo.Move("branch_file.txt", "renamed_branch_file.txt");
                repo.Unstage(new string[] { "branch_file.txt", "renamed_branch_file.txt" });

                RepositoryStatus status = repo.RetrieveStatus();
                Assert.Equal(FileStatus.DeletedFromWorkdir, status["branch_file.txt"].State);
                Assert.Equal(FileStatus.NewInWorkdir, status["renamed_branch_file.txt"].State);
            }
        }
Example #26
0
        public void CanUnstageTheRemovalOfAFile()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                int count = repo.Index.Count;

                const string filename = "deleted_staged_file.txt";

                string fullPath = Path.Combine(repo.Info.WorkingDirectory, filename);
                Assert.False(File.Exists(fullPath));

                Assert.Equal(FileStatus.DeletedFromIndex, repo.RetrieveStatus(filename));

                repo.Unstage(filename);
                Assert.Equal(count + 1, repo.Index.Count);

                Assert.Equal(FileStatus.DeletedFromWorkdir, repo.RetrieveStatus(filename));
            }
        }
Example #27
0
        public void MergeCanSpecifyMergeFileFavorOption(MergeFileFavor fileFavorFlag)
        {
            const string conflictFile       = "a.txt";
            const string conflictBranchName = "conflicts";

            string path = SandboxMergeTestRepo();

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

                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.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)));
            }
        }
        public void CanCreateABlobFromAFileInTheWorkingDirectory()
        {
            string path = InitNewRepository();
            using (var repo = new Repository(path))
            {
                Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus("hello.txt"));

                File.AppendAllText(Path.Combine(repo.Info.WorkingDirectory, "hello.txt"), "I'm a new file\n");

                Blob blob = repo.ObjectDatabase.CreateBlob("hello.txt");
                Assert.NotNull(blob);
                Assert.Equal("dc53d4c6b8684c21b0b57db29da4a2afea011565", blob.Sha);

                /* The file is unknown from the Index nor the Head ... */
                Assert.Equal(FileStatus.Untracked, repo.RetrieveStatus("hello.txt"));

                /* ...however, it's indeed stored in the repository. */
                var fetchedBlob = repo.Lookup<Blob>(blob.Id);
                Assert.Equal(blob, fetchedBlob);
            }
        }
Example #29
0
        public void CanLimitStatusToWorkDirOnly(StatusShowOption show, FileStatus expected)
        {
            var clone = SandboxStandardTestRepo();

            using (var repo = new Repository(clone))
            {
                Touch(repo.Info.WorkingDirectory, "file.txt", "content");

                RepositoryStatus status = repo.RetrieveStatus(new StatusOptions() { Show = show });
                Assert.Equal(expected, status["file.txt"].State);
            }
        }
        public void CanOpenABareRepoAsIfItWasAStandardOne()
        {
            File.Copy(Path.Combine(StandardTestRepoPath, "index"), newIndex);

            var options = new RepositoryOptions { WorkingDirectoryPath = newWorkdir, IndexPath = newIndex };

            using (var repo = new Repository(BareTestRepoPath, options))
            {
                var st = repo.RetrieveStatus("1/branch_file.txt");
                Assert.Equal(FileStatus.Missing, st);
            }
        }
Example #31
0
        public void CanUnstageBothSidesOfARename()
        {
            using (var repo = new Repository(SandboxStandardTestRepo()))
            {
                Commands.Move(repo, "branch_file.txt", "renamed_branch_file.txt");
                Commands.Unstage(repo, new string[] { "branch_file.txt", "renamed_branch_file.txt" });

                RepositoryStatus status = repo.RetrieveStatus();
                Assert.Equal(FileStatus.DeletedFromWorkdir, status["branch_file.txt"].State);
                Assert.Equal(FileStatus.NewInWorkdir, status["renamed_branch_file.txt"].State);
            }
        }
Example #32
0
        public void CanRetrieveTheStatusOfAnUntrackedFile(string filePath)
        {
            var clone = SandboxStandardTestRepo();

            using (var repo = new Repository(clone))
            {
                Touch(repo.Info.WorkingDirectory, filePath, "content");

                FileStatus status = repo.RetrieveStatus(filePath);
                Assert.Equal(FileStatus.NewInWorkdir, status);
            }
        }
Example #33
0
        public void RetrievingTheStatusOfAnEmptyRepositoryHonorsTheGitIgnoreDirectives()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                const string relativePath = "look-ma.txt";
                Touch(repo.Info.WorkingDirectory, relativePath, "I'm going to be ignored!");

                RepositoryStatus status = repo.RetrieveStatus();
                Assert.Equal(new[] { relativePath }, status.Untracked.Select(s => s.FilePath));

                Touch(repo.Info.WorkingDirectory, ".gitignore", "*.txt" + Environment.NewLine);

                RepositoryStatus newStatus = repo.RetrieveStatus();
                Assert.Equal(".gitignore", newStatus.Untracked.Select(s => s.FilePath).Single());

                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(relativePath));
                Assert.Equal(new[] { relativePath }, newStatus.Ignored.Select(s => s.FilePath));
            }
        }
Example #34
0
        public void UnstagingUnknownPathsAgainstAnOrphanedHeadWithStrictUnmatchedExplicitPathsValidationThrows(string relativePath, FileStatus currentStatus)
        {
            using (var repo = new Repository(SandboxStandardTestRepo()))
            {
                repo.Refs.UpdateTarget("HEAD", "refs/heads/orphaned");
                Assert.True(repo.Info.IsHeadUnborn);

                Assert.Equal(currentStatus, repo.RetrieveStatus(relativePath));

                Assert.Throws <UnmatchedPathException>(() => repo.Unstage(relativePath, new ExplicitPathsOptions()));
            }
        }
Example #35
0
        public void CanUnstageBothSidesOfARename()
        {
            using (var repo = new Repository(CloneStandardTestRepo()))
            {
                repo.Move("branch_file.txt", "renamed_branch_file.txt");
                repo.Unstage(new string[] { "branch_file.txt", "renamed_branch_file.txt" });

                RepositoryStatus status = repo.RetrieveStatus();
                Assert.Equal(FileStatus.Missing, status["branch_file.txt"].State);
                Assert.Equal(FileStatus.Untracked, status["renamed_branch_file.txt"].State);
            }
        }
Example #36
0
        public void CanCheckoutAnExistingBranch(string branchName)
        {
            string path = SandboxStandardTestRepo();

            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.RetrieveStatus().IsDirty);

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

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

                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.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(branch.Tip.Id, reflogEntry.To);
                Assert.NotNull(reflogEntry.Committer.Email);
                Assert.NotNull(reflogEntry.Committer.Name);
                Assert.Equal(string.Format("checkout: moving from master to {0}", branchName), reflogEntry.Message);
            }
        }
Example #37
0
        public void RetrievingTheStatusOfTheRepositoryHonorsTheGitIgnoreDirectivesThroughoutDirectories()
        {
            char dirSep = Path.DirectorySeparatorChar;

            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                Touch(repo.Info.WorkingDirectory, "bin/look-ma.txt", "I'm going to be ignored!");
                Touch(repo.Info.WorkingDirectory, "bin/what-about-me.txt", "Huh?");

                const string gitIgnore = ".gitignore";
                Touch(repo.Info.WorkingDirectory, gitIgnore, "bin");

                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus("bin/look-ma.txt"));
                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus("bin/what-about-me.txt"));

                RepositoryStatus newStatus = repo.RetrieveStatus();
                Assert.Equal(new[] { "bin" + dirSep }, newStatus.Ignored.Select(s => s.FilePath));

                var sb = new StringBuilder();
                sb.AppendLine("bin/*");
                sb.AppendLine("!bin/w*");
                Touch(repo.Info.WorkingDirectory, gitIgnore, sb.ToString());

                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus("bin/look-ma.txt"));
                Assert.Equal(FileStatus.NewInWorkdir, repo.RetrieveStatus("bin/what-about-me.txt"));

                newStatus = repo.RetrieveStatus();

                Assert.Equal(new[] { "bin" + dirSep + "look-ma.txt" }, newStatus.Ignored.Select(s => s.FilePath));
                Assert.True(newStatus.Untracked.Select(s => s.FilePath).Contains("bin" + dirSep + "what-about-me.txt"));
            }
        }
Example #38
0
        static void Main(string[] args)
        {
            var argIndex   = 0;
            var directory  = args[argIndex++];
            var extensions = new List <string>();

            while (argIndex < args.Length)
            {
                extensions.Add("." + args[argIndex++].Trim('.'));
            }
            if (!extensions.Any())
            {
                extensions = null;
            }

            var tempFile = Path.GetTempFileName();

            try
            {
                using (var repository = new Repository(directory))
                {
                    foreach (var i in repository.RetrieveStatus().Where(i => i.State == FileStatus.ModifiedInWorkdir))
                    {
                        var file = Path.Combine(directory, i.FilePath);
                        if (extensions?.Any(j => file.EndsWith(j, StringComparison.OrdinalIgnoreCase)) ?? true)
                        {
                            using (var reader = File.OpenText(file))
                                using (var writer = File.CreateText(tempFile))
                                {
                                    writer.NewLine = "\n";
                                    for (string line; (line = reader.ReadLine()) != null;)
                                    {
                                        writer.WriteLine(line);
                                    }
                                }
                            if (new FileInfo(file).Length != new FileInfo(tempFile).Length)
                            {
                                File.Copy(tempFile, file, true);
                                Console.WriteLine(i.FilePath);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
Example #39
0
        public void CheckoutRetainsUnstagedChanges()
        {
            string repoPath = InitNewRepository();

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

                // Generate an unstaged change.
                string fullPathFileA = Touch(repo.Info.WorkingDirectory, originalFilePath, alternateFileContent);

                // Verify that there is a modified entry.
                Assert.Equal(1, repo.RetrieveStatus().Modified.Count());
                Assert.Equal(FileStatus.ModifiedInWorkdir, repo.RetrieveStatus(fullPathFileA));

                repo.Checkout(otherBranchName);

                // Verify modified entry still exists.
                Assert.Equal(1, repo.RetrieveStatus().Modified.Count());
                Assert.Equal(FileStatus.ModifiedInWorkdir, repo.RetrieveStatus(fullPathFileA));
            }
        }
Example #40
0
        private static void InvalidMoveUseCases(string sourcePath, FileStatus sourceStatus, IEnumerable <string> destPaths)
        {
            using (var repo = new Repository(StandardTestRepoPath))
            {
                Assert.Equal(sourceStatus, repo.RetrieveStatus(sourcePath));

                foreach (var destPath in destPaths)
                {
                    string path = destPath;
                    Assert.Throws <LibGit2SharpException>(() => repo.Move(sourcePath, path));
                }
            }
        }
Example #41
0
        public void CanStageConflictedIgnoredFiles(string filename, FileStatus expected)
        {
            var path = SandboxMergedTestRepo();

            using (var repo = new Repository(path))
            {
                File.WriteAllText(Path.Combine(repo.Info.WorkingDirectory, ".gitignore"),
                                  String.Format("{0}\n", filename));

                repo.Stage(filename);
                Assert.Equal(expected, repo.RetrieveStatus(filename));
            }
        }
Example #42
0
        public void CanStageTheRemovalOfAStagedFile()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                int          count    = repo.Index.Count;
                const string filename = "new_tracked_file.txt";
                Assert.NotNull(repo.Index[filename]);

                Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(filename));

                File.Delete(Path.Combine(repo.Info.WorkingDirectory, filename));
                Assert.Equal(FileStatus.NewInIndex | FileStatus.DeletedFromWorkdir, repo.RetrieveStatus(filename));

                repo.Stage(filename);
                Assert.Null(repo.Index[filename]);

                Assert.Equal(count - 1, repo.Index.Count);
                Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus(filename));
            }
        }
Example #43
0
        /// <summary>
        /// Utilise la commande Git push
        /// Avant de faire le push cette méthode réalise un pull et un commit
        /// </summary>
        public void pushContent()
        {
            if (_gitRepoIsOk)
            {
                try
                {
                    RepositoryStatus repoStatus = _repository.RetrieveStatus();

                    pullContent();

                    if (repoStatus.IsDirty)
                    {
                        LibGit2Sharp.Commands.Stage(_repository, "*");
                        Commit commited = _repository.Commit("VSObserver coloring files modification !", _signature, _signature);
                    }

                    PushOptions pushOptions = new PushOptions()
                    {
                        OnPushStatusError      = OnPushStatusError,
                        OnPushTransferProgress = (current, total, bytes) =>
                        {
                            Console.WriteLine(string.Format("Transfer Progress {0} out of {1}, Bytes {2}", current, total, bytes));
                            return(true);
                        }
                    };
                    pushOptions.CredentialsProvider = (url, user, cred) => new UsernamePasswordCredentials {
                        Username = _login, Password = _password
                    };

                    Remote remote      = _network.Remotes["origin"];
                    var    pushRefSpec = _repository.Branches["master"].CanonicalName;
                    _network.Push(remote, pushRefSpec, pushOptions);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error GITSYNC : \n" + e.ToString());
                }
            }
        }
        /// <summary>
        /// Discards all local changes for the logged in user and the local repository is updated with latest remote commit (origin/master)
        /// </summary>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="repository">The name of the repository</param>
        public void ResetCommit(string owner, string repository)
        {
            string localServiceRepoFolder = _settings.GetServicePath(owner, repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext));

            using (Repository repo = new Repository(localServiceRepoFolder))
            {
                if (repo.RetrieveStatus().IsDirty)
                {
                    repo.Reset(ResetMode.Hard, "origin/master");
                    repo.RemoveUntrackedFiles();
                }
            }
        }
Example #45
0
        public void IgnoredFilesAreOnlyStagedIfTheyreInTheRepo(string filename, FileStatus expected)
        {
            var path = SandboxStandardTestRepoGitDir();

            using (var repo = new Repository(path))
            {
                File.WriteAllText(Path.Combine(repo.Info.WorkingDirectory, ".gitignore"),
                                  String.Format("{0}\n", filename));

                repo.Stage(filename);
                Assert.Equal(expected, repo.RetrieveStatus(filename));
            }
        }
Example #46
0
        public void CanCreateABlobFromAFileInTheWorkingDirectory()
        {
            string path = InitNewRepository();

            using (var repo = new Repository(path))
            {
                Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus("hello.txt"));

                File.AppendAllText(Path.Combine(repo.Info.WorkingDirectory, "hello.txt"), "I'm a new file\n");

                Blob blob = repo.ObjectDatabase.CreateBlob("hello.txt");
                Assert.NotNull(blob);
                Assert.Equal("dc53d4c6b8684c21b0b57db29da4a2afea011565", blob.Sha);

                /* The file is unknown from the Index nor the Head ... */
                Assert.Equal(FileStatus.NewInWorkdir, repo.RetrieveStatus("hello.txt"));

                /* ...however, it's indeed stored in the repository. */
                var fetchedBlob = repo.Lookup <Blob>(blob.Id);
                Assert.Equal(blob, fetchedBlob);
            }
        }
Example #47
0
        public bool Status()
        {
            using (Repository repo = new Repository(_localPath))
            {
                var state = repo.RetrieveStatus(new StatusOptions());
                //foreach (var item in repo.RetrieveStatus(new StatusOptions()))
                //{
                //    var state = item.State;
                //}
            }

            return(true);
        }
Example #48
0
        public void CanExcludeStatusOfFilesInSubmodule()
        {
            var path = SandboxSubmoduleTestRepo();
            using (var repo = new Repository(path))
            {
                string[] expected = new string[] {
                    ".gitmodules",
                };

                RepositoryStatus status = repo.RetrieveStatus(new StatusOptions() { ExcludeSubmodules = true });
                Assert.Equal(expected, status.Modified.Select(x => x.FilePath).ToArray());
            }
        }
Example #49
0
        public void AddingAnEntryToTheIndexFromAUnknwonFileInTheWorkdirThrows()
        {
            var path = SandboxStandardTestRepoGitDir();

            using (var repo = new Repository(path))
            {
                const string filePath = "i_dont_exist.txt";
                var          before   = repo.RetrieveStatus(filePath);
                Assert.Equal(FileStatus.Nonexistent, before);

                Assert.Throws <NotFoundException>(() => repo.Index.Add(filePath));
            }
        }
Example #50
0
        public void CanStageAndUnstageAnIgnoredFile()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                Touch(repo.Info.WorkingDirectory, ".gitignore", "*.ign" + Environment.NewLine);

                const string relativePath = "Champa.ign";
                Touch(repo.Info.WorkingDirectory, relativePath, "On stage!" + Environment.NewLine);

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

                Commands.Stage(repo, relativePath, new StageOptions {
                    IncludeIgnored = true
                });
                Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(relativePath));

                Commands.Unstage(repo, relativePath);
                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus(relativePath));
            }
        }
        public void CanExcludeStatusOfFilesInSubmodule()
        {
            var path = SandboxSubmoduleTestRepo();
            using (var repo = new Repository(path))
            {
                string[] expected = new string[] {
                    ".gitmodules",
                };

                RepositoryStatus status = repo.RetrieveStatus(new StatusOptions() { ExcludeSubmodules = true });
                Assert.Equal(expected, status.Modified.Select(x => x.FilePath).ToArray());
            }
        }
Example #52
0
        public static FileStatus GetGitFileType(string filePath)
        {
            if (!filePath.Contains(_repositoryPath) ||
                filePath.Equals(_repositoryPath) ||
                filePath.Contains(".git"))
            {
                return(FileStatus.Nonexistent);
            }

            string newPath = filePath.Replace(_repositoryPath + "\\", "");

            return(Repository.RetrieveStatus(filePath));
        }
Example #53
0
 private void StageChanges(Repository repo)
 {
     try
     {
         var status    = repo.RetrieveStatus();
         var filePaths = status.Modified.Select(mods => mods.FilePath).ToList();
         filePaths.ForEach(filePath => { repo.Index.Add(filePath); repo.Index.Write(); });
     }
     catch (Exception ex)
     {
         Console.WriteLine("Exception:RepoActions:StageChanges " + ex.Message);
     }
 }
        public void CanLimitStatusToIndexOnly(StatusShowOption show, FileStatus expected)
        {
            var clone = SandboxStandardTestRepo();

            using (var repo = new Repository(clone))
            {
                Touch(repo.Info.WorkingDirectory, "file.txt", "content");
                Commands.Stage(repo, "file.txt");

                RepositoryStatus status = repo.RetrieveStatus(new StatusOptions() { Show = show });
                Assert.Equal(expected, status["file.txt"].State);
            }
        }
Example #55
0
        public CheckoutBranch(Repository repo, Branch branch)
        {
            this.repo = repo;
            if (repo.RetrieveStatus(new StatusOptions {
                IncludeIgnored = false
            }).Any())
            {
                throw new Exception("Repository must have no changes.");
            }

            oldBranch = repo.Head;
            Commands.Checkout(repo, branch);
        }
Example #56
0
        public void RetrievingTheStatusOfAFilePathHonorsTheIgnoreCaseConfigurationSetting(
            bool shouldIgnoreCase,
            FileStatus expectedLowercaseFileStatus,
            FileStatus expectedUppercaseFileStatus
            )
        {
            string       lowercasePath;
            const string lowercaseFileName = "plop";

            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                repo.Config.Set("core.ignorecase", shouldIgnoreCase);

                lowercasePath = Touch(repo.Info.WorkingDirectory, lowercaseFileName);

                Commands.Stage(repo, lowercaseFileName);
                repo.Commit("initial", Constants.Signature, Constants.Signature);
            }

            using (var repo = new Repository(repoPath))
            {
                const string uppercaseFileName = "PLOP";

                string uppercasePath = Path.Combine(repo.Info.WorkingDirectory, uppercaseFileName);

                //Workaround for problem with .NET Core 1.x on macOS where going directly from lowercasePath to uppercasePath fails
                //https://github.com/dotnet/corefx/issues/18521
                File.Move(lowercasePath, "__tmp__");
                File.Move("__tmp__", uppercasePath);

                Assert.Equal(expectedLowercaseFileStatus, repo.RetrieveStatus(lowercaseFileName));
                Assert.Equal(expectedUppercaseFileStatus, repo.RetrieveStatus(uppercaseFileName));

                AssertStatus(shouldIgnoreCase, expectedLowercaseFileStatus, repo, uppercasePath.ToLowerInvariant());
                AssertStatus(shouldIgnoreCase, expectedUppercaseFileStatus, repo, uppercasePath.ToUpperInvariant());
            }
        }
Example #57
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.NewInWorkdir, repo.RetrieveStatus(fullPathFileB));

                Commands.Checkout(repo, otherBranchName);

                // Verify untracked entry still exists.
                Assert.Equal(1, repo.RetrieveStatus().Untracked.Count());
                Assert.Equal(FileStatus.NewInWorkdir, repo.RetrieveStatus(fullPathFileB));
            }
        }
        public Task InitializeAsync()
        {
            return(Task.Run(async() =>
            {
                _repo = new Repository(new DirectoryInfo(BasePath).Parent.Parent.FullName.ToString(), new RepositoryOptions());

                var settings = GitHelper.GetGitSettings();
                var options = new FetchOptions
                {
                    CredentialsProvider = new CredentialsHandler((url, usernameFromUrl, types) =>
                                                                 new UsernamePasswordCredentials()
                    {
                        Username = settings.Username,
                        Password = RegistrySettings.DecryptData(settings.Password)
                    })
                };
                if (_repo.RetrieveStatus().IsDirty)
                {
                    throw new Exception("Dirty repo: " + FullName);
                }



                var minimum = new System.Version(2, 50, 0, 0);
                if (RemoteProject == null || RemoteProject.Version == null)
                {
                    SuggestedVersion = minimum;
                }
                else
                {
                    var v = System.Version.Parse(RemoteProject.Version);
                    if (v < minimum)
                    {
                        SuggestedVersion = minimum;
                    }
                    else
                    {
                        SuggestedVersion = new System.Version(v.Major, v.Minor, v.Build, v.Revision + 1);
                    }
                }



                await GetDependenciesAsync();

                Translations = await TranslatorParser.GetTranslations(Name, Path.GetDirectoryName(CsProjPath));

                CanBeUpdated = (ProjectType == ProjectType.Module || Name == "Panacea") &&
                               (HasDifferentHash || HasDifferentTranslations);
            }));
        }
Example #59
0
        public void CheckoutCurrentReference()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path, new RepositoryOptions {
                Identity = Constants.Identity
            }))
            {
                Branch master = repo.Branches["master"];
                Assert.True(master.IsCurrentRepositoryHead);

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

                var reflogEntriesCount = repo.Refs.Log(repo.Refs.Head).Count();

                // Checkout branch
                repo.Checkout(master);

                Assert.Equal(reflogEntriesCount, repo.Refs.Log(repo.Refs.Head).Count());

                var before = DateTimeOffset.Now.TruncateMilliseconds();

                // Checkout in detached mode
                repo.Checkout(master.Tip.Sha);

                Assert.True(repo.Info.IsHeadDetached);
                AssertRefLogEntry(repo, "HEAD",
                                  string.Format("checkout: moving from master to {0}", master.Tip.Sha),
                                  master.Tip.Id, master.Tip.Id, Constants.Identity, before);

                // Checkout detached "HEAD" => nothing should happen
                reflogEntriesCount = repo.Refs.Log(repo.Refs.Head).Count();

                repo.Checkout(repo.Head);

                Assert.Equal(reflogEntriesCount, repo.Refs.Log(repo.Refs.Head).Count());

                // Checkout attached "HEAD" => nothing should happen
                repo.Checkout("master");
                reflogEntriesCount = repo.Refs.Log(repo.Refs.Head).Count();

                repo.Checkout(repo.Head);

                Assert.Equal(reflogEntriesCount, repo.Refs.Log(repo.Refs.Head).Count());

                repo.Checkout("HEAD");

                Assert.Equal(reflogEntriesCount, repo.Refs.Log(repo.Refs.Head).Count());
            }
        }
Example #60
0
        public void CanRenameAFile()
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                Assert.Equal(0, repo.Index.Count);

                const string oldName = "polite.txt";

                Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus(oldName));

                Touch(repo.Info.WorkingDirectory, oldName, "hello test file\n");
                Assert.Equal(FileStatus.NewInWorkdir, repo.RetrieveStatus(oldName));

                repo.Stage(oldName);
                Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(oldName));

                // Generated through
                // $ echo "hello test file" | git hash-object --stdin
                const string expectedHash = "88df547706c30fa19f02f43cb2396e8129acfd9b";
                Assert.Equal(expectedHash, repo.Index[oldName].Id.Sha);

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

                Signature who = Constants.Signature;
                repo.Commit("Initial commit", who, who);

                Assert.Equal(FileStatus.Unaltered, repo.RetrieveStatus(oldName));

                const string newName = "being.frakking.polite.txt";

                repo.Move(oldName, newName);
                Assert.Equal(FileStatus.DeletedFromIndex, repo.RetrieveStatus(oldName));
                Assert.Equal(FileStatus.NewInIndex, repo.RetrieveStatus(newName));

                Assert.Equal(1, repo.Index.Count);
                Assert.Equal(expectedHash, repo.Index[newName].Id.Sha);

                who = who.TimeShift(TimeSpan.FromMinutes(5));
                Commit commit = repo.Commit("Fix file name", who, who);

                Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus(oldName));
                Assert.Equal(FileStatus.Unaltered, repo.RetrieveStatus(newName));

                Assert.Equal(expectedHash, commit.Tree[newName].Target.Id.Sha);
            }
        }