mirror of
https://github.com/badlogic/pi-mono.git
synced 2026-12-05 13:56:25 +00:00
The edit tool rewrote the line endings of lines it did not touch. It could also fail after the file was already written, for example by running out of memory while diffing a large file. Encoding handling (non-UTF-8, UTF-16) was split out into a separate PR. ## Line endings (#8544) **Problem.** The edit tool looked for the first line ending in the file, normalized the whole file to LF for matching, and wrote the whole file back with that one ending: ``` a\nb\r\nX = 1\r\n edit X = 1 -> X = 2 => a\nb\nX = 2\n (both CRLF became LF) a\r\nb\nc edit c -> C => a\r\nb\r\nC (the LF became CRLF) a\rb\nX = 1\n edit X = 1 -> X = 2 => a\nb\nX = 2\n (untouched lone CR became LF) ``` **Solution.** Matching still runs on the LF-normalized text, so matching itself is unchanged: exact and fuzzy matching, multiple edits, duplicates, overlaps and error messages. `applyEditsToNormalizedContent` now also returns the replacements it applied. `applyReplacementsToOriginal` maps each replacement back to the original text and splices it in there. Normalizing only shortens CRLF to LF, so the original offset is the normalized offset plus the number of CRLFs before it. A range that covers a normalized LF therefore covers the whole CRLF. Text outside the replaced ranges keeps its bytes. Line breaks in the new text use the line ending of the line where the replaced range starts. For an unterminated last line, they use the ending of the line before. A lone CR is used only in files with no LF at all (classic Mac files). Elsewhere a lone CR is more likely a control character inside a line. Fuzzy matches still rewrite the whole lines they touch, as before. They now return those lines as one replacement instead of rebuilding the file, so lines outside the replacement keep their endings. A kept CR and an LF can meet at a splice seam and would then merge into one CRLF line break. For example, in `a\rb\nc` the edit `b -> \nB` would write `a\r\nB\nc` (normalized `a\nB\nc`) while the diff shows `a\n\nB\nc`. Deleting `b` would write `a\r\nc` while the diff shows `a\n\nc`. Whenever a piece ending in CR is followed by a piece starting with LF, an LF is added at the seam. This turns the CR into a CRLF of its own, so the written file normalizes to exactly the content the diff and patch describe. No kept byte is changed or removed; the one added byte sits where the replaced text was. For a pure deletion between a lone CR and an LF there is no other way to keep both line breaks. Writing the merged bytes and diffing them instead would silently join two lines the model meant to keep apart. Pure LF and pure CRLF files produce the same output as before. For files without any CR, the normalized result is written directly, as before. ## Diff before writing, only around the changes **Problem.** `execute` wrote the file and then ran `generateDiffString` and `generateUnifiedPatch`. Each diffs the whole file with jsdiff, which takes roughly 10 to 15 times the file size in memory, however small the change. A two-line edit of a 50 MB file crashed with `--max-old-space-size=256` after the new content was already on disk, and took about 4 s with the default heap. The TUI preview (`computeEditsDiff`) diffed the whole file again. **Solution.** - The diff and patch are computed before the file is written, so a failure there leaves the file unchanged. - The edit tool and the preview use a new internal `generateEditDiff`. The replacement positions are known, so it diffs only a window around each replacement: the replaced lines plus 32 unchanged lines on each side, with overlapping windows merged. jsdiff still does the diffing; the window results are renumbered to file line numbers. The display diff uses the same formatter as `generateDiffString` (extracted into `formatDisplayDiff`), and the patch is jsdiff's `structuredPatch` hunks shifted and written with `formatPatch`, as `createTwoFilesPatch` does. - `details.diff`, `details.patch` and `firstChangedLine` have the same format and content as before for every file size. The one possible difference: in runs of repeated lines, jsdiff may align a change differently within a window than over the whole file. The patch still applies and describes the same edit. - The exported `generateDiffString` and `generateUnifiedPatch` are unchanged. - The model-visible result is unchanged. ## Behavior differences - Files with mixed line endings or lone CRs keep their bytes outside the edited text. Files that use only CR line endings now get CR in inserted lines; before, the whole file was converted to LF. - Not changed: matching still builds a few file-sized strings (the normalized text and the fuzzy normalization used to count duplicates), so a very large file can still run out of memory during matching, before anything is written. - Removed unused internal helpers: `detectLineEnding`, `restoreLineEndings` and `applyReplacementsPreservingUnchangedLines`, which became the private `widenReplacementsToLines`. None of them were exported from the package. `packages/durable` has its own copy and is not changed. ## Testing - `npm run check`: clean. - `test/tools.test.ts`, the edit test files, `test/edit-diff-window.test.ts`, `test/file-mutation-queue.test.ts`, the BOM regression and `test/tool-execution-component.test.ts`: 174 passed. - New tests, all with `Buffer.equals` on the written bytes: - mixed endings with LF first and with CRLF first (#8544) - lone CR - pure CRLF and pure LF with inserted lines (unchanged behavior) - multiple edits in a mixed file, each new line getting its line's ending - fuzzy match widening in a mixed file - diff before write: `generateEditDiff` is mocked to throw, and `writeFile` is never called - `test/edit-diff-window.test.ts`: 2000 random edits on files with distinct lines give exactly the whole-file `generateDiffString` and `generateUnifiedPatch` output; 2000 random edits on files of repeated lines give a patch that applies to the old content and yields the new content; a small change in a 20 MB file is diffed in a child process with a 96 MB heap, where the whole-file diff runs out of memory; a replacement of 150,000 lines (no call-stack overflow) - seams: insertion after a lone CR, deletion between a lone CR and an LF (written bytes checked, and the patch applied to the old content gives the intended content), and an inserted CR ending before a kept LF - random property test: 3000 random mixed `\n`/`\r\n`/`\r` files with random edits, checking that the written content normalized to LF equals the content that was diffed. It fails without the seam rule. - On `origin/main`, all new tests fail except pure CRLF and pure LF, which pass there because that behavior is unchanged. Without the seam rule, the three seam tests fail. - Ad-hoc random comparison against `origin/main`'s implementation, 40k random edits: - On pure LF and pure CRLF files, the written output and the error messages are identical. - On files mixing `\n`, `\r\n` and `\r`, the normalized result is identical. - Memory and time, 50 MB file with a two-line edit: - before, `--max-old-space-size=256`: heap out-of-memory crash with the edit already written; default heap: about 4 s, about 1 GB RSS - after, `--max-old-space-size=256`: succeeds in about 0.9 s, about 410 MB RSS, normal 21-line patch; default heap: about 0.9 s, about 490 MB RSS This PR is AI-generated.
108 lines
4.7 KiB
TypeScript
108 lines
4.7 KiB
TypeScript
import { execFileSync } from "child_process";
|
|
import { applyPatch } from "diff";
|
|
import { resolve } from "path";
|
|
import { pathToFileURL } from "url";
|
|
import { describe, expect, it } from "vitest";
|
|
import {
|
|
generateDiffString,
|
|
generateEditDiff,
|
|
generateUnifiedPatch,
|
|
type TextReplacement,
|
|
} from "../src/core/tools/edit-diff.ts";
|
|
|
|
/** Small deterministic generator (mulberry32), using the high bits. */
|
|
function createRandom(seed: number): (max: number) => number {
|
|
let state = seed;
|
|
return (max) => {
|
|
state = (state + 0x6d2b79f5) | 0;
|
|
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
|
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
|
return Math.floor((((t ^ (t >>> 14)) >>> 0) / 4294967296) * max);
|
|
};
|
|
}
|
|
|
|
function applyReplacements(content: string, replacements: TextReplacement[]): string {
|
|
let result = "";
|
|
let position = 0;
|
|
for (const replacement of replacements) {
|
|
result += content.slice(position, replacement.matchIndex) + replacement.newText;
|
|
position = replacement.matchIndex + replacement.matchLength;
|
|
}
|
|
return result + content.slice(position);
|
|
}
|
|
|
|
/** Random content and sorted, disjoint, non-empty replacements; `distinct` makes every line unique. */
|
|
function randomCase(random: (max: number) => number, distinct: boolean) {
|
|
const lineCount = random(400);
|
|
const lines = Array.from({ length: lineCount }, (_, i) => (distinct ? `line ${i}` : ["a", "b", "", "}"][random(4)]));
|
|
const content = lines.join("\n") + (random(2) === 0 ? "\n" : "");
|
|
const replacements: TextReplacement[] = [];
|
|
let position = 0;
|
|
const count = 1 + random(4);
|
|
for (let i = 0; i < count && position < content.length; i++) {
|
|
const matchIndex = position + random(Math.min(content.length - position, 300));
|
|
if (matchIndex >= content.length) break;
|
|
const matchLength = 1 + random(Math.min(content.length - matchIndex, 120));
|
|
const newLines = Array.from({ length: random(4) }, (_, j) => `new ${i} ${j}`);
|
|
const newText = random(3) === 0 ? "" : newLines.join("\n") + (random(2) === 0 ? "\n" : "");
|
|
replacements.push({ matchIndex, matchLength, newText });
|
|
position = matchIndex + matchLength;
|
|
}
|
|
return { content, replacements, newContent: applyReplacements(content, replacements) };
|
|
}
|
|
|
|
describe("generateEditDiff", () => {
|
|
it("matches the whole-file diff and patch when lines are distinct", () => {
|
|
const random = createRandom(1);
|
|
for (let run = 0; run < 2000; run++) {
|
|
const { content, replacements, newContent } = randomCase(random, true);
|
|
if (content === newContent) continue;
|
|
const windowed = generateEditDiff("f.txt", content, newContent, replacements);
|
|
const whole = generateDiffString(content, newContent);
|
|
expect(windowed, `run ${run}`).toEqual({
|
|
diff: whole.diff,
|
|
patch: generateUnifiedPatch("f.txt", content, newContent),
|
|
firstChangedLine: whole.firstChangedLine,
|
|
});
|
|
}
|
|
});
|
|
|
|
it("produces a patch that applies when lines repeat", () => {
|
|
const random = createRandom(2);
|
|
for (let run = 0; run < 2000; run++) {
|
|
const { content, replacements, newContent } = randomCase(random, false);
|
|
if (content === newContent) continue;
|
|
const { patch } = generateEditDiff("f.txt", content, newContent, replacements);
|
|
expect(applyPatch(content, patch), `run ${run}`).toBe(newContent);
|
|
}
|
|
});
|
|
|
|
it("handles a replacement of many lines", () => {
|
|
const newText = "x\n".repeat(150000);
|
|
const replacements = [{ matchIndex: 0, matchLength: 2, newText }];
|
|
const { patch } = generateEditDiff("f.txt", "a\nb\n", `${newText}b\n`, replacements);
|
|
expect(applyPatch("a\nb\n", patch)).toBe(`${newText}b\n`);
|
|
});
|
|
|
|
it("diffs a small change in a 20 MB file with a 96 MB heap", () => {
|
|
// A child process, so a regression to diffing the whole file runs out of memory instead of passing.
|
|
const sourceResolverUrl = pathToFileURL(resolve(__dirname, "../src/experimental/source-resolver.ts")).href;
|
|
const editDiffUrl = pathToFileURL(resolve(__dirname, "../src/core/tools/edit-diff.ts")).href;
|
|
const script = `
|
|
import { generateEditDiff } from ${JSON.stringify(editDiffUrl)};
|
|
const filler = "x".repeat(99) + "\\n";
|
|
const half = filler.repeat(100000);
|
|
const base = half + "TARGET = 1\\n" + half;
|
|
const replacement = { matchIndex: half.length, matchLength: 10, newText: "TARGET = 2" };
|
|
const changed = half + "TARGET = 2\\n" + half;
|
|
const { diff } = generateEditDiff("big.txt", base, changed, [replacement]);
|
|
process.stdout.write(diff.split("\\n").filter((line) => /^[+-]/.test(line)).join("\\n"));
|
|
`;
|
|
const output = execFileSync(
|
|
process.execPath,
|
|
["--max-old-space-size=96", "--import", sourceResolverUrl, "--input-type=module", "--eval", script],
|
|
{ encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] },
|
|
);
|
|
expect(output).toBe("-100001 TARGET = 1\n+100001 TARGET = 2");
|
|
});
|
|
});
|