Java操作Git遠(yuǎn)程文件(ssh和http模式)

背景

  • 在實(shí)際的項(xiàng)目開發(fā)中,有些需求要求將最新的配置自動(dòng)提交到git上,然后合作方按照git上的配置進(jìn)行業(yè)務(wù)的開展,看著有點(diǎn)分布式配置中心感覺。
  • 本文提供了兩種git操作常見的方式(ssh和http),除了必要的連接地址之外,ssh方式要求你有私鑰(private_key),而http則要求提供username和password。

pom依賴

  • 不同版本的jgit依賴區(qū)別比較大,請謹(jǐn)慎選擇!
        <dependency>
            <groupId>org.eclipse.jgit</groupId>
            <artifactId>org.eclipse.jgit</artifactId>
            <version>4.11.0.201803080745-r</version>
        </dependency>

ssh實(shí)現(xiàn)

  • ssh實(shí)現(xiàn)僅提供clone,pull和push操作,其它涉及到與遠(yuǎn)程git服務(wù)器的操作都需要進(jìn)行私鑰鑒權(quán)。
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 = "<window/linux文件夾>"; //本地文件夾
    private static String remoteRepoPath = "ssh://<你的遠(yuǎn)程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;
            }
        };
    }

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

        Git git = Git.cloneRepository().setURI(remoteRepoPath) //設(shè)置遠(yuǎn)程URI
                .setBranch(branch)   //設(shè)置clone下來的分支,默認(rèn)master
                .setDirectory(new File(localCodeDir))
                .setTransportConfigCallback(transport -> {
                    SshTransport sshTransport = (SshTransport) transport;
                    sshTransport.setSshSessionFactory(sshSessionFactory);
                })//設(shè)置下載存放路徑
                .call();
        git.close();
    }

    //pull遠(yuǎn)程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中的內(nèi)容,可以根據(jù)需求添加邏輯
    public boolean commitAndPush(String fileName, String desc, String content) {
        //先先進(jìn)行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();
            //推送到遠(yuǎn)程
            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實(shí)現(xiàn)

  • http實(shí)現(xiàn)僅提供pull和push方法,需要提供具有pull和push權(quán)限的用戶名+密碼
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://<你的遠(yuǎn)程git地址>.git"; //git地址
    private static String localCodeDir = "<window/linux文件夾>"; //本地文件夾

    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) {
        //先先進(jìn)行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();
            //推送到遠(yuǎn)程
            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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容