0

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.

Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
TlmaK0
  • 3,578
  • 2
  • 31
  • 51
  • If you feel an answer solved the problem, please mark it as 'accepted' by clicking the green check mark. This helps keep the focus on older posts which still don't have answers. – Rüdiger Herrmann Jul 10 '16 at 00:17

1 Answers1

0

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

Community
  • 1
  • 1
Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
  • Thanks Rüdiger, but unfutunally git doesn't have NameRev() method in NGit. – TlmaK0 Jul 11 '16 at 08:16
  • I did this before to post the question, but no matching id between commit Id and tagref.objectId. I don't know if it is a bug because NGit has more than 3 years without maintenance. Finally I have changed to libgit2sharp and I have fixed the problem. – TlmaK0 Jul 11 '16 at 12:03
  • @TlmaK0 I'd suggest to delete this question then. – Rüdiger Herrmann Jul 11 '16 at 13:30