美文网首页
JGit SSH密钥 clone/pull/log操作

JGit SSH密钥 clone/pull/log操作

作者: 大锤强无敌 | 来源:发表于2020-12-03 19:43 被阅读0次

    不多说了,copy的累死我了,真心不好找 -_-

    JGit 通过SSH私钥文件clone/pull代码

    1.目的及准备工作

    # 目的:通过jgit框架通过SSH密钥文件来连接git仓库并clone代码到本地
    
    # 准备工作:
        1.需要一个私钥文件,比如C:\Users\xxx\.ssh\id_rsa这个文件,如果是ppk文件(putty生成的用来验证git仓库权限的文件),则找到 puttygen.exe,双击运行后,点击Conversions->import Key(导入ppk文件)->Save private key(保存为一个无后缀名的文件)
        2.项目引入Jgit依赖
            <dependency>
                 <groupId>org.eclipse.jgit</groupId>
                 <artifactId>org.eclipse.jgit</artifactId>
                 <version>3.7.0.201502260915-r</version>
            </dependency>
    

    2.通过java代码进行clone

    package com.jgittest.util;
    
    import java.io.File;
    
    import org.eclipse.jgit.api.CloneCommand;
    import org.eclipse.jgit.api.Git;
    import org.eclipse.jgit.lib.Repository;
    import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
    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.transport.UsernamePasswordCredentialsProvider;
    import org.eclipse.jgit.util.FS;
    
    import com.jcraft.jsch.JSch;
    import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.Session;
    
    /**
     * git操作工具类
     * @author houjiayin.co
     *
     */
    public class GitUtil {
        
        public static void main(String[] args) {
            String localCodeDir = "H:/myGitRepository"; //本地文件夹
            String remoteRepoPath = "ssh://***"; //git地址
            String keyPath = "H:/private_key"  //私钥文件
            gitClone(remoteRepoPath, localCodeDir,keyPath);
            
        }
        
        //localRepoPath 为本地文件夹
        //keyPath 私钥文件 path
        //remoteRepoPath 为 ssh git远端仓库地址
        protected static void gitClone(String remoteRepoPath, String localRepoPath,String keyPath) {
            //ssh session的工厂,用来创建密匙连接
            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 sch = super.createDefaultJSch(fs);
                    sch.addIdentity(keyPath); //添加私钥文件
                    return sch;
                }
              };
    
            //克隆代码库命令
            CloneCommand cloneCommand = Git.cloneRepository();
            Git git = null;
            try {
                git = cloneCommand.setURI(remoteRepoPath) //设置远程URI
                    .setTransportConfigCallback(transport -> {
                        SshTransport sshTransport = ( SshTransport )transport;
                        sshTransport.setSshSessionFactory( sshSessionFactory );
                    })
                    .setDirectory(new File(localRepoPath)) //设置下载存放路径
                    .call();
                System.out.println("success");
            } catch (Exception e) {
                System.out.println("fail");
                e.printStackTrace();
            } finally {
                if (git != null) {
                    git.close();
                }
            }
        }
        
    

    3. pull代码

    //localRepoPath 为 .git 的 path 如 : D:\\gitRepository\\.git
    //keyPath 私钥文件 path
    public static void pullCode(String remoteRepoPath, String localRepoPath, String keyPath) {
            System.out.println("===" + remoteRepoPath + "===" + localRepoPath + "===" + keyPath);
            //ssh session的工厂,用来创建密匙连接
            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 sch = super.createDefaultJSch(fs);
                    sch.addIdentity(keyPath);
                    return sch;
                }
            };
            try {
                //关联到本地仓库
                FileRepository fileRepository = new FileRepository(new File(localRepoPath));
                Git pullGit = new Git(fileRepository);
                //设置密钥,拉取文件
                PullCommand pullCommand = pullGit
                        .pull()
                        .setTransportConfigCallback(
                                transport -> {
                                    SshTransport sshTransport = ( SshTransport )transport;
                                    sshTransport.setSshSessionFactory( sshSessionFactory );
                                });
                pullCommand.call();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    

    JGit 获取提交信息/详细提交日志

    1.提交信息

    //此方法获取了仓库内(path下,有可能为仓库下子文件夹)的所有提交版本号
    public static List<String> getGitVersions(String path) {
        List<String> versions = new ArrayList<>();
         try {
            Git git = Git.open(new File(path));
            Repository repository = git.getRepository();
            Git git1 = new Git(repository);
             Iterable<RevCommit> commits = git.log().all().call();
             int count = 0;
             for (RevCommit commit : commits) {
                 System.out.println("LogCommit: " + commit);
                 System.out.println("===" + commit.getFullMessage());
                 String version = commit.getName(); //版本号,用来查询详细信息
                 versions.add(version);
                 System.out.println("===" + commit.getName());
                 System.out.println("===" + commit.getAuthorIdent());                
                 count++;
             }
             return versions;
         }catch (Exception e) {
            e.printStackTrace();
         }
        return null;
     }
    
    

    2. 获取提交的详细信息

    /**
     * 获取两个版本间提交详细记录
     * @param path
     */
    //version 为 上一个方法查询出来的版本号
    public static void showDiff(String path,String oldVersion,String newVersion) {
        try {
            Git git = Git.open(new File(path));
            Repository repository = git.getRepository();
            //旧版本
            AbstractTreeIterator oldTreeParser = prepareTreeParser(repository, oldVersion);
            //新版本
            AbstractTreeIterator newTreeParser = prepareTreeParser(repository, newVersion);
            
            List<DiffEntry> diff = git.diff().
                    setOldTree(oldTreeParser).
                    setNewTree(newTreeParser).
                    call();
            for (DiffEntry entry : diff) {
                System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
                //此处可传一个输出流获取提交详情
                DiffFormatter formatter = new DiffFormatter(System.out);
                formatter.setRepository(repository);
                formatter.format(entry);
            }
            
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    附几个有用的 jgit 资料地址

    # git官网对jgit的介绍
    https://git-scm.com/book/zh/v2/%E9%99%84%E5%BD%95-B%3A-%E5%9C%A8%E4%BD%A0%E7%9A%84%E5%BA%94%E7%94%A8%E4%B8%AD%E5%B5%8C%E5%85%A5-Git-JGit
    
    # jgit超有用的各种demo地址
    https://github.com/centic9/jgit-cookbook 
    
    # 一些常用的jgit方法
    https://my.oschina.net/u/4339481/blog/4748737
    

    相关文章

      网友评论

          本文标题:JGit SSH密钥 clone/pull/log操作

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