Retrieving RevCommit Object Declaration Information in JGit

I called the jgit log command and returned some RevCommit objects. I can get basic information from him, and I use the following code to get a list of files that have changed. There are two more things I need:

1) how to get the information below when the commit has no parent?

2) how do I get the difference in the content that has changed in each file

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());
}
+5
source share
1 answer

1) Use the overloaded method scanwith AbstractTreeIteratorand call it as follows if there is no parent:

df.scan(new EmptyTreeIterator(),
        new CanonicalTreeParser(null, rw.getObjectReader(), commit.getTree());

The case without a parent element is only for the initial commit, in which case the "before" diff value is empty.

2) git diff, :

df.format(diff);

diff , . , , DiffFormatter . DiffFormatter ByteArrayOutputStream, reset . :

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();
}

, Git , toString(). . , toByteArray().


. , RevWalk DiffFormat release().

+6
source

All Articles