java代码操作git_java代码操作git实现仓库代码下载至指定目录

packagecom.ct.asi.filecenter.controller;importlombok.extern.slf4j.Slf4j;importorg.apache.commons.lang3.StringUtils;importorg.eclipse.jgit.api.Git;importorg.eclipse.jgit.internal.storage.file.FileRepository;importorg.eclipse.jgit.lib.Repository;importorg.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;importorg.junit.Test;importjava.io.File;/*** @Author Ctrl`

* @Since 2020/10/16.*/@Slf4jpublic classGitController {privateString localPath;privateRepository localRepo;privateGit git;

@Testpublic voidtt(){

download("test","http://***.git","dev");

}/*** git代码下载*/

publicString download(String projectName, String gitUrl,String branch) {if(StringUtils.isBlank(gitUrl)){return "git仓库地址不能为空";

}//认证凭据

UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("登录git的邮箱","登录密码");try{//代码指定存储目录

localPath = "E:\\git_repository" + File.separator +projectName;

System.out.println("============localPath==========" +localPath);

localRepo= new FileRepository(localPath + "/.git");

git= newGit(localRepo);

File localPathFile= newFile(localPath);if (!localPathFile.exists()) {

gitClone(gitUrl, branch, localPath,credentialsProvider);

}else{

gitPull(branch,credentialsProvider);

}

}catch(Exception e) {

log.error(e.getMessage());

e.printStackTrace();

}returnlocalPath;

}/*** 如果没有该代码目录,执行git clone*/

private void gitClone(String gitUrl, String branch, String localPath,UsernamePasswordCredentialsProvider credentialsProvider) throwsException {

Git.cloneRepository().setURI(gitUrl).setBranch(branch)

.setDirectory(newFile(localPath)).setCredentialsProvider(credentialsProvider).call();

}/*** 如果有代码,git pull*/

private void gitPull(String branch,UsernamePasswordCredentialsProvider credentialsProvider) throwsException {

git.pull().setRemoteBranchName(branch).setCredentialsProvider(credentialsProvider).call();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值