java成功操作GIT进行克隆和更新,Java获取git的分支

本文介绍了如何使用Java成功地操作Git进行克隆和更新仓库,并提供了亲测有效的方法,同时增加了获取Git分支的功能。
摘要由CSDN通过智能技术生成
1. 我自己就用了几个可以,其它的没有测试
2. testClone 、gitPull亲测可以
 

import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.File;
import java.io.IOException;

/**
 * JGit API测试
 */
public class GitUtils {
   

    public String reUrl = "http://user@10.1.2.1:8080/project.git";//远程库路径
    public String locPath = "D:\\project\\";//下载已有仓库到本地路径
    public String initPath = "D:\\test\\";//本地路径新建


    /**
     * 克隆远程库
     *
     * @throws IOException
     * @throws GitAPIException
     */

    public static Boolean testClone(String username, String password, String branch, String localPath, String remoteUrl) throws IOException, GitAPIException {
   
        //设置远程服务器上的用户名和密码
        UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider = new
                UsernamePasswordCredentialsProvider(username, password);

        //克隆代码库命令
        CloneCommand cloneCommand = Git.cloneRepository();

        Git git = cloneCommand.setURI(remoteUrl) //设置远程URI
                .setBranch("master") //设置clone下来的分支
                .setDirectory(new File(localPath)) //设置下载存放路径
                .setCredentialsProvider(usernamePasswordCredentialsProvider) //设置权限验证
                .call();
        //打开连接后一定要关闭,否则一个git文件夹删除不了
        git.close();
        return true;
    }

    public static Boolean testClone(String branch, String localPath, String remoteUrl) throws IOException, GitAPIException {
   


        //克隆代码库命令
        CloneCommand cloneCommand = Git.cloneRepository();

        Git git = cloneCommand.setURI(remoteUrl) //设置远程URI
                .setBranch("master") //设置clone下来的分支
                .setDirectory(new File(localPath)) //设置下载存放路径
                .call();
 //打开连接后一定要关闭,否则一个git文件夹删除不了
        git.close();
        return true;
    }

    /**
     * 本地新建仓库
     */

    public void testCreate() throws IOException {
   
        //本地新建仓库地址
        Repository newRepo = FileRepositoryBuilder.create(new File(initPath + "/.git"
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值