Skip to content

fix(libnpmdiff): keep a final blank context line in the diff - #10231

Open
simshanith wants to merge 1 commit into
npm:latestfrom
simshanith:fix/libnpmdiff-trailing-context
Open

simshanith wants to merge 1 commit into
npm:latestfrom
simshanith:fix/libnpmdiff-trailing-context

Conversation

@simshanith

@simshanith simshanith commented Nov 5, 2026 •

Copy link
Copy Markdown

formatDiff in libnpmdiff ends with return res.trim() to drop the patch's final newline. trim() also strips trailing whitespace, though. In unified diff format an unchanged blank line is a single space, so when the last hunk ends on one, trim() deletes it. The hunk header still counts that line, and git apply rejects the output as a corrupt patch.

This change removes only the final newline: return res.replace(/\n$/, '').

Repro, from the issue:

  1. In an empty directory, with npm 12.2.2 and git on the path, unpack lit-ui-router 1.19.0. Its successor 1.19.1 ends the diff on a blank context line in src/view-rendered.ts:

    npm pack lit-ui-router@1.19.0
    mkdir a && tar -xzf lit-ui-router-1.19.0.tgz -C a --strip-components=1
  2. With the default npm config (no diff-* options set).

  3. Run npm diff --diff=lit-ui-router@1.19.0 --diff=lit-ui-router@1.19.1 > out.diff, then cd a && git init -q && git apply --check ../out.diff.

  4. See the error: error: corrupt patch at ../out.diff:1232. The last hunk's header is @@ -99,9 +113,8 @@, but the hunk holds only 8 old and 7 new lines.

The new test, keep a blank context line that ends the diff, diffs a\nb\n\n against a\nc\n\n. It checks for the @@ -1,3 +1,3 @@ header and that the output ends with the blank context line. It fails before this change.

Fixes #10230

Written by an agent (Claude Code, claude-opus-5-5).

formatDiff trimmed its output to drop the final newline, but trim() also
removed a trailing blank context line (a single space), leaving the last
hunk one line short of its header and the patch corrupt.
@simshanith
simshanith marked this pull request as ready for review November 5, 2026 06:19
@simshanith
simshanith requested a review from a team as a code owner November 5, 2026 06:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] npm diff drops a final blank context line, so its output is a corrupt patch

1 participant