我调用了jgit log命令并找回了一些RevCommit对象.我可以从中获取一些基本信息,并使用以下代码获取更改的文件列表.我还需要做两件事:
1)如果提交没有父母,我如何获得以下信息?
2)如何获取每个文件中更改的内容的差异
RevCommit commit = null;
RevWalk rw = new RevWalk(repository);
RevCommit parent = null;
if (commit.getParent(0) != null) {
parent = rw.parseCommit(commit.getParent(0).getId());
}
DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
df.setRepository(repository);
df.setDiffComparator(RawTextComparator.DEFAULT);
df.setDetectRenames(true);
List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
for (DiffEntry diff : diffs) {
System.out.println(getCommitMessage());
System.out.println("changeType=" + diff.getChangeType().name()
+ " newMode=" + diff.getNewMode().getBits()
+ " newPath=" + diff.getNewPath()
+ " id=" + getHash());
}
Run Code Online (Sandbox Code Playgroud)
1)使用重载scan
方法,AbstractTreeIterator
如果没有父节点,则按如下方式调用:
df.scan(new EmptyTreeIterator(),
new CanonicalTreeParser(null, rw.getObjectReader(), commit.getTree());
Run Code Online (Sandbox Code Playgroud)
没有父项的情况仅用于初始提交,在这种情况下,diff的"之前"为空.
2)如果您想要git diff
样式输出,请使用以下内容:
df.format(diff);
Run Code Online (Sandbox Code Playgroud)
并且diff将被写入传递给构造函数的输出流.因此,要单独获取每个差异,应该可以为DiffFormatter
每个文件使用一个实例.或者您可以使用DiffFormatter
a ByteArrayOutputStream
,获取内容并在格式化下一个文件之前重置它.大概是这样的:
ByteArrayOutputStream out = new ByteArrayOutputStream();
DiffFormatter df = new DiffFormatter(out);
// ...
for (DiffEntry diff : diffs) {
df.format(diff);
String diffText = out.toString("UTF-8");
// use diffText
out.reset();
}
Run Code Online (Sandbox Code Playgroud)
请注意,Git不知道文件的编码,必须在toString()
方法中指定.在这里它使用合理的默认值.根据您的使用情况,您最好不要使用它来解码它toByteArray()
.
一般说明:确保始终释放RevWalk
和DiffFormat
使用的资源release()
.