In Git, a commit does not belong to a branch. A commit is immutable, whereas branches can change their name as well as the commit they point to.
A commit is reachable from a branch (or tag, or other ref) if there is a branch that either directly points to the commit or to a successor of the commit.
In JGit the NameRevCommand
can be used to find a branch, if any, that directly points to a commit. For example:
Map<ObjectId, String> map = git
.nameRev()
.addPrefix("refs/heads")
.add(ObjectId.fromString("<SHA-1>"))
.call();
The above snippet looks in the refs/heads
namespace for a ref that points to the given commit. The returned map contains at most one entry where the key is the given commit id and the value denotes the branch which points to it.