我正在尝试使用JGit来获取上次提交的文件与最近未提交的更改之间的差异。我怎么能用JGit做到这一点? (使用命令行将是git diff HEAD
)
经过多次讨论(link1,link2)后,我提供了一段能够找到未提交文件的代码,但我无法区分文件
Repository db = new FileRepository("/path/to/git");
Git git = new Git(db);
AbstractTreeIterator oldTreeParser = this.prepareTreeParser(db, Constants.HEAD);
List<DiffEntry> diff = git.diff().setOldTree(oldTreeParser).call();
for (DiffEntry entry : diff) {
System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
DiffFormatter formatter = new DiffFormatter(System.out);
formatter.setRepository(db);
formatter.format(entry);
}
更新
这个问题很久以前了。我现有的用于显示未提交的代码。在显示差异的上下文中,我用于prepareTreeParser
的当前代码是:
public void gitDiff() throws Exception {
Repository db = new FileRepository("/path/to/git" + DEFAULT_GIT);
Git git = new Git(db);
ByteArrayOutputStream out = new ByteArrayOutputStream();
DiffFormatter formatter = new DiffFormatter( out );
formatter.setRepository(git.getRepository());
AbstractTreeIterator commitTreeIterator = prepareTreeParser(git.getRepository(), Constants.HEAD);
FileTreeIterator workTreeIterator = new FileTreeIterator( git.getRepository() );
List<DiffEntry> diffEntries = formatter.scan( commitTreeIterator, workTreeIterator );
for( DiffEntry entry : diffEntries ) {
System.out.println("DIFF Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
formatter.format(entry);
String diffText = out.toString("UTF-8");
System.out.println(diffText);
out.reset();
}
git.close();
db.close();
// This code is untested. It is slighting different for the code I am using in production,
// but it should be very easy to adapt it for your needs
}
private static AbstractTreeIterator prepareTreeParser(Repository repository, String ref) throws Exception {
Ref head = repository.getRef(ref);
RevWalk walk = new RevWalk(repository);
RevCommit commit = walk.parseCommit(head.getObjectId());
RevTree tree = walk.parseTree(commit.getTree().getId());
CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
ObjectReader oldReader = repository.newObjectReader();
try {
oldTreeParser.reset(oldReader, tree.getId());
} finally {
oldReader.release();
}
return oldTreeParser;
}
答案 0 :(得分:6)
以下设置适用于我:
DiffFormatter formatter = new DiffFormatter( System.out );
formatter.setRepository( git.getRepository() );
AbstractTreeIterator commitTreeIterator = prepareTreeParser( git.getRepository(), Constants.HEAD );
FileTreeIterator workTreeIterator = new FileTreeIterator( git.getRepository() );
List<DiffEntry> diffEntries = formatter.scan( commitTreeIterator, workTreeIterator );
for( DiffEntry entry : diffEntries ) {
System.out.println( "Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId() );
formatter.format( entry );
}
通过FileTreeIterator
可以访问未提交的更改。使用formatter.scan()
代替DiffCommand
具有以下优势:格式化程序已正确设置以处理FileTreeIterator
。否则,当格式化程序尝试从存储库中的工作树中查找更改时,您将获得MissingObjectException
。