1. 引入Pom
<!-- jgit用于在Java中操作Git -->
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>5.9.0.202009080501-r</version>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit.archive</artifactId>
<version>5.9.0.202009080501-r</version>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit.ssh.jsch</artifactId>
<version>5.9.0.202009080501-r</version>
</dependency>
2. 创建代码仓库, 设置项目令牌


3. 工具类
package cn.com.baidu.base.util.git;
import cn.com.baidu.base.annot.CLog;
import cn.com.baidu.base.enums.GitPathType;
import cn.com.baidu.base.util.project.BaseProjectConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.*;
import org.springframework.stereotype.Component;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
// 3个配置文件 GitMaster 分支名称 (master) | GitSwitch 是否开启同步到仓库 (true) | GitLocalPath 本地仓库地址 (D:\codeGit) , 可替换成你的配置方式
// GitPathType为我自定义的枚举 , 用于拼接路径使用 , 因为我的业务时是将在线编辑的SQL , Js , Css , Html 代码字符串同步到仓库, 因此不同的代码加了不同枚举用于区分.
@Component
@Slf4j
@CLog
public class GitUtils {
private static String url = "https://e.coding.net/tsteam/xxx/xxx.git";// 项目地址
private static String projectKey = "ptxxxxxxxxza";// 项目令牌用户名
private static String projectToken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";// 项目令牌密码
private static String originName = "origin";
private static Git gitClass;
public GitUtils() {}
/**
* 用于字符串转为文件 , 并提交至仓库
* @param gitPathType
* @param content 内容
* @param path 例如 xxx/xxx/xxx.name.js
* @param message 文字说明
* @throws GitAPIException
*/
public static void addToFileToLocalGit(GitPathType gitPathType, String content, String path, String message) throws GitAPIException, IOException {
if ( !BaseProjectConfigUtil.getSwitch("GitSwitch") ) return;
openRpo();
writeContentToFile(BaseProjectConfigUtil.getText("GitLocalPath") + File.separator + gitPathType.getName() + File.separator + path, content);
pull();
addFile((gitPathType.getName() + File.separator + path).replaceAll("\\\\", "/"));
commit(message);
push();
}
private static Git openRpo() {
Git git = null;
try {
if (gitClass != null) {
// 切换 | 不存在则报错
gitClass.checkout().setName(BaseProjectConfigUtil.getText("GitMaster")).call();
git = gitClass;
return git;
}
if(!new File(BaseProjectConfigUtil.getText("GitLocalPath") + File.separator + ".git" + File.separator).exists()) {
git = Git.cloneRepository()
.setURI(url)
.setCredentialsProvider(new UsernamePasswordCredentialsProvider(projectKey, projectToken))
.setDirectory(new File(String.valueOf(BaseProjectConfigUtil.getText("GitLocalPath"))))
.setBranch(BaseProjectConfigUtil.getText("GitMaster"))
.call();
git.getRepository().close();
git.close();
}
Repository repository = new FileRepositoryBuilder().setGitDir(Paths.get(BaseProjectConfigUtil.getText("GitLocalPath"), ".git").toFile()).build();
git = new Git(repository);
git.checkout().setName(BaseProjectConfigUtil.getText("GitMaster")).call();
} catch (Exception e) {
e.printStackTrace();
log.error("获取Git操作对象失败...", e);
}
gitClass = git;
return git;
}
private static void pull() throws GitAPIException {
Git git = openRpo();
git.pull().setRemoteBranchName(BaseProjectConfigUtil.getText("GitMaster")).setCredentialsProvider(new UsernamePasswordCredentialsProvider(projectKey, projectToken)).call();
}
private static void push() throws GitAPIException {
Git git = openRpo();
git.push().setRemote(originName).setCredentialsProvider(new UsernamePasswordCredentialsProvider(projectKey, projectToken)).call();
}
private static void writeContentToFile(String storagePath, String content) throws IOException {
// 构建完整的文件名,包括路径和后缀名
String filePath = storagePath;
File file = new File(filePath);
if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
// 使用FileWriter和BufferedWriter将内容写入文件
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write(content);
} catch (IOException e) {
throw e;
}
}
// 添加所有更改的文件
private static void addFile(String filePath) throws GitAPIException {
Git git = openRpo();
git.add().addFilepattern(filePath).call();
}
// 提交更改
private static void commit(String message) throws GitAPIException {
Git git = openRpo();
git.commit().setMessage(message).call();
}
}
4. 代码中调用
try {
String sqlTitle = "查找用户信息(传入UserId)";
String sqlCode = "sak12ss2";
String sqlContent = "-- Key : userId | 用户ID\r\nSELECT * FROM sys_user WHERE user_id = '${userId}'";
GitUtils.addToFileToLocalGit(GitPathType.SQL, sqlContent , sqlCode + ".sql", sqlTitle + "-" + sqlCode + "新增");
} catch (Exception e) {
e.printStackTrace();
throw new SaveException("同步到Git失败");
}