fix(core): count changed lines that start with ++ or --

countPatch skipped every line beginning with +++ or ---, so additions
and deletions went uncounted for content like SQL and Lua comments and
markdown rules. Only the file headers that precede a hunk are skipped
now. Mercurial diff rows read these counts.
This commit is contained in:
Kit Langton
2026-11-06 17:09:00 -08:00
Unverified
parent b2b5da600e
commit d130cddd02
2 changed files with 54 additions and 2 deletions
+10 -2
View File
@@ -24,9 +24,17 @@ export const deletePatch = (file: string, content: string) =>
export const countPatch = (patch: string) => {
let additions = 0
let deletions = 0
// Headers come only before a file's first hunk, so a changed line whose content starts with `++` or `--`
// (SQL and Lua comments, markdown rules) still counts. A `diff --git` line repeats the next file's headers.
let headers = true
for (const line of patch.split("\n")) {
if (line.startsWith("+") && !line.startsWith("+++")) additions++
else if (line.startsWith("-") && !line.startsWith("---")) deletions++
if (line.startsWith("diff --git ")) headers = true
else if (line.startsWith("@@")) headers = false
else if (line.startsWith("+")) {
if (!headers || !line.startsWith("+++")) additions++
} else if (line.startsWith("-")) {
if (!headers || !line.startsWith("---")) deletions++
}
}
return { additions, deletions }
}
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, test } from "bun:test"
import { VcsPatch } from "@opencode/core/vcs/patch"
describe("VcsPatch countPatch", () => {
test("counts a plain change", () => {
const patch = ["--- a/a.txt", "+++ b/a.txt", "@@ -1 +1 @@", "-old", "+new"].join("\n")
expect(VcsPatch.countPatch(patch)).toEqual({ additions: 1, deletions: 1 })
})
test("counts changed lines whose content starts with ++ or --", () => {
const patch = [
"--- a/query.sql",
"+++ b/query.sql",
"@@ -1,2 +1,2 @@",
"--- removed comment",
"+++ added comment",
" select 1;",
].join("\n")
expect(VcsPatch.countPatch(patch)).toEqual({ additions: 1, deletions: 1 })
})
test("ignores the file headers of every file in a patch", () => {
const patch = [
"diff --git a/a.txt b/a.txt",
"--- a/a.txt",
"+++ b/a.txt",
"@@ -1 +1 @@",
"-old",
"+new",
"diff --git a/b.txt b/b.txt",
"--- a/b.txt",
"+++ b/b.txt",
"@@ -1 +1 @@",
"-gone",
"+kept",
].join("\n")
expect(VcsPatch.countPatch(patch)).toEqual({ additions: 2, deletions: 2 })
})
test("counts a file added from nothing", () => {
const patch = ["--- /dev/null", "+++ b/new.txt", "@@ -0,0 +1,2 @@", "+first", "+second"].join("\n")
expect(VcsPatch.countPatch(patch)).toEqual({ additions: 2, deletions: 0 })
})
})