public BranchPicker(GitRepository repository)
 {
     InitializeComponent();
     this.repository = repository;
     _branches = new ObservableCollection<GitBranchInfo>();
     
     comboBranches.ItemsSource = _branches;
     //this.list = list;
 }
Exemplo n.º 2
0
        public string FindNoCommitedFiles()
        {
            var result = "";
            var breakLine = "";

            foreach (var directory in DirectoriesPaths())
            {
                GitRepository repository = new GitRepository(directory.Value);
                result += breakLine + directory.Key + " : " + repository.ModifiedFiles().ToString();
                breakLine = ";";
            }

            return result;
        }
Exemplo n.º 3
0
 public static void ShowStashManager(GitRepository repo)
 {
     using (var dlg = new StashManagerDialog(repo))
         MessageService.ShowCustomDialog(dlg);
 }
Exemplo n.º 4
0
        public void MinimalGitData()
        {
            var repoDir = Temp.CreateDirectory();

            var gitDir = repoDir.CreateDirectory(".git");

            gitDir.CreateFile("HEAD").WriteAllText("1111111111111111111111111111111111111111");
            gitDir.CreateFile("config").WriteAllText(@"[remote ""origin""]url=""http://github.com/test-org/test-repo""");
            gitDir.CreateDirectory("objects");
            gitDir.CreateDirectory("refs");
            repoDir.CreateFile(".gitignore").WriteAllText("ignore_this_*");

            // submodule:
            var gitModules = repoDir.CreateFile(".gitmodules").WriteAllText(@"
[submodule ""my submodule""]
  path = sub
  url = https://github.com/test-org/test-sub
");

            var subDir = repoDir.CreateDirectory("sub");

            subDir.CreateFile(".git").WriteAllText("gitdir: ../.git/modules/sub");
            subDir.CreateFile(".gitignore").WriteAllText("ignore_in_submodule_*");

            var gitDirSub = gitDir.CreateDirectory("modules").CreateDirectory("sub");

            gitDirSub.CreateFile("HEAD").WriteAllText("2222222222222222222222222222222222222222");
            gitDirSub.CreateDirectory("objects");
            gitDirSub.CreateDirectory("refs");

            var repository = GitRepository.OpenRepository(repoDir.Path, GitEnvironment.Empty) !;

            Assert.Equal("http://github.com/test-org/test-repo", GitOperations.GetRepositoryUrl(repository, remoteName: null));
            Assert.Equal("1111111111111111111111111111111111111111", repository.GetHeadCommitSha());

            var warnings    = new List <(string, object?[])>();
            var sourceRoots = GitOperations.GetSourceRoots(repository, remoteName: null, (message, args) => warnings.Add((message, args)));

            AssertEx.Equal(new[]
            {
                $@"'{repoDir.Path}{s}' SourceControl='git' RevisionId='1111111111111111111111111111111111111111' ScmRepositoryUrl='http://github.com/test-org/test-repo'",
                $@"'{repoDir.Path}{s}sub{s}' SourceControl='git' RevisionId='2222222222222222222222222222222222222222' NestedRoot='sub/' ContainingRoot='{repoDir.Path}{s}' ScmRepositoryUrl='https://github.com/test-org/test-sub'",
            }, sourceRoots.Select(TestUtilities.InspectSourceRoot));

            AssertEx.Equal(new string[0], warnings.Select(TestUtilities.InspectDiagnostic));

            var files = new[]
            {
                new MockItem(@"ignore_this_a"),
                new MockItem(@"b"),
                new MockItem(@"ignore_this_c"),
                new MockItem(@"sub\ignore_in_submodule_d"),
            };

            var untrackedFiles = GitOperations.GetUntrackedFiles(repository, files, repoDir.Path);

            AssertEx.Equal(new[]
            {
                "ignore_this_a",
                "ignore_this_c",
                MockItem.AdjustSeparators(@"sub\ignore_in_submodule_d"),
            }, untrackedFiles.Select(item => item.ItemSpec));
        }
Exemplo n.º 5
0
        private static GitPullRequest CreatePullRequestInternal(ClientSampleContext context, GitRepository repo, GitHttpClient gitClient)
        {
            // we need a new branch with changes in order to create a PR
            // first, find the default branch
            string defaultBranchName = WithoutRefsPrefix(repo.DefaultBranch);
            GitRef defaultBranch     = gitClient.GetRefsAsync(repo.Id, filter: defaultBranchName).Result.First();

            // next, craft the branch and commit that we'll push
            GitRefUpdate newBranch = new GitRefUpdate()
            {
                Name        = $"refs/heads/vsts-api-sample/{ChooseRefsafeName()}",
                OldObjectId = defaultBranch.ObjectId,
            };
            string       newFileName = $"{ChooseItemsafeName()}.md";
            GitCommitRef newCommit   = new GitCommitRef()
            {
                Comment = "Add a sample file",
                Changes = new GitChange[]
                {
                    new GitChange()
                    {
                        ChangeType = VersionControlChangeType.Add,
                        Item       = new GitItem()
                        {
                            Path = $"/vsts-api-sample/{newFileName}"
                        },
                        NewContent = new ItemContent()
                        {
                            Content     = "# Thank you for using VSTS!",
                            ContentType = ItemContentType.RawText,
                        },
                    }
                },
            };

            // create the push with the new branch and commit
            GitPush push = gitClient.CreatePushAsync(new GitPush()
            {
                RefUpdates = new GitRefUpdate[] { newBranch },
                Commits    = new GitCommitRef[] { newCommit },
            }, repo.Id).Result;

            // finally, create a PR
            var pr = gitClient.CreatePullRequestAsync(new GitPullRequest()
            {
                SourceRefName = newBranch.Name,
                TargetRefName = repo.DefaultBranch,
                Title         = $"Add {newFileName} (from VSTS REST samples)",
                Description   = "Adding this file from the pull request samples",
            },
                                                      repo.Id).Result;

            return(pr);
        }
        internal override void InternalExecute()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            //////////////////////////////////////////////////
            var sourceGitRepoService = me.Source.Collection.GetService <GitRepositoryService>();
            var sourceGitRepos       = sourceGitRepoService.QueryRepositories(me.Source.Name);
            //////////////////////////////////////////////////
            var targetGitRepoService = me.Target.Collection.GetService <GitRepositoryService>();
            var targetGitRepos       = targetGitRepoService.QueryRepositories(me.Target.Name);

            WorkItemStoreContext targetStore = new WorkItemStoreContext(me.Target, WorkItemStoreFlags.BypassRules);
            TfsQueryContext      tfsqc       = new TfsQueryContext(targetStore);

            tfsqc.AddParameter("TeamProject", me.Target.Name);
            tfsqc.Query = string.Format(@"SELECT [System.Id] FROM WorkItems WHERE  [System.TeamProject] = @TeamProject");
            WorkItemCollection workitems = tfsqc.Execute();

            Trace.WriteLine(string.Format("Update {0} work items?", workitems.Count));
            //////////////////////////////////////////////////
            int  current   = workitems.Count;
            int  count     = 0;
            long elapsedms = 0;
            int  noteFound = 0;

            foreach (WorkItem workitem in workitems)
            {
                Stopwatch witstopwatch = new Stopwatch();
                witstopwatch.Start();
                workitem.Open();
                List <ExternalLink> newEL    = new List <ExternalLink>();
                List <ExternalLink> removeEL = new List <ExternalLink>();
                Trace.WriteLine(string.Format("WI: {0}?", workitem.Id));
                List <string> gitWits = new List <string>
                {
                    "Branch",
                    "Fixed in Commit",
                    "Pull Request"
                };

                foreach (Link l in workitem.Links)
                {
                    if (l is ExternalLink && gitWits.Contains(l.ArtifactLinkType.Name))
                    {
                        ExternalLink el = (ExternalLink)l;
                        //vstfs:///Git/Commit/25f94570-e3e7-4b79-ad19-4b434787fd5a%2f50477259-3058-4dff-ba4c-e8c179ec5327%2f41dd2754058348d72a6417c0615c2543b9b55535
                        string   guidbits     = el.LinkedArtifactUri.Substring(el.LinkedArtifactUri.LastIndexOf('/') + 1);
                        string[] bits         = Regex.Split(guidbits, "%2f", RegexOptions.IgnoreCase);
                        string   oldCommitId  = null;
                        string   oldGitRepoId = bits[1];
                        if (bits.Count() >= 3)
                        {
                            oldCommitId = $"{bits[2]}";
                            for (int i = 2; i < bits.Count(); i++)
                            {
                                oldCommitId += $"%2f{bits[i]}";
                            }
                        }
                        else
                        {
                            oldCommitId = bits[2];
                        }
                        var oldGitRepo =
                            (from g in sourceGitRepos where g.Id.ToString() == oldGitRepoId select g)
                            .SingleOrDefault();

                        if (oldGitRepo != null)
                        {
                            // Find the target git repo
                            GitRepository newGitRepo        = null;
                            var           repoNameToLookFor = !string.IsNullOrEmpty(_config.TargetRepository)
                                ? _config.TargetRepository
                                : oldGitRepo.Name;

                            // Source and Target project names match
                            if (oldGitRepo.ProjectReference.Name == me.Target.Name)
                            {
                                newGitRepo = (from g in targetGitRepos
                                              where
                                              g.Name == repoNameToLookFor &&
                                              g.ProjectReference.Name == oldGitRepo.ProjectReference.Name
                                              select g).SingleOrDefault();
                            }
                            // Source and Target project names do not match
                            else
                            {
                                newGitRepo = (from g in targetGitRepos
                                              where
                                              g.Name == repoNameToLookFor &&
                                              g.ProjectReference.Name != oldGitRepo.ProjectReference.Name
                                              select g).SingleOrDefault();
                            }

                            // Fix commit links if target repo has been found
                            if (newGitRepo != null)
                            {
                                Trace.WriteLine($"Fixing {oldGitRepo.RemoteUrl} to {newGitRepo.RemoteUrl}?");

                                // Create External Link object
                                ExternalLink newLink = null;
                                switch (l.ArtifactLinkType.Name)
                                {
                                case "Branch":
                                    newLink = new ExternalLink(targetStore.Store.RegisteredLinkTypes[ArtifactLinkIds.Branch],
                                                               $"vstfs:///git/ref/{newGitRepo.ProjectReference.Id}%2f{newGitRepo.Id}%2f{oldCommitId}");
                                    break;

                                case "Fixed in Commit":
                                    newLink = new ExternalLink(targetStore.Store.RegisteredLinkTypes[ArtifactLinkIds.Commit],
                                                               $"vstfs:///git/commit/{newGitRepo.ProjectReference.Id}%2f{newGitRepo.Id}%2f{oldCommitId}");
                                    break;

                                case "Pull Request":
                                    newLink = new ExternalLink(targetStore.Store.RegisteredLinkTypes[ArtifactLinkIds.PullRequest],
                                                               $"vstfs:///Git/PullRequestId/{newGitRepo.ProjectReference.Id}%2f{newGitRepo.Id}%2f{oldCommitId}");
                                    break;

                                default:
                                    Trace.WriteLine(String.Format("Skipping unsupported link type {0}", l.ArtifactLinkType.Name));
                                    break;
                                }

                                if (newLink != null)
                                {
                                    var elinks = from Link lq in workitem.Links
                                                 where gitWits.Contains(lq.ArtifactLinkType.Name)
                                                 select(ExternalLink) lq;
                                    var found =
                                        (from Link lq in elinks
                                         where (((ExternalLink)lq).LinkedArtifactUri.ToLower() == newLink.LinkedArtifactUri.ToLower())
                                         select lq).SingleOrDefault();
                                    if (found == null)
                                    {
                                        newEL.Add(newLink);
                                    }
                                    removeEL.Add(el);
                                }
                            }
                            else
                            {
                                Trace.WriteLine($"FAIL: cannot map {oldGitRepo.RemoteUrl} to ???");
                            }
                        }
                        else
                        {
                            Trace.WriteLine($"FAIL could not find source git repo");
                            noteFound++;
                        }
                    }
                }
                // add and remove
                foreach (ExternalLink eln in newEL)
                {
                    try
                    {
                        Trace.WriteLine("Adding " + eln.LinkedArtifactUri, Name);
                        workitem.Links.Add(eln);
                    }
                    catch (Exception)
                    {
                        // eat exception as sometimes TFS thinks this is an attachment
                    }
                }
                foreach (ExternalLink elr in removeEL)
                {
                    if (workitem.Links.Contains(elr))
                    {
                        try
                        {
                            Trace.WriteLine("Removing " + elr.LinkedArtifactUri, Name);
                            workitem.Links.Remove(elr);
                        }
                        catch (Exception)
                        {
                            // eat exception as sometimes TFS thinks this is an attachment
                        }
                    }
                }

                if (workitem.IsDirty)
                {
                    Trace.WriteLine($"Saving {workitem.Id}");
                    workitem.Save();
                }

                witstopwatch.Stop();
                elapsedms = elapsedms + witstopwatch.ElapsedMilliseconds;
                current--;
                count++;
                TimeSpan average   = new TimeSpan(0, 0, 0, 0, (int)(elapsedms / count));
                TimeSpan remaining = new TimeSpan(0, 0, 0, 0, (int)(average.TotalMilliseconds * current));
                Trace.WriteLine(string.Format("Average time of {0} per work item and {1} estimated to completion",
                                              string.Format(@"{0:s\:fff} seconds", average),
                                              string.Format(@"{0:%h} hours {0:%m} minutes {0:s\:fff} seconds", remaining)));
            }
            Trace.WriteLine(string.Format("Did not find old repo for {0} links?", noteFound));
            //////////////////////////////////////////////////
            stopwatch.Stop();
            Console.WriteLine(@"DONE in {0:%h} hours {0:%m} minutes {0:s\:fff} seconds", stopwatch.Elapsed);
        }
Exemplo n.º 7
0
 internal void Refresh(GitRepository tracker, MyToolWindow toolWindow)
 {
     this.toolWindow = toolWindow;
     this.tracker = tracker;
     RefreshPrompt();
 }
Exemplo n.º 8
0
 public static string GetGitHubCompareTagsUrl(this GitRepository repository, string startTag, string endTag)
 {
     Assert.True(repository.IsGitHubRepository());
     return($"https://github.com/{repository.Identifier}/compare/{endTag}...{startTag}");
 }
Exemplo n.º 9
0
 public static string GetGitHubCommitUrl(this GitRepository repository, string commitSha)
 {
     Assert.True(repository.IsGitHubRepository());
     return($"https://github.com/{repository.Identifier}/commit/{commitSha}");
 }
Exemplo n.º 10
0
 public static string GetGitHubCompareCommitsUrl(this GitRepository repository, string startCommitSha, string endCommitSha)
 {
     Assert.True(repository.IsGitHubRepository());
     return($"https://github.com/{repository.Identifier}/compare/{endCommitSha}^...{startCommitSha}");
 }
Exemplo n.º 11
0
 public static string GetGitHubCompareTagToHeadUrl(this GitRepository repository, string tag)
 {
     Assert.True(repository.IsGitHubRepository());
     return($"https://github.com/{repository.Identifier}/compare/{tag}...HEAD");
 }
Exemplo n.º 12
0
 public static string GetGitHubName(this GitRepository repository)
 {
     Assert.True(repository.IsGitHubRepository());
     return(repository.Identifier.Split('/')[1]);
 }
Exemplo n.º 13
0
        private async Task <OperationResult <AgentInformation> > RunAgentAsync(StartAgentInformation startAgentInformation, GitRepository agentRepository)
        {
            var args = new ShellRunnerArgs(agentRepository.Directory,
                                           "docker", false, $"run -p {startAgentInformation.Port}:80 -d agent:latest");
            var runAgentResult = await shellRunner.RunAsync(args);

            if (!runAgentResult.IsSuccessful)
            {
                return(OperationResult <AgentInformation> .Failed($"Cannot run container with agent. Error: {runAgentResult.Error}"));
            }

            logger.LogInformation(await runAgentResult.Value.Output.ReadToEndAsync());

            return(OperationResult <AgentInformation> .Success(new AgentInformation(new Uri($"http://localhost:{startAgentInformation.Port}"))));
        }
        public override bool OnBeginCommit(ChangeSet changeSet)
        {
            // In this callback we check if the user information configured in Git
            // matches the user information configured in MonoDevelop. If the configurations
            // don't match, it shows a dialog asking the user what to do.

            GitRepository repo = (GitRepository)changeSet.Repository;

            if (!widget.CommitterIsAuthor)
            {
                if (widget.AuthorName.Length > 0)
                {
                    changeSet.ExtendedProperties ["Git.AuthorName"] = widget.AuthorName;
                }
                if (widget.AuthorMail.Length > 0)
                {
                    changeSet.ExtendedProperties ["Git.AuthorEmail"] = widget.AuthorMail;
                }
            }

            Solution sol = null;

            // Locate the solution to which the changes belong
            foreach (Solution s in IdeApp.Workspace.GetAllSolutions())
            {
                if (s.BaseDirectory == changeSet.BaseLocalPath || changeSet.BaseLocalPath.IsChildPathOf(s.BaseDirectory))
                {
                    sol = s;
                    break;
                }
            }
            if (sol == null)
            {
                return(true);
            }

            string user;
            string email;

            repo.GetUserInfo(out user, out email);

            string val = sol.UserProperties.GetValue <string> ("GitUserInfo");

            if (val == "UsingMD")
            {
                // If the solution is configured to use the MD configuration, make sure the Git config is up to date.
                if (user != sol.AuthorInformation.Name || email != sol.AuthorInformation.Email)
                {
                    repo.SetUserInfo(sol.AuthorInformation.Name, sol.AuthorInformation.Email);
                }
            }
            else if (val != "UsingGIT")
            {
                if (repo.IsUserInfoDefault())
                {
                    var dlg = new UserGitConfigDialog();
                    try {
                        if (MessageService.RunCustomDialog(dlg) == (int)Gtk.ResponseType.Ok)
                        {
                            user  = dlg.UserText;
                            email = dlg.EmailText;
                            repo.SetUserInfo(dlg.UserText, dlg.EmailText);
                        }
                        else
                        {
                            return(false);
                        }
                    } finally {
                        dlg.Destroy();
                    }
                }

                if (user != sol.AuthorInformation.Name || email != sol.AuthorInformation.Email)
                {
                    // There is a conflict. Ask the user what to do
                    string gitInfo = GetDesc(user, email);
                    string mdInfo  = GetDesc(sol.AuthorInformation.Name, sol.AuthorInformation.Email);

                    UserInfoConflictDialog dlg = new UserInfoConflictDialog(mdInfo, gitInfo);
                    try {
                        if (MessageService.RunCustomDialog(dlg) == (int)Gtk.ResponseType.Ok)
                        {
                            if (dlg.UseMonoDevelopConfig)
                            {
                                repo.SetUserInfo(sol.AuthorInformation.Name, sol.AuthorInformation.Email);
                                sol.UserProperties.SetValue("GitUserInfo", "UsingMD");
                            }
                            else
                            {
                                sol.UserProperties.SetValue("GitUserInfo", "UsingGIT");
                            }
                            sol.SaveUserProperties();
                        }
                        else
                        {
                            return(false);
                        }
                    } finally {
                        dlg.Destroy();
                    }
                }
            }
            return(true);
        }
Exemplo n.º 15
0
        public void ClonePublic()
        {
            string repos = GetTempPath();
            using (GitClient git = new GitClient())
            {
                GitCloneArgs ca = new GitCloneArgs();
                ca.Synchronous = true;

                git.Clone(new Uri("https://github.com/libgit2/TestGitRepository.git"), repos, ca);

                List<string> found = new List<string>();

                GitStatusArgs sa = new GitStatusArgs();
                sa.IncludeUnmodified = true;
                sa.UseGlobPath = true;

                git.Status(repos, sa,
                    delegate(object sender, GitStatusEventArgs e)
                    {
                        found.Add(e.RelativePath);
                    });

                Assert.That(found.Count, Is.EqualTo(8));
                Assert.That(found, Is.All.Not.Null);
                Assert.That(found, Is.Unique);

                found.Clear();

                git.Status(repos + "/a/*", sa,
                    delegate(object sender, GitStatusEventArgs e)
                    {
                        found.Add(e.RelativePath);
                    });

                Assert.That(found.Count, Is.EqualTo(3));
                Assert.That(found, Is.All.Not.Null);
                Assert.That(found, Is.Unique);

                GitFetchArgs fa = new GitFetchArgs();
                fa.All = true;
                git.Fetch(repos, fa);

                using (GitRepository repo = new GitRepository(repos))
                {
                    Assert.That(repo.HeadBranch, Is.Not.Null);

                    Assert.That(repo.HeadBranch.Name, Is.EqualTo("refs/heads/master"));
                    Assert.That(repo.HeadBranch.UpstreamReference, Is.Not.Null);
                    Assert.That(repo.HeadBranch.UpstreamReference.Name, Is.EqualTo("refs/remotes/origin/master"));
                    Assert.That(repo.HeadBranch.IsHead, "Head knows that it is head");
                    //Assert.That(repo.HeadBranch.TrackedBranch, Is.Null);

                    Assert.That(repo.HeadBranch.Name, Is.EqualTo("refs/heads/master"));
                    Assert.That(repo.HeadBranch.IsRemote, Is.False, "Local branch");
                    Assert.That(repo.HeadBranch.RemoteName, Is.EqualTo("origin"));

                    foreach (GitBranch b in repo.Branches.Remote)
                    {
                        Assert.That(b.IsRemote, "Remote branch");
                        Assert.That(b.IsLocal, Is.False, "Not local");
                        Assert.That(b.Name, Is.StringStarting("refs/remotes/origin/"));
                        Assert.That(b.IsHead, Is.False);
                        Assert.That(b.UpstreamReference, Is.Null);
                        Assert.That(b.LocalUpstreamName, Is.Null);
                        Assert.That(b.RemoteName, Is.EqualTo("origin"));
                    }

                    foreach (GitBranch b in repo.Branches.Local)
                    {
                        Assert.That(b.IsLocal, "Local branch");
                        Assert.That(b.IsRemote, Is.False, "Not remote");
                        Assert.That(b.Name, Is.StringStarting("refs/").Or.EqualTo("master"));
                        Assert.That(b.IsHead, Is.EqualTo(b.ShortName == "master"));
                        Assert.That(b.RemoteName, Is.EqualTo("origin"));
                        if (!b.IsHead)
                        {
                            Assert.That(b.LocalUpstreamName, Is.Not.Null);

                            GitBranch tracked = b.TrackedBranch;
                            Assert.That(tracked, Is.Not.Null, "Have tracked");

                            Assert.That(b.RemoteName, Is.Not.Null);
                        }
                    }

                    foreach (GitRemote r in repo.Remotes)
                    {
                        Assert.That(r.Name, Is.Not.Null);
                        Assert.That(r.TagSynchronize, Is.EqualTo(GitTagSynchronize.Auto));
                        //Assert.That(r.Save(new GitFetchArgs()));

                        foreach (GitRefSpec rs in r.FetchRefSpecs)
                        {

                        }

                        foreach (GitRefSpec rs in r.PushRefSpecs)
                        {

                        }
                    }
                }

                git.Pull(repos);

                // libgit2's local push code only supports bare repositories at
                // this time, so we use a few more clones to test the real push

                string cloneDir = GetTempPath();
                GitCloneArgs cca = new GitCloneArgs();
                cca.InitArgs.CreateBareRepository = true;
                git.Clone(repos, cloneDir, cca);

                string clone2Dir = GetTempPath();

                git.Clone(cloneDir, clone2Dir);

                GitPushArgs pa = new GitPushArgs();
                pa.Mode = GitPushMode.All;
                git.Push(clone2Dir, pa);
            }
        }
Exemplo n.º 16
0
 public static bool IsGitHubRepository(this GitRepository repository)
 {
     return(repository != null && repository.Endpoint.EqualsOrdinalIgnoreCase("github.com"));
 }
Exemplo n.º 17
0
        public void UseGitClient()
        {
            GitCommitArgs ga = new GitCommitArgs();
            ga.Author.Name = "Tester";
            ga.Author.EmailAddress = "*****@*****.**";
            ga.Signature.Name = "Other";
            ga.Signature.EmailAddress = "*****@*****.**";

            // Use stable time and offset to always produce the same hash
            DateTime ct = new DateTime(2002, 01, 01, 0, 0, 0, DateTimeKind.Utc);
            ga.Author.When = ct;
            ga.Author.TimeOffsetInMinutes = 120;
            ga.Signature.When = ct;
            ga.Signature.TimeOffsetInMinutes = 120;

            string repoDir = GetTempPath();
            string repo2Dir = GetTempPath();
            GitId firstResult;
            GitId lastCommit;
            using (GitRepository repo = GitRepository.Create(repoDir))
            using (GitClient git = new GitClient())
            {
                string ignoreFile = Path.Combine(repoDir, ".gitignore");
                string file = Path.Combine(repoDir, "newfile");
                string subDir = Path.Combine(repoDir, "dir");
                string fileInSubDir = Path.Combine(subDir, "file2");
                string file3 = Path.Combine(repoDir, "other");
                string file4 = Path.Combine(repoDir, "q.ignore");
                File.WriteAllText(file, "Some body");
                Directory.CreateDirectory(subDir);
                File.WriteAllText(fileInSubDir, "Some other body");
                File.WriteAllText(file3, "file3");

                File.WriteAllText(ignoreFile, "*.ignore\n");
                File.WriteAllText(file4, "file4");

                git.Add(ignoreFile);
                git.Add(file);
                git.Commit(repoDir, ga, out firstResult);

                git.Add(fileInSubDir);

                int ticked = 0;

                File.AppendAllText(file, "\nExtra Line");

                GitStatusArgs gsa = new GitStatusArgs();
                gsa.IncludeIgnored = true;
                gsa.IncludeUnmodified = true;

                Assert.That(git.Status(repoDir, gsa,
                    delegate(object sender, GitStatusEventArgs e)
                    {
                        switch (e.RelativePath)
                        {
                            case "newfile":
                                //Assert.That(e.IndexStatus, Is.EqualTo(GitStatus.Added));
                                Assert.That(e.IndexStatus, Is.EqualTo(GitStatus.Normal), "newfile index normal");
                                Assert.That(e.WorkingDirectoryStatus, Is.EqualTo(GitStatus.Normal), "newfile wc modified");
                                Assert.That(e.WorkingDirectoryModified);
                                Assert.That(e.Ignored, Is.False);
                                break;
                            case "dir/file2":
                                Assert.That(e.IndexStatus, Is.EqualTo(GitStatus.New), "file2 index added");
                                Assert.That(e.WorkingDirectoryStatus, Is.EqualTo(GitStatus.Normal), "file2 wc normal");
                                Assert.That(e.Ignored, Is.False);
                                break;
                            case "other":
                                Assert.That(e.IndexStatus, Is.EqualTo(GitStatus.None));
                                Assert.That(e.WorkingDirectoryStatus, Is.EqualTo(GitStatus.New));
                                Assert.That(e.Ignored, Is.False);
                                break;
                            case ".gitignore":
                                Assert.That(e.IndexStatus, Is.EqualTo(GitStatus.Normal));
                                Assert.That(e.WorkingDirectoryStatus, Is.EqualTo(GitStatus.Normal));
                                Assert.That(e.Ignored, Is.False);
                                break;
                            case "q.ignore":
                                // TODO: Make this ignored
                                Assert.That(e.IndexStatus, Is.EqualTo(GitStatus.None));
                                Assert.That(e.WorkingDirectoryStatus, Is.EqualTo(GitStatus.Normal));
                                Assert.That(e.Ignored, Is.True);
                                break;
                            default:
                                Assert.Fail("Invalid node found: {0}", e.RelativePath);
                                break;
                        }

                        Assert.That(e.FullPath, Is.EqualTo(Path.GetFullPath(Path.Combine(repoDir, e.RelativePath))));
                        ticked++;
                    }), Is.True);

                Assert.That(ticked, Is.EqualTo(5), "Ticked");

                ga.LogMessage = "Intermediate";
                git.Commit(repoDir, ga);

                Assert.That(git.Delete(fileInSubDir));
                Assert.That(git.Add(file));

                GitId commit;

                ga.LogMessage = "A log message to remember";

                // The passed path is currently just used to find the local repository
                lastCommit = new GitId("996cf198b49ed6fce3bcba232e2d88eb473560f9");

                Assert.That(git.Commit(repoDir, ga, out commit));
                Assert.That(commit, Is.EqualTo(lastCommit));

                File.Move(file, file + ".a");

                ticked = 0;
                gsa.IncludeIgnored = false;
                gsa.IncludeUnversioned = true;
                gsa.IncludeUnmodified = false;
                Assert.That(git.Status(repoDir, gsa,
                    delegate(object sender, GitStatusEventArgs e)
                    {
                        switch (e.RelativePath)
                        {
                            /*case "dir":
                                Assert.That(e.IndexStatus, Is.EqualTo(GitStatus.Normal), "dir index normal");
                                Assert.That(e.WorkingDirectoryStatus, Is.EqualTo(GitStatus.New), "dir wc normal");
                                break;*/
                            case "newfile":
                                Assert.That(e.IndexStatus, Is.EqualTo(GitStatus.None), "newfile index normal");
                                Assert.That(e.WorkingDirectoryStatus, Is.EqualTo(GitStatus.Deleted), "newfile wc deleted");
                                break;
                            case "newfile.a":
                                Assert.That(e.IndexStatus, Is.EqualTo(GitStatus.None), "newfile.a index normal");
                                Assert.That(e.WorkingDirectoryStatus, Is.EqualTo(GitStatus.New), "newfile.a wc new");
                                break;
                            case "other":
                                Assert.That(e.IndexStatus, Is.EqualTo(GitStatus.None), "other index normal");
                                Assert.That(e.WorkingDirectoryStatus, Is.EqualTo(GitStatus.New), "other wc normal");
                                break;
                            default:
                                Assert.Fail("Invalid node found: {0}", e.RelativePath);
                                break;
                        }

                        Assert.That(e.FullPath, Is.EqualTo(Path.GetFullPath(Path.Combine(repoDir, e.RelativePath))));
                        ticked++;
                    }), Is.True);

                Assert.That(ticked, Is.EqualTo(3));

                GitCloneArgs gc = new GitCloneArgs();
                gc.Synchronous = true;

                git.Clone(repoDir, repo2Dir, gc);

                GitCommit theCommit;
                Assert.That(repo.Lookup(commit, out theCommit));
                Assert.That(repo.Branches.Create(theCommit, "vNext"));
                Assert.That(repo.Branches, Is.Not.Empty);
            }

            using (GitRepository repo1 = new GitRepository(repoDir))
            using (GitRepository repo2 = new GitRepository(repo2Dir))
            {
                GitReference head = repo1.HeadReference;
                Assert.That(head, Is.Not.Null, "Has head");

                Assert.That(head.Name, Is.EqualTo("refs/heads/master"));
                //Assert.That(repo2.Head, Is.Not.Null);

                GitId headId;
                Assert.That(repo1.ResolveReference(repo1.HeadReference, out headId));
                Assert.That(headId, Is.EqualTo(lastCommit));
                GitCommit commit;

                Assert.That(repo1.Lookup(headId, out commit));
                Assert.That(commit, Is.Not.Null, "Have a commit");

                Assert.That(commit.Id, Is.EqualTo(lastCommit));
                Assert.That(commit.Ancestors, Is.Not.Empty);
                Assert.That(commit.Ancestor, Is.Not.Null);
                Assert.That(commit.Ancestor.Ancestor, Is.Not.Null);
                Assert.That(commit.Ancestor.Ancestor.Ancestor, Is.Null);
                Assert.That(commit.Ancestor.Ancestor.Id, Is.EqualTo(firstResult));

                Assert.That(commit.Author, Is.Not.Null);
                Assert.That(commit.Author.Name, Is.EqualTo("Tester"));
                Assert.That(commit.Author.EmailAddress, Is.EqualTo("*****@*****.**"));

                Assert.That(commit.Committer, Is.Not.Null);
                Assert.That(commit.Committer.Name, Is.EqualTo("Other"));
                Assert.That(commit.Committer.EmailAddress, Is.EqualTo("*****@*****.**"));

                Assert.That(commit.Committer.TimeOffsetInMinutes, Is.EqualTo(120), "Time offset"); // CEST dependent
                Assert.That(commit.Committer.When, Is.EqualTo(ct), "Exact time");
                Assert.That(commit.LogMessage, Is.EqualTo("A log message to remember\n"));

                Assert.That(commit.Parents, Is.Not.Empty);
                Assert.That(commit.ParentIds, Is.Not.Empty);

                Assert.That(commit.Tree, Is.Not.Empty);
                Assert.That(commit.Tree.Count, Is.EqualTo(2));
                Assert.That(commit.Ancestor.Tree.Count, Is.EqualTo(3));
                Assert.That(commit.Ancestor.Ancestor.Tree.Count, Is.EqualTo(2));
                Assert.That(commit.Tree.Id, Is.Not.EqualTo(commit.Ancestor.Tree.Id));

                GitId id;
                Assert.That(repo1.LookupViaPrefix(commit.Id.ToString(), out id));
                Assert.That(id, Is.EqualTo(commit.Id));

                Assert.That(repo1.LookupViaPrefix(commit.Id.ToString().Substring(0, 10), out id));
                Assert.That(id, Is.EqualTo(commit.Id));

                Assert.That(commit.Peel<GitObject>().Id, Is.EqualTo(commit.Tree.Id));
                Assert.That(commit.Peel<GitTree>(), Is.EqualTo(commit.Tree)); // Compares members
                Assert.That(commit.Tree.Peel<GitObject>(), Is.Null);

                GitTagArgs ta = new GitTagArgs();
                ta.Signature.When = ct;
                ta.Signature.Name = "Me";
                ta.Signature.EmailAddress = "[email protected]";
                ta.LogMessage = "Some message";
                ga.Author.TimeOffsetInMinutes = 120;
                Assert.That(commit.Tag("MyTag", ta, out id));
                Assert.That(id, Is.EqualTo(new GitId("db31f8333fc64d7e7921ea91f6e007b755dcfcbb")));

                GitTag tag;
                Assert.That(repo1.Lookup(id, out tag));
                Assert.That(tag, Is.Not.Null);
                Assert.That(tag.Name, Is.EqualTo("MyTag"));
                Assert.That(tag.LogMessage, Is.EqualTo("Some message\n"));
                Assert.That(tag.Tagger.Name, Is.EqualTo("Me"));

                Assert.That(tag.Target.Id, Is.EqualTo(commit.Id));
                Assert.That(tag.Peel<GitTree>(), Is.EqualTo(commit.Peel<GitTree>()));

                repo1.CheckOut(commit.Tree);

                //Console.WriteLine("1:");
                //foreach (GitTreeEntry e in commit.Tree)
                //{
                //    Console.WriteLine(string.Format("{0}: {1} ({2})", e.Name, e.Kind, e.Children.Count));
                //}

                //Console.WriteLine("2:");
                //foreach (GitTreeEntry e in commit.Ancestor.Tree)
                //{
                //    Console.WriteLine(string.Format("{0}: {1} ({2})", e.Name, e.Kind, e.Children.Count));
                //}

                //Console.WriteLine("3:");
                //foreach (GitTreeEntry e in commit.Ancestor.Ancestor.Tree)
                //{
                //    Console.WriteLine(string.Format("{0}: {1} ({2})", e.Name, e.Kind, e.Children.Count));
                //}
                //Console.WriteLine("-");
            }
        }
Exemplo n.º 18
0
        public static string GetGitHubName(this GitRepository repository)
        {
            ControlFlow.Assert(repository.IsGitHubRepository(), text: "repository.IsGitHubRepository()");

            return(repository.Identifier.Split('/')[1]);
        }
Exemplo n.º 19
0
 internal void Refresh(GitRepository tracker)
 {
     this.tracker = tracker;
     RefreshPrompt();
 }
Exemplo n.º 20
0
        private static string GetMethod([CanBeNull] string relativePath, GitHubItemType itemType, GitRepository repository)
        {
            var absolutePath = repository.LocalDirectory != null && relativePath != null
                ? NormalizePath(Path.Combine(repository.LocalDirectory, relativePath))
                : null;

            if (itemType == GitHubItemType.Directory || Directory.Exists(absolutePath) || relativePath == null)
            {
                return("tree");
            }

            if (itemType == GitHubItemType.File || File.Exists(absolutePath))
            {
                return("blob");
            }

            return(null);
        }
Exemplo n.º 21
0
        private static bool IsRelevantCommit(GitRepository repository, GitTree tree, GitTree parent, string relativePath, IReadOnlyList <FilterPath> filters)
        {
            // Walk over all child nodes in the current tree. If a child node was found in the parent,
            // remove it, so that after the iteration the parent contains all nodes which have been
            // deleted.
            foreach (var child in tree.Children)
            {
                var          entry       = child.Value;
                GitTreeEntry?parentEntry = null;

                // If the entry is not present in the parent commit, it was added;
                // if the Sha does not match, it was modified.
                if (!parent.Children.TryGetValue(child.Key, out parentEntry) ||
                    parentEntry.Sha != child.Value.Sha)
                {
                    // Determine whether the change was relevant.
                    var fullPath = $"{relativePath}{entry.Name}";

                    bool isRelevant =
                        // Either there are no include filters at all (i.e. everything is included), or there's an explicit include filter
                        (!filters.Any(f => f.IsInclude) || filters.Any(f => f.Includes(fullPath, repository.IgnoreCase)))
                        // The path is not excluded by any filters
                        && !filters.Any(f => f.Excludes(fullPath, repository.IgnoreCase));

                    // If the change was relevant, and the item is a directory, we need to recurse.
                    if (isRelevant && !entry.IsFile)
                    {
                        isRelevant = IsRelevantCommit(
                            repository,
                            repository.GetTree(entry.Sha),
                            parentEntry == null ? GitTree.Empty : repository.GetTree(parentEntry.Sha),
                            $"{fullPath}/",
                            filters);
                    }

                    // Quit as soon as any relevant change has been detected.
                    if (isRelevant)
                    {
                        return(true);
                    }
                }

                if (parentEntry != null)
                {
                    parent.Children.Remove(child.Key);
                }
            }

            // Inspect removed entries (i.e. present in parent but not in the current tree)
            foreach (var child in parent.Children)
            {
                // Determine whether the change was relevant.
                var fullPath = Path.Combine(relativePath, child.Key);

                bool isRelevant =
                    filters.Any(f => f.Includes(fullPath, repository.IgnoreCase)) &&
                    !filters.Any(f => f.Excludes(fullPath, repository.IgnoreCase));

                if (isRelevant)
                {
                    return(true);
                }
            }

            // No relevant changes have been detected
            return(false);
        }
Exemplo n.º 22
0
        protected virtual void DoFetch(IGitTfsRemote remote, bool stopOnFailMergeCommit)
        {
            if (remote.Repository.IsBare)
            {
                if (string.IsNullOrEmpty(BareBranch))
                {
                    throw new GitTfsException("error : specify a git branch to fetch on...");
                }
                if (!remote.Repository.HasRef(GitRepository.ShortToLocalName(BareBranch)))
                {
                    throw new GitTfsException("error : the specified git branch doesn't exist...");
                }
                if (!ForceFetch && remote.MaxCommitHash != remote.Repository.GetCommit(BareBranch).Sha)
                {
                    throw new GitTfsException("error : fetch is not allowed when there is ahead commits!",
                                              new List <string>()
                    {
                        "Remove ahead commits and retry", "use the --force option (ahead commits will be lost!)"
                    });
                }
            }

            // It is possible that we have outdated refs/remotes/tfs/<id>.
            // E.g. someone already fetched changesets from TFS into another git repository and we've pulled it since
            // in that case tfs fetch will retrieve same changes again unnecessarily. To prevent it we will scan tree from HEAD and see if newer changesets from
            // TFS exists (by checking git-tfs-id mark in commit's comments).
            // The process is similar to bootstrapping.
            if (!ForceFetch)
            {
                globals.Repository.MoveTfsRefForwardIfNeeded(remote);
            }
            var exportMetadatasFilePath = Path.Combine(globals.GitDir, "git-tfs_workitem_mapping.txt");

            if (ExportMetadatas)
            {
                remote.ExportMetadatas = true;
                remote.Repository.SetConfig(GitTfsConstants.ExportMetadatasConfigKey, "true");
                if (!string.IsNullOrEmpty(ExportMetadatasFile))
                {
                    if (File.Exists(ExportMetadatasFile))
                    {
                        File.Copy(ExportMetadatasFile, exportMetadatasFilePath);
                    }
                    else
                    {
                        throw new GitTfsException("error: the work items mapping file doesn't exist!");
                    }
                }
            }
            else
            {
                if (remote.Repository.GetConfig(GitTfsConstants.ExportMetadatasConfigKey) == "true")
                {
                    remote.ExportMetadatas = true;
                }
            }
            remote.ExportWorkitemsMapping = new Dictionary <string, string>();
            if (remote.ExportMetadatas && File.Exists(exportMetadatasFilePath))
            {
                try
                {
                    foreach (var lineRead in File.ReadAllLines(exportMetadatasFilePath))
                    {
                        if (string.IsNullOrWhiteSpace(lineRead))
                        {
                            continue;
                        }
                        var values      = lineRead.Split('|');
                        var oldWorkitem = values[0].Trim();
                        if (!remote.ExportWorkitemsMapping.ContainsKey(oldWorkitem))
                        {
                            remote.ExportWorkitemsMapping.Add(oldWorkitem, values[1].Trim());
                        }
                    }
                }
                catch (Exception)
                {
                    throw new GitTfsException("error: bad format of workitems mapping file! One line format should be: OldWorkItemId|NewWorkItemId");
                }
            }

            try
            {
                remote.Fetch(stopOnFailMergeCommit);
            }
            finally
            {
                Trace.WriteLine("Cleaning...");
                remote.CleanupWorkspaceDirectory();

                if (remote.Repository.IsBare)
                {
                    remote.Repository.UpdateRef(GitRepository.ShortToLocalName(BareBranch), remote.MaxCommitHash);
                }
            }
        }
Exemplo n.º 23
0
        public void FromUrlProtocolTest(string url, GitProtocol protocol)
        {
            var repository = GitRepository.FromUrl(url);

            repository.Protocol.Should().Be(protocol);
        }
Exemplo n.º 24
0
 internal GitSet(GitRepository repository)
 {
     Repository = repository ?? throw new ArgumentNullException(nameof(repository));
 }
Exemplo n.º 25
0
        private static bool FindAnyRepository(ClientSampleContext context, Guid projectId, out GitRepository repo)
        {
            // Check if we already have a repo loaded
            if (!context.TryGetValue <GitRepository>("$someRepo", out repo))
            {
                VssConnection connection = context.Connection;
                GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

                using (new ClientSampleHttpLoggerOutputSuppression())
                {
                    // Check if an ID was already set (this could have been provided by the caller)
                    Guid repoId;
                    if (!context.TryGetValue <Guid>("repositoryId", out repoId))
                    {
                        // Get the first repo
                        repo = gitClient.GetRepositoriesAsync(projectId).Result.FirstOrDefault();
                    }
                    else
                    {
                        // Get the details for this repo
                        repo = gitClient.GetRepositoryAsync(repoId.ToString()).Result;
                    }
                }

                if (repo != null)
                {
                    context.SetValue <GitRepository>("$someRepo", repo);
                }
                else
                {
                    // create a project here?
                    throw new Exception("No repos available for running the sample.");
                }
            }

            return(repo != null);
        }
Exemplo n.º 26
0
        public static (string gitHubOwner, string repositoryName) GetGitHubRepositoryInfo(GitRepository gitRepository)
        {
            ControlFlow.Assert(gitRepository.IsGitHubRepository(), $"The {nameof(gitRepository)} parameter must reference a GitHub repository.");

            var split = gitRepository.Identifier.Split('/');

            return(split[0], split[1]);
        }
Exemplo n.º 27
0
 internal void Refresh(GitRepository tracker)
 {
     this.tracker = tracker;
     RefreshPrompt();
 }
Exemplo n.º 28
0
 internal void Refresh(GitRepository tracker, MyToolWindow toolWindow)
 {
     this.toolWindow = toolWindow;
     this.tracker    = tracker;
     RefreshPrompt();
 }
Exemplo n.º 29
0
 public static void ShowConfigurationDialog(GitRepository repo)
 {
     using (var dlg = new GitConfigurationDialog(repo))
         MessageService.ShowCustomDialog(dlg);
 }
Exemplo n.º 30
0
        public GitConfigurationDialog(VersionControlSystem vcs, string repoPath, string repoUrl)
        {
            this.Build();
            this.repo         = new GitRepository(vcs, repoPath, repoUrl, false);
            this.HasSeparator = false;

            this.UseNativeContextMenus();

            // Branches list

            storeBranches               = new ListStore(typeof(Branch), typeof(string), typeof(string), typeof(string));
            listBranches.Model          = storeBranches;
            listBranches.SearchColumn   = -1;           // disable the interactive search
            listBranches.HeadersVisible = true;

            SemanticModelAttribute modelAttr = new SemanticModelAttribute("storeBranches__Branch", "storeBranches__DisplayName", "storeBranches__Tracking", "storeBranches__Name");

            TypeDescriptor.AddAttributes(storeBranches, modelAttr);

            listBranches.AppendColumn(GettextCatalog.GetString("Branch"), new CellRendererText(), "markup", 1);
            listBranches.AppendColumn(GettextCatalog.GetString("Tracking"), new CellRendererText(), "text", 2);

            listBranches.Selection.Changed += delegate {
                TreeIter it;
                bool     anythingSelected =
                    buttonRemoveBranch.Sensitive = buttonEditBranch.Sensitive = buttonSetDefaultBranch.Sensitive = listBranches.Selection.GetSelected(out it);
                if (!anythingSelected)
                {
                    return;
                }
                if (repo == null || repo.IsDisposed)
                {
                    return;
                }
                string currentBranch = repo.GetCurrentBranch();
                var    b             = (Branch)storeBranches.GetValue(it, 0);
                buttonRemoveBranch.Sensitive     = b.FriendlyName != currentBranch;
                buttonSetDefaultBranch.Sensitive = !b.IsCurrentRepositoryHead;
            };
            buttonRemoveBranch.Sensitive = buttonEditBranch.Sensitive = buttonSetDefaultBranch.Sensitive = false;

            // Sources tree

            storeRemotes               = new TreeStore(typeof(Remote), typeof(string), typeof(string), typeof(string), typeof(string));
            treeRemotes.Model          = storeRemotes;
            treeRemotes.SearchColumn   = -1;           // disable the interactive search
            treeRemotes.HeadersVisible = true;

            SemanticModelAttribute remotesModelAttr = new SemanticModelAttribute("storeRemotes__Remote", "storeRemotes__Name", "storeRemotes__Url", "storeRemotes__BranchName", "storeRemotes__FullName");

            TypeDescriptor.AddAttributes(storeRemotes, remotesModelAttr);

            treeRemotes.AppendColumn(GettextCatalog.GetString("Remote Source / Branch"), new CellRendererText(), "markup", 1);
            treeRemotes.AppendColumn(GettextCatalog.GetString("Url"), new CellRendererText(), "text", 2);

            treeRemotes.Selection.Changed += delegate {
                TreeIter it;
                bool     anythingSelected = treeRemotes.Selection.GetSelected(out it);
                buttonTrackRemote.Sensitive = false;
                buttonFetch.Sensitive       = buttonEditRemote.Sensitive = buttonRemoveRemote.Sensitive = anythingSelected;
                if (!anythingSelected)
                {
                    return;
                }
                string branchName = (string)storeRemotes.GetValue(it, 3);
                if (branchName != null)
                {
                    buttonTrackRemote.Sensitive = true;
                }
            };
            buttonTrackRemote.Sensitive = buttonFetch.Sensitive = buttonEditRemote.Sensitive = buttonRemoveRemote.Sensitive = false;

            // Tags list

            storeTags               = new ListStore(typeof(string));
            listTags.Model          = storeTags;
            listTags.SearchColumn   = -1;           // disable the interactive search
            listTags.HeadersVisible = true;

            SemanticModelAttribute tagsModelAttr = new SemanticModelAttribute("storeTags__Name");

            TypeDescriptor.AddAttributes(storeTags, tagsModelAttr);

            listTags.AppendColumn(GettextCatalog.GetString("Tag"), new CellRendererText(), "text", 0);

            listTags.Selection.Changed += delegate {
                TreeIter it;
                buttonRemoveTag.Sensitive = buttonPushTag.Sensitive = listTags.Selection.GetSelected(out it);
            };
            buttonRemoveTag.Sensitive = buttonPushTag.Sensitive = false;

            // Fill data

            FillBranches();
            FillRemotes();
            FillTags();
        }
Exemplo n.º 31
0
        public void DualStart()
        {
            string master = GetTempPath();
            using (GitClient git = new GitClient())
            {
                GitInitArgs ia = new GitInitArgs();
                ia.CreateBareRepository = true;
                ia.Description = "Harry & Sally root";

                git.Init(master, ia);
            }

            Uri masterUri = new Uri(master);

            string harry = GetTempPath();
            string sally = GetTempPath();

            using (GitClient git = new GitClient()) // Harry
            {
                git.Clone(masterUri, harry);

                using (GitRepository harryRepo = new GitRepository(harry))
                {
                    harryRepo.Configuration.Set(GitConfigurationLevel.Repository, "user.name", "Harry");
                    harryRepo.Configuration.Set(GitConfigurationLevel.Repository, "user.email", "*****@*****.**");
                }

                string src = Path.Combine(harry, "src");
                Directory.CreateDirectory(src);

                string index = Path.Combine(src, "index.txt");

                File.WriteAllText(index, "This is index.txt\n");

                git.Add(index);
                GitId result;
                GitCommitArgs cma = new GitCommitArgs();
                cma.Signature.When = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                cma.Author.When = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                git.Commit(harry, cma, out result);

                using (GitRepository harryRepo = new GitRepository(harry))
                {
                    GitCommit commit;
                    Assert.That(harryRepo.Lookup(result, out commit));

                    Assert.That(commit.Author.Name, Is.EqualTo("Harry"));
                }
            }

            using (GitClient git = new GitClient()) // Sally
            {
                git.Clone(masterUri, sally);

                using (GitRepository sallyRepo = new GitRepository(sally))
                {
                    sallyRepo.Configuration.Set(GitConfigurationLevel.Repository, "user.name", "Sally");
                    sallyRepo.Configuration.Set(GitConfigurationLevel.Repository, "user.email", "*****@*****.**");
                }

                string iota = Path.Combine(sally, "iota.txt");

                File.WriteAllText(iota, "This is iota\n");

                git.Stage(iota);

                GitCommitArgs cma = new GitCommitArgs();
                cma.Signature.When = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                cma.Author.When = new DateTime(2001, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                git.Commit(sally, cma);

                string src = Path.Combine(sally, "src");
                string index = Path.Combine(src, "index.txt");

                Assert.That(File.Exists(index), Is.False);
            }

            using (GitClient git = new GitClient()) // Harry
            {
                GitPushArgs pa = new GitPushArgs();
                pa.Mode = GitPushMode.All;
                git.Push(harry, pa);
            }

            using (GitClient git = new GitClient()) // Sally
            {
                GitPullArgs pa = new GitPullArgs();
                pa.FetchArgs.All = true;

                git.Pull(sally, pa);

                string src = Path.Combine(sally, "src");
                string index = Path.Combine(src, "index.txt");

                Assert.That(File.Exists(index), Is.True);
            }
        }
Exemplo n.º 32
0
 /// <summary>
 ///     Gets the available branches list.
 /// </summary>
 /// <returns>List of branches</returns>
 public IEnumerable <BranchInfo> GetBranches() =>
 GitRepository.ListBranches(new ListBranches(
                                GetSetting(GitSettingKeys.Url),
                                GetSetting(GitSettingKeys.Username),
                                GetSetting(GitSettingKeys.Password)));
Exemplo n.º 33
0
        public void PushChanges()
        {
            string master = GetTempPath();
            using (GitClient git = new GitClient())
            {
                GitInitArgs ia = new GitInitArgs();
                ia.CreateBareRepository = true;
                ia.Description = "Harry & Sally root";

                git.Init(master, ia);
            }

            Uri masterUri = new Uri(master);

            string harry = GetTempPath();
            string sally = GetTempPath();

            using (GitClient git = new GitClient()) // Harry
            {
                git.Clone(masterUri, harry);

                using (GitRepository harryRepo = new GitRepository(harry))
                {
                    harryRepo.Configuration.Set(GitConfigurationLevel.Repository, "user.name", "Harry");
                    harryRepo.Configuration.Set(GitConfigurationLevel.Repository, "user.email", "*****@*****.**");
                }

                string src = Path.Combine(harry, "src");
                Directory.CreateDirectory(src);

                string index = Path.Combine(src, "index.txt");

                File.WriteAllText(index, "This is index.txt\n");

                string appCode = Path.Combine(harry, "app.c");
                File.WriteAllText(appCode, @"
            #include <stdio.h>

            int main(int argc, const char **argv)
            {
            printf(""hello world\n"");
            return 0;
            }
            ");

                git.Add(index);
                git.Add(appCode);
                GitId result;
                GitCommitArgs cma = new GitCommitArgs();
                cma.Signature.When = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                cma.Author.When = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                git.Commit(harry, cma, out result);

                using (GitRepository harryRepo = new GitRepository(harry))
                {
                    GitCommit commit;
                    Assert.That(harryRepo.Lookup(result, out commit));

                    Assert.That(commit.Author.Name, Is.EqualTo("Harry"));
                }
            }

            using (GitClient git = new GitClient()) // Sally
            {
                git.Clone(masterUri, sally);

                using (GitRepository sallyRepo = new GitRepository(sally))
                {
                    sallyRepo.Configuration.Set(GitConfigurationLevel.Repository, "user.name", "Sally");
                    sallyRepo.Configuration.Set(GitConfigurationLevel.Repository, "user.email", "*****@*****.**");
                }

                string src = Path.Combine(sally, "src");
                string index = Path.Combine(src, "index.txt");

                Assert.That(File.Exists(index), Is.False);
            }

            using (GitClient git = new GitClient()) // Harry
            {
                GitPushArgs pa = new GitPushArgs();
                pa.Mode = GitPushMode.All;
                git.Push(harry, pa);
            }

            using (GitClient git = new GitClient()) // Sally
            {
                GitPullArgs pa = new GitPullArgs();
                pa.FetchArgs.All = true;

                git.Pull(sally, pa);

                string src = Path.Combine(sally, "src");
                string index = Path.Combine(src, "index.txt");

                Assert.That(File.Exists(index), Is.True);

                string appCode = Path.Combine(sally, "app.c");
                File.WriteAllText(appCode, @"
            #include <stdio.h>

            int main(int argc, const char **argv)
            {
            int i;

            if (argc != 1)
            {
            fprintf(stderr, ""Usage %s <int>\n"", argv[0]);
            return 1;
            }
            for (i = 0; i < atoi(argv[1]); i++
            printf(""hello world %d\n"", i);

            return 0;
            }
            ");
                git.Add(appCode);

                GitId result;
                GitCommitArgs cma = new GitCommitArgs();
                cma.Signature.When = new DateTime(2000, 1, 2, 0, 0, 0, DateTimeKind.Utc);
                cma.Author.When = new DateTime(2000, 1, 2, 0, 0, 0, DateTimeKind.Utc);
                git.Commit(sally, cma, out result);

                GitPushArgs ph = new GitPushArgs();
                ph.Mode = GitPushMode.All;
                git.Push(sally, ph);
            }

            using (GitClient git = new GitClient()) // Harry
            {
                string appCode = Path.Combine(harry, "app.c");
                File.WriteAllText(appCode, @"
            #include <stdio.h>

            int main(int argc, const char **argv)
            {
            if (argc > 0 && strcmp(argv[1], ""-V"")
            {
            printf(""%s version 1.0 (c) QQn\n"");
            return 0;
            }
            printf(""hello world\n"");
            return 0;
            }
            ");

                git.Add(appCode);

                GitId result;
                GitCommitArgs cma = new GitCommitArgs();
                cma.Signature.When = new DateTime(2000, 1, 3, 0, 0, 0, DateTimeKind.Utc);
                cma.Author.When = new DateTime(2000, 1, 3, 0, 0, 0, DateTimeKind.Utc);
                git.Commit(harry, cma, out result); // Local commit will succeed

                GitPushArgs ph = new GitPushArgs();
                ph.Mode = GitPushMode.All;
                try
                {
                    git.Push(harry, ph); // But push fails, as it conflicts
                    Assert.Fail("Should have failed"); // ###
                }
                catch(GitException ge)
                {
                    Assert.That(ge.Message, Is.StringContaining("Cannot push"));
                }

                GitPullArgs pa = new GitPullArgs();
                pa.FetchArgs.All = true;

                git.Pull(harry, pa);

                bool gotConflict = false;
                git.Status(harry,
                    delegate(object sender, GitStatusEventArgs e)
                    {
                        switch (e.RelativePath)
                        {
                            case "app.c":
                                gotConflict = true;
                                Assert.That(e.WorkingDirectoryStatus, Is.EqualTo(GitStatus.Normal));
                                Assert.That(e.IndexStatus, Is.EqualTo(GitStatus.Normal));
                                Assert.That(e.Conflicted, Is.True, "Conflicted");
                                break;
                            default:
                                Assert.Fail("Unexpected path: {0}", e.RelativePath);
                                break;
                        }
                    });

                Assert.That(gotConflict, "Found conflict status");

                try
                {
                    git.Push(harry, ph); // But push fails, as it conflicts
                    Assert.Fail("Should still fail");
                }
                catch (GitException ge)
                {
                    Assert.That(ge.Message, Is.StringContaining("Cannot push"));
                }

                GitResetArgs ra = new GitResetArgs();
                ra.Mode = GitResetMode.Hard;
                git.Reset(harry, ra);
            }
        }
Exemplo n.º 34
0
 public VersionResolver(GitRepository gitRepository, string versionPath, ILogger <VersionResolver> logger)
 {
     this.gitRepository = gitRepository ?? throw new ArgumentNullException(nameof(gitRepository));
     this.versionPath   = versionPath ?? throw new ArgumentNullException(nameof(versionPath));
     this.logger        = logger ?? throw new ArgumentNullException(nameof(logger));
 }
Exemplo n.º 35
0
        private GitRepository CreateProxiedTestGitManager(string branch = null)
        {
            DeleteDirectory(GitRepositoryFixture.LocalTestProxyRepository);
            DeleteDirectory(GitRepositoryFixture.LocalRepository);
            RegisterForCleanup(GitRepositoryFixture.LocalTestProxyRepository);
            RegisterForCleanup(GitRepositoryFixture.LocalRepository);

            var testRepo = new GitRepository()
            {
                Branch = branch,
                LocalRepositoryPath = GitRepositoryFixture.LocalTestProxyRepository,
                RemoteRepositoryPath = GitRepositoryFixture.RemoteRepository,
            }.Update();

            return new GitRepository()
            {
                Branch = branch,
                LocalRepositoryPath = GitRepositoryFixture.LocalRepository,
                RemoteRepositoryPath = GitRepositoryFixture.LocalTestProxyRepository,
            };
        }
Exemplo n.º 36
0
        /// <summary>
        /// Finalizes the changelog by moving all entries from `[vNext]` to the version specified by release.
        /// <p>If <paramref name="repository"/> is specified a summary with all versions and links to list the changes directly on GitHub is appended to the end of the changelog.</p>
        /// </summary>
        /// <param name="changelogFile">The path to the changelog file.</param>
        /// <param name="tag">The <see cref="NuGetVersion"/> to finalize the changelog.</param>
        /// <param name="repository">The repository to create the version overview for.</param>
        /// <seealso cref="FinalizeChangelog(ChangeLog,NuGetVersion,GitRepository)"/>
        public static void FinalizeChangelog(ChangeLog changelogFile, NuGetVersion tag, [CanBeNull] GitRepository repository = null)
        {
            Logger.Info($"Finalizing {PathConstruction.GetRelativePath(NukeBuild.RootDirectory, changelogFile.Path)} for '{tag}'...");

            var unreleasedNotes = changelogFile.Unreleased;
            var releaseNotes    = changelogFile.ReleaseNotes;
            var lastReleased    = changelogFile.LatestVersion;

            ControlFlow.Assert(unreleasedNotes != null, "Changelog should have draft section.");
            ControlFlow.Assert(releaseNotes.Any(x => x.Version != null && x.Version.Equals(tag)), $"Tag '{tag}' already exists.");
            ControlFlow.Assert(lastReleased != null && tag.CompareTo(lastReleased.Version) > 0, $"Tag '{tag}' is not greater compared to last tag '{lastReleased.NotNull().Version}'.");

            var path = changelogFile.Path;

            var content = TextTasks.ReadAllLines(path).ToList();

            content.Insert(unreleasedNotes.StartIndex + 1, string.Empty);
            content.Insert(unreleasedNotes.EndIndex + 2, $"## [{tag}] / {DateTime.Now:yyyy-MM-dd}");

            UpdateVersionSummary(tag.ToString(), content, repository);

            content.Add(string.Empty);

            TextTasks.WriteAllLines(path, content);
        }
        public void Run_Spider_Inflate_And_Save_Results_To_GitHub()
        {
            DateTime Start = new DateTime(2013, 2, 15);
            DateTime End = new DateTime(2013, 2, 18);

            WebSiteDownloaderOptions options =
             new WebSiteDownloaderOptions();
            options.DestinationFolderPath =
                new DirectoryInfo(dataDir);
            options.DestinationFileName = String.Format("Session-Activity[{0}][{1}].state",
                                            Start.Date.ToShortDateString().Replace("/", "-"),
                                            End.Date.ToShortDateString().Replace("/", "-"));

            options.MaximumLinkDepth = 4;
            options.TargetSession = 28;
            options.DownloadUri =
                new Uri(String.Format(@"http://www.legis.state.ak.us/basis/range_multi.asp?session={0}&Date1={1}&Date2={2}",
                            options.TargetSession,
                            Start.Date.ToShortDateString(),
                            End.Date.ToShortDateString()));

            WebSiteDownloader rslt = Spider.DownloadingProcessor(options);

            /*
            1. Select Bill Names
            * We need to know the bill name (HB16), so we can save data in a folder of the same name.
            */

            //Static List of Bills
            var masterlist = (from r in rslt.Resources
                              where r.Index == 1 && (r.AbsoluteUri.AbsoluteUri.Contains(@"get_bill.asp"))
                              select r).ToList();

            //Match bill titles in the URI (HB16,SB12..)
            Regex billTitles = new Regex(@"(?<=[=])[H|R|S][B|C|R|J]{0,3}[0-9]{1,4}", RegexOptions.IgnoreCase);

            //Return a list of the first matches
            var bills = (from b in masterlist
                         let matches = billTitles.Matches(b.AbsoluteUri.AbsoluteUri)
                         where matches.Count > 0
                         select new
                         {
                             resource = b,
                             url = b.AbsoluteUri,
                             name = matches.Cast<Match>().FirstOrDefault()
                         }).ToList();

            /*
            2. Build out directory structure for bill data.
            * We have a list of bills, now where are we going to save the data?
            */

            DirectoryInfo session = new DirectoryInfo(String.Format(@"{0}/{1}", dataDir, 28));
            if (!session.Exists)
                session.Create();

            foreach (var item in bills)
            {
                //bill directory
                DirectoryInfo bill = new DirectoryInfo(String.Format(@"{0}/{1}/{2}", dataDir, 28, item.name));
                if (!bill.Exists)
                    bill.Create();
            }

            /*
            3. Associated bill data
            *  Grab associated bill data. Name, Title, LongTitle,
             *  Minutes Content, Bill Revisions, Bill Activity
            */

            foreach (var bill in bills)
            {

                //Results placeholders
                List<iCollector> meta = new List<iCollector>();
                List<iCollector> revisions = new List<iCollector>();
                List<iCollector> minutes = new List<iCollector>();
                List<iCollector> committee = new List<iCollector>();

                //Document history, activity and kvp..
                meta.AddRange((from h in rslt.Parsings
                               where h.source.AbsoluteUri.AbsoluteUri == bill.url.AbsoluteUri
                                  || h.source.Parent.AbsoluteUri == bill.url.AbsoluteUri
                               select h).ToList());

                //Bill Content
                revisions.AddRange((from d in rslt.Parsings
                                    where d.source.Parent.AbsoluteUri
                                           .Contains(String.Format(@"get_fulltext.asp?session={0}&bill={1}", 28, bill.name))
                                    select d).ToList());

                //Committee
                committee.AddRange((from d in rslt.Resources
                           join p in rslt.Parsings
                           on d.AbsoluteUri.AbsoluteUri equals
                                     p.source.Parent.AbsoluteUri
                           where p.source.AbsoluteUri.AbsoluteUri.Contains("get_minutes.asp")
                           && d.AbsoluteUri.AbsoluteUri.Contains(String.Format("{0}", bill.name))
                           select p).ToList());

                //Minutes Transcript
                minutes.AddRange((from d in rslt.Resources
                                  join p in rslt.Parsings
                                  on d.AbsoluteUri.AbsoluteUri equals
                                     p.source.Parent.AbsoluteUri
                                  where p.source.AbsoluteUri.AbsoluteUri
                                         .Contains(@"get_single_minute.asp")
                                         && d.AbsoluteUri.AbsoluteUri
                                         .Contains(String.Format("{0}", bill.name))
                                  select p).ToList());

                /*
                4. Start saving off the data
                * We have a list of bills, now where are we going to save the data?
                */

                String fileLoc = String.Format(@"{0}\{1}\", 28, bill.name);

                GitRepository gr = new GitRepository();
                gr.ProcessBill(fileLoc, new ParsedBill() {
                    meta = meta,
                    minutes = minutes,
                    revisions = revisions,
                    committee = committee });

            }

            Assert.IsTrue(true);
        }
Exemplo n.º 38
0
 public CommitGraphChain(GitRepository repository, string chain) : base(repository, "CommitChain:" + chain)
 {
     _chainDir = chain;
 }
 public GitObject(GitRepository entry)
 {
     this.name = entry.name;
     this.size = entry.size;
     this.type = "repository";
 }
Exemplo n.º 40
0
        private MonitoredPath GetMonitoredPath(MonitoredPath monitoredPath, string repository, string branchName, int days)
        {
            List <GitCommit> commits = new List <GitCommit>();

            //if (days == 0)
            //{
            //    days = monitoredPath.Days == 0 ? Convert.ToInt32(Startup.Configuration["Defaults:DefaultDays"]) : monitoredPath.Days;
            //}

            DirectoryInfo[] directoriesToScan;
            if (!string.IsNullOrWhiteSpace(repository))
            {
                directoriesToScan = new DirectoryInfo(monitoredPath.Path).GetDirectories(repository, SearchOption.TopDirectoryOnly);
            }
            else
            {
                if (monitoredPath.AllFolders)
                {
                    directoriesToScan = new DirectoryInfo(monitoredPath.Path).GetDirectories("*", SearchOption.TopDirectoryOnly);
                }
                else
                {
                    directoriesToScan = new DirectoryInfo[monitoredPath.Repositories.Count];
                    int i = 0;
                    foreach (var dir in monitoredPath.Repositories)
                    {
                        directoriesToScan[i++] = new DirectoryInfo(Path.Combine(monitoredPath.Path, dir.Name));
                    }
                }
            }

            //if (days == 0)
            //{
            //    days = Convert.ToInt32(Startup.Configuration["Defaults:DefaultDays"]);
            //}

            if (days > 0)
            {
                days = days * -1;
            }

            MonitoredPath newmonitoredPath = new MonitoredPath();

            foreach (var dir in directoriesToScan)
            {
                try
                {
                    GitRepository gitrepo = this.TryGetRepo(monitoredPath, dir.Name);
                    using (var repo = new Repository(dir.FullName))
                    {
                        DateTime startDate   = DateTime.Now.AddDays(days);
                        int      commitCount = 0;
                        if (string.IsNullOrEmpty(branchName))
                        {
                            branchName = "master";
                        }

                        string branch = repo.Info.IsBare ? branchName : $"origin/{branchName}";
                        gitrepo.Branch = branch;
                        foreach (
                            LibGit2Sharp.Commit com in
                            repo.Branches[branch].Commits.Where(s => s.Committer.When >= startDate)
                            .OrderByDescending(s => s.Author.When))
                        {
                            if (!monitoredPath.IncludeMergeCommits)
                            {
                                // filter out merge commits
                                if (com.Parents.Count() > 1)
                                {
                                    continue;
                                }
                            }

                            //string[] nameexclusions = Startup.Configuration["Defaults:DefaultUserNameExcludeFilter"].Split(',');
                            //if (nameexclusions.Any(name => com.Author.Name.Contains(name)))
                            //{
                            //    continue;
                            //}

                            string url = string.IsNullOrWhiteSpace(gitrepo.CommitUrl)
                                ? string.Empty
                                : string.Format($"{gitrepo.CommitUrl}{com.Sha}");
                            string repositoryUrl = string.Empty;
                            if (repo.Network.Remotes?["origin"] != null)
                            {
                                repositoryUrl = repo.Network.Remotes["origin"].Url;
                            }

                            commits.Add(new GitCommit
                            {
                                Author                 = com.Author.Name,
                                AuthorEmail            = string.IsNullOrWhiteSpace(com.Author.Email) ? string.Empty : com.Author.Email,
                                AuthorWhen             = com.Author.When.UtcDateTime,
                                Committer              = com.Committer.Name,
                                CommitterEmail         = string.IsNullOrWhiteSpace(com.Committer.Email) ? string.Empty : com.Committer.Email,
                                CommitterWhen          = com.Committer.When.UtcDateTime,
                                Sha                    = com.Sha,
                                Message                = com.Message,
                                RepositoryFriendlyName = gitrepo.FriendlyName,
                                RepositoryName         = dir.Name,
                                RepositoryUrl          = repositoryUrl,
                                CommitUrl              = url,
                                IsMerge                = com.Parents.Count() > 1
                            });
                            commitCount++;
                        }

                        gitrepo.CommitCount = commitCount;
                        newmonitoredPath.Repositories.Add(gitrepo);
                        newmonitoredPath.AllowFetch = monitoredPath.AllowFetch;
                    }

                    newmonitoredPath.Name        = monitoredPath.Name;
                    newmonitoredPath.AllowFetch  = monitoredPath.AllowFetch;
                    newmonitoredPath.AllFolders  = monitoredPath.AllFolders;
                    newmonitoredPath.Days        = days;
                    newmonitoredPath.Path        = monitoredPath.Path;
                    newmonitoredPath.CommitCount = commits.Count;
                    newmonitoredPath.Commits     = commits;
                    newmonitoredPath.Commits.Sort((x, y) => - DateTime.Compare(x.CommitterWhen, y.CommitterWhen));
                }
                catch (Exception ex)
                {
                    this.locallogger.LogError("GetMonitoredItem Bad - ", ex);
                }
            }

            return(newmonitoredPath);
        }
        public RepositoryGraph(string repository)
        {
            this.workingDirectory = repository;

            _repository = RepositoryManager.Instance.GetTrackerForPath(workingDirectory);
        }
Exemplo n.º 42
0
        private static int GetCommitHeight(GitRepository repository, GitCommit startingCommit, GitWalkTracker tracker, Func <GitCommit, bool>?continueStepping)
        {
            if (continueStepping is object && !continueStepping(startingCommit))
            {
                return(0);
            }

            var commitsToEvaluate = new Stack <GitCommit>();

            bool TryCalculateHeight(GitCommit commit)
            {
                // Get max height among all parents, or schedule all missing parents for their own evaluation and return false.
                int  maxHeightAmongParents = 0;
                bool parentMissing         = false;

                foreach (GitObjectId parentId in commit.Parents)
                {
                    var parent = repository.GetCommit(parentId);
                    if (!tracker.TryGetVersionHeight(parent, out int parentHeight))
                    {
                        if (continueStepping is object && !continueStepping(parent))
                        {
                            // This parent isn't supposed to contribute to height.
                            continue;
                        }

                        commitsToEvaluate.Push(parent);
                        parentMissing = true;
                    }
                    else
                    {
                        maxHeightAmongParents = Math.Max(maxHeightAmongParents, parentHeight);
                    }
                }

                if (parentMissing)
                {
                    return(false);
                }

                var versionOptions = tracker.GetVersion(commit);
                var pathFilters    = versionOptions?.PathFilters;

                var includePaths =
                    pathFilters
                    ?.Where(filter => !filter.IsExclude)
                    .Select(filter => filter.RepoRelativePath)
                    .ToList();

                var excludePaths = pathFilters?.Where(filter => filter.IsExclude).ToList();

                var ignoreCase = repository.IgnoreCase;

                /*
                 * bool ContainsRelevantChanges(IEnumerable<TreeEntryChanges> changes) =>
                 *  excludePaths.Count == 0
                 *      ? changes.Any()
                 *      // If there is a single change that isn't excluded,
                 *      // then this commit is relevant.
                 *      : changes.Any(change => !excludePaths.Any(exclude => exclude.Excludes(change.Path, ignoreCase)));
                 */

                int height = 1;

                if (pathFilters != null)
                {
                    var relevantCommit = true;

                    foreach (var parentId in commit.Parents)
                    {
                        var parent = repository.GetCommit(parentId);
                        relevantCommit = IsRelevantCommit(repository, commit, parent, pathFilters);

                        // If the diff between this commit and any of its parents
                        // does not touch a path that we care about, don't bump the
                        // height.
                        if (!relevantCommit)
                        {
                            break;
                        }
                    }

                    /*
                     * // If there are no include paths, or any of the include
                     * // paths refer to the root of the repository, then do not
                     * // filter the diff at all.
                     * var diffInclude =
                     *  includePaths.Count == 0 || pathFilters.Any(filter => filter.IsRoot)
                     *      ? null
                     *      : includePaths;
                     *
                     * // If the diff between this commit and any of its parents
                     * // does not touch a path that we care about, don't bump the
                     * // height.
                     * var relevantCommit =
                     *  commit.Parents.Any()
                     *      ? commit.Parents.Any(parent => ContainsRelevantChanges(commit.GetRepository().Diff
                     *          .Compare<TreeChanges>(parent.Tree, commit.Tree, diffInclude, DiffOptions)))
                     *      : ContainsRelevantChanges(commit.GetRepository().Diff
                     *          .Compare<TreeChanges>(null, commit.Tree, diffInclude, DiffOptions));
                     */

                    if (!relevantCommit)
                    {
                        height = 0;
                    }
                }

                tracker.RecordHeight(commit, height + maxHeightAmongParents);
                return(true);
            }

            commitsToEvaluate.Push(startingCommit);
            while (commitsToEvaluate.Count > 0)
            {
                GitCommit commit = commitsToEvaluate.Peek();
                if (tracker.TryGetVersionHeight(commit, out _) || TryCalculateHeight(commit))
                {
                    commitsToEvaluate.Pop();
                }
            }

            Assumes.True(tracker.TryGetVersionHeight(startingCommit, out int result));
            return(result);
        }