Getting all branches with JGit

拟墨画扇 提交于 2019-12-08 16:23:27

问题


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

回答1:


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



回答2:


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;
            }


来源:https://stackoverflow.com/questions/24518782/getting-all-branches-with-jgit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!