gpt4 book ai didi

libgit2 - 查找指向提交的标签的最快方法是什么?

转载 作者:行者123 更新时间:2023-12-02 21:14:49 27 4
gpt4 key购买 nike

使用 libgit2sharp 我想执行以下操作:

foreach( Commit commit in repo.Commits )
{
// How to implement assignedTags?
foreach( Tag tag in commit.assignedTags ) {}
}

我想获取分配给当前提交的所有标签。最好的方法是什么?遍历所有标签并查看是否 tag.Target.Sha == commit.Sha?那不是很高效。还有别的办法吗?

最佳答案

So I want to get all tags assigned to the current commit. Whats the best way to do that? Iterate through all Tags and see if tag.Target.Sha == commit.Sha? Thats not very performant. Is there another way?

涉及标签时需要考虑两件事。

  • 标签可以指向提交以外的其他内容(例如,树或 Blob)
  • 一个标签可以指向另一个标签(链式注释标签)

考虑到上述几点,下面的代码应该可以满足您的需求。

注意: repo.Commits 只会枚举可从当前分支 (HEAD) 访问的提交。下面的代码扩展它可以轻松浏览所有可到达的提交。

...

using (var repo = new Repository("Path/to/your/repo"))
{
// Build up a cached dictionary of all the tags that point to a commit
var dic = TagsPerPeeledCommitId(repo);

// Let's enumerate all the reachable commits (similarly to `git log --all`)
foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter {Since = repo.Refs}))
{
foreach (var tags in AssignedTags(commit, dic))
{
Console.WriteLine("Tag {0} points at {1}", tags.Name, commit.Id);
}
}
}

....

private static IEnumerable<Tag> AssignedTags(Commit commit, Dictionary<ObjectId, List<Tag>> tags)
{
if (!tags.ContainsKey(commit.Id))
{
return Enumerable.Empty<Tag>();
}

return tags[commit.Id];
}

private static Dictionary<ObjectId, List<Tag>> TagsPerPeeledCommitId(Repository repo)
{
var tagsPerPeeledCommitId = new Dictionary<ObjectId, List<Tag>>();

foreach (Tag tag in repo.Tags)
{
GitObject peeledTarget = tag.PeeledTarget;

if (!(peeledTarget is Commit))
{
// We're not interested by Tags pointing at Blobs or Trees
continue;
}

ObjectId commitId = peeledTarget.Id;

if (!tagsPerPeeledCommitId.ContainsKey(commitId))
{
// A Commit may be pointed at by more than one Tag
tagsPerPeeledCommitId.Add(commitId, new List<Tag>());
}

tagsPerPeeledCommitId[commitId].Add(tag);
}

return tagsPerPeeledCommitId;
}

关于libgit2 - 查找指向提交的标签的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19808208/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com