Getting all branches with JGit
If it is the remote branches that you are missing, you have to set the ListMode
of the ListBranchCommand
to ALL
or REMOTE
. By default, the command returns only local branches.
new Git(repository).branchList().setListMode(ListMode.ALL).call();
I use the below method for git branches without cloning the repo using Jgit
This goes in the pom.xml
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>4.0.1.201506240215-r</version>
</dependency>
Method
public static List<String> fetchGitBranches(String gitUrl)
{
Collection<Ref> refs;
List<String> branches = new ArrayList<String>();
try {
refs = Git.lsRemoteRepository()
.setHeads(true)
.setRemote(gitUrl)
.call();
for (Ref ref : refs) {
branches.add(ref.getName().substring(ref.getName().lastIndexOf("/")+1, ref.getName().length()));
}
Collections.sort(branches);
} catch (InvalidRemoteException e) {
LOGGER.error(" InvalidRemoteException occured in fetchGitBranches",e);
e.printStackTrace();
} catch (TransportException e) {
LOGGER.error(" TransportException occurred in fetchGitBranches",e);
} catch (GitAPIException e) {
LOGGER.error(" GitAPIException occurred in fetchGitBranches",e);
}
return branches;
}