Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the last commit for a folder using LibGit2Sharp?

Tags:

libgit2sharp

I've got a large number of projects all in a single repository. I want to determine the volatility of all of these projects, i.e., when there was last a commit that affected each project. I've got a list of all of the project paths, and I'm trying to find the last commit for each one. My code looks like this:

    public CommitInfo GetLastCommit(string path)
    {
        // resolve any \..\ and pathing weirdness
        path = Path.GetDirectoryName(Path.GetFullPath(path));

        var relativePath = path.Substring(BaseRepoPath.Length + 1).Replace("\\", "/");

        if (!CommitCache.TryGetValue(relativePath, out CommitInfo result))
        {
            var options = new RepositoryOptions()
            {
                WorkingDirectoryPath = BaseRepoPath
            };

            using (var repo = new Repository(BaseRepoPath, options))
            {
                var filter = new CommitFilter()
                {
                    IncludeReachableFrom = BranchName
                };

                var commit =  repo.Commits.QueryBy(relativePath, filter).First().Commit;

                result = new CommitInfo
                {
                    When = commit.Author.When.DateTime,
                    Who = commit.Author.Name,
                    Message = commit.Message,
                    Files = commit.Tree.Select(x => x.Name).ToList()
                };

                repo.Dispose();
            }

            CommitCache.Add(relativePath, result);
        }

        return result;
    }

This works, but the line where the commit is actually retrieved:

var commit =  repo.Commits.QueryBy(relativePath, filter).First().Commit;

Can take up to eight minutes to complete. As far as I can tell, there's nothing especially complex about those folders...a sample of them reveals maybe twenty commits. I suspect I'm doing something wrong like loading the entire repo graph when I need something more specific, but I haven't been able to figure out a better way.

Thoughts?

like image 893
Chris B. Behrens Avatar asked Dec 03 '18 17:12

Chris B. Behrens


1 Answers

Your requirement is producing following git command through lib2gitsharp package.

$ git log -1 -C "relativePath"

You can limit the size of commits with the help of Take(numberOfCommits) extension in lib2gitsharp. Please have a try with putting Take(1) before your First() like following;

var commit =  repo.Commits.QueryBy(relativePath, filter).Take(1).First().Commit;

Hope this helps.

like image 93
Ayberk Avatar answered Oct 11 '22 13:10

Ayberk