From a088e310dca3d32d3a475f1614295473aae68921 Mon Sep 17 00:00:00 2001 From: Nadya Zabrodina Date: Wed, 20 Jul 2016 01:33:29 +0300 Subject: [PATCH] [patch]: IDEA-158750 "Apply Patch" adds spurious newline at the end of file, tests added * existence of new line should be inherited by result from base content (before) if no hunks override it; * if some hunk overrides last line - it should be inherited from this hunk (after content); --- .../impl/patch/apply/GenericPatchApplier.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/apply/GenericPatchApplier.java b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/apply/GenericPatchApplier.java index cd1ec959c12b..9db55395370b 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/apply/GenericPatchApplier.java +++ b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/apply/GenericPatchApplier.java @@ -43,6 +43,7 @@ public class GenericPatchApplier { private final TreeMap myTransformations; private final List myLines; private final List myHunks; + private final boolean myBaseFileEndsWithNewLine; private boolean myHadAlreadyAppliedMet; private final ArrayList myNotBound; @@ -61,6 +62,7 @@ public class GenericPatchApplier { debug("GenericPatchApplier created, hunks: " + hunks.size()); myLines = new ArrayList(); Collections.addAll(myLines, LineTokenizer.tokenize(text, false)); + myBaseFileEndsWithNewLine = StringUtil.endsWithLineBreak(text); myHunks = hunks; final Comparator textRangeComparator = (o1, o2) -> new Integer(o1.getStartOffset()).compareTo(new Integer(o2.getStartOffset())); @@ -1041,16 +1043,25 @@ public class GenericPatchApplier { for (SplitHunk hunk : myNotBound) { linesToSb(sb, hunk.getAfterAll()); } - iterateTransformations(range -> linesToSb(sb, myLines.subList(range.getStartOffset(), range.getEndOffset() + 1)), range -> { + iterateTransformations(range -> { + linesToSb(sb, myLines.subList(range.getStartOffset(), range.getEndOffset() + 1)); + if (containsLastLine(range) && myBaseFileEndsWithNewLine) { + sb.append('\n'); + } + }, range -> { final MyAppliedData appliedData = myTransformations.get(range); linesToSb(sb, appliedData.getList()); + if (containsLastLine(range) && !mySuppressNewLineInEnd) { + sb.append('\n'); + } }); - if (! mySuppressNewLineInEnd) { - sb.append('\n'); - } return sb.toString(); } + private boolean containsLastLine(@NotNull TextRange range) { + return range.getEndOffset() == myLines.size() - 1; + } + private static void linesToSb(final StringBuilder sb, final List list) { if (sb.length() > 0 && !list.isEmpty()) { sb.append("\n");