Reputation: 221
I need to obtain the name of the branch that is associated with a specific commit using JGit. I used JGit to obtain the complete list of commit SHA's for a repository and now I need to know the name of the branch it belongs to.
Appreciate if someone can let me know how I can achieve this.
Upvotes: 8
Views: 3854
Reputation: 20985
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.
Upvotes: 5
Reputation: 30858
As the document says,
Class ListBranchCommand
ListBranchCommand setContains(String containsCommitish)
setContains
public ListBranchCommand setContains(String containsCommitish)
If this is set, only the branches that contain the specified commit-ish as an ancestor are returned.
Parameters:
containsCommitish - a commit ID or ref name
Returns:
this instance
Since:
3.4
This api is corresponding to git branch --contains <commit-ish>
You may also need this api if you'd like to list the remote branches (-r
) or both the remote and local branches (-a
),
setListMode
public ListBranchCommand setListMode(ListBranchCommand.ListMode listMode)
Parameters:
listMode - optional: corresponds to the -r/-a options; by default, only local branches will be listed
Returns:
this instance
Sample:
#list all the branches that "HEAD" belongs to.
try {
Git git = Git.open(new File("D:/foo/.git"));
List<Ref> refs = git.branchList().setContains("HEAD").setListMode(ListBranchCommand.ListMode.ALL).call();
System.out.println(refs);
} catch (Exception e) {
System.out.println(e);
}
Upvotes: 3