Example #1
0
 public void CannotCleanABareRepository()
 {
     using (var repo = new Repository(BareTestRepoPath))
     {
         Assert.Throws<BareRepositoryException>(() => repo.RemoveUntrackedFiles());
     }
 }
Example #2
0
 public void CannotCleanABareRepository()
 {
     string path = SandboxBareTestRepo();
     using (var repo = new Repository(path))
     {
         Assert.Throws<BareRepositoryException>(() => repo.RemoveUntrackedFiles());
     }
 }
        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.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 #4
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);
                }
            }
        }
        public void CanNotCommitAnEmptyCommit()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                Assert.Throws <EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature));
            }
        }
        /// <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 #7
0
        private static void UpdateRepo(Repository repository, string repo, string baseFolder, string folder,
                                       bool hardPull = false)
        {
            if (hardPull)
            {
                repository.Reset(ResetMode.Hard);
                repository.RemoveUntrackedFiles();
            }

            var branch = repository.Branches["master"];

            if (branch == null)
            {
                // repository return null object when branch not exists
                Console.WriteLine($"Master not found for {repo}");
                return;
            }

            var currentBranch = Commands.Checkout(repository, branch);
            var options       = new PullOptions
            {
                FetchOptions = new FetchOptions()
                {
                    TagFetchMode       = TagFetchMode.All,
                    Prune              = true,
                    OnTransferProgress = OnTransferProgress
                }
            };

            if (configuration.AuthRequired)
            {
                options.FetchOptions.CredentialsProvider = new CredentialsHandler(
                    (url, usernameFromUrl, types) =>
                    new UsernamePasswordCredentials()
                {
                    Username = configuration.Username,
                    Password = configuration.PasswordHash
                });
            }

            var uname  = repository.Config.Get <string>("user.name");
            var uemail = repository.Config.Get <string>("user.email");

            if (uname == null || uemail == null)
            {
                Console.WriteLine($"Username and email not defined for repository {repo}. Please update repository settings");
                return;
            }
            Commands.Pull(repository, new Signature(uname.Value, uemail.Value, DateTimeOffset.UtcNow), options);
        }
Example #8
0
        public void Reset(IFolder repositoryFolder, string headTipIdSha, IErrorsAndInfos errorsAndInfos)
        {
            using var repo = new Repository(repositoryFolder.FullName, new RepositoryOptions());
            var commit = repo.Head.Commits.FirstOrDefault(c => c.Sha == headTipIdSha);

            if (commit == null)
            {
                errorsAndInfos.Errors.Add(string.Format(Properties.Resources.CommitNotFound, headTipIdSha));
            }
            else
            {
                repo.Reset(ResetMode.Hard, commit);
                repo.RemoveUntrackedFiles();
            }
        }
        public void UnalteredFilesDontMarkIndexAsDirty()
        {
            var path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                RepositoryStatus status = repo.RetrieveStatus(new StatusOptions() { IncludeUnaltered = true });

                Assert.False(status.IsDirty);
                Assert.Equal(9, status.Count());
            }
        }
        public void CanCommitAnEmptyCommitWhenForced()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
                            new CommitOptions {
                    AllowEmptyCommit = true
                });
            }
        }
Example #11
0
        public void CanCleanWorkingDirectory()
        {
            TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo(StandardTestRepoWorkingDirPath);
            using (var repo = new Repository(path.RepositoryPath))
            {
                // Verify that there are the expected number of entries and untracked files
                Assert.Equal(6, repo.Index.RetrieveStatus().Count());
                Assert.Equal(1, repo.Index.RetrieveStatus().Untracked.Count());

                repo.RemoveUntrackedFiles();

                // Verify that there are the expected number of entries and 0 untracked files
                Assert.Equal(5, repo.Index.RetrieveStatus().Count());
                Assert.Equal(0, repo.Index.RetrieveStatus().Untracked.Count());
            }
        }
Example #12
0
        public void CanCleanWorkingDirectory()
        {
            string path = SandboxStandardTestRepo();
            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 #13
0
        public void CanAmendAnEmptyMergeCommit()
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n");
                Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);

                Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
                    new CommitOptions { AmendPreviousCommit = true });
                AssertCommitHasBeenAmended(repo, amendedCommit, newMergedCommit);
            }
        }
Example #14
0
        public void CanAmendAnEmptyCommitWhenForced()
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                Commit emptyCommit = repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
                    new CommitOptions { AllowEmptyCommit = true });

                Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
                    new CommitOptions { AmendPreviousCommit = true, AllowEmptyCommit = true });
                AssertCommitHasBeenAmended(repo, amendedCommit, emptyCommit);
            }
        }
Example #15
0
        public override Task <string> UpdateAsync(GitUpdateOptions options)
        {
            try
            {
                this.log.LogDebug($"Using repository at '{this.repository.LocalRepositoryPath}'...");
                using (var repository = new Repository(this.repository.LocalRepositoryPath))
                {
                    this.log.LogDebug("Fetching commits from origin...");
                    Commands.Fetch(repository, "origin", new string[0], new FetchOptions {
                        CredentialsProvider = this.CredentialsHandler, Prune = true
                    }, null);
                    var refName = "FETCH_HEAD";
                    if (options.Branch != null)
                    {
                        refName = "origin/" + options.Branch;
                    }
                    else if (options.Ref != null)
                    {
                        refName = options.Ref;
                    }
                    this.log.LogDebug($"Resetting the index and working tree to {refName}...");
                    repository.Reset(ResetMode.Hard, refName);
                    repository.RemoveUntrackedFiles();

                    if (options.RecurseSubmodules)
                    {
                        foreach (var submodule in repository.Submodules)
                        {
                            repository.Submodules.Update(submodule.Name, new SubmoduleUpdateOptions {
                                CredentialsProvider = this.CredentialsHandler, Init = true
                            });
                        }
                    }

                    return(Task.FromResult(repository.Head?.Tip?.Sha));
                }
            }
            catch (Exception ex)
            {
                // gitsharp exceptions are not always serializable
                throw new ExecutionFailureException("Update failed: " + ex.Message);
            }
            finally
            {
                this.EndOperation();
            }
        }
Example #16
0
        public void CanCleanWorkingDirectory()
        {
            TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo(StandardTestRepoWorkingDirPath);

            using (var repo = new Repository(path.RepositoryPath))
            {
                // Verify that there are the expected number of entries and untracked files
                Assert.Equal(6, repo.Index.RetrieveStatus().Count());
                Assert.Equal(1, repo.Index.RetrieveStatus().Untracked.Count());

                repo.RemoveUntrackedFiles();

                // Verify that there are the expected number of entries and 0 untracked files
                Assert.Equal(5, repo.Index.RetrieveStatus().Count());
                Assert.Equal(0, repo.Index.RetrieveStatus().Untracked.Count());
            }
        }
Example #17
0
 internal static void CleanRepository(string repository)
 {
     try
     {
         if (IsValidRepository(repository))
         {
             using (var repo = new Repository(repository))
             {
                 repo.RemoveUntrackedFiles();
             }
         }
     }
     catch (Exception e)
     {
         Log.Warn(e);
     }
 }
Example #18
0
        public void CanCleanWorkingDirectory()
        {
            string path = SandboxStandardTestRepo();

            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 #19
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);
            }
        }
        public void CanAmendAnEmptyMergeCommit()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n");
                Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);

                Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
                                                   new CommitOptions {
                    AmendPreviousCommit = true
                });
                AssertCommitHasBeenAmended(repo, amendedCommit, newMergedCommit);
            }
        }
        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 bool Pull(string directory)
        {
            try
            {
                using (var repo = new Repository(directory))
                {
                    Utility.Log(LogStatus.Info, "Pull", directory, Logs.MainLog);

                    repo.Reset(ResetMode.Hard);
                    repo.RemoveUntrackedFiles();
                    repo.Network.Pull(
                        new Signature(Config.Instance.Username, $"{Config.Instance.Username}@joduska.me", DateTimeOffset.Now),
                        new PullOptions
                    {
                        MergeOptions =
                            new MergeOptions
                        {
                            FastForwardStrategy  = FastForwardStrategy.Default,
                            FileConflictStrategy = CheckoutFileConflictStrategy.Theirs,
                            MergeFileFavor       = MergeFileFavor.Theirs,
                            CommitOnSuccess      = true
                        }
                    });

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

                    if (repo.Info.IsHeadDetached)
                    {
                        Utility.Log(LogStatus.Error, "Pull", "Update+Detached", Logs.MainLog);
                    }
                }

                return(true);
            }
            catch (Exception e)
            {
                Utility.Log(LogStatus.Error, "Pull", e.Message, Logs.MainLog);
                return(false);
            }
        }
Example #23
0
        public void CanNotAmendAnEmptyCommit()
        {
            string path = CloneStandardTestRepo();

            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
                            new CommitOptions {
                    AllowEmptyCommit = true
                });

                Assert.Throws <EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
                                                                       new CommitOptions {
                    AmendPreviousCommit = true
                }));
            }
        }
        public void CanCommitAnEmptyCommitWhenMerging()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n");

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

                Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);

                Assert.Equal(2, newMergedCommit.Parents.Count());
                Assert.Equal(newMergedCommit.Parents.First().Sha, "32eab9cb1f450b5fe7ab663462b77d7f4b703344");
                Assert.Equal(newMergedCommit.Parents.Skip(1).First().Sha, "f705abffe7015f2beacf2abe7a36583ebee3487e");
            }
        }
        public void CanAmendAnEmptyCommitWhenForced()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                Commit emptyCommit = repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
                                                 new CommitOptions {
                    AllowEmptyCommit = true
                });

                Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature,
                                                   new CommitOptions {
                    AmendPreviousCommit = true, AllowEmptyCommit = true
                });
                AssertCommitHasBeenAmended(repo, amendedCommit, emptyCommit);
            }
        }
Example #26
0
        public void DetachedHeadIsNotATrackingBranch()
        {
            string path = CloneStandardTestRepo();

            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

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

                Assert.False(repo.Head.IsTracking);
                Assert.Null(repo.Head.TrackedBranch);

                Assert.NotNull(repo.Head.TrackingDetails);
                Assert.Null(repo.Head.TrackingDetails.AheadBy);
                Assert.Null(repo.Head.TrackingDetails.BehindBy);
                Assert.Null(repo.Head.TrackingDetails.CommonAncestor);
            }
        }
Example #27
0
        public void DetachedHeadIsNotATrackingBranch()
        {
            TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo(StandardTestRepoWorkingDirPath);

            using (var repo = new Repository(path.DirectoryPath))
            {
                repo.Reset(ResetOptions.Hard);
                repo.RemoveUntrackedFiles();

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

                Assert.False(repo.Head.IsTracking);
                Assert.Null(repo.Head.TrackedBranch);

                Assert.NotNull(repo.Head.TrackingDetails);
                Assert.Null(repo.Head.TrackingDetails.AheadBy);
                Assert.Null(repo.Head.TrackingDetails.BehindBy);
                Assert.Null(repo.Head.TrackingDetails.CommonAncestor);
            }
        }
Example #28
0
        /// <summary>
        /// Fetches changes and hard resets the specified repository to the latest commit of a specified branch. If no
        /// repository is found, it will be cloned before.
        /// </summary>
        /// <param name="sourceUrl">The url of the repository.</param>
        /// <param name="path">The directory path where to find/clone the repository.</param>
        /// <param name="branch">The branch use on the repository.</param>
        /// <returns>The synced repository on the latest commit of the specified branch.</returns>
        public static Repository GetSyncRepository(string sourceUrl, string path, string branch = "master")
        {
            // Clone this repository to the specified branch if it doesn't exist
            bool clone = !Directory.Exists(path);

            if (clone)
            {
                Console.WriteLine($"Clonning {sourceUrl} to {path}");

                var options = new CloneOptions()
                {
                    BranchName = branch
                };
                Repository.Clone(sourceUrl, path, options);
            }

            var repository = new Repository(path);

            // Otherwise fetch changes and checkout to the specified branch
            if (!clone)
            {
                Console.WriteLine($"Hard reset {path} to HEAD");
                repository.Reset(ResetMode.Hard);
                repository.RemoveUntrackedFiles();

                Console.WriteLine($"Fetching changes from origin to {path}");
                var remote = repository.Network.Remotes["origin"];
                Commands.Fetch(repository, remote.Name, new string[0], null, null); // WTF is this API libgit2sharp?

                Console.WriteLine($"Checking out {path} to {branch} branch");
                var remoteBranch = $"origin/{branch}";
                Commands.Checkout(repository, remoteBranch);
            }

            Console.WriteLine();

            return(repository);
        }
Example #29
0
        /// <summary>
        /// Generate the documentation and the associated xref map of a specified repository with DocFx.
        /// </summary>
        /// <param name="repository">The repository to generate docs from.</param>
        /// <param name="commit">The commit of the <param name="repository"> to generate the docs from.</param>
        /// <param name="generatedDocsPath">
        /// The directory where the documentation will be generated (`output` property of `docfx build`, by default
        /// `_site`).
        /// </param>
        private static void GenerateXrefMap(Repository repository, string commit,
                                            string generatedDocsPath = GeneratedDocsPath)
        {
            // Hard reset the repository
            Console.WriteLine($"Hard reset {repository.Info.WorkingDirectory} to {commit}");
            repository.Reset(ResetMode.Hard, commit);
            repository.RemoveUntrackedFiles();

            // Clear DocFx's temp files and previous generated site
            var pathsToClear = new string[] { DocFxTempPath, generatedDocsPath };

            foreach (var path in pathsToClear)
            {
                if (Directory.Exists(path))
                {
                    Directory.Delete(path, recursive: true);
                }
            }

            // Generate site and xref map
            var output = Utils.RunCommand($"docfx");

            Console.WriteLine(output);
        }
Example #30
0
        /// <summary>
        /// Generate the documentation and the associated xref map of a specified repository with DocFx.
        /// </summary>
        /// <param name="repository">The repository to generate docs from.</param>
        /// <param name="commit">The commit of the <param name="repository"> to generate the docs from.</param>
        /// <param name="generatedDocsPath">
        /// The directory where the documentation will be generated (`output` property of `docfx build`, by default
        /// `_site`).
        /// </param>
        private static void GenerateXrefMap(Repository repository, string commit,
                                            string generatedDocsPath = GeneratedDocsPath)
        {
            // Hard reset the repository
            Console.WriteLine($"Hard reset '{repository.Info.WorkingDirectory}' to '{commit}'");
            repository.Reset(ResetMode.Hard, commit);

            try
            {
                repository.RemoveUntrackedFiles();
            }
            catch (LibGit2Sharp.NotFoundException) { }

            // Clear DocFx's temp files and previous generated site
            var pathsToClear = new string[] { DocFxMetadataPath, generatedDocsPath };

            foreach (var path in pathsToClear)
            {
                if (Directory.Exists(path))
                {
                    Directory.Delete(path, recursive: true);
                }
            }

            // Fix the csproj
            Console.WriteLine($"Fixing the csproj of '{commit}'");
            foreach (string csprojFilePath in UnityCsprojPaths)
            {
                string fullFilePath = Path.Combine(UnityRepoPath, csprojFilePath);
                FixCsprojForDocFx(fullFilePath);
            }

            // Generate site and xref map
            Console.WriteLine($"Running DocFX on '{commit}'");
            Utils.RunCommand("docfx", output => Console.WriteLine(output), error => Console.WriteLine(error));
        }
Example #31
0
        /// <summary>
        /// Reset and clean current working directory. This will ensure that the current
        /// working directory matches the current Head commit.
        /// </summary>
        /// <param name="repo">Repository whose current working directory should be operated on.</param>
        private void ResetAndCleanWorkingDirectory(Repository repo)
        {
            // Reset the index and the working tree.
            repo.Reset(ResetOptions.Hard);

            // Clean the working directory.
            repo.RemoveUntrackedFiles();
        }
Example #32
0
        /// <summary>
        /// Method updates repository
        /// </summary>
        public void UpdateRepository()
        {
            //// https://github.com/libgit2/libgit2sharp/blob/2f8ad262b7613e9e68aefd4f55956bf24b05d042/LibGit2Sharp.Tests/MergeFixture.cs
            //// https://github.com/libgit2/libgit2sharp/blob/2f8ad262b7613e9e68aefd4f55956bf24b05d042/LibGit2Sharp.Tests/FetchFixture.cs#L129-L153

            string remoteName = this.remoteName, branchName = this.branchName;
            bool   cloneAlways = this.cloneAlways;
            string url         = this.repoUrl;

            Credentials crednt(string curl, string usernameFromUrl, SupportedCredentialTypes types) => this.credentials;

            string workingDirectory = this.localFolder.FullName;

            if (Directory.Exists(workingDirectory))
            {
                if (!cloneAlways)
                {
                    try
                    {
                        using (var repo = new Repository(workingDirectory))
                        {
                            repo.Reset(ResetMode.Hard);
                            repo.RemoveUntrackedFiles();

                            var remote = repo.Network.Remotes.FirstOrDefault(r => r.Name == remoteName);

                            string pushRefs = "refs/heads/testsyed";
                            Branch branchs  = null;
                            foreach (var branch in repo.Branches)
                            {
                                if (branch.FriendlyName.ToLower().Equals(branchName.ToLower()))
                                {
                                    branchs  = branch;
                                    pushRefs = branch.Reference.CanonicalName;
                                }
                            }

                            var fetchOptions = new FetchOptions()
                            {
                                CredentialsProvider = crednt
                            };
                            repo.Network.Fetch(remote.Name, new string[] { pushRefs }, fetchOptions);

                            PullOptions pullOptions = new PullOptions()
                            {
                                MergeOptions = new LibGit2Sharp.MergeOptions()
                                {
                                    FastForwardStrategy = FastForwardStrategy.Default,
                                },
                                FetchOptions = fetchOptions
                            };

                            MergeResult mergeResult = Commands.Pull(
                                repo,
                                new Signature(this.authorName, this.authorEmail, DateTimeOffset.Now),
                                pullOptions);
                        }

                        return;
                    }
                    catch (LibGit2Sharp.RepositoryNotFoundException r)
                    {
                        Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine(" " + r.Message + "<br>");
                        Console.WriteLine(r.Message);
                    }
                }
                else
                {
                    try
                    {
                        DirectoryInfo attachments_AR = new DirectoryInfo(workingDirectory);
                        this.EmptyFolder(attachments_AR);
                    }
                    catch (Exception ex)
                    {
                        Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine(" " + ex.Message + "<br>");
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            else
            {
                Directory.CreateDirectory(workingDirectory);
            }

            var cloneOptions = new CloneOptions
            {
                CredentialsProvider = crednt
            };

            cloneOptions.BranchName = branchName;

            try
            {
                Repository.Clone(url, workingDirectory, cloneOptions);
                this.cloneAlways = false;
            }
            catch
            {
                Singleton.SolutionFileInfoInstance.WebJobsLog.AppendLine(" One possibility for the exception could be check for branch or incorrect branch" + branchName + "<br>");
                Console.WriteLine("One possibility for the exception could be check for branch or incorrect branch" + branchName);
                throw;
            }
        }
Example #33
0
        public void UnalteredFilesDontMarkIndexAsDirty()
        {
            var path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                RepositoryStatus status = repo.RetrieveStatus(new StatusOptions() { IncludeUnaltered = true });

                Assert.Equal(false, status.IsDirty);
                Assert.Equal(9, status.Count());
            }
        }
Example #34
0
        public void CanNotAmendAnEmptyCommit()
        {
            string path = SandboxStandardTestRepo();
            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
                    new CommitOptions { AllowEmptyCommit = true });

                Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
                    new CommitOptions { AmendPreviousCommit = true }));
            }
        }
Example #35
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 #36
0
        public void CanNotCommitAnEmptyCommit()
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature));
            }
        }
Example #37
0
        public void CanCommitAnEmptyCommitWhenMerging()
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n");

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

                Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature);

                Assert.Equal(2, newMergedCommit.Parents.Count());
                Assert.Equal(newMergedCommit.Parents.First().Sha, "32eab9cb1f450b5fe7ab663462b77d7f4b703344");
                Assert.Equal(newMergedCommit.Parents.Skip(1).First().Sha, "f705abffe7015f2beacf2abe7a36583ebee3487e");
            }
        }
Example #38
0
 public static void RemoveUntrackedFiles()
 {
     Console.WriteLine("Removing untracked files");
     CurrentRepo.RemoveUntrackedFiles();
 }
Example #39
0
        public void CanCommitAnEmptyCommitWhenForced()
        {
            string path = CloneStandardTestRepo();
            using (var repo = new Repository(path))
            {
                repo.Reset(ResetMode.Hard);
                repo.RemoveUntrackedFiles();

                repo.Commit("Empty commit!", Constants.Signature, Constants.Signature,
                    new CommitOptions { AllowEmptyCommit = true });
            }
        }