fix(edit): correct diff @@ hunk headers at file boundaries

hunkBounds approximated one-sided start lines by reusing the opposite side's number, and re-assigned it every iteration inside the count==0 guard. For pure insertion/deletion hunks (e.g. writing into an empty file, or deleting a whole file) this produced wrong headers like '@@ -2,0 +1,2 @@' instead of '@@ -0,0 +1,2 @@'. flattenDiffLines now records both running line numbers on every line, so hunkBounds takes the start from the first line directly and applies GNU's zero-count convention (line-before-change, clamped to 0). Adds TestGenerateDiffHunkHeaderBounds.
This commit is contained in:
2026-06-20 00:33:32 +01:00
parent 53bc06df7f
commit b2c4101b5b
2 changed files with 42 additions and 23 deletions
+23
View File
@@ -427,6 +427,29 @@ func TestGenerateDiffLineLevelAccuracy(t *testing.T) {
}
}
// Hunk @@ headers must be correct at file boundaries (previously approximate).
func TestGenerateDiffHunkHeaderBounds(t *testing.T) {
e := &Engine{dmp: diffmatchpatch.New()}
tests := []struct {
name string
original string
modified string
wantHdr string
}{
{name: "insert into empty file", original: "", modified: "X\nY\n", wantHdr: "@@ -0,0 +1,2 @@"},
{name: "delete entire file", original: "a\nb\n", modified: "", wantHdr: "@@ -1,2 +0,0 @@"},
{name: "mid-file change keeps 1-based start", original: "l1\nl2\nl3\nl4\nl5\n", modified: "l1\nl2\nCHANGED\nl4\nl5\n", wantHdr: "@@ -1,5 +1,5 @@"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
diff := e.generateDiff(tt.original, tt.modified, "f.txt")
if !strings.Contains(diff, tt.wantHdr) {
t.Errorf("expected hunk header %q, got:\n%s", tt.wantHdr, diff)
}
})
}
}
func TestGenerateDiffNoPhantomChanges(t *testing.T) {
// Regression test: replacing a line range should not produce phantom
// +/- lines for unchanged code after the edit region.