From 4d7cb9c9fdaac2a1533ce622238640d67e2e4b57 Mon Sep 17 00:00:00 2001 From: Greg Oledzki Date: Wed, 26 Aug 2026 14:22:46 +0200 Subject: [PATCH] Don't add a newline to a file which doesn't end with a newline --- .../openrewrite/jgit/api/ApplyCommand.java | 5 ++- .../jgit/api/ApplyCommandTest.java | 39 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/jgit/src/main/java/org/openrewrite/jgit/api/ApplyCommand.java b/jgit/src/main/java/org/openrewrite/jgit/api/ApplyCommand.java index d9ea89f7e..e6078af66 100644 --- a/jgit/src/main/java/org/openrewrite/jgit/api/ApplyCommand.java +++ b/jgit/src/main/java/org/openrewrite/jgit/api/ApplyCommand.java @@ -702,7 +702,10 @@ && canApplyAt(hunkLines, newLines, 0)) { } afterLastHunk = applyAt; } - if (!isNoNewlineAtEndOfFile(fh)) { + boolean noNewlineAtEnd = afterLastHunk < newLines.size() + ? rt.isMissingNewlineAtEnd() + : isNoNewlineAtEndOfFile(fh); + if (!noNewlineAtEnd) { newLines.add(null); } if (!rt.isMissingNewlineAtEnd()) { diff --git a/jgit/src/test/java/org/openrewrite/jgit/api/ApplyCommandTest.java b/jgit/src/test/java/org/openrewrite/jgit/api/ApplyCommandTest.java index 237fd9fb9..0e473ddab 100644 --- a/jgit/src/test/java/org/openrewrite/jgit/api/ApplyCommandTest.java +++ b/jgit/src/test/java/org/openrewrite/jgit/api/ApplyCommandTest.java @@ -165,6 +165,45 @@ void multiHunkPatchWithMismatchedContextIsRejected() .hasMessageContaining("hunk"); } + /** + * Test that applying a mid-file hunk to a file that has no trailing newline + * preserves the missing trailing newline, matching {@code git apply}. + */ + @Test + void midFileHunkPreservesMissingTrailingNewline() throws Exception { + // given + StringBuilder fileContent = new StringBuilder(); + for (int i = 1; i <= 20; i++) { + fileContent.append("Line ").append(i); + if (i < 20) { + fileContent.append('\n'); + } + } + writeFileAndCommit("test.txt", fileContent.toString()); + + String patch = "diff --git a/test.txt b/test.txt\n" + + "--- a/test.txt\n" + + "+++ b/test.txt\n" + + "@@ -5,6 +5,7 @@\n" + + " Line 5\n" + + " Line 6\n" + + " Line 7\n" + + "+New Line\n" + + " Line 8\n" + + " Line 9\n" + + " Line 10\n"; + + // when + ApplyResult result = applyPatch(patch); + + // then + assertThat(result.getUpdatedFiles()).isNotEmpty(); + String resultContent = readFile("test.txt"); + assertThat(resultContent).contains("New Line"); + assertThat(resultContent).doesNotEndWith("\n"); + assertThat(resultContent).endsWith("Line 20"); + } + private String multiHunkPatch(String eol) { return "diff --git a/test.txt b/test.txt" + eol + "--- a/test.txt" + eol