Getting all branches with JGit

Evgenij Reznik picture Evgenij Reznik · Jul 1, 2014 · Viewed 9.3k times · Source

How can I get all branches in a repository with JGit? Let's take an example repository. As we can see, it has 5 branches.
Here I found this example:

int c = 0;
List<Ref> call = new Git(repository).branchList().call();
for (Ref ref : call) {
    System.out.println("Branch: " + ref + " " + ref.getName() + " "
            + ref.getObjectId().getName());
    c++;
}
System.out.println("Number of branches: " + c);

But all I get is this:

Branch: Ref[refs/heads/master=d766675da9e6bf72f09f320a92b48fa529ffefdc] refs/heads/master d766675da9e6bf72f09f320a92b48fa529ffefdc
Number of branches: 1
Branch: master

Answer

R&#252;diger Herrmann picture Rüdiger Herrmann · Jul 1, 2014

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();