How to get actual tag with NGit?

281 Views Asked by At

I need to know the current tag with NGit in a detached branch (after a git checkout tagname)

I have tried to list Git tags with

foreach(var tag in git.GetRepository().GetTags()){

}

but I was unable to find how to relate this tag with the last commit.

1

There are 1 best solutions below

3
On

Git does not store which tag is currently checked out. If you want to reliably access this information, you need to store it while separately while checking out the tag.

However, you can have Git list all refs that point to a certain commit.

ObjectId headCommitId = repository.resolve( Constants.HEAD );
Map<ObjectId, String> refs = git.nameRev()
  .add( headCommitId )
  .addPrefix( Constants.R_TAGS )
  .call();

The snippet is written in Java but should be easily translated to C#. It first resolves the HEAD reference and then calls the NameRevCommand to list all refs that point to this commit id.

addPrefix() limits the refs to those in the refs/tags/ namespace.

The returned Map holds the commit id (key) and the first ref pointing to it that could be found (value).

In your case, the tag that you checked out earlier should be among the returned refs. Be beware, if multiple tags were created for this commit, any of them could be returned - not necessarily the one that was checked out earlier.

EDIT 2016-07-11

Alternatively, you can obtain a list of all tags from the repository with git.tagList().call() and search for the tag that points to the commit in question.

See my answer to this question for the particularities of finding the commit id to which a tag points to: List commits associated with a given tag with JGit