11

如何获取包含特定文件的提交列表,即相当于git log pathfor LibGit2Sharp

它没有被实施还是有我遗漏的方法?

4

4 回答 4

5

我正在努力使用 LibGit2Sharp 将相同的功能添加到我的应用程序中。

我编写了下面的代码,它将列出包含该文件的所有提交。不包括 GitCommit 类,但它只是属性的集合。

我的意图是让代码仅列出文件已更改的提交,类似于 SVN 日志,但我还没有写那部分。

请注意,代码尚未优化,这只是我的初步尝试,但我希望它会有用。

/// <summary>
/// Loads the history for a file
/// </summary>
/// <param name="filePath">Path to file</param>
/// <returns>List of version history</returns>
public List<IVersionHistory> LoadHistory(string filePath)
{
    LibGit2Sharp.Repository repo = new Repository(this.pathToRepo);

    string path = filePath.Replace(this.pathToRepo.Replace(System.IO.Path.DirectorySeparatorChar + ".git", string.Empty), string.Empty).Substring(1);
    List<IVersionHistory> list = new List<IVersionHistory>();

    foreach (Commit commit in repo.Head.Commits)
    {
        if (this.TreeContainsFile(commit.Tree, path) && list.Count(x => x.Date == commit.Author.When) == 0)
        {
            list.Add(new GitCommit() { Author = commit.Author.Name, Date = commit.Author.When, Message = commit.MessageShort} as IVersionHistory);
        }
    }

    return list;
}

/// <summary>
/// Checks a GIT tree to see if a file exists
/// </summary>
/// <param name="tree">The GIT tree</param>
/// <param name="filename">The file name</param>
/// <returns>true if file exists</returns>
private bool TreeContainsFile(Tree tree, string filename)
{
    if (tree.Any(x => x.Path == filename))
    {
        return true;
    }
    else
    {
        foreach (Tree branch in tree.Where(x => x.Type == GitObjectType.Tree).Select(x => x.Target as Tree))
        {
            if (this.TreeContainsFile(branch, filename))
            {
                return true;
            }
        }
    }

    return false;
}
于 2012-10-29T15:53:58.417 回答
4

LibGit2Sharp来自 C 库libgit2 ...它首先没有包含git log;)

然而,LibGit2Sharp 有它自己的git log功能:
它的页面git log涉及Filters,但 Filter 似乎没有按路径过滤(详见“如何在查询 refs 时排除存储? ”)。
所以目前似乎没有实施。

于 2012-10-29T13:13:39.317 回答
4

每次更改树/blob 时,它都会获得新的 id 哈希。您只需要与父提交树/blob 项目哈希进行比较:

var commits = repository.Commits
   .Where(c => c.Parents.Count() == 1 && c.Tree["file"] != null &&
      (c.Parents.FirstOrDefault().Tree["file"] == null ||
         c.Tree["file"].Target.Id !=
         c.Parents.FirstOrDefault().Tree["file"].Target.Id));
于 2014-02-11T16:16:46.500 回答
1

与 dmck 的答案非常相似,但更新的更多

private bool TreeContainsFile(Tree tree, string filePath)
{
    //filePath is the relative path of your file to the root directory
    if (tree.Any(x => x.Path == filePath))
    {
        return true;
    }

    return tree.Where(x => x.GetType() == typeof (TreeEntry))
        .Select(x => x.Target)
        .OfType<Tree>()
        .Any(branch => TreeContainsFile(branch, filePath));
}
于 2016-07-06T06:17:35.287 回答