use*_*330 9 java git github jgit
如何使用JGit获取存储库中的所有分支?我们来看一个示例存储库.我们可以看到,它有5个分支.
在这里我找到了这个例子:
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);
Run Code Online (Sandbox Code Playgroud)
但我得到的只是:
Branch: Ref[refs/heads/master=d766675da9e6bf72f09f320a92b48fa529ffefdc] refs/heads/master d766675da9e6bf72f09f320a92b48fa529ffefdc
Number of branches: 1
Branch: master
Run Code Online (Sandbox Code Playgroud)
Rüd*_*ann 17
如果它是你缺少的远程分支,你必须设置ListMode的ListBranchCommand对ALL或REMOTE.默认的ListMode(ListMode)仅返回本地分支.
new Git(repository).branchList().setListMode(ListMode.ALL).call();
Run Code Online (Sandbox Code Playgroud)
我将下面的方法用于 git 分支,而不使用 Jgit 克隆 repo
这在 pom.xml 中
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>4.0.1.201506240215-r</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
方法
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;
}
Run Code Online (Sandbox Code Playgroud)