Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai c3e0b8bd58 fix(vcs): stop rescanning the file per hunk when opening large diffs
Opening a working-tree diff from the commit panel computes a key for
every hunk (hunkKeys). Each key called currentHunkText, which rebuilt the
line-start table of the whole file, so a file with many changes cost
hunks x file size: a 9.4 MB JSON with 17,931 changes kept the web view
busy for minutes and froze the window.

rollbackEdit and currentHunkText now take an optional precomputed
lineStarts table. hunkKeys builds it once. The other per-hunk loops pass
theirs too: line-level partial commits (commitSelection), the partial
commit projection, the commit-check rollback fallback, and stage/unstage
from the gutter.
2026-12-01 06:25:35 +08:00
6 змінених файлів з 48 додано та 18 видалено

No files matched your search

+15
Переглянути файл
@@ -224,6 +224,21 @@ describe("hunkKeys", () => {
const twice = hunkKeys("B\nB\n", [h("modified", 0, 1, 0, 1, "b\n"), h("modified", 1, 1, 1, 1, "b\n")]);
expect(twice[0]).not.toBe(twice[1]);
});
it("scans the text once, not once per hunk (#6892)", () => {
// A generated file with a change on every other line: thousands of hunks over one text.
const text = Array.from({ length: 2_000 }, (_, i) => `line ${i}\n`).join("");
const hunks = Array.from({ length: 1_000 }, (_, i) => h("modified", i * 2, 1, i * 2, 1, `old ${i}\n`));
const indexOf = vi.spyOn(String.prototype, "indexOf");
try {
const keys = hunkKeys(text, hunks);
expect(new Set(keys).size).toBe(hunks.length);
// One `indexOf` per line break; rescanning per hunk would make it about 2,000,000.
expect(indexOf.mock.calls.length).toBeLessThan(10_000);
} finally {
indexOf.mockRestore();
}
});
});
describe("hunksInSelection (Rollback Lines)", () => {
+3 -2
Переглянути файл
@@ -32,7 +32,7 @@ import { useVcs } from "./store";
import { commitTodoRules, todoCheckResult, todosForCommit } from "./commitTodo";
import { commitTestSelection, runCommitTests } from "./commitTests";
import { stopPendingPostCommitTests } from "./postCommitChecks";
import { hunkKeys, rollbackEdit } from "./hunks";
import { hunkKeys, lineStarts, rollbackEdit } from "./hunks";
import { keepsExcludedChanges, partialCommitProjection } from "./partialCommitProjection";
import type { CommitCheck, CommitCheckContext, CommitFix } from "./commitCheckRegistry";
import { getCommitChecks, registerCommitCheck } from "./commitCheckRegistry";
@@ -170,8 +170,9 @@ export async function prepareSnapshotModifications(
if (accept && !accept(composed)) {
// Some servers return a full-document replacement for a small edit.
const hunks = await commands.vcsDiffHunks(updated.toString(), before);
const starts = lineStarts(before);
composed = ChangeSet.of(
hunks.map((h) => rollbackEdit(before, h)),
hunks.map((h) => rollbackEdit(before, h, starts)),
original.length,
);
if (!accept(composed) || !composed.apply(original).eq(updated)) return;
+3 -2
Переглянути файл
@@ -22,7 +22,7 @@ import { useChangelists } from "./changelists";
import { protectedAmendBranches } from "./amendTargets";
import { inclusionChecks, stagedRepositories, stagedRepositoryScope, stagingAreaOn, statusForCommit } from "./staging";
import { sameCommitDraft, useCommit } from "./commitStore";
import { currentHunkText, hunkKeys } from "./hunks";
import { currentHunkText, hunkKeys, lineStarts } from "./hunks";
import { baseName, rootOf, stripSlash } from "./model";
import { saveAll } from "./ops";
import { currentRepo, refreshNow, useVcs, type VcsState } from "./store";
@@ -176,6 +176,7 @@ async function partialCommitFiles(paths: readonly string[]): Promise<{ files: Pa
// oxlint-disable-next-line no-await-in-loop -- hunks are diffed per path before the stale-diff check and before pushing to the ordered result arrays
const hunks = await commands.vcsDiffHunks(head ?? "", text);
const keys = hunkKeys(text, hunks);
const starts = lineStarts(text);
const excluded = excludedHunks.get(path) ?? excludedHunks.get(`${path}/`);
const linesByHunk = excludedHunkLines.get(path) ?? excludedHunkLines.get(`${path}/`);
if (linesByHunk && [...linesByHunk.keys()].some((key) => !keys.includes(key))) throw staleDiff();
@@ -190,7 +191,7 @@ async function partialCommitFiles(paths: readonly string[]): Promise<{ files: Pa
lineHunks.push({
range,
oldText: h.oldText,
newText: currentHunkText(text, h),
newText: currentHunkText(text, h, starts),
deletions: includedOffsets(oldLines, selection.old),
additions: includedOffsets(lines, selection.current),
});
+11 -5
Переглянути файл
@@ -248,14 +248,20 @@ export async function updateStagedLines(target: GutterChangeTarget, operation: "
if (index?.version !== version || view.state.doc !== working || !stagingAreaOn())
throw new Error(tx("The displayed versions have changed. Refresh the diff and try again."));
const text = working.toString();
const starts = lineStarts(text);
const indexStarts = lineStarts(index.text);
const edits = hunks
.map((hunk) => {
const range = hunk.staging!;
return rollbackEdit(index.text, {
start: range.indexStart,
lines: range.indexLines,
oldText: operation === "stage" ? currentHunkText(text, hunk) : hunk.oldText,
});
return rollbackEdit(
index.text,
{
start: range.indexStart,
lines: range.indexLines,
oldText: operation === "stage" ? currentHunkText(text, hunk, starts) : hunk.oldText,
},
indexStarts,
);
})
.sort((a, b) => b.from - a.from);
let next = index.text;
+14 -7
Переглянути файл
@@ -15,16 +15,19 @@ export function lineStarts(text: string): number[] {
return starts;
}
function startOfLine(starts: number[], line: number): number {
function startOfLine(starts: readonly number[], line: number): number {
return starts[Math.min(line, starts.length - 1)]!;
}
/** The edit that restores the hunk's original text (IDEA "Rollback Lines"). */
/**
* The edit that restores the hunk's original text (IDEA "Rollback Lines"). Callers handling
* many hunks of one text pass its `lineStarts` once instead of rescanning the text per hunk.
*/
export function rollbackEdit(
text: string,
hunk: Pick<LineHunk, "start" | "lines" | "oldText">,
starts: readonly number[] = lineStarts(text),
): { from: number; to: number; insert: string } {
const starts = lineStarts(text);
const from = startOfLine(starts, hunk.start);
const to = hunk.lines === 0 ? from : startOfLine(starts, hunk.start + hunk.lines);
// Hunks are computed over terminator-inclusive lines, so a plain replacement restores
@@ -76,10 +79,13 @@ export function prevHunk<H extends Pick<LineHunk, "start" | "lines">>(
return hunks[hunks.length - 1];
}
/** Current text of the hunk's lines (for the popup's "new" side). */
export function currentHunkText(text: string, hunk: Pick<LineHunk, "start" | "lines">): string {
/** Current text of the hunk's lines (for the popup's "new" side); `starts` as in `rollbackEdit`. */
export function currentHunkText(
text: string,
hunk: Pick<LineHunk, "start" | "lines">,
starts: readonly number[] = lineStarts(text),
): string {
if (hunk.lines === 0) return "";
const starts = lineStarts(text);
return text.slice(startOfLine(starts, hunk.start), startOfLine(starts, hunk.start + hunk.lines));
}
@@ -112,8 +118,9 @@ export function hunksOverlapping(
*/
export function hunkKeys(text: string, hunks: readonly Pick<LineHunk, "start" | "lines" | "oldText">[]): string[] {
const seen = new Map<string, number>();
const starts = lineStarts(text);
return hunks.map((h) => {
const body = `${h.oldText}\u0000${currentHunkText(text, h)}`;
const body = `${h.oldText}\u0000${currentHunkText(text, h, starts)}`;
let x = 0x811c9dc5;
for (let i = 0; i < body.length; i++) x = Math.imul(x ^ body.charCodeAt(i), 0x01000193);
const base = `${(x >>> 0).toString(36)}:${body.length}`;
+2 -2
Переглянути файл
@@ -21,11 +21,11 @@ export function partialCommitProjection(
if (whole.delete(id)) continue;
const partial = lines.get(id);
if (!partial) {
edits.push(rollbackEdit(text, hunk));
edits.push(rollbackEdit(text, hunk, starts));
continue;
}
lines.delete(id);
if (partial.oldText !== hunk.oldText || partial.newText !== currentHunkText(text, hunk)) return null;
if (partial.oldText !== hunk.oldText || partial.newText !== currentHunkText(text, hunk, starts)) return null;
const additions = new Set(partial.additions);
const deletions = new Set(partial.deletions);
const oldLines = hunk.oldText.match(/[^\n]*\n|[^\n]+$/g) ?? [];