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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With