JGit: Retrieve tag associated with a git commit

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.


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());
    }
}

Tags:

Jgit