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

use*_*329 6 libgit2 libgit2sharp

使用libgit2sharp我想做以下事情:

foreach( Commit commit in repo.Commits )
{
    // How to implement assignedTags?
    foreach( Tag tag in commit.assignedTags ) {}
}
Run Code Online (Sandbox Code Playgroud)

我想将所有标签分配给当前提交.什么是最好的方法呢?迭代所有标签,看看是否tag.Target.Sha == commit.Sha?多数表现不太好.还有另外一种方法吗?

nul*_*ken 8

所以我想将所有标签分配给当前提交.什么是最好的方法呢?迭代所有标签,看看是否tag.Target.Sha == commit.Sha?多数表现不太好.还有另外一种方法吗?

在标签方面,有两件事需要考虑.

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

下面的代码应该考虑到上述这些要点,以满足您的需求.

注意: repo.Commits只会枚举当前branch(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;
}
Run Code Online (Sandbox Code Playgroud)