1. jGit 针对单个文件比较这个文件最新的 commit
path 为文件路径
private static List<DiffEntry> diff(String path) throws GitAPIException, IOException {
try (Repository repository = RepositoryUtil.getRepository()) {
try (Git git = new Git(repository)) {
Iterable<RevCommit> commits = git.log()
.addPath(path)
.call();
RevCommit latestCommit =
StreamSupport.stream(commits.spliterator(), false)
.reduce((c1, c2) -> c1.getCommitTime() > c2.getCommitTime() ? c1 : c2)
.orElseThrow(NullPointerException::new);
AbstractTreeIterator oldTreeParser = TreeParserUtil.parser(repository, latestCommit.name());
return git.diff()
.setOldTree(oldTreeParser)
.setPathFilter(PathFilter.create(path))
.call();
}
}
}
2. 如果你想对 git diff 的结果进行输出
有两种办法:
2.1 对结果 DiffEntry 进行输出
public static void printDiff(DiffEntry entries){
DiffFormatter diffFormatter = new DiffFormatter(System.out);
try {
diffFormatter.setRepository(RepositoryUtil.getRepository());
diffFormatter.format(entries);
} catch (IOException e) {
e.printStackTrace();
}finally {
diffFormatter.close();
}
}
2.2 在进行 git.diff()方法调用的时候再调用.setOutputStream(System.out)
就像这样,当然传入的参数不止可以是 System.out,只要是 OutputStream 就行
return git.diff().setOutputStream(System.out)
.setOldTree(oldTreeParser)
.setPathFilter(PathFilter.create(path))
.call();
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于