我在 LibGit2Sharp
中循环提交:
Repository repo = new Repository("Z:/www/gg");
foreach (LibGit2Sharp.Commit commit in repo.Commits)
{
...
}
我可以检索 Author
和 Message
等属性,但我看不到它属于哪个分支?理想情况下,我希望有一个指向分支对象的指针,但在这种情况下,即使是名称也可以。
这是调试器显示的内容:
这就是我要找的:
TortoiseGit 显示最相关分支名称的行为:
示例存储库:https://docs.google.com/open?id=0B-3-X85VysdNcmZIaGVTSDZSenVGbTJxYlI2SUlsZw
最佳答案
目前没有内置的方式来模仿git branch --contains <commit>
.
但是,您可以通过显式遍历每个分支并将每个 pop 的提交与搜索到的提交进行比较来解决此限制。
下面的测试证明了这一点
[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;
}
}
注意:此代码已针对 the current tip of the development 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;
}
}
关于c# - 在 LibGit2Sharp 中找出提交所属的分支?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9452092/