Skip to content

apply_patch deletes the final blank line of files that end with one #42081

Closed as not planned

Description

@codeAnqiang-ma

Description

apply_patch deletes the final blank line of any file whose content ends with \n\n, even when the patch doesn't touch that line. The tool's own response confirms the unrequested change: it reports 2 deletions for a patch that asked for 1, and repeated edits keep eating one trailing newline each time.

Root cause: derive() in packages/core/src/patch.ts:71-81 uses the same test ("last array element is empty") for two different things. On the way in it pops the sentinel empty string produced by split("\n"); on the way out it checks updated.at(-1) !== "" to decide whether to push the sentinel back. When the file's last line is genuinely blank, the last element is still "" after popping, so the sentinel is never restored and one \n is lost. The legacy implementation has the same flaw (packages/opencode/src/patch/index.ts:314-327, under the comment "Ensure trailing newline").

Only LF files are affected (a CRLF file's last split element is "\r", not ""). Not the same as #37090 (CRLF→LF conversion) or #29124 (about adding a newline to files that lack one).

Disclosure: found and reproduced with AI assistance; I reviewed and verified every claim locally.

Plugins

No response

OpenCode version

dev @ 959c8bd

Steps to reproduce

  1. Create f.txt containing alpha\nbeta\n\n (ends with a blank line).
  2. Apply a patch that only changes alpha:
*** Begin Patch
*** Update File: f.txt
@@
-alpha
+ALPHA
*** End Patch
  1. Expected on disk: ALPHA\nbeta\n\n. Actual: ALPHA\nbeta\n — the trailing blank line is gone.

The unified diff the tool reports back shows the unrequested deletion:

@@ -1,3 +1,2 @@
-alpha
+ALPHA
 beta
-

Minimal reproduction against the function itself:

import { Patch } from "@opencode-ai/core/patch"
Patch.derive("f.txt", [{ oldLines: ["alpha"], newLines: ["ALPHA"] }], "alpha\nbeta\n\n").content
// returns "ALPHA\nbeta\n", expected "ALPHA\nbeta\n\n"

Screenshot and/or share link

No response

Operating System

macOS 15

Terminal

No response

Activity

  1. github-actions commented on Oct 13, 2026

    @github-actions
    Contributor

    To stay organized issues are automatically closed after 60 days of no activity. If the issue is still relevant please open a new one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions