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

夙愿已清 提交于 2019-12-10 14:33:26

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/53598990/how-can-i-get-the-last-commit-for-a-folder-using-libgit2sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!