引入jgit
<dependency> <groupId>org.eclipse.jgit</groupId> <artifactId>org.eclipse.jgit</artifactId> <version>3.7.0.201502260915-r</version> </dependency>
初始化一些变量
1.拉远程分支到本地:
/**
* 拉取远程分支到本地
*
* @return
*/
public static String cloneRepository() {
String msg = "";
try {
Git git = Git.cloneRepository()
.setURI(REMOTEREPOURI)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(USER, PASSWORD))
.setBranch("master")
.setDirectory(new File(LOCALPATH)).call();
msg = "git init success!";
ListBranchCommand listBranchCommand = git.branchList();
System.out.println(listBranchCommand.getRepository().getBranch());
} catch (Exception e) {
System.out.println(e.getMessage());
msg = "git已经初始化!";
}
System.out.println(msg);
return msg;
}
运行结果:
可以看到项目目录下生成了demo文件夹,代码已经拉了下来
2.获取所有分支
/**
* 获取所有分支
*
* @param url
*/
public static void getRemoteBranchs(String url) {
try {
Collection<org.eclipse.jgit.lib.Ref> refList;
UsernamePasswordCredentialsProvider pro = new UsernamePasswordCredentialsProvider(USER, PASSWORD);
refList = Git.lsRemoteRepository().setRemote(url).setCredentialsProvider(pro).call();
List<String> branchnameList = new ArrayList<>(4);
for (Ref ref : refList) {
String refName = ref.getName();
if (refName.startsWith("refs/heads/")) { //需要进行筛选
String branchName = refName.replace("refs/heads/", "");
branchnameList.add(branchName);
}
}
System.out.println("共用分支" + branchnameList.size() + "个");
branchnameList.forEach(System.out::println);
} catch (Exception e) {
System.out.println("error");
}
}
运行结果: