使用jGit 通过gitUrl 获取Git的所有分支

码农天地 -
使用jGit 通过gitUrl 获取Git的所有分支

使用jGit 通过gitUrl 获取Git的所有分支

本文代码已经同步到码云 ,欢迎大家 star https://gitee.com/njitzyd/JavaDemoCollection

问题引入

在企业中,在针对代码规范规约的时候,就需要保证你的jar包的代码是可追溯的。尤其在大的企业里,对代码质量的检查也是很多的,比如通过sonar进行代码的管理,通过自己编写maven 插件来自定义规范并通过Jenkins 去自动化持续发布和部署。那么在进行提交你所发布的jar包时就需要根据你的git地址去拉取你的分支,然后你要选择你的分支,那如何根据git地址获取所有分支?

jGit 的使用新建maven工程,添加依赖
 <!--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

可以看到代码的所有分支已经拿到,这样就实现了功能!!!

特别申明:本文内容来源网络,版权归原作者所有,如有侵权请立即与我们联系(cy198701067573@163.com),我们将及时处理。

Tags 标签

加个好友,技术交流

1628738909466805.jpg