JGit - How to reuse the DiffFormatter

China☆狼群 提交于 2019-12-10 13:18:28

问题


It's a followup question of jgit - git diff based on file extension.

I am trying to add the formatted diff to List<String> but If I try to use same DiffFormatter as below then previous entries getting appended to the next one.

List<String> changes = new LinkedList<>();
            try (OutputStream outputStream = new ByteArrayOutputStream();
                    DiffFormatter diffFormatter = new DiffFormatter(outputStream)) {
                diffFormatter.setRepository(git1.getRepository());
                TreeFilter treeFilter = PathSuffixFilter.create(".txt");
                diffFormatter.setPathFilter(treeFilter);
                List<DiffEntry> entries = diffFormatter.scan(newTree, oldTree);
                for (DiffEntry diffEntry : entries) {
                    diffFormatter.format(diffEntry);
                    changes.add(outputStream.toString());
                    diffFormatter.flush();
                }
            }

Therefore I forced to create a DIffFormatter for every diff entry.

Is there a better way to create List<String> from List<DiffEntry> without creating a new DiffFormatter every time?


回答1:


The cause for the previous entries getting appended is that the same output stream is used. Calling outputStream.toString() returns a string of all the bytes that have been written so far. Hence each calling toString within the for loop will return all previously created diffs, plus the current one.

I see two ways of solving this issue:

  • Use a separate DiffFormatter within the for loop for each diff entry.

  • Implement a custom OutputStream that allows to discard previously written content.



来源:https://stackoverflow.com/questions/54019259/jgit-how-to-reuse-the-diffformatter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!