Search code examples
libgit2sharp

How to easily get all Refs for a given Commit?


Is there an easy way to find all References (e.g. Tags) for a given Commit? For example:

using( Repository repo = new Repository( path_to_repo ) )
{
    foreach( Commit commit in repo.Commits )
    {
        List<Reference> assignedRefs = commit.Refs; // <- how to do this?
    }
}

Solution

  • The code below retrieves all the references that can reach the selected commit.

    using( Repository repo = new Repository( path_to_repo ) )
    {
        foreach( Commit commit in repo.Commits )
        {
            IEnumerable<Reference> refs =
                   repo.Refs.ReachableFrom(new[] { commit });
        }
    }
    

    If you want to only retrieve Tags, the method exposes an overload to help you with this.

    using( Repository repo = new Repository( path_to_repo ) )
    {
        var allTags = repo.Refs.Where(r => r.IsTag()).ToList();
    
        foreach( Commit commit in repo.Commits )
        {
            IEnumerable<Reference> refs =
                   repo.Refs.ReachableFrom(allTags, new[] { commit });
        }
    }
    

    Note: This code will retrieve all refs that either directly point to the chosen commit or point to an ancestor of this commit. In this sense, it behaves similarly to the git rev-list command.