需求说明
JGit 提供了一个Git 命令的Java API,你可以在项目中使用git,像命令行一样方便操作,查询git项目。JGit项目目前由Eclipse维护,JGit主页https://www.eclipse.org/jgit/
我想查询一个git项目,他的某一个文件的历史改动记录,git命令中用
git log -p [file]
即可很容易实现,jgit中的LogCommand里面有很多参数可以设置命令,但是-p这个,无法实现,所以只能用DiffFormatter来依次对比该文件提交的所有历史版本不同
public static void test() {
try {
File gitWorkDir = new File("/home/test/GITTEST/");
Git git = null;
git = Git.open(gitWorkDir);
Repository repo = git.getRepository();
LogCommand log = git.log();
log.addPath("lakmal.txt");
ObjectId lastCommitId = repo.resolve(Constants.HEAD);
RevWalk rw = new RevWalk(repo);
RevCommit parent = rw.parseCommit(lastCommitId);
rw.sort(RevSort.COMMIT_TIME_DESC);
rw.markStart(parent);
log.setMaxCount(3);
Iterable<RevCommit> logMsgs = log.call();
for (RevCommit commit : logMsgs) {
System.out.println("\n\n\n\n\n\n\n\n\n\n----------------------------------------");
System.out.println("commit " + commit);
System.out.println("commit.toObjectId() " + commit.toObjectId());
System.out.println(" commit.getAuthorIdent().getName() " + commit.getAuthorIdent().getName());
System.out.println("" + commit.getAuthorIdent().getWhen());
System.out.println(" commit.getFullMessage())--- " + commit.getFullMessage());
System.out.println("---DIF STARTING ------------------------");
//RevTree tree = commit.getTree();DisabledOutputStream.INSTANCE
ByteArrayOutputStream out = new ByteArrayOutputStream();
DiffFormatter df = new DiffFormatter(out); // DisabledOutputStream.INSTANCE
df.setRepository(repo);
df.setDiffComparator(RawTextComparator.DEFAULT);
df.setDetectRenames(true);
//df.format(parent.getTree(), commit.getTree());
List<DiffEntry> diffs = df.scan(commit.getTree(), commit.getParent(0).getTree()); //df.scan(parent.getTree(), commit.getTree());
for (DiffEntry diff : diffs) {
//System.out.println(getCommitMessage());
//df.format(diff);
System.out.println("changeType=" + diff.getChangeType().name()
+ " \n newMode=" + diff.getNewMode().getBits()
+ " \nnewPath=" + diff.getNewPath()
+ " \nold path " + diff.getOldPath()
+ " \nHash code " + diff.hashCode()
+ " \nString " + diff.toString()
+ " \nchange " + diff.getChangeType().toString()
);
df.format(diff);
String diffText = out.toString("UTF-8");
System.out.println(diffText);
}
df.release();
out.close();
parent = commit;
}
} catch (Exception e) {
System.out.println("no head exception : " + e);
}
}