Reputation: 618
I am working on a Git client, and right now I am trying to implement the checkout of a specific branch. I have a combo box that I populate with branch names, and I would like to find out which branch is the default, so that I can set it as the preselected item in the combo box when connecting to a valid Git repository.
I am listing all the remote branches as you can see below, but I cannot figure out which is the default one.
Map<String, Ref> callAsMap = Git.lsRemoteRepository()
.setRemote("https://github.com/example")
.setCredentialsProvider(credentialsProvider)
.callAsMap();
So, is there a way (standard or "hacky") to detect which Ref
object represents the default branch? And how can I get its name?
Upvotes: 5
Views: 2661
Reputation: 394
After the chain with .get("HEAD")
, if it is a symbolic link, you can chain it with .getTarget().getName()
to "extract" its name e.g.
Map<String, Ref> callAsMap = Git.lsRemoteRepository()
.setRemote("https://github.com/example")
.setCredentialsProvider(credentialsProvider)
.callAsMap().get("HEAD").getTarget().getName()
Source: https://www.eclipse.org/lists/jgit-dev/msg03320.html
Upvotes: 0
Reputation: 20985
Repository::getFullBranch
returns the current branch of the local repository.
To get the default branch of a remote repository, you need to ask for its HEAD
ref. The map that is returned by the snippet that you posted should contain an entry with key HEAD
and (if I'm not mistaken) a value that denotes the name of the default branch.
If HEAD
refers to an object id, you could obtain a list of all remote refs with repository.getRefDatabase().getRefs(Constants.R_REMOTES)
to look up the HEAD id. This approach may be inaccurate as multiple refs could point to the same object id.
Note that it is not required for a remote repository to advertise a default branch.
See also these posts for how C-Git finds the default branch: git - how to get default branch? and What determines default branch after "git clone"?)
Upvotes: 2