jgit应用

628 阅读2分钟

这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战

jgit应用

jgit是一个java代码提交git的插件,可以通过代码连接git远程仓库,在本地建立版本库,进行拉取、提交、推送等操作。

Java 类org.eclipse.jgit.api.ListBranchCommand

获取远程git分支列表ListBranchCommand。获取链接方式,通过密钥连接git。输入参数包括gitUrl即可,连接上远程git后,返回对象就是Collection < Ref > 。对获取的分支列表进行过滤,只获取有效的分支。

 public List<String> getBranchs(String url){
        List<String> branchnameList = new ArrayList<>(4);
       
       // 
       final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host host, Session session) {
                session.setConfig("StrictHostKeyChecking", "no");
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch jSch = super.createDefaultJSch(fs);
                jSch.addIdentity(identityPath);
                jSch.setKnownHosts(knownHostsPath);
                return jSch;
            }
        };
        try{
       // 输入url
         Collection<Ref> call = Git.lsRemoteRepository().setRemote(url).setTransportConfigCallback(new TransportConfigCallback() {
            @Override
            public void configure(Transport transport) {
                SshTransport sshTransport = (SshTransport) transport;
                sshTransport.setSshSessionFactory(sshSessionFactory);
            }
        }).call();
//对获取的分支列表进行过滤,只获取有效的分支。
            for (Ref ref : call) {
                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) {
            return branchnameList;
        }
        return branchnameList;
    }

主要用到的包  org.eclipse.jgit.api

连接git,下载代码。

 /**
     * 注意事项
     * 生成的密钥需要使用-m PEM格式,命令如下:
     * ssh-keygen -t rsa -f id_rsa_git -m pem -C xxx@yy.com
     * @param gitUrl
     * @param codePath
     * @param commitId
     * @return
     * @throws GitAPIException
     */
    public Git cloneRepositoryViaSSH(String gitUrl, String codePath, String commitId) throws GitAPIException {

        final SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host host, Session session) {
                session.setConfig("StrictHostKeyChecking", "no");
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch jSch = super.createDefaultJSch(fs);
                jSch.addIdentity(identityPath);
                jSch.setKnownHosts(knownHostsPath);
                return jSch;
            }
        };

        Git git = Git.cloneRepository()
                .setURI(gitUrl)
                .setTransportConfigCallback(new TransportConfigCallback() {
                    @Override
                    public void configure(Transport transport) {
                        SshTransport sshTransport = (SshTransport) transport;
                        sshTransport.setSshSessionFactory(sshSessionFactory);
                    }
                })
//                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
                .setDirectory(new File(codePath))
                .setBranch(commitId)
                .call();
        // 切换到指定commitId
        checkoutBranch(git, commitId);
        return git;
    }

上面这个就是通过密钥登陆git,连接git操作各种命令。当然也有使用账号密码的情况,不过那样不太安全,直接把账号密码暴露在代码中,很容易被拿到。通过将密钥放在服务器上,然后通过SpringBoot的配置文件获取密钥,连接上git。

在类文件中通过SpringBoot的注解引用配置文件中的参数。

@Value(value = "${gitlab.ssh.knownHostsPath}")
private String knownHostsPath;

@Value(value = "${gitlab.ssh.identityPath}")
private String identityPath;

在配置文件中加入参数。通过一些特定方法生成了密钥之后,放在指定的目录下,然后将路径写到配置文件中。

gitlab.ssh.knownHostsPath=${user.home}/git/.ssh/known_hosts
gitlab.ssh.identityPath=${user.home}/git/.ssh/id_rsa_git