使用jGit 經過gitUrl 獲取Git的全部分支java
本文代碼已經同步到碼雲 ,歡迎你們 star https://gitee.com/njitzyd/JavaDemoCollectiongit
在企業中,在針對代碼規範規約的時候,就須要保證你的jar包的代碼是可追溯的。尤爲在大的企業裏,對代碼質量的檢查也是不少的,好比經過sonar進行代碼的管理,經過本身編寫maven 插件來自定義規範並經過Jenkins 去自動化持續發佈和部署。那麼在進行提交你所發佈的jar包時就須要根據你的git地址去拉取你的分支,而後你要選擇你的分支,那如何根據git地址獲取全部分支?apache
<!--jGit --> <dependency> <groupId>org.eclipse.jgit</groupId> <artifactId>org.eclipse.jgit</artifactId> <version>5.5.1.201910021850-r<ersion> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.10<ersion> </dependency>
public class GitTest { public static void main(String[] args) throws Exception { GitTest test = new GitTest(); test.getRemoteBranchs("https://gitee.com/njitzyd/JavaDemoCollection.git","你的倉庫用戶名","你的倉庫密碼"); } public void getRemoteBranchs(String url, String username, String password){ try { Collection<Ref> refList; if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) { UsernamePasswordCredentialsProvider pro = new UsernamePasswordCredentialsProvider(username, password); refList = Git.lsRemoteRepository().setRemote(url).setCredentialsProvider(pro).call(); } else { refList = Git.lsRemoteRepository().setRemote(url).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"); } } }
共用分支2個 develop master
能夠看到代碼的全部分支已經拿到,這樣就實現了功能!!!eclipse