使用org.eclipse.jgit.diff;(org.eclipse.igit:org.eclipse.igit)
//以下是读取变更行
Git git = init(gitPath);
ByteArrayOutputStream out = new ByteArrayOutputStream();
DiffFormatter df = new DiffFormatter(out);
// 设置比较器为忽略空白字符对比(Ignores all whitespace)
df.setDiffComparator(RawTextComparator.WS_IGNORE_ALL);
df.setRepository(git.getRepository());
df.format(diffEntry); // 打印文件差异具体内容
String diffText = new String(out.toByteArray(), "UTF-8");
public Git init(String remotePath) {
String dirName = remotePath.replace("gitlab", "igit").replace("igit.58corp.com:", "igit.58corp.com/").split("igit.58corp.com/")[1].replace("/", "_").replace(".git", "").replace("http:", "https:");
remotePath = remotePath.replace("http:", "https:");
logger.debug("start git init:" + remotePath + "; " + dirName);
// 设置远程服务器上的用户名和密码
// 克隆代码库命令
Git git = null;
try {
File localPath = new File(CoverageConstants.GIT_CODEBASE_ROOT + dirName);
if (!localPath.exists()) {
CloneCommand cloneCommand = Git.cloneRepository();
git = cloneCommand.setURI(remotePath.replace("gitlab", "igit").replace("git@igit.58corp.com:", "https://igit.58corp.com/")) // 设置远程URI
//.setBranch("master") // 设置clone下来的分支
.setDirectory(localPath) // 设置下载存放路径
.setCredentialsProvider(usernamePasswordCredentialsProvider) // 设置权限验证
.call();
git.fetch().setRemote("origin").setCredentialsProvider(usernamePasswordCredentialsProvider).call();
} else {
String URL = CoverageConstants.GIT_CODEBASE_ROOT + dirName + "/.git";
git = Git.open(new File(URL));
git.fetch().setRemote("origin").setCredentialsProvider(usernamePasswordCredentialsProvider).call();
}
} catch (TransportException e) {
logger.error("init git error:" + remotePath + ":" + e.getMessage());
} catch (IOException e) {
logger.error("init git error:" + remotePath + ":" + e.getMessage());
} catch (InvalidRemoteException e) {
logger.error(e.getMessage());
} catch (GitAPIException e) {
logger.error("init git error:" + remotePath + ":" + e.getMessage());
}
logger.debug("init completed:");
return git;
}
本文介绍了如何使用EclipseJGit库进行Git操作,包括初始化Git仓库、从GitLab克隆代码并设置忽略空白字符比较。方法涉及设置远程服务器凭证、执行克隆和fetch命令,以及处理异常情况。

2万+

被折叠的 条评论
为什么被折叠?



