目前没有内置的方法来模仿git branch --contains <commit>
.
但是,您可以通过显式遍历每个分支并将每个弹出的提交与搜索的提交进行比较来解决此限制。
以下测试证明了这一点
[Test]
public void CanSearchBranchesContainingASpecificCommit()
{
using (var repo = new Repository(StandardTestRepoPath))
{
const string commitSha = "5b5b025afb0b4c913b4c338a42934a3863bf3644";
IEnumerable<Branch> branches = ListBranchesContaininingCommit(repo, commitSha);
branches.Count().ShouldEqual(6);
}
}
private IEnumerable<Branch> ListBranchesContaininingCommit(Repository repo, string commitSha)
{
foreach (var branch in repo.Branches)
{
var commits = repo.Commits.QueryBy(new CommitFilter { Since = branch }).Where(c => c.Sha == commitSha);
if (!commits.Any())
{
continue;
}
yield return branch;
}
}
注意:此代码已针对LibGit2Sharp开发分支的当前提示成功测试。
更新:
在评论中的讨论之后,这里有一些更新,希望能满足您的要求。
下面的代码将返回包含搜索到的提交的所有分支。如果提交恰好是至少一个分支的尖端,则将返回这些分支。
[Test]
public void CanSearchBranchesContainingASpecificCommit()
{
using (var repo = new Repository(StandardTestRepoPath))
{
const string commitSha = "5b5b025afb0b4c913b4c338a42934a3863bf3644";
IEnumerable<Branch> branches = ListBranchesContaininingCommit(repo, commitSha);
branches.Count().ShouldEqual(6);
const string otherCommitSha = "4a202b346bb0fb0db7eff3cffeb3c70babbd2045";
branches = ListBranchesContaininingCommit(repo, otherCommitSha);
branches.Count().ShouldEqual(1); // origin/packed-test
}
}
private IEnumerable<Branch> ListBranchesContaininingCommit(Repository repo, string commitSha)
{
bool directBranchHasBeenFound = false;
foreach (var branch in repo.Branches)
{
if (branch.Tip.Sha != commitSha)
{
continue;
}
directBranchHasBeenFound = true;
yield return branch;
}
if (directBranchHasBeenFound)
{
yield break;
}
foreach (var branch in repo.Branches)
{
var commits = repo.Commits.QueryBy(new CommitFilter { Since = branch }).Where(c => c.Sha == commitSha);
if (!commits.Any())
{
continue;
}
yield return branch;
}
}