Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all branches with JGit

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
like image 963
Evgenij Reznik Avatar asked Jul 01 '14 20:07

Evgenij Reznik


2 Answers

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();
like image 67
Rüdiger Herrmann Avatar answered Nov 01 '22 23:11

Rüdiger Herrmann


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;
            }
like image 27
Upen Avatar answered Nov 01 '22 23:11

Upen