java代码操作git实现仓库代码下载至指定目录
想要用代码操作gitlab,实现仓库代码下载。
依赖jgit工具:
<dependency> <groupId>org.eclipse.jgit</groupId> <artifactId>org.eclipse.jgit</artifactId> <version>5.8.1.202007141445-r</version> </dependency>
全量代码:
package com.controller; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.internal.storage.file.FileRepository; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.junit.Test; import java.io.File; /** * @Author Ctrl` * @Since 2020/10/16. */ @Slf4j public class GitController { private String localPath; private Repository localRepo; private Git git; @Test public void tt(){ download("test","http://***.git","dev"); } /** * git代码下载 */ public String 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 = new Git(localRepo); File localPathFile = new File(localPath); if (!localPathFile.exists()) { gitClone(gitUrl, branch, localPath,credentialsProvider); } else { gitPull(branch,credentialsProvider); } } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } return localPath; } /** * 如果没有该代码目录,执行git clone */ private void gitClone(String gitUrl, String branch, String localPath,UsernamePasswordCredentialsProvider credentialsProvider) throws Exception { Git.cloneRepository().setURI(gitUrl).setBranch(branch) .setDirectory(new File(localPath)).setCredentialsProvider(credentialsProvider).call(); } /** * 如果有代码,git pull */ private void gitPull(String branch,UsernamePasswordCredentialsProvider credentialsProvider) throws Exception { git.pull().setRemoteBranchName(branch).setCredentialsProvider(credentialsProvider).call(); } }
使用ssh时会报错,后续更新。