Skip to content

Commit 5d8ebf3

Browse files
authored
refactor(session-ui): parse session diff patches with pierre (#59017)
1 parent 1743d1a commit 5d8ebf3

2 files changed

Lines changed: 168 additions & 70 deletions

File tree

‎packages/session-ui/src/components/session-diff.test.ts‎

Lines changed: 100 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, test } from "bun:test"
22
import { parseDiffFromFile } from "@pierre/diffs"
3+
import { createTwoFilesPatch } from "diff"
34
import { completePatchContents, normalize, resolveFileDiff, text } from "./session-diff"
45

56
const header = "diff --git a/a.ts b/a.ts\nindex 1a2b3c4..5d6e7f8 100644\n--- a/a.ts\n+++ b/a.ts\n"
@@ -103,7 +104,10 @@ describe("session diff", () => {
103104
})
104105

105106
test.each([
106-
["missing final newlines", "@@ -1,2 +1,2 @@\n one\n-two\n\\ No newline at end of file\n+three\n\\ No newline at end of file\n"],
107+
[
108+
"missing final newlines",
109+
"@@ -1,2 +1,2 @@\n one\n-two\n\\ No newline at end of file\n+three\n\\ No newline at end of file\n",
110+
],
107111
["an added final newline", "@@ -1,2 +1,2 @@\n one\n-two\n\\ No newline at end of file\n+two\n"],
108112
["CRLF lines", "@@ -1,3 +1,3 @@\n one\r\n-two\r\n+three\r\n four\r\n"],
109113
["a new file", "@@ -0,0 +1,3 @@\n+one\n+two\n+three\n"],
@@ -119,13 +123,19 @@ describe("session diff", () => {
119123
{ name: "a.ts", contents: contents.after },
120124
)
121125

122-
expect({ ...resolveFileDiff({ file: "a.ts", patch }), cacheKey: undefined }).toEqual({ ...expected, cacheKey: undefined })
126+
expect({ ...resolveFileDiff({ file: "a.ts", patch }), cacheKey: undefined }).toEqual({
127+
...expected,
128+
cacheKey: undefined,
129+
})
123130
})
124131

125-
test.each(["a\tb.ts", "a\nb.ts", '"quoted"', " padded.ts "])("keeps the exact file name %j for complete patches", (file) => {
126-
expect(resolveFileDiff({ file, patch: `${header}@@ -1,2 +1,2 @@\n one\n-old\n+new\n` }).name).toBe(file)
127-
expect(resolveFileDiff({ file, patch: `${header}@@ -0,0 +0,0 @@\n` }).name).toBe(file)
128-
})
132+
test.each(["a\tb.ts", "a\nb.ts", '"quoted"', " padded.ts "])(
133+
"keeps the exact file name %j for complete patches",
134+
(file) => {
135+
expect(resolveFileDiff({ file, patch: `${header}@@ -1,2 +1,2 @@\n one\n-old\n+new\n` }).name).toBe(file)
136+
expect(resolveFileDiff({ file, patch: `${header}@@ -0,0 +0,0 @@\n` }).name).toBe(file)
137+
},
138+
)
129139

130140
test("collapses unchanged runs in complete patches into the hunks of a fresh file diff", () => {
131141
const before = Array.from({ length: 40 }, (_, index) => `line ${index}\n`)
@@ -188,16 +198,16 @@ describe("session diff", () => {
188198
expect(resolveFileDiff({ file: "b.ts", patch }).name).toBe("b.ts")
189199
})
190200

191-
test.each([
192-
"@@ -1 +1 @@\n-old\n+new\n",
193-
"--- a.ts\t\n+++ a.ts\t\n@@ -1 +1 @@\n-old\n+new\n",
194-
])("reuses a highlight identity for the same cached patch: %s", (patch) => {
195-
const first = resolveFileDiff({ file: "a.ts", patch })
196-
expect(first.cacheKey).toBeString()
197-
expect(resolveFileDiff({ file: "a.ts", patch }).cacheKey).toBe(first.cacheKey)
198-
expect(resolveFileDiff({ file: "b.ts", patch }).cacheKey).not.toBe(first.cacheKey)
199-
expect(resolveFileDiff({ file: "a.ts", patch: patch.replace("+new", "+next") }).cacheKey).not.toBe(first.cacheKey)
200-
})
201+
test.each(["@@ -1 +1 @@\n-old\n+new\n", "--- a.ts\t\n+++ a.ts\t\n@@ -1 +1 @@\n-old\n+new\n"])(
202+
"reuses a highlight identity for the same cached patch: %s",
203+
(patch) => {
204+
const first = resolveFileDiff({ file: "a.ts", patch })
205+
expect(first.cacheKey).toBeString()
206+
expect(resolveFileDiff({ file: "a.ts", patch }).cacheKey).toBe(first.cacheKey)
207+
expect(resolveFileDiff({ file: "b.ts", patch }).cacheKey).not.toBe(first.cacheKey)
208+
expect(resolveFileDiff({ file: "a.ts", patch: patch.replace("+new", "+next") }).cacheKey).not.toBe(first.cacheKey)
209+
},
210+
)
201211

202212
test("keys preloaded content diffs by file name and content", () => {
203213
const diff = { file: "a.ts", before: "one\n", after: "two\n", additions: 1, deletions: 1 }
@@ -212,8 +222,9 @@ describe("session diff", () => {
212222
const patch = "@@ -1 +1 @@\n-old\n+new\n"
213223
const first = resolveFileDiff({ file: "evicted.ts", patch })
214224

215-
const keys = Array.from({ length: 20 }, (_, index) =>
216-
resolveFileDiff({ file: "evicted.ts", patch: patch.replace("+new", `+new${index}`) }).cacheKey,
225+
const keys = Array.from(
226+
{ length: 20 },
227+
(_, index) => resolveFileDiff({ file: "evicted.ts", patch: patch.replace("+new", `+new${index}`) }).cacheKey,
217228
)
218229

219230
expect(keys).not.toContain(first.cacheKey)
@@ -266,4 +277,75 @@ describe("session diff", () => {
266277
expect(text(view, "deletions")).toBe("")
267278
expect(text(view, "additions")).toBe("")
268279
})
280+
281+
describe("real patches", () => {
282+
const before = Array.from({ length: 30 }, (_, index) => `const line${index} = ${index}\n`).join("")
283+
const after = before.replace("const line3 = 3\n", "const line3 = 33\n").replace("const line25 = 25\n", "")
284+
const sum = 'import { a } from "./a"\n\nexport function sum(x: number, y: number) {\n return x + y\n}\n'
285+
286+
const git = (header: string) =>
287+
`diff --git ${header}\nindex da208dc..e8d3c2d 100644\n--- ${header.split(" ")[0]}\n+++ ${header.split(" ")[1]}\n@@ -1,5 +1,5 @@\n import { a } from "./a"\n \n-export function sum(x: number, y: number) {\n- return x + y\n+export function sum(x: number, y: number, z = 0) {\n+ return x + y + z\n }\n`
288+
289+
test("reads an edit tool patch as partial hunks", () => {
290+
// The edit and write tools call createTwoFilesPatch with jsdiff's default context and no headers.
291+
const fileDiff = resolveFileDiff({
292+
file: "src/lines.ts",
293+
patch: createTwoFilesPatch("src/lines.ts", "src/lines.ts", before, after),
294+
})
295+
296+
expect(fileDiff.name).toBe("src/lines.ts")
297+
expect(fileDiff.isPartial).toBe(true)
298+
expect(
299+
fileDiff.hunks.map((hunk) => [hunk.deletionStart, hunk.deletionCount, hunk.additionStart, hunk.additionCount]),
300+
).toEqual([
301+
[1, 8, 1, 8],
302+
[22, 9, 22, 8],
303+
])
304+
expect(fileDiff.deletionLines).toContain("const line3 = 3\n")
305+
expect(fileDiff.additionLines).toContain("const line3 = 33\n")
306+
expect(fileDiff.additionLines).not.toContain("const line25 = 25\n")
307+
})
308+
309+
test.each([
310+
["an edit", before, after],
311+
["a new file", "", "one\ntwo\n"],
312+
["a deleted file", "one\ntwo\n", ""],
313+
["CRLF lines without a final newline", "one\r\ntwo\r\nthree", "one\r\n2\r\nthree"],
314+
["an added final newline", "one\ntwo", "one\ntwo\n"],
315+
])("renders a full-context snapshot patch of %s like a fresh file diff", (_, before, after) => {
316+
const patch = createTwoFilesPatch("a.ts", "a.ts", before, after, "", "", { context: 2_147_483_647 })
317+
318+
expect(completePatchContents(patch)).toEqual({ before, after })
319+
expect({ ...resolveFileDiff({ file: "a.ts", patch }), cacheKey: undefined }).toEqual({
320+
...parseDiffFromFile({ name: "a.ts", contents: before }, { name: "a.ts", contents: after }),
321+
cacheKey: undefined,
322+
})
323+
})
324+
325+
test.each(["a/sum.ts b/sum.ts", "sum.ts sum.ts", "i/sum.ts w/sum.ts"])(
326+
"renders a full-context git patch with header %j as a complete diff",
327+
(header) => {
328+
// Git's diff.noprefix and diff.mnemonicPrefix settings change the header, not the hunks.
329+
expect(completePatchContents(git(header))).toEqual({
330+
before: sum,
331+
after: sum.replace("y: number)", "y: number, z = 0)").replace("x + y\n", "x + y + z\n"),
332+
})
333+
expect(resolveFileDiff({ file: "sum.ts", patch: git(header) }).isPartial).toBe(false)
334+
},
335+
)
336+
337+
test("keeps a missing final newline from a real CRLF git patch", () => {
338+
const patch =
339+
"diff --git a/crlf.txt b/crlf.txt\nindex bc16163..88fdbd5 100644\n--- a/crlf.txt\n+++ b/crlf.txt\n@@ -1,3 +1,3 @@\n one\r\n-two\r\n+2\r\n three\n\\ No newline at end of file\n"
340+
341+
expect(completePatchContents(patch)).toEqual({ before: "one\r\ntwo\r\nthree", after: "one\r\n2\r\nthree" })
342+
})
343+
344+
test("ignores an edit tool patch whose hunk lost a line", () => {
345+
const patch = createTwoFilesPatch("a.ts", "a.ts", before, after).replace(" const line1 = 1\n", "")
346+
347+
expect(resolveFileDiff({ file: "a.ts", patch }).hunks).toEqual([])
348+
expect(completePatchContents(patch)).toBeUndefined()
349+
})
350+
})
269351
})

‎packages/session-ui/src/components/session-diff.ts‎

Lines changed: 68 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { parseDiffFromFile, parsePatchFiles, processFile, type FileDiffMetadata } from "@pierre/diffs"
2-
import { parsePatch } from "diff"
32
import { checksum } from "@opencode/util/encode"
43
import type { FileDiffInfo } from "@opencode/client/promise"
54
import type { PresentationFileDiff } from "../file-presentation"
@@ -65,11 +64,10 @@ function fileDiffFromPatch(file: string, patch: string) {
6564
}
6665

6766
const complete = completePatch(patch)
68-
const input = complete ? undefined : patchInput(file, patch)
6967

7068
const value = complete
7169
? fileDiffFromCompletePatch(file, complete)
72-
: ((input ? parsePatchFiles(input)[0]?.files[0] : undefined) ?? emptyFileDiff(file))
70+
: (partialFileDiff(file, patch) ?? emptyFileDiff(file))
7371

7472
// The patch text fixes both the content and the producer's alignment, so equal keys always mean equal hunks.
7573
value.cacheKey = highlightKey(key)
@@ -89,64 +87,84 @@ export function completePatchContents(patch: string) {
8987
}
9088

9189
function completePatch(patch: string) {
92-
try {
93-
const parsed = parsePatch(patch)[0]
94-
95-
if (!parsed || (!parsed.index && !parsed.oldFileName && !parsed.newFileName)) return
96-
97-
// Snapshot and VCS producers request full context. Tool patches use jsdiff's shorter default context.
98-
if (!patch.startsWith("diff --git ") && !/^--- [^\n]*\t\r?\n\+\+\+ [^\n]*\t(?:\r?\n|$)/m.test(patch)) return
90+
const parsed = splitPatch(patch)
9991

100-
// Full patches collapse into one leading hunk. Separated hunks omit ranges and must stay partial.
101-
if (parsed.hunks.length !== 1) return
92+
if (!parsed) return
10293

103-
const hunk = parsed.hunks[0]
94+
// Snapshot and VCS producers request full context. Tool patches use jsdiff's shorter default context.
95+
if (!parsed.header.startsWith("diff --git ") && !/^--- [^\n]*\t\r?\n\+\+\+ [^\n]*\t(?:\r?\n|$)/m.test(parsed.header))
96+
return
10497

105-
if (!hunk || hunk.oldStart > 1 || hunk.newStart > 1) return
98+
// Full patches collapse into one leading hunk. Separated hunks omit ranges and must stay partial.
99+
if (parsed.hunks.length !== 1) return
106100

107-
const before: Array<{ text: string; newline: boolean }> = []
108-
const after: Array<{ text: string; newline: boolean }> = []
109-
let previous: "-" | "+" | " " | undefined
101+
const hunk = parsed.hunks[0]!
110102

111-
for (const line of hunk.lines) {
112-
if (line.startsWith("\\")) {
113-
if (previous === "-" || previous === " ") {
114-
const value = before.at(-1)
103+
// An empty side's start names the line before the hunk, so `-1,0` begins after line 1.
104+
if (hunk.deletionStart + (hunk.deletionCount ? 0 : 1) > 1 || hunk.additionStart + (hunk.additionCount ? 0 : 1) > 1)
105+
return
115106

116-
if (value) value.newline = false
117-
}
107+
const lines: string[] = []
108+
const before: Array<{ text: string; newline: boolean }> = []
109+
const after: Array<{ text: string; newline: boolean }> = []
110+
let previous: "-" | "+" | " " | undefined
118111

119-
if (previous === "+" || previous === " ") {
120-
const value = after.at(-1)
112+
for (const line of parsed.body.split("\n").slice(1)) {
113+
if (before.length >= hunk.deletionCount && after.length >= hunk.additionCount && !line.startsWith("\\")) break
114+
lines.push(line)
121115

122-
if (value) value.newline = false
123-
}
116+
if (line.startsWith("\\")) {
117+
if (previous === "-" || previous === " ") {
118+
const value = before.at(-1)
124119

125-
continue
120+
if (value) value.newline = false
126121
}
127122

128-
if (line.startsWith("-")) {
129-
before.push({ text: line.slice(1), newline: true })
130-
previous = "-"
131-
continue
132-
}
123+
if (previous === "+" || previous === " ") {
124+
const value = after.at(-1)
133125

134-
if (line.startsWith("+")) {
135-
after.push({ text: line.slice(1), newline: true })
136-
previous = "+"
137-
continue
126+
if (value) value.newline = false
138127
}
139128

140-
if (!line.startsWith(" ")) return
129+
continue
130+
}
131+
132+
if (line.startsWith("-")) {
141133
before.push({ text: line.slice(1), newline: true })
134+
previous = "-"
135+
continue
136+
}
137+
138+
if (line.startsWith("+")) {
142139
after.push({ text: line.slice(1), newline: true })
143-
previous = " "
140+
previous = "+"
141+
continue
144142
}
145143

146-
const text = (lines: Array<{ text: string; newline: boolean }>) =>
147-
lines.map((line) => line.text + (line.newline ? "\n" : "")).join("")
144+
before.push({ text: line.slice(1), newline: true })
145+
after.push({ text: line.slice(1), newline: true })
146+
previous = " "
147+
}
148+
149+
const text = (lines: Array<{ text: string; newline: boolean }>) =>
150+
lines.map((line) => line.text + (line.newline ? "\n" : "")).join("")
151+
152+
return { before: text(before), after: text(after), lines }
153+
}
154+
155+
// Splits a one-file patch at its first hunk. Pierre's strict parser checks the hunks behind a fixed header, so a
156+
// malformed hunk rejects the patch while unusual file headers stay readable.
157+
function splitPatch(patch: string) {
158+
const start = patch.search(/^@@ /m)
159+
const header = start === -1 ? patch : patch.slice(0, start)
160+
const body = start === -1 ? "" : patch.slice(start)
148161

149-
return { before: text(before), after: text(after), lines: hunk.lines }
162+
try {
163+
const hunks = body
164+
? (processFile(`--- a\n+++ a\n${body}`, { isGitDiff: false, throwOnError: true })?.hunks ?? [])
165+
: []
166+
167+
return { header, body, hunks }
150168
} catch {
151169
return
152170
}
@@ -237,20 +255,18 @@ function splitHunk(lines: string[]) {
237255
.join("\n")
238256
}
239257

240-
function patchInput(file: string, patch: string) {
241-
try {
242-
const parsed = parsePatch(patch)[0]
258+
function partialFileDiff(file: string, patch: string) {
259+
const parsed = splitPatch(patch)
243260

244-
if (!parsed) return
261+
if (!parsed) return
245262

246-
if (parsed.index || parsed.oldFileName || parsed.newFileName) return patch
263+
if (/^(?:Index:|diff(?: -r \w+)+|---|\+\+\+)\s/m.test(parsed.header)) return parsePatchFiles(patch)[0]?.files[0]
247264

248-
if (!parsed.hunks.length) return
265+
if (!parsed.hunks.length) return
249266

250-
return `Index: ${file}\n===================================================================\n--- ${file}\t\n+++ ${file}\t\n${patch}`
251-
} catch {
252-
return
253-
}
267+
return parsePatchFiles(
268+
`Index: ${file}\n===================================================================\n--- ${file}\t\n+++ ${file}\t\n${patch}`,
269+
)[0]?.files[0]
254270
}
255271

256272
function fileDiffFromContent(file: string, before: string, after: string) {

0 commit comments

Comments
 (0)