loadwise 0.6.2 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +152 -100
- package/dist/bin/loadwise.js +126 -49
- package/dist/lib/accessibility/frontend-detect.js +6 -5
- package/dist/lib/accessibility/usage.js +10 -2
- package/dist/lib/editor/configured-setup.js +61 -0
- package/dist/lib/editor/editor-launcher.js +165 -0
- package/dist/lib/editor/fix-edits.js +19 -0
- package/dist/lib/editor/jetbrains-setup.js +53 -0
- package/dist/lib/editor/language-server.js +31 -14
- package/dist/lib/editor/managed-config.js +37 -0
- package/dist/lib/editor/native-setup.js +85 -0
- package/dist/lib/editor/release-vsix.js +61 -0
- package/dist/lib/editor/server-commands.js +2 -0
- package/dist/lib/editor/setup-server.js +87 -0
- package/dist/lib/editor/setup-vim.js +61 -0
- package/dist/lib/editor/setup.js +131 -0
- package/dist/lib/editor/stdio-setup.js +6 -0
- package/dist/lib/maintainability/cli/inputs.js +3 -2
- package/dist/lib/maintainability/cli.js +14 -5
- package/dist/lib/maintainability/examples.js +4 -0
- package/dist/lib/maintainability/rule-ids.js +3 -0
- package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
- package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
- package/dist/lib/performance/cli/changed-lines.js +8 -1
- package/dist/lib/performance/cli/cli-arguments.js +19 -8
- package/dist/lib/performance/cli/cli-output.js +3 -0
- package/dist/lib/performance/cli.js +8 -4
- package/dist/lib/performance/datastores/pg-integrity.js +7 -0
- package/dist/lib/performance/datastores/pooling.js +6 -1
- package/dist/lib/performance/engine/native-syntax.js +3 -0
- package/dist/lib/performance/frontend/frontend-perf.js +80 -20
- package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
- package/dist/lib/performance/request/fastify-receivers.js +93 -0
- package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
- package/dist/lib/performance/request/mongoose-lean.js +140 -53
- package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
- package/dist/lib/performance/request/phase5-ast.js +6 -7
- package/dist/lib/performance/request/phase5-rules.js +133 -13
- package/dist/lib/performance/request/request-handlers.js +120 -23
- package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
- package/dist/lib/performance/site-fixes/collections.js +1 -2
- package/dist/lib/performance/site-fixes/frontend-fixes.js +10 -6
- package/dist/lib/performance/site-fixes/helpers.js +3 -4
- package/dist/lib/performance/site-fixes/integrity.js +2 -4
- package/dist/lib/reliability/react-bugs.js +11 -3
- package/dist/lib/reliability/usage.js +16 -5
- package/dist/lib/security/cli.js +15 -4
- package/dist/lib/shared/agent/agent-init.js +26 -4
- package/dist/lib/shared/agent/agent-prompt.js +74 -0
- package/dist/lib/shared/agent/agent-session.js +6 -1
- package/dist/lib/shared/agent/agent-verify.js +54 -10
- package/dist/lib/shared/agent/review-delivery.js +1 -1
- package/dist/lib/shared/analysis/scan-cache.js +3 -2
- package/dist/lib/shared/check.js +172 -20
- package/dist/lib/shared/fix/fix-convergence.js +15 -29
- package/dist/lib/shared/fix/fix-handoff.js +16 -11
- package/dist/lib/shared/fix/fix-imports.js +47 -38
- package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
- package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
- package/dist/lib/shared/fix/fix-presentation.js +4 -3
- package/dist/lib/shared/fix/fix-safety.js +26 -1
- package/dist/lib/shared/fix/fix-scope.js +82 -0
- package/dist/lib/shared/fix/fix-terminal.js +28 -1
- package/dist/lib/shared/fix/project-file-access.js +17 -26
- package/dist/lib/shared/fix/read-fix-text.js +20 -0
- package/dist/lib/shared/fix.js +215 -102
- package/dist/lib/shared/report-fp.js +93 -0
- package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
- package/dist/lib/shared/reporting/check-text.js +50 -0
- package/dist/lib/shared/reporting/pillars.js +45 -16
- package/dist/lib/shared/reporting/source-report.js +2 -0
- package/dist/lib/shared/system/atomic-write.js +5 -2
- package/dist/lib/shared/system/sentry.js +203 -0
- package/dist/lib/shared/system/shell-argument.js +5 -1
- package/dist/lib/shared/system/terminal-safe.js +3 -2
- package/dist/lib/shared/system/terminal-style.js +131 -0
- package/docs/assets/cli-workflow.gif +0 -0
- package/integrations/sublime/plugin.py +22 -0
- package/integrations/zed/Cargo.lock +845 -0
- package/integrations/zed/Cargo.toml +11 -0
- package/integrations/zed/extension.toml +11 -0
- package/integrations/zed/src/lib.rs +25 -0
- package/package.json +11 -3
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/commands/loadwise.md +11 -6
- package/schema/loadwise.config.schema.json +2 -0
|
@@ -30,6 +30,50 @@ function changedRows(beforeRows, afterRows) {
|
|
|
30
30
|
same++;
|
|
31
31
|
return { first, beforeEnd: beforeRows.length - same, afterEnd: afterRows.length - same };
|
|
32
32
|
}
|
|
33
|
+
const maxDiffCells = 4_000_000;
|
|
34
|
+
// Line hunks `{ start, end, rows }` that turn `before` rows into `after` rows, or undefined when
|
|
35
|
+
// the changed region is too large to compare.
|
|
36
|
+
function lineHunks(before, after) {
|
|
37
|
+
const { first, beforeEnd, afterEnd } = changedRows(before, after);
|
|
38
|
+
const left = before.slice(first, beforeEnd);
|
|
39
|
+
const right = after.slice(first, afterEnd);
|
|
40
|
+
if ((left.length + 1) * (right.length + 1) > maxDiffCells)
|
|
41
|
+
return;
|
|
42
|
+
// Longest common subsequence lengths of the suffixes left[i..] and right[j..].
|
|
43
|
+
const width = right.length + 1;
|
|
44
|
+
const common = new Uint32Array((left.length + 1) * width);
|
|
45
|
+
for (let i = left.length - 1; i >= 0; i--) {
|
|
46
|
+
for (let j = right.length - 1; j >= 0; j--) {
|
|
47
|
+
common[i * width + j] =
|
|
48
|
+
left[i] === right[j]
|
|
49
|
+
? common[(i + 1) * width + j + 1] + 1
|
|
50
|
+
: Math.max(common[(i + 1) * width + j], common[i * width + j + 1]);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const hunks = [];
|
|
54
|
+
let open;
|
|
55
|
+
let i = 0;
|
|
56
|
+
let j = 0;
|
|
57
|
+
while (i < left.length || j < right.length) {
|
|
58
|
+
if (i < left.length && j < right.length && left[i] === right[j]) {
|
|
59
|
+
if (open)
|
|
60
|
+
hunks.push(open);
|
|
61
|
+
open = undefined;
|
|
62
|
+
i++;
|
|
63
|
+
j++;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
open ??= { start: first + i, end: first + i, rows: [] };
|
|
67
|
+
if (j < right.length && (i === left.length || common[i * width + j + 1] >= common[(i + 1) * width + j])) {
|
|
68
|
+
open.rows.push(right[j++]);
|
|
69
|
+
}
|
|
70
|
+
else
|
|
71
|
+
open.end = first + ++i;
|
|
72
|
+
}
|
|
73
|
+
if (open)
|
|
74
|
+
hunks.push(open);
|
|
75
|
+
return hunks;
|
|
76
|
+
}
|
|
33
77
|
// Tracks which rows of a file each applied change owns while Prettier rewrites them. A segment is a
|
|
34
78
|
// run of rows: unchanged original rows, or rows written by changes (`owners`) that replaced
|
|
35
79
|
// `originalLength` original rows.
|
|
@@ -154,4 +198,4 @@ function styleRegions(segments, beforeRowsOf) {
|
|
|
154
198
|
}
|
|
155
199
|
return regions;
|
|
156
200
|
}
|
|
157
|
-
export { bottomFirst, changedRows, followSteps, ownedHunks, rangesOf, replaceRows, segmentsOf, splitRows, styleRegions, };
|
|
201
|
+
export { lineHunks, bottomFirst, changedRows, followSteps, ownedHunks, rangesOf, replaceRows, segmentsOf, splitRows, styleRegions, };
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// How an applied fix reads in the project: a one-line comment above the fixed statement says why it changed, and the
|
|
2
2
|
// project's own Prettier reformats only the changed lines. Prettier's API is asynchronous while the fix paths are
|
|
3
3
|
// not, so formatting runs once per fix run in a child process started from this file.
|
|
4
|
-
import
|
|
4
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
5
5
|
import { createRequire } from 'node:module';
|
|
6
6
|
import path from 'node:path';
|
|
7
7
|
import * as ts from 'typescript';
|
|
8
8
|
import { pillarOfRule, rulesByPillar } from '../rule-registry.js';
|
|
9
|
+
import { readFixText } from './read-fix-text.js';
|
|
9
10
|
import { writeFileAtomic } from '../system/atomic-write.js';
|
|
10
11
|
import { createWhyCommentTools, formatComment, withoutComment } from './fix-presentation-comments.js';
|
|
11
12
|
import { formatInChild, formatRanges, missingPrettierNote, scriptFile } from './fix-presentation-prettier.js';
|
|
@@ -147,7 +148,7 @@ function createWriteTracker() {
|
|
|
147
148
|
const files = [...segmentsByFile].map(([file, segments]) => ({
|
|
148
149
|
file,
|
|
149
150
|
segments,
|
|
150
|
-
text:
|
|
151
|
+
text: readFixText(file),
|
|
151
152
|
ranges: bottomFirst(rangesOf(segments)).map(({ start, end }) => [start, end]),
|
|
152
153
|
}));
|
|
153
154
|
const stepsByFile = formatRanges(import.meta.filename, root, files.map(({ file, text, ranges }) => ({ file, text, ranges })));
|
|
@@ -159,7 +160,7 @@ function createWriteTracker() {
|
|
|
159
160
|
: matchFileStyle(loadTs, file, text, styleRegions(segments, beforeRowsOf));
|
|
160
161
|
if (formattedText === text)
|
|
161
162
|
continue;
|
|
162
|
-
if (
|
|
163
|
+
if (readFixText(file) !== text)
|
|
163
164
|
continue;
|
|
164
165
|
writeFileAtomic(file, formattedText);
|
|
165
166
|
const formatted = ownedHunks(steps?.length ? followSteps(segments, text, steps) : segments, [], splitRows(formattedText));
|
|
@@ -31,6 +31,31 @@ function introducedSyntaxError(file, before, after) {
|
|
|
31
31
|
remaining.set(key, (remaining.get(key) ?? 0) - 1);
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
|
+
function validateSource(file, text) {
|
|
35
|
+
if (!javaScriptFile.test(file))
|
|
36
|
+
return;
|
|
37
|
+
const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
|
|
38
|
+
ts.bindSourceFile(source, {});
|
|
39
|
+
const [diagnostic] = source.bindDiagnostics ?? [];
|
|
40
|
+
if (diagnostic)
|
|
41
|
+
throw new Error(`${file}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, ' ')} No fixes applied.`);
|
|
42
|
+
const hasBody = (declaration) => (ts.isFunctionDeclaration(declaration) ||
|
|
43
|
+
ts.isMethodDeclaration(declaration) ||
|
|
44
|
+
ts.isConstructorDeclaration(declaration)) &&
|
|
45
|
+
Boolean(declaration.body);
|
|
46
|
+
function duplicateImplementation(node) {
|
|
47
|
+
if ((ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node) || ts.isConstructorDeclaration(node)) &&
|
|
48
|
+
node.body &&
|
|
49
|
+
(node.symbol?.declarations?.filter((declaration) => declaration.kind === node.kind && hasBody(declaration))
|
|
50
|
+
.length ?? 0) > 1) {
|
|
51
|
+
return node.name?.getText(source) ?? 'constructor';
|
|
52
|
+
}
|
|
53
|
+
return ts.forEachChild(node, duplicateImplementation);
|
|
54
|
+
}
|
|
55
|
+
const duplicate = duplicateImplementation(source);
|
|
56
|
+
if (duplicate)
|
|
57
|
+
throw new Error(`${file}: duplicate implementation of ${duplicate}. No fixes applied.`);
|
|
58
|
+
}
|
|
34
59
|
function refusalReason(file, syntaxError) {
|
|
35
60
|
return `${file}: the fix would introduce a syntax error (${syntaxError}), so the file was not changed`;
|
|
36
61
|
}
|
|
@@ -61,4 +86,4 @@ function applyFixSafely(applyFix, fix, { readFile, writeFile }, ...options) {
|
|
|
61
86
|
writeFile(file, text);
|
|
62
87
|
return result;
|
|
63
88
|
}
|
|
64
|
-
export { applyFixSafely, introducedSyntaxError, refusalReason };
|
|
89
|
+
export { applyFixSafely, introducedSyntaxError, refusalReason, validateSource };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { collectChangedLines, fileKey } from '../../performance/cli/changed-lines.js';
|
|
4
|
+
import { discoverWorkspaces, isWithin, selectWorkspaces } from '../workspaces.js';
|
|
5
|
+
import { realTarget } from '../system/real-target.js';
|
|
6
|
+
import { hunkRange } from './fix-convergence.js';
|
|
7
|
+
function scopedWorkspaceRoots({ directory, workspace }) {
|
|
8
|
+
if (!workspace.length)
|
|
9
|
+
return;
|
|
10
|
+
const { packages, withoutConfig } = discoverWorkspaces(directory);
|
|
11
|
+
return selectWorkspaces([...packages, ...withoutConfig], directory, workspace).map((entry) => realTarget(entry.directory));
|
|
12
|
+
}
|
|
13
|
+
// Every contiguous block of untouched original lines must survive in order. Anchor the first
|
|
14
|
+
// and last blocks to their file boundaries. This also handles edits far apart in a large file.
|
|
15
|
+
function preservesOutsideRanges(before, after, ranges) {
|
|
16
|
+
const rows = before.split('\n');
|
|
17
|
+
const output = '\n' + after + '\n';
|
|
18
|
+
let originalRow = 0;
|
|
19
|
+
let outputOffset = 0;
|
|
20
|
+
for (const [start, end] of ranges) {
|
|
21
|
+
const nextRow = Math.min(start - 1, rows.length);
|
|
22
|
+
if (originalRow < nextRow) {
|
|
23
|
+
const block = '\n' + rows.slice(originalRow, nextRow).join('\n') + '\n';
|
|
24
|
+
const found = output.indexOf(block, outputOffset);
|
|
25
|
+
if (found < 0 || (originalRow === 0 && found !== 0))
|
|
26
|
+
return false;
|
|
27
|
+
outputOffset = found + block.length - 1;
|
|
28
|
+
}
|
|
29
|
+
originalRow = Math.max(originalRow, end);
|
|
30
|
+
}
|
|
31
|
+
if (originalRow >= rows.length)
|
|
32
|
+
return true;
|
|
33
|
+
const suffix = '\n' + rows.slice(originalRow).join('\n') + '\n';
|
|
34
|
+
return output.endsWith(suffix) && output.length - suffix.length >= outputOffset;
|
|
35
|
+
}
|
|
36
|
+
export function fixScopeGuard(scope) {
|
|
37
|
+
const roots = scopedWorkspaceRoots(scope);
|
|
38
|
+
if (!roots && !scope.staged && scope.ref === undefined)
|
|
39
|
+
return;
|
|
40
|
+
// Git reports paths relative to its working directory; fix targets use physical paths.
|
|
41
|
+
const directory = realTarget(scope.directory);
|
|
42
|
+
function currentRanges() {
|
|
43
|
+
if (!scope.staged && scope.ref === undefined)
|
|
44
|
+
return;
|
|
45
|
+
const changed = collectChangedLines({ staged: scope.staged, ref: scope.ref, allFiles: true }, directory);
|
|
46
|
+
if (scope.staged) {
|
|
47
|
+
// Staged ranges use index coordinates; a partially staged working file can have different lines there.
|
|
48
|
+
const unstaged = execFileSync('git', ['diff', '--relative', '--name-only', '--no-renames', '-z', '--', '.'], {
|
|
49
|
+
cwd: directory,
|
|
50
|
+
encoding: 'utf8',
|
|
51
|
+
});
|
|
52
|
+
for (const name of unstaged.split('\0').filter(Boolean))
|
|
53
|
+
changed.delete(fileKey(path.resolve(directory, name)));
|
|
54
|
+
}
|
|
55
|
+
return changed;
|
|
56
|
+
}
|
|
57
|
+
const ranges = currentRanges();
|
|
58
|
+
function inWorkspace(file) {
|
|
59
|
+
return !roots || roots.some((root) => isWithin(root, file));
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
allowsChange(change) {
|
|
63
|
+
const file = realTarget(path.resolve(directory, change.file));
|
|
64
|
+
if (!inWorkspace(file))
|
|
65
|
+
return false;
|
|
66
|
+
if (!ranges)
|
|
67
|
+
return true;
|
|
68
|
+
const [first, last] = hunkRange(change);
|
|
69
|
+
return (!change.create && Boolean(ranges.get(fileKey(file))?.some(([start, end]) => start <= first && last <= end)));
|
|
70
|
+
},
|
|
71
|
+
validateUpdates(updates) {
|
|
72
|
+
if (!updates.length || !ranges)
|
|
73
|
+
return;
|
|
74
|
+
const latest = currentRanges();
|
|
75
|
+
for (const { file, before, after } of updates) {
|
|
76
|
+
const permitted = latest?.get(fileKey(realTarget(file)));
|
|
77
|
+
if (!permitted?.length || before === undefined || !preservesOutsideRanges(before, after, permitted))
|
|
78
|
+
throw new Error(`Final edits to ${file} extend outside the verified changed lines. No fixes applied.`);
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { changedRows, lineHunks } from './fix-presentation-rows.js';
|
|
1
2
|
import * as readline from 'node:readline/promises';
|
|
2
3
|
async function askChoice(prompt) {
|
|
3
4
|
const reader = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
@@ -62,4 +63,30 @@ function labelledLines(label, text, indentation = ' ') {
|
|
|
62
63
|
const hanging = ' '.repeat(head.length);
|
|
63
64
|
return wrapWords(text, terminalNoteWidth - head.length).map((line, index) => (index ? hanging : head) + line);
|
|
64
65
|
}
|
|
65
|
-
|
|
66
|
+
// Keep line terminators while comparing so the preview also shows a missing final newline.
|
|
67
|
+
function* previewDiff(before, after) {
|
|
68
|
+
const lines = (text) => text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
69
|
+
const removed = lines(before);
|
|
70
|
+
const added = lines(after);
|
|
71
|
+
let hunks = lineHunks(removed, added);
|
|
72
|
+
if (!hunks) {
|
|
73
|
+
const { first, beforeEnd, afterEnd } = changedRows(removed, added);
|
|
74
|
+
hunks = [{ start: first, end: beforeEnd, rows: added.slice(first, afterEnd) }];
|
|
75
|
+
}
|
|
76
|
+
let offset = 0;
|
|
77
|
+
for (const { start, end, rows } of hunks) {
|
|
78
|
+
const count = end - start;
|
|
79
|
+
yield `@@ -${start + Number(count > 0)},${count} +${start + offset + Number(rows.length > 0)},${rows.length} @@`;
|
|
80
|
+
yield* patchLines('-', removed.slice(start, end));
|
|
81
|
+
yield* patchLines('+', rows);
|
|
82
|
+
offset += rows.length - count;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function* patchLines(marker, lines) {
|
|
86
|
+
for (const line of lines) {
|
|
87
|
+
yield marker + line.replace(/\r?\n$/, '');
|
|
88
|
+
if (!line.endsWith('\n'))
|
|
89
|
+
yield '\';
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
export { previewDiff, askChoice, diffLines, labelledLines, wrapWords };
|
|
@@ -6,6 +6,7 @@ import fs from 'node:fs';
|
|
|
6
6
|
import path from 'node:path';
|
|
7
7
|
import { renameWithRetry, unlinkWithRetry, writeResolvedFileAtomic } from '../system/atomic-write.js';
|
|
8
8
|
import { errorCode, errorMessage } from '../system/error-code.js';
|
|
9
|
+
import { currentText, readFixText } from './read-fix-text.js';
|
|
9
10
|
import { realTarget } from '../system/real-target.js';
|
|
10
11
|
const byteOrderMark = '\uFEFF';
|
|
11
12
|
// What `link` reports when a filesystem or a system policy does not allow hard links. Windows reports a volume
|
|
@@ -44,7 +45,7 @@ function projectFileAccess(roots, base = roots[0]) {
|
|
|
44
45
|
assertCanFix: resolveSafe,
|
|
45
46
|
readFile(file) {
|
|
46
47
|
const { absolute, real } = resolveSafe(file);
|
|
47
|
-
const text =
|
|
48
|
+
const text = readFixText(real);
|
|
48
49
|
if (!text.startsWith(byteOrderMark))
|
|
49
50
|
return text;
|
|
50
51
|
marked.add(absolute);
|
|
@@ -52,22 +53,13 @@ function projectFileAccess(roots, base = roots[0]) {
|
|
|
52
53
|
},
|
|
53
54
|
writeFile(file, text) {
|
|
54
55
|
const { absolute, real } = resolveSafe(file);
|
|
56
|
+
currentText(real); // Recheck the target before replacing it, including files created since the plan.
|
|
55
57
|
// A fix can create a file, such as a migration, in a folder that does not exist yet.
|
|
56
58
|
fs.mkdirSync(path.dirname(real), { recursive: true });
|
|
57
59
|
writeResolvedFileAtomic(real, (marked.has(absolute) ? byteOrderMark : '') + text);
|
|
58
60
|
},
|
|
59
61
|
};
|
|
60
62
|
}
|
|
61
|
-
function currentText(filename) {
|
|
62
|
-
try {
|
|
63
|
-
return fs.readFileSync(filename, 'utf8');
|
|
64
|
-
}
|
|
65
|
-
catch (error) {
|
|
66
|
-
if (errorCode(error) === 'ENOENT')
|
|
67
|
-
return undefined;
|
|
68
|
-
throw error;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
63
|
// A hard link makes the complete staged file appear at once and never replaces an existing one. The exclusive copy
|
|
72
64
|
// used where links are unavailable does not replace one either. Returns whether the file was linked.
|
|
73
65
|
function publishNewFile(temporary, file) {
|
|
@@ -82,16 +74,20 @@ function publishNewFile(temporary, file) {
|
|
|
82
74
|
fs.copyFileSync(temporary, file, fs.constants.COPYFILE_EXCL);
|
|
83
75
|
return false;
|
|
84
76
|
}
|
|
77
|
+
function assertCurrentTarget(file, expected) {
|
|
78
|
+
if (realTarget(file) !== file || currentText(file) !== expected)
|
|
79
|
+
throw new Error('File changed while applying fixes: ' + file);
|
|
80
|
+
}
|
|
85
81
|
function commitStagedUpdates(staged, written) {
|
|
86
82
|
for (const update of staged) {
|
|
87
83
|
const { file, before, temporary } = update;
|
|
88
|
-
if (currentText(file) !== before || realTarget(file) !== file)
|
|
89
|
-
throw new Error('File changed while applying fixes: ' + file);
|
|
90
84
|
let linked = false;
|
|
91
|
-
if (before === undefined)
|
|
85
|
+
if (before === undefined) {
|
|
86
|
+
assertCurrentTarget(file, before);
|
|
92
87
|
linked = publishNewFile(temporary, file);
|
|
88
|
+
}
|
|
93
89
|
else
|
|
94
|
-
renameWithRetry(temporary, file);
|
|
90
|
+
renameWithRetry(temporary, file, () => assertCurrentTarget(file, before));
|
|
95
91
|
written.push(update);
|
|
96
92
|
// Drop the staged name at once: later fixes refuse a file with two names. A failure here rolls the run back.
|
|
97
93
|
if (linked)
|
|
@@ -105,8 +101,7 @@ function writeFixUpdates(updates) {
|
|
|
105
101
|
try {
|
|
106
102
|
for (const update of updates) {
|
|
107
103
|
const { file, before } = update;
|
|
108
|
-
|
|
109
|
-
throw new Error('File changed while applying fixes: ' + file);
|
|
104
|
+
assertCurrentTarget(file, before);
|
|
110
105
|
if (before === undefined)
|
|
111
106
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
112
107
|
else
|
|
@@ -128,15 +123,11 @@ function writeFixUpdates(updates) {
|
|
|
128
123
|
catch (error) {
|
|
129
124
|
const unrestored = [];
|
|
130
125
|
for (const { file, before, after, temporary } of written.reverse()) {
|
|
131
|
-
const
|
|
126
|
+
const assertStillApplied = () => assertCurrentTarget(file, after);
|
|
132
127
|
try {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
unlinkWithRetry(file, () => {
|
|
137
|
-
if (hasChanged())
|
|
138
|
-
throw new Error('File changed during rollback: ' + file);
|
|
139
|
-
});
|
|
128
|
+
assertStillApplied();
|
|
129
|
+
if (before === undefined)
|
|
130
|
+
unlinkWithRetry(file, assertStillApplied);
|
|
140
131
|
else {
|
|
141
132
|
const mode = fs.statSync(file).mode;
|
|
142
133
|
const descriptor = fs.openSync(temporary, 'wx', mode);
|
|
@@ -148,7 +139,7 @@ function writeFixUpdates(updates) {
|
|
|
148
139
|
finally {
|
|
149
140
|
fs.closeSync(descriptor);
|
|
150
141
|
}
|
|
151
|
-
renameWithRetry(temporary, file);
|
|
142
|
+
renameWithRetry(temporary, file, assertStillApplied);
|
|
152
143
|
}
|
|
153
144
|
}
|
|
154
145
|
catch {
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { isUtf8 } from 'node:buffer';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { errorCode } from '../system/error-code.js';
|
|
4
|
+
// Validate bytes before decoding: replacement characters inserted by Node cannot be recovered on write.
|
|
5
|
+
export function readFixText(file) {
|
|
6
|
+
const bytes = fs.readFileSync(file);
|
|
7
|
+
if (!isUtf8(bytes))
|
|
8
|
+
throw new Error('Invalid UTF-8 in fix target: ' + file + '. Save the file as UTF-8 before applying fixes.');
|
|
9
|
+
return bytes.toString('utf8');
|
|
10
|
+
}
|
|
11
|
+
export function currentText(file) {
|
|
12
|
+
try {
|
|
13
|
+
return readFixText(file);
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
if (errorCode(error) === 'ENOENT')
|
|
17
|
+
return undefined;
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
}
|