我正在尝试使用LibGit2Sharp重新创建git show-brach --independent的功能,根据docs的说法,它实现了以下功能:Among the <reference>s given, display only the ones that cannot be reached from any other <reference>.
到目前为止,我最好的尝试是:
List<Commit> GetIndependent(IRepository repo, IEnumerable<Commit> commits)
{
var indep = new List<Commit>();
foreach (var commit in commits)
{
if (repo.Commits.QueryBy(new CommitFilter
{
FirstParentOnly = false,
IncludeReachableFrom = commit,
ExcludeReachableFrom = commits.Where(x => x.Equals(commit) == false)
}).Any())
{
indep.Add(commit);
}
}
return indep;
}不幸的是,随着历史数据量的增加,这会变得极其缓慢。实际上,与使用上面的代码相比,直接执行git、解析输出并让LibGit2Sharp查找生成的SHA要快得多。我认为这与Git有一些优化有关,而LibGit2没有。这真的是我想要的吗?如果是这样的话,有没有更好的方法在LibGit2Sharp中实现这一点呢?
发布于 2017-08-15 04:12:01
多亏了this question为我指明了正确的方向,我终于找到了一种利用合并基础的更好的方法。
这是新的代码:
/// <summary>
/// Implementation of `git show-branch --indepenent`
///
/// "Among the <reference>s given, display only the ones that cannot be reached from any other <reference>"
/// </summary>
/// <param name="commitsToCheck"></param>
/// <returns></returns>
private List<Commit> GetIndependent(IRepository repo, IEnumerable<Commit> commitsToCheck)
{
var commitList = commitsToCheck.ToList();
for (var i = commitList.Count - 1; i > 0; --i)
{
var first = commitList[i];
for (var j = commitList.Count - 1; j >= 0; --j)
{
if (i == j) continue;
var second = commitList[j];
var mergeBase = repo.ObjectDatabase.FindMergeBase(first, second);
if (first.Equals(mergeBase))
{
// First commit (i) is reachable from second (j), so drop i
commitList.RemoveAt(i);
// No reason to check anything else against this commit
j = -1;
} else if (second.Equals(mergeBase))
{
// Second (j) is reachable from first, so drop j
commitList.RemoveAt(j);
// If this was at a lower index than i, dec i since we shifted one down
if (j < i)
{
--i;
}
}
}
}
return commitList;
}https://stackoverflow.com/questions/45469123
复制相似问题