Java操作Git远程文件(ssh和http模式)

背景

  • 在实际的项目开发中,有些需求要求将最新的配置自动提交到git上,然后合作方按照git上的配置进行业务的开展,看着有点分布式配置中心感觉。
  • 本文提供了两种git操作常见的方式(ssh和http),除了必要的连接地址之外,ssh方式要求你有私钥(private_key),而http则要求提供username和password

pom依赖

  • 不同版本的jgit依赖区别比较大,请谨慎选择!
        
            org.eclipse.jgit
            org.eclipse.jgit
            4.11.0.201803080745-r
        

ssh实现

  • ssh实现仅提供clone,pull和push操作,其它涉及到与远程git服务器的操作都需要进行私钥鉴权。
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.transport.SshTransport;
import org.eclipse.jgit.util.FS;

import java.io.File;


public class GitUtil {
    private static String keyPath = "<你的私钥文件>"; //私钥文件
    private static String localCodeDir = ""; //本地文件夹
    private static String remoteRepoPath = "ssh://<你的远程git地址>.git"; //git地址
    private static SshSessionFactory sshSessionFactory;

    static {
        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 sch = super.createDefaultJSch(fs);
                sch.addIdentity(keyPath); //添加私钥文件
                return sch;
            }
        };
    }

    //克隆代码,一般只执行一次!branch:分支
    public void clone(String branch) throws Exception {

        Git git = Git.cloneRepository().setURI(remoteRepoPath) //设置远程URI
                .setBranch(branch)   //设置clone下来的分支,默认master
                .setDirectory(new File(localCodeDir))
                .setTransportConfigCallback(transport -> {
                    SshTransport sshTransport = (SshTransport) transport;
                    sshTransport.setSshSessionFactory(sshSessionFactory);
                })//设置下载存放路径
                .call();
        git.close();
    }

    //pull远程git的代码
    public boolean pull() {
        boolean pullFlag = true;
        try (Git git = Git.open(new File(localCodeDir))) {
            git.pull().setTransportConfigCallback(
                    transport -> {
                        SshTransport sshTransport = (SshTransport) transport;
                        sshTransport.setSshSessionFactory(sshSessionFactory);
                    }
            ).call();
        } catch (Exception e) {
            e.printStackTrace();
            pullFlag = false;
        }
        return pullFlag;
    }

    //add/commit/push
    //fileName:文件名。如果有上级目录那则是path/filename
    //desc:commit的描述
    //content:filename中的内容,可以根据需求添加逻辑
    public boolean commitAndPush(String fileName, String desc, String content) {
        //先先进行pull
        boolean pull = this.pull();
        if (pull) {
            System.out.println(String.format("Pull successful!! filePath:%s,desc:%s", fileName, desc));
        }

        boolean commitAndPushFlag = true;
        try (Git git = Git.open(new File(localCodeDir))) {
            FileUtils.writeStringToFile(
                    new File(localCodeDir, fileName),
                    content,
                    "UTF-8"
            );
            git.add().addFilepattern(fileName).call();
            //提交
            git.commit().setMessage(desc).call();
            //推送到远程
            git.push().setTransportConfigCallback(
                    transport -> {
                        SshTransport sshTransport = (SshTransport) transport;
                        sshTransport.setSshSessionFactory(sshSessionFactory);
                    }
            ).call();
            System.out.println("Commit And Push file " + fileName + " to repository at " + git.getRepository().getDirectory());
        } catch (Exception e) {
            e.printStackTrace();
            commitAndPushFlag = false;
            System.out.println("Commit And Push error! \n" + e.getMessage());
        }
        return commitAndPushFlag;
    }
}

http实现

  • http实现仅提供pull和push方法,需要提供具有pull和push权限的用户名+密码
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.*;
import java.io.File;

public class GitUtil {

    private static String username = "<你的用户名>";
    private static String password = "<你的密码>";
    private static String remoteRepoPath = "http://<你的远程git地址>.git"; //git地址
    private static String localCodeDir = ""; //本地文件夹

    private CredentialsProvider createCredential() {
        return new UsernamePasswordCredentialsProvider(username, password);
    }

    public boolean pull() {
        boolean pullFlag = true;
        try (Git git = Git.open(new File(localCodeDir))) {
            git.pull().setCredentialsProvider(createCredential()).call();
        } catch (Exception e) {
            e.printStackTrace();
            pullFlag = false;
        }
        return pullFlag;
    }

    public boolean commitAndPush(String filePath, String desc, String content) {
        //先先进行pull
        boolean pull = this.pull();
        if (pull) {
            System.out.println(String.format("Pull successful!! filePath:%s,desc:%s", fileName, desc));
        }

        boolean commitAndPushFlag = true;
        try (Git git = Git.open(new File(localCodeDir))) {
            FileUtils.writeStringToFile(
                    new File(localCodeDir, filePath),
                    content,
                    "UTF-8"
            );
            git.add().addFilepattern(filePath).call();
            //提交
            git.commit().setMessage(desc).call();
            //推送到远程
            git.push().setCredentialsProvider(createCredential()).call();
            System.out.println("Commit And Push file " + filePath + " to repository at " + git.getRepository().getDirectory());
        } catch (Exception e) {
            e.printStackTrace();
            commitAndPushFlag = false;
            System.out.println("Commit And Push error! \n" + e.getMessage());
        }
        return commitAndPushFlag;
    }
}

你可能感兴趣的:(Java操作Git远程文件(ssh和http模式))