Kamal
Kamal

Reputation: 325

JGit: Retrieve tag associated with a git commit

I want to use JGit API to retrieve the tags associated with a specific commit hash (if there is any)?

Please provide code snippet for the same.

Upvotes: 10

Views: 6888

Answers (3)

Nathan
Nathan

Reputation: 8920

This answer uses tagList(). After looking through the code in ListTagCommand, I came up with this simplified solution.

List<Ref> tags;
ObjectId commit;

commit = ObjectId.fromString("hash");

tags = m_git.
   getRepository().
   getRefDatabase().
   getRefsByPrefix(Constants.R_TAGS).
   stream().
   filter(ref -> ref.getObjectId().equals(commit)).
   collect(Collections.toList());

Upvotes: 0

Marcin Pietraszek
Marcin Pietraszek

Reputation: 3214

Git object model describes tag as an object containing information about specific object ie. commit (among other things) thus it's impossible in pure git to get information you want (commit object don't have information about related tags). This should be done "backwards", take tag object and then refer to specific commit.

So if you want get information about tags specified for particular commit you should iterate over them (tags) and choose appropriate.

List<RevTag> list = git.tagList().call();
ObjectId commitId = ObjectId.fromString("hash");
Collection<ObjectId> commits = new LinkedList<ObjectId>();
for (RevTag tag : list) {
    RevObject object = tag.getObject();
    if (object.getId().equals(commitId)) {;
        commits.add(object.getId());
    }
}

Upvotes: 12

Max Hohenegger
Max Hohenegger

Reputation: 1639

If you know that there is exactly one tag for your commit, you could use describe, in more recent versions of JGit (~ November 2013).

Git.wrap(repository).describe().setTarget(ObjectId.fromString("hash")).call()

You could parse the result, to see if a tag exists, but if there can be multiple tags, you should go with Marcins solution.

Upvotes: 7

Related Questions