16

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
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181

2 Answers2

29

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();
Rüdiger Herrmann
  • 20,512
  • 11
  • 62
  • 79
5

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;
            }
Upen
  • 1,388
  • 1
  • 22
  • 49