Search code examples
jgit

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.


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