Exemple #1
0
 /// <summary>
 /// Calculate most frequent contributor for list of commits.
 /// </summary>
 /// <param name="commits"></param>
 /// <returns></returns>
 private static LibGit2Sharp.Signature GetMostFrequentContributor(ICommitLog commits)
 {
     return(commits.GroupBy(x => x.Author)
            .Select(x => new { Author = x.Key, CommitsCount = x.Count() })
            .OrderBy(x => x.CommitsCount)
            .FirstOrDefault()?.Author);
 }
Exemple #2
0
        public IEnumerable <CommitAggregate> Get()
        {
            ICommitLog commitLog = _repo.Commits.QueryBy(new CommitFilter());

            IEnumerator <LibGit2Sharp.Commit> commitEnumerator = commitLog.GetEnumerator();

            commitEnumerator.MoveNext();
            LibGit2Sharp.Commit previousCommit = commitEnumerator.Current;

            while (commitEnumerator.MoveNext())
            {
                // As the enumerator reads the history top down, the current enumerator value
                // is the older commit. Therefore, the previousCommit is the newer commit.
                Tree  olderCommitTree  = commitEnumerator.Current.Tree;
                Tree  newerCommmitTree = previousCommit.Tree;
                Patch patch            = _repo.Diff.Compare <Patch>(olderCommitTree, newerCommmitTree);
                previousCommit = commitEnumerator.Current;

                yield return(new CommitAggregate
                {
                    Commit = commitEnumerator.Current,
                    Changes = patch
                });
            }
        }
Exemple #3
0
        private Commit FindMostRecentCommitBefore(ICommitLog commits, DateTime beforeDateTime)
        {
            var mostRecentCommit = commits
                                   .Where(c => c.Author.When < beforeDateTime)
                                   .Aggregate((Commit)null, (curMax, c) => (curMax == null || c.Author.When > curMax.Author.When ? c : curMax));

            return(mostRecentCommit);
        }
        private static void AssertEnumerationOfCommitsInRepo(IRepository repo, Func <IRepository, CommitFilter> filterBuilder, IEnumerable <string> abbrevIds)
        {
            ICommitLog commits = repo.Commits.QueryBy(filterBuilder(repo));

            IEnumerable <string> commitShas = commits.Select(c => c.Id.ToString(7)).ToArray();

            Assert.Equal(abbrevIds, commitShas);
        }
 private void ProcessCommits(ICommitLog commits)
 {
     foreach (var commit in commits)
     {
         var message = RemovePullRequestSubstring(commit.Message);
         AddTicketNumbersFrom(message);
         IncrementNumberOfCommits();
     }
 }
        public Statistics(ICommitLog commits)
        {
            TicketNumbers   = new List <int>();
            NumberOfCommits = 0;
            Points          = 0;
            LastCommitSha   = commits.First().Sha;

            ProcessCommits(commits);
        }
Exemple #7
0
        private Commit FindVersionSynchronizationEnabledCommit(ICommitLog commits)
        {
            var syncEnabledCommitMessage = "TeamCity change in '<Root project>' project: Synchronization with own VCS root is enabled";
            var syncEnabledCommit        = commits.First(c => c.Message == syncEnabledCommitMessage);

            if (syncEnabledCommit == null)
            {
                throw new Exception("Cannot find commit with \"{syncEnabledCommitMessage}\" message.");
            }

            return(syncEnabledCommit);
        }
        IEnumerable <Migrator> GetLogMigrators(IRepository repository, ICommitLog log, List <IMigration> deferred, Commit previousCommit, MigrationMode mode)
        {
            foreach (var commit in log)
            {
                if (previousCommit != null)
                {
                    var migrations = GetCommitMigrations(repository, previousCommit, commit).ToList();

                    deferred.AddRange(migrations.Where(m => m.IsIdempotent));

                    migrations.RemoveAll(m => m.IsIdempotent);
                    if (migrations.Any())
                    {
                        yield return(new Migrator(migrations.Where(m => !m.IsIdempotent).ToImmutableList(), mode, commit.Id));
                    }
                }
                previousCommit = commit;
            }
        }
Exemple #9
0
        private IEnumerable <Migrator> GetLogMigrators(IRepository repository, ICommitLog log, List <IMigration> deferred, Commit previousCommit, MigrationMode mode)
        {
            var context    = new ModelObjectSerializationContext(_container);
            var serializer = _repositorySerializerFactory(context);

            foreach (var commit in log)
            {
                if (previousCommit != null)
                {
                    var migrations = GetCommitMigrations(repository, previousCommit, commit, serializer).ToList();

                    deferred.AddRange(migrations.Where(m => m.IsIdempotent));

                    migrations.RemoveAll(m => m.IsIdempotent);
                    if (migrations.Any())
                    {
                        yield return(new Migrator(migrations.Where(m => !m.IsIdempotent).ToImmutableList(), mode, commit.Id));
                    }
                }
                previousCommit = commit;
            }
        }
Exemple #10
0
 private void updateDropdownList()
 {
     // init repo
     if (tb_ondisk.Text.Length > 0)
     {
         git = new Repository(tb_ondisk.Text);
         List <BisectStep> bss     = new List <BisectStep>();
         StringBuilder     sb      = new StringBuilder();
         ICommitLog        commits = git.Branches["master"].Commits;
         for (int i = commits.Count() - 1; i >= 0; i--)
         {
             bss.Add(new BisectStep(commits.ElementAt(i)));
         }
         steps = bss.ToArray();
         cb_from.DataSource = bss;
         cb_from.Enabled    = cb_to.Enabled = b_start.Enabled = true;
     }
     else
     {
         cb_from.Enabled = cb_to.Enabled = b_start.Enabled = false;
     }
 }
 public UnknownBranch(DateTimeOffset when)
 {
     commits_ = new UnknownCommitLog(when);
 }
 private static DateTime GetFirstCommit(ICommitLog commitLog)
 {
     return(commitLog.Last().Author.When.Date);
 }
        public List <Commit> Get(String path, String username, String password, String branch)
        {
            DirectoryInfo di = new DirectoryInfo("tempRepo/");

            if (di.Exists)
            {
                BranchController.setAttributesNormal(di);
                di.Delete(true);
            }
            string clone;

            if (username != null && password != null)
            {
                var cloneOptions = new CloneOptions()
                {
                    CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
                    {
                        Username = username,
                        Password = password
                    }
                };
                clone = Repository.Clone(path, "tempRepo/", cloneOptions);
            }
            else
            {
                clone = Repository.Clone(path, "tempRepo/");
            }
            var list = new List <Commit>();

            using (var repo = new Repository(@clone))
            {
                // Object lookup
                var obj    = repo.Lookup("sha");
                var commit = repo.Lookup <LibGit2Sharp.Commit>("sha");
                var tree   = repo.Lookup <Tree>("sha");
                // var tag = repo.Lookup<Tag>("sha");

                ICommitLog commits = null;

                if (branch == null)
                {
                    commits = repo.Head.Commits;
                }
                else
                {
                    commits = repo.Branches[branch].Commits;
                }

                foreach (var tempCommit in commits.Take(100))
                {
                    string message;
                    string type = "None";
                    if (tempCommit.Message.Contains(":"))
                    {
                        string[] strings = tempCommit.Message.Split(":");
                        message = strings[1];
                        type    = strings[0];
                    }
                    else
                    {
                        message = tempCommit.Message;
                    }

                    var commitObj = new Commit
                    {
                        author = tempCommit.Author, commiter = tempCommit.Committer, message = message, type = type
                    };
                    list.Add(commitObj);
                }

                return(list);

                // Branches
                // special kind of reference
            }
        }
 internal CommitCollection(ICommitLog collection) => this.innerCollection = collection.NotNull();
Exemple #15
0
        private static IEnumerable <Tuple <ObjectId, ObjectId> > SplitRepository(Repository baseRepo, ICommitLog commits, string name, string path, IEnumerable <SharedRepo> sharedRepos, IEnumerable <MergedRepo> mergedRepos)
        {
            var shared = sharedRepos.Where(r => r.Paths.Any(p => p.StartsWith(path + "/"))).Select(r => new
            {
                Repo    = "../" + r.Name + ".git",
                Path    = r.Paths.First(p => p.StartsWith(path + "/")).Substring(path.Length + 1),
                Commits = r.Commits
            });
            var merged = mergedRepos.Where(r => r.Name == name);

            using (var repo = new Repository(Repository.Init(Path.Combine("output", name))))
            {
                File.Copy(Path.Combine(Config.Instance.MainRepo, ".gitignore"), Path.Combine("output", name, ".gitignore"));
                repo.Index.Add(".gitignore");
                File.Copy(Path.Combine(Config.Instance.MainRepo, ".gitattributes"), Path.Combine("output", name, ".gitattributes"));
                repo.Index.Add(".gitattributes");

                foreach (var toMerge in merged)
                {
                    using (var mergeRepo = new Repository(toMerge.Repo))
                    {
                        foreach (var c in mergeRepo.Commits.QueryBy(new CommitFilter {
                            SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Reverse
                        }))
                        {
                            bool any = false;

                            foreach (var m in toMerge.Mapping)
                            {
                                if (Merge(repo, c, m.Key, m.Value))
                                {
                                    any = true;
                                }
                            }

                            if (any)
                            {
                                var rewrittenCommit = repo.Commit(c.Message, new Signature(c.Author.Name, Config.Instance.MapEmail(c.Author.Email), c.Author.When), new Signature(c.Committer.Name, Config.Instance.MapEmail(c.Author.Email), c.Author.When), new CommitOptions {
                                    AllowEmptyCommit = true
                                });
                                yield return(new Tuple <ObjectId, ObjectId>(c.Id, rewrittenCommit.Id));
                            }
                        }
                    }
                    repo.Index.Clear();
                    repo.Index.Add(".gitignore");
                    repo.Index.Add(".gitattributes");
                }

                if (shared.Any())
                {
                    File.WriteAllText(Path.Combine("output", name, ".gitmodules"), string.Join("", shared.Select(s => $"[submodule \"{s.Path}\"]\n    path = {s.Path}\n    url = {s.Repo}\n")));
                    repo.Index.Add(".gitmodules");
                }

                foreach (var c in commits)
                {
                    if (c.Tree[path] == null)
                    {
                        continue;
                    }

                    TreeDefinition tree = null;
                    foreach (var s in shared)
                    {
                        var mapping = s.Commits.FirstOrDefault(commit => c.Id == commit.Item1);
                        if (mapping != null)
                        {
                            if (tree == null)
                            {
                                var tempCommit = repo.Commit("temp", new Signature("temp", "*****@*****.**", DateTimeOffset.UtcNow), new Signature("temp", "*****@*****.**", DateTimeOffset.UtcNow), new CommitOptions {
                                    AllowEmptyCommit = true
                                });
                                tree = TreeDefinition.From(tempCommit);
                                repo.Reset(ResetMode.Soft, tempCommit.Parents.First());
                            }
                            tree.AddGitLink(s.Path, mapping.Item2);
                        }
                    }
                    if (tree != null)
                    {
                        repo.Index.Replace(repo.ObjectDatabase.CreateTree(tree));
                    }

                    var oldTree = c.Parents.FirstOrDefault()?.Tree?[path]?.Target as Tree;
                    if (oldTree != null)
                    {
                        var diff = baseRepo.Diff.Compare <TreeChanges>(oldTree, (Tree)c.Tree[path].Target);
                        if (!diff.Any())
                        {
                            continue;
                        }
                        foreach (var file in diff)
                        {
                            if (file.Mode == Mode.Directory)
                            {
                                continue;
                            }

                            if (!file.Exists || (file.OldPath != file.Path && file.Status != ChangeKind.Copied))
                            {
                                if (!shared.Any(s => file.OldPath.Replace('\\', '/').StartsWith(s.Path + '/')))
                                {
                                    File.Delete(Path.Combine("output", name, file.OldPath));
                                    repo.Index.Remove(file.OldPath);
                                }
                            }

                            if (file.Exists)
                            {
                                if (!shared.Any(s => file.Path.Replace('\\', '/').StartsWith(s.Path + '/')))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine("output", name, file.Path)));
                                    using (var input = baseRepo.Lookup <Blob>(file.Oid).GetContentStream())
                                        using (var output = File.Create(Path.Combine("output", name, file.Path)))
                                        {
                                            input.CopyTo(output);
                                        }
                                    repo.Index.Add(file.Path);
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (var entry in RecursiveTree((Tree)c.Tree[path].Target, path))
                        {
                            if (shared.Any(s => entry.Item1.Replace('\\', '/').StartsWith(s.Path + '/')))
                            {
                                continue;
                            }
                            var fullPath = Path.Combine("output", name, entry.Item1);
                            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
                            using (var content = entry.Item2.GetContentStream())
                                using (var output = File.Create(fullPath))
                                {
                                    content.CopyTo(output);
                                }
                            repo.Index.Add(entry.Item1);
                        }
                    }

                    var email           = Config.Instance.MapEmail(c.Author.Email);
                    var rewrittenCommit = repo.Commit(c.Message, new Signature(c.Author.Name, email, c.Author.When), new Signature(c.Committer.Name, email, c.Author.When), new CommitOptions {
                        AllowEmptyCommit = true
                    });
                    yield return(new Tuple <ObjectId, ObjectId>(c.Id, rewrittenCommit.Id));
                }

                repo.Network.Remotes.Add("origin", Config.Instance.Origin(name));

                Console.WriteLine("Copying LFS files...");
                var lfsCount = CopyLfsFiles(repo, Path.Combine("output", name, ".git", "lfs", "objects"), new[] { Path.Combine(baseRepo.Info.WorkingDirectory, ".git", "lfs", "objects") }.Concat(merged.Where(r => r.Name == name).Select(r => Path.Combine(r.Repo, ".git", "lfs", "objects"))));
                Console.WriteLine($"Copied {lfsCount} files.");

                // LibGit2Sharp doesn't support git gc, so we use the command line:
                using (var gc = Process.Start(new ProcessStartInfo("git", "gc --aggressive")
                {
                    WorkingDirectory = repo.Info.WorkingDirectory,
                    UseShellExecute = false
                }))
                {
                    gc.WaitForExit();
                }
            }
        }
 internal CommitCollection(ICommitLog collection) => innerCollection = collection;
 public UnknownBranch(DateTimeOffset when)
 {
     commits_ = new UnknownCommitLog(when);
 }
 public MockQueryableCommitLog(ICommitLog commits)
 {
     this.commits = commits;
 }
 public MockQueryableCommitLog(ICommitLog commits)
 {
     this.commits = commits;
 }