Tow*_*wer 4 c# git libgit2 libgit2sharp
我正在循环提交LibGit2Sharp:
Repository repo = new Repository("Z:/www/gg");
foreach (LibGit2Sharp.Commit commit in repo.Commits)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我可以检索像Author和的属性Message,但我没有看到它属于哪个分支?理想情况下,我希望有一个指向分支对象的指针,但在这种情况下,即使名称也没问题.
这是调试器显示的内容:

这就是我要找的东西:

TortoiseGit显示最相关分支名称的行为:

示例存储库:https://docs.google.com/open?id = 0B-3-X85VysdNcmZIaGVTSDZSenVGbTJxYlI2SUlsZw
目前没有内置的模仿方式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;
}
}
Run Code Online (Sandbox Code Playgroud)
注意:此代码已成功针对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;
}
}
Run Code Online (Sandbox Code Playgroud)