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.
Looking up changes for a specific commit If you have the hash for a commit, you can use the git show command to display the changes for that single commit. The output is identical to each individual commit when using git log -p .
On Bitbucket, access your repository and click the branch link. The branch should now be created and active. You can confirm which branch you are working on by looking at the branch button.
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.
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);
}
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