美文网首页
Java操作Git远程文件(ssh和http模式)

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

作者: _Kantin | 来源:发表于2022-04-01 19:18 被阅读0次

背景

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

pom依赖

  • 不同版本的jgit依赖区别比较大,请谨慎选择!
        <dependency>
            <groupId>org.eclipse.jgit</groupId>
            <artifactId>org.eclipse.jgit</artifactId>
            <version>4.11.0.201803080745-r</version>
        </dependency>

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 = "<window/linux文件夹>"; //本地文件夹
    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 = "<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) {
        //先先进行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模式)

    背景 在实际的项目开发中,有些需求要求将最新的配置自动提交到git上,然后合作方按照git上的配置进行业务的开展,...

  • Git基本操作和错误

    创建SSH Key 本地创建仓库操作 创建本地仓库 将文件添加进Git 提交 Git远程仓库操作 查看远程仓库 添...

  • Git 常用命令

    Git 常用命令 配置 远程仓库操作 SSH Key 操作 创建忽略文件 添加 查询 撤销(回滚) 删除 标签 分...

  • Git常用指令

    在进行git操作之前,首先得创建一个远程git仓库。由于你的本地Git仓库和远程Git仓库之间的传输是通过SSH加...

  • Git SSH 不是有效的指令

    问题描述: 使用git时,用ssh连接远程库总是失败,查看之后发现本地没有ssh文件,新建ssh文件时又发现ssh...

  • 踩坑日常

    基本推送流程 克隆远程仓库到本地仓库:git clone 仓库地址(ssh/http)本地仓库连接远程仓库:git...

  • Git 教程(一)--Git简介及操作流程

    前言 Git 教程(一)--Git简介及操作流程Git 教程(二)--Git文件操作Git 教程(三)--远程仓库...

  • Git 教程(五)--远程分支

    前言 Git 教程(一)--Git简介及操作流程Git 教程(二)--Git文件操作Git 教程(三)--远程仓库...

  • Git 教程(四)--分支原理

    前言 Git 教程(一)--Git简介及操作流程Git 教程(二)--Git文件操作Git 教程(三)--远程仓库...

  • Git 教程(三)--远程仓库

    前言 Git 教程(一)--Git简介及操作流程Git 教程(二)--Git文件操作Git 教程(三)--远程仓库...

网友评论

      本文标题:Java操作Git远程文件(ssh和http模式)

      本文链接:https://www.haomeiwen.com/subject/wmwajrtx.html