如何获取包含特定文件的提交列表,即相当于 LibGit2Sharp
的 git log path
命令。
这个功能是否已经实现或者我是否遗漏了某些方法?
如何获取包含特定文件的提交列表,即相当于 LibGit2Sharp
的 git log path
命令。
这个功能是否已经实现或者我是否遗漏了某些方法?
/// <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;
}
IVersionHistory
是什么? - toofarsidewaysLibGit2Sharp源自C库libgit2......该库一开始并没有包含git log
;)
然而,LibGit2Sharp有自己的git log
函数:
它的git log
页面涉及过滤器,但是一个过滤器似乎不能按路径过滤(正如在"如何在查询引用时排除存储?"中详细说明的那样)。
因此,目前似乎还没有实现。
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));
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));
}