2014-07-01 43 views
5

如何使用JGit獲取存儲庫中的所有分支機構? 我們拿example repository。正如我們所看到的,它有5個分支。
Here我發現這個例子:使用JGit獲取所有分支機構

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

但我得到的是這樣的:

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

回答

9

如果您缺少遠程分支,您必須將ListBranchCommandListMode設爲ALLREMOTE。默認的ListMode(null)只返回本地分支。

new Git(repository).branchList().setListMode(ListMode.ALL).call(); 
+3

我已經更新了例如在jgit-cookbook中也展示了這一點。 – centic

0

我使用的Git分支下面的方法,無需克隆使用Jgit

這正好在pom.xml回購

<dependency> 
     <groupId>org.eclipse.jgit</groupId> 
     <artifactId>org.eclipse.jgit</artifactId> 
     <version>4.0.1.201506240215-r</version> 
    </dependency> 

方法

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 occurr in fetchGitBranches",e); 
       } 
       return branches; 
      }