Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List all tags in current branch with JGit

Tags:

java

git

jgit

How do I list all tags in the current branch with JGit?
I can list all tags easily

List<Ref> call = jGit.tagList().call();
for (Ref ref : call) {
    System.out.println("Tag: " + ref);
}

but how do I list only the ones that are in the current branch?

like image 339
sydd Avatar asked Sep 06 '25 12:09

sydd


1 Answers

To list all tags for a given branch, you need to walk the history commit by commit, starting from the head commit of the branch. For each commit in the history you then need to find all tags that point to this commit.

For example:

git.commit().setMessage("tagged").call();
git.tag().setName("mytag").call();
git.commit().setMessage("untagged").call();

Iterable<RevCommit> commits = git.log().call();
for (RevCommit commit : commits) {
  Map<ObjectId, String> namedCommits = git.nameRev().addPrefix("refs/tags/").add(commit).call();
  if (namedCommits.containsKey(commit.getId())) {
    System.out.println("tag " + namedCommits.get(commit.getId()) + " -> " + commit);
  }
}

The output will be something like this

tag mytag -> commit 92a85dcb2326caf08f4ad1ddb6132f92ee0b3e7c 1438794838 ----sp

where the commit is the taggsd one.

the LogCommand returns an iterator that starts with the the head commit of the current branch. The NameRecCommand called within the loop finds all tags that point to the given commit.

An optimized variant could use the ListTagCommand to once retrieve a list of all tags and then replace the git.nameRev code with code that looks up the current commit in the list of tags.

like image 83
Rüdiger Herrmann Avatar answered Sep 09 '25 04:09

Rüdiger Herrmann