首页 > 解决方案 > 在 JGit 中,是否为单个 DiffEntry 调用 DiffFormatter.format(DiffEntry) 应该为整个提交提供差异?

问题描述

当我通过 DiffEntrys 迭代工作区和头部提交之间的差异时,看起来每个 DiffEntry 代表一个文件。但是,当我调用 formatter.format(DiffEntry) 时,我得到一个字符串,表示工作区和头部提交之间的所有差异。不仅仅是与 DiffEntry 关联的文件。那是它应该如何工作的吗?如何获得与 DiffEntry 关联的一个文件的差异?我需要自己解析字符串吗?

import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.DiffEntry;

...

    repository=m_git.getRepository();
    outputStream=new ByteArrayOutputStream()
    headObjectId=repository.resolve(Constants.HEAD);
    revWalk!=new RevWalk(repository);
    headRevCommit=revWalk.parseCommit(headObjectId);`
    
    // Get a list of diffs between the working tree and head commit
    formatter = new DiffFormatter(outputStream);
    formatter.setRepository(repository);
    commitTreeIterator = prepareTreeParser(headRevCommit);
    workTreeIterator = new FileTreeIterator(repository);
    diffEntries = formatter.scan(commitTreeIterator, workTreeIterator);
    while (diffIter.hasNext()) {  
   
        // Capture all the  differences into a string
        entry=cast(DiffEntry,diffIter.next());
        formatter.format(entry);
        x=outputStream.toString();
        
        // x has diffs for all files and not just the file this DiffEntry represents!
        System.out.println(entry.getNewPath());
        System.out.println(x); 
   }

它甚至在文档中声明它为一个文件条目格式化补丁脚本,所以我不明白为什么我将所有文件条目都放在一个字符串中:https://download.eclipse.org/jgit/site/5.8。 1.202007141445-r/apidocs/org/eclipse/jgit/diff/DiffFormatter.html#format-org.eclipse.jgit.diff.DiffEntry-

标签: javagitdiffjgit

解决方案


正如@Rüdiger Herrmann 指出的那样,我的代码将每个 DiffEntry 附加到 OutputStream。因为我使用的是 ByteArrayOutputStream,所以我可以在条目之间调用 ByteArrayOutputStream.reset(),这样每次调用 ByteOutputStream.toString() 时我只会得到一个 DiffEntry。

在我的代码示例中,它看起来像这样:

while (diffIter.hasNext()) {  

    // Capture all the  differences into a string
    entry=cast(DiffEntry,diffIter.next());
    formatter.format(entry);
    x=outputStream.toString();
    outputStream.reset(); 
    
    // x has diffs for all files and not just the file this DiffEntry represents!
    System.out.println(entry.getNewPath());
    System.out.println(x); 
}

推荐阅读