-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck-test-remove-tree.mjs
More file actions
207 lines (182 loc) · 6.71 KB
/
Copy pathcheck-test-remove-tree.mjs
File metadata and controls
207 lines (182 loc) · 6.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/**
* Test teardown that deletes a tree calls `removeTree`. A bare `rm` with
* `recursive: true` and no `maxRetries` races a late writer and flakes with ENOTEMPTY.
*
* Catches bare `rm(`, aliased `import { rm as remove }` calls, and `ns.rm(` when
* `ns` is a namespace/default import from node:fs, fs, or their /promises forms.
*
* Call, option, and import-binding detection is parser-backed (typescript-5):
* only real node:fs(/promises) ImportDeclaration bindings count, only Node-bound
* call expressions are considered, and `recursive` / `maxRetries` are read from
* the second argument's object-literal properties (including quoted keys). Nested
* objects in the path argument, member calls, comments, strings, regexes, and
* template substitutions are handled by the AST rather than text masking.
*/
import { createRequire } from 'node:module';
import { readdir, readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const require = createRequire(join(dirname(fileURLToPath(import.meta.url)), '../packages/agent-bundle/package.json'));
/** @type {typeof import('typescript-5')} */
const ts = require('typescript-5');
const roots = [
'packages/agent-bundle/tests',
'packages/workbench/tests',
'packages/rsc-runtime/tests',
'packages/rsc-markdown-stream/tests',
'packages/create-agent-bundle/tests',
];
const nodeFsSpecifier = /^(?:node:)?fs(?:\/promises)?$/u;
const isRemoveTreeHelper = (file) => /(?:^|\/)remove-tree\.ts$/u.test(file.replaceAll('\\', '/'));
const walk = async (directory, files) => {
let entries;
try {
entries = await readdir(directory, { withFileTypes: true });
} catch (error) {
if (error?.code === 'ENOENT') return;
throw error;
}
for (const entry of entries) {
const path = join(directory, entry.name);
if (entry.isDirectory()) await walk(path, files);
else if (/\.(?:ts|mts|mjs|js|tsx)$/u.test(entry.name)) files.push(path);
}
};
/**
* Named/aliased rm bindings and namespace/default bindings that expose .rm.
* Import bindings are collected from the TypeScript AST so comments and local
* identifiers cannot forge Node fs.rm bindings.
*/
export const removalBindings = (text, fileName = 'bindings.ts') => {
const bareNames = new Set();
const namespaceNames = new Set();
const sourceFile = ts.createSourceFile(
fileName,
text,
ts.ScriptTarget.Latest,
true,
scriptKindFor(fileName),
);
for (const statement of sourceFile.statements) {
if (!ts.isImportDeclaration(statement) || statement.importClause === undefined) continue;
if (statement.moduleSpecifier === undefined || !ts.isStringLiteral(statement.moduleSpecifier)) {
continue;
}
if (!nodeFsSpecifier.test(statement.moduleSpecifier.text)) continue;
const { importClause } = statement;
if (importClause.isTypeOnly) continue;
if (importClause.name !== undefined) {
namespaceNames.add(importClause.name.text);
}
const bindings = importClause.namedBindings;
if (bindings === undefined) continue;
if (ts.isNamespaceImport(bindings)) {
namespaceNames.add(bindings.name.text);
continue;
}
if (!ts.isNamedImports(bindings)) continue;
for (const element of bindings.elements) {
if (element.isTypeOnly) continue;
if (element.propertyName !== undefined) {
if (element.propertyName.text !== 'rm') continue;
bareNames.add(element.name.text);
continue;
}
if (element.name.text !== 'rm') continue;
bareNames.add('rm');
}
}
return { bareNames, namespaceNames };
};
const propertyName = (name) => {
if (ts.isIdentifier(name)) return name.text;
if (ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name)) return name.text;
return undefined;
};
/** Options flags from a call's second-argument object literal only. */
const optionsFlags = (optionsArg) => {
if (optionsArg === undefined || !ts.isObjectLiteralExpression(optionsArg)) {
return { recursive: false, hasRetries: false };
}
let recursive = false;
let hasRetries = false;
for (const property of optionsArg.properties) {
if (!ts.isPropertyAssignment(property)) continue;
const key = propertyName(property.name);
if (key === 'recursive' && property.initializer.kind === ts.SyntaxKind.TrueKeyword) {
recursive = true;
}
if (key === 'maxRetries') hasRetries = true;
}
return { recursive, hasRetries };
};
const isNodeBoundRmCall = (expression, bareNames, namespaceNames) => {
if (ts.isIdentifier(expression)) return bareNames.has(expression.text);
if (
ts.isPropertyAccessExpression(expression)
&& !expression.questionDotToken
&& expression.name.text === 'rm'
&& ts.isIdentifier(expression.expression)
) {
return namespaceNames.has(expression.expression.text);
}
return false;
};
const scriptKindFor = (fileName) => {
if (fileName.endsWith('.tsx')) return ts.ScriptKind.TSX;
if (fileName.endsWith('.jsx')) return ts.ScriptKind.JSX;
if (fileName.endsWith('.mjs') || fileName.endsWith('.js')) return ts.ScriptKind.JS;
return ts.ScriptKind.TS;
};
export const recursiveRmCalls = (text, fileName = 'check.ts') => {
const { bareNames, namespaceNames } = removalBindings(text);
const sourceFile = ts.createSourceFile(
fileName,
text,
ts.ScriptTarget.Latest,
true,
scriptKindFor(fileName),
);
const calls = [];
const visit = (node) => {
if (ts.isCallExpression(node) && isNodeBoundRmCall(node.expression, bareNames, namespaceNames)) {
const flags = optionsFlags(node.arguments[1]);
if (flags.recursive) {
const start = node.getStart(sourceFile);
calls.push({
call: text.slice(start, node.getEnd()),
hasRetries: flags.hasRetries,
line: sourceFile.getLineAndCharacterOfPosition(start).line + 1,
});
}
}
ts.forEachChild(node, visit);
};
visit(sourceFile);
return calls;
};
export const bareRecursiveRmFailures = (file, text) => {
if (isRemoveTreeHelper(file)) return [];
const failures = [];
for (const call of recursiveRmCalls(text, file)) {
if (call.hasRetries) continue;
failures.push(`${file}:${call.line} bare recursive rm. Use removeTree.`);
}
return failures;
};
const run = async () => {
const failures = [];
const files = [];
for (const root of roots) await walk(root, files);
for (const file of files) {
const text = await readFile(file, 'utf8');
failures.push(...bareRecursiveRmFailures(file, text));
}
if (failures.length > 0) {
console.error(failures.join('\n'));
process.exitCode = 1;
}
};
const invokedDirectly = process.argv[1] !== undefined
&& import.meta.url === pathToFileURL(process.argv[1]).href;
if (invokedDirectly) await run();