Skip to content

Read and write empty hunk ranges the way diff and git do - #236

Open
youdie006 wants to merge 1 commit into
java-diff-utils:masterfrom
youdie006:empty-range-hunk-start
Open

youdie006 wants to merge 1 commit into
java-diff-utils:masterfrom
youdie006:empty-range-hunk-start

Conversation

@youdie006

@youdie006 youdie006 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

In a unified diff, a range with a count of 0 names the line before it: diff -U0 and git diff -U0 write an insertion after line 2 as @@ -2,0 +3 @@. java-diff-utils reads and writes that start as the first affected line instead. Its own round trip agrees with itself, but patches exchanged with other tools land one line off:

a,b,c -> a,b,X,c:

master this PR
GNU diff -U0 output parsed by UnifiedDiffUtils.parseUnifiedDiff + applyTo [a, X, b, c] [a, b, X, c]
same with UnifiedDiffReader.parseUnifiedDiff [a, X, b, c] [a, b, X, c]
generateUnifiedDiff(..., 0) header @@ -3,0 +3,1 @@ @@ -2,0 +3,1 @@
that patch applied by GNU patch a,b,c,X a,b,X,c

The parsers already treat -0,0 this way (if (old_ln == 0) old_ln = 1), and the writers already emit @@ -0,0 +1,n @@ for a new file; this extends the same rule to -N,0 for N > 0. Diffs with context of 1 or more only have an empty range when a file is empty, so they are unaffected otherwise.

Compatibility: zero-context patches generated by earlier versions of this library with a -N,0 or +N,0 range (N > 0) will now be read one line later.

Tests are added next to testNewFileCreation in GenerateUnifiedDiffTest, next to testWriteWithNewFile in UnifiedDiffWriterTest, and in UnifiedDiffReaderTest; they fail on master. mvn -B package passes on JDK 8 (154 tests); an earlier run also passed on JDK 11 and for the core module on JDK 17. I also checked the table above against GNU diff and patch.

Written with AI assistance (Claude); I have reviewed the change.

In a unified diff a range with a count of 0 names the line before it,
so "@@ -2,0 +3 @@" inserts after line 2. Both parsers took the start
as the first affected line and both writers wrote it that way, so a
zero-context diff from GNU diff or git was applied one line early, and
GNU patch applied ours one line late.

This branch has not been deployed

No deployments
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.

1 participant