Skip to content

Commit 5ff247b

Browse files
authored
test: prefer auto-cleaning temp dir helper (#93209)
Summary: - The branch adds `useAutoCleanupTempDirTracker()`, broadens the temp-dir warning reporter to flag new manual helper imports/usages, updates docs, and migrates two script tests to the new helper. - PR surface: Tests +301, Docs +1, Other +248. Total +550 across 8 files. - Reproducibility: not applicable. this is test/tooling cleanup, and the changed behavior is exercised through helper/reporter tests and CI evidence rather than a user reproduction path. Automerge notes: - PR branch already contained follow-up commit before automerge: test: harden temp dir helper guard - PR branch already contained follow-up commit before automerge: test: clarify auto cleanup temp dir helper name - PR branch already contained follow-up commit before automerge: test: cover existing mkdtemp temp dir forms - PR branch already contained follow-up commit before automerge: test: read staged temp helper source from index Validation: - ClawSweeper review passed for head 1fdd7d2. - Required merge gates passed before the squash merge. Prepared head SHA: 1fdd7d2 Review: #93209 (comment) Co-authored-by: Mason Huang <[email protected]> Approved-by: hxy91819
1 parent 7fa26e0 commit 5ff247b

8 files changed

Lines changed: 614 additions & 64 deletions

‎docs/help/testing.md‎

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -50,37 +50,38 @@ temporary directories. They make ownership explicit and keep cleanup in the same
5050
test lifecycle:
5151

5252
```ts
53-
import { afterEach } from "vitest";
54-
import { createTempDirTracker } from "../helpers/temp-dir.js";
53+
import { useAutoCleanupTempDirTracker } from "../helpers/temp-dir.js";
5554

56-
const tempDirs = createTempDirTracker();
57-
58-
afterEach(tempDirs.cleanup);
55+
const tempDirs = useAutoCleanupTempDirTracker();
5956

6057
it("uses a temp workspace", () => {
6158
const workspace = tempDirs.make("openclaw-example-");
6259
// use workspace
6360
});
6461
```
6562

66-
Use `makeTempDir(tempDirs, prefix)` and `cleanupTempDirs(tempDirs)` when a test
67-
already owns an array or set of paths. Avoid new bare `fs.mkdtemp*` calls in
68-
tests unless a case is explicitly verifying raw temp-dir behavior. Add an
69-
auditable allow comment with a concrete reason when a test intentionally needs a
70-
bare temp directory:
63+
`useAutoCleanupTempDirTracker()` intentionally exposes no manual cleanup method; Vitest
64+
owns cleanup after each test. Existing lower-level helpers remain for tests that
65+
have not moved yet, but new and migrated tests should use the auto-cleaning
66+
tracker. Avoid new manual `makeTempDir`, `cleanupTempDirs`, or
67+
`createTempDirTracker` usage and avoid new bare `fs.mkdtemp*` calls in tests
68+
unless a case is explicitly verifying raw temp-dir behavior. Add an auditable
69+
allow comment with a concrete reason when a test intentionally needs a bare temp
70+
directory:
7171

7272
```ts
7373
// openclaw-temp-dir: allow verifies raw fs cleanup behavior
7474
const workspace = fs.mkdtempSync(prefix);
7575
```
7676

7777
For migration visibility, `node scripts/report-test-temp-creations.mjs` reports
78-
new bare temp-dir creation in added diff lines without blocking existing cleanup
79-
styles. Its file scope intentionally follows the same test-path classification
80-
used by `scripts/changed-lanes.mjs` instead of maintaining a separate test-helper
81-
filename heuristic, while skipping the shared helper implementation itself.
82-
`check:changed` runs this report for changed test paths as a warning-only CI
83-
signal; findings are GitHub warning annotations, not failures.
78+
new bare temp-dir creation and new manual shared-helper usage in added diff
79+
lines without blocking existing cleanup styles. Its file scope intentionally
80+
follows the same test-path classification used by `scripts/changed-lanes.mjs`
81+
instead of maintaining a separate test-helper filename heuristic, while skipping
82+
the shared helper implementation itself. `check:changed` runs this report for
83+
changed test paths as a warning-only CI signal; findings are GitHub warning
84+
annotations, not failures.
8485

8586
When debugging real providers/models (requires real creds):
8687

‎scripts/report-test-temp-creations.mjs‎

Lines changed: 256 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
#!/usr/bin/env node
22

33
import { execFileSync } from "node:child_process";
4+
import fs from "node:fs";
5+
import path from "node:path";
6+
import ts from "typescript";
47
import { isChangedLaneTestPath } from "./changed-lanes.mjs";
58
import { booleanFlag, parseFlagArgs, stringFlag } from "./lib/arg-utils.mjs";
69
import { runAsScript } from "./lib/ts-guard-utils.mjs";
710

811
const DEFAULT_BASE_REF = "origin/main";
912
const DEFAULT_HEAD_REF = "HEAD";
1013
const TEMP_DIR_HELPER_PATH = "test/helpers/temp-dir.ts";
14+
const TEMP_DIR_HELPER_TEST_PATH = "test/helpers/temp-dir.test.ts";
15+
const MANUAL_TEMP_DIR_HELPERS = new Set(["cleanupTempDirs", "createTempDirTracker", "makeTempDir"]);
1116
const FINDING_PATTERNS = [
1217
{
1318
pattern: /\bmkdtemp(?:Sync)?\s*\(/u,
@@ -25,9 +30,9 @@ function usage() {
2530
return `Usage: node scripts/report-test-temp-creations.mjs [options]
2631
2732
Description:
28-
Reports new bare test temp-directory creation patterns in added diff lines.
33+
Reports new test temp-directory migration warnings in added diff lines.
2934
This is a low-noise migration aid, not a cleanup data-flow checker. It does
30-
not scan existing lines and does not decide whether cleanup is sufficient.
35+
not scan existing lines for bare temp dirs and does not decide whether cleanup is sufficient.
3136
Add "openclaw-temp-dir: allow <reason>" in a same-line or immediately
3237
preceding added comment when a test intentionally needs bare temp creation.
3338
File scope intentionally reuses scripts/changed-lanes.mjs test-path
@@ -64,6 +69,11 @@ function shouldInspectFile(filePath) {
6469
return normalizedPath !== TEMP_DIR_HELPER_PATH && isChangedLaneTestPath(normalizedPath);
6570
}
6671

72+
function shouldInspectManualHelperUsage(filePath) {
73+
const normalizedPath = normalizePath(filePath);
74+
return normalizedPath !== TEMP_DIR_HELPER_TEST_PATH && shouldInspectFile(normalizedPath);
75+
}
76+
6777
function isTruthyEnvFlag(value) {
6878
const normalized = String(value ?? "")
6979
.trim()
@@ -93,7 +103,7 @@ export function formatGithubWarning(finding) {
93103
const file = escapeGithubCommandProperty(finding.file);
94104
const line = escapeGithubCommandProperty(finding.line);
95105
const message = escapeGithubCommandValue(
96-
`${finding.reason}: prefer test/helpers/temp-dir.ts for new test-owned temp directories.`,
106+
`${finding.reason}: prefer useAutoCleanupTempDirTracker() from test/helpers/temp-dir.ts for new test-owned temp directories.`,
97107
);
98108
return `::warning file=${file},line=${line}::${message}`;
99109
}
@@ -133,8 +143,228 @@ function readDiff(args, cwd = process.cwd()) {
133143
});
134144
}
135145

136-
export function collectTempCreationFindingsFromDiff(diffText) {
146+
function readWorktreeSource(filePath, cwd) {
147+
try {
148+
return fs.readFileSync(path.join(cwd, filePath), "utf8");
149+
} catch {
150+
return "";
151+
}
152+
}
153+
154+
function readStagedSource(filePath, cwd) {
155+
try {
156+
return execFileSync("git", ["show", `:${filePath}`], {
157+
cwd,
158+
encoding: "utf8",
159+
maxBuffer: 64 * 1024 * 1024,
160+
stdio: ["ignore", "pipe", "pipe"],
161+
});
162+
} catch {
163+
return "";
164+
}
165+
}
166+
167+
function readSourceForDiff(filePath, args, cwd) {
168+
// Staged checks must parse the index blob. Reading the worktree mixes in
169+
// unstaged edits and can warn on code that will not be committed.
170+
return args.staged ? readStagedSource(filePath, cwd) : readWorktreeSource(filePath, cwd);
171+
}
172+
173+
function stripKnownExtension(filePath) {
174+
return filePath.replace(/\.(?:c|m)?[jt]sx?$/u, "");
175+
}
176+
177+
function isTempDirHelperImportSpec(filePath, specifier) {
178+
const normalizedSpecifier = normalizePath(specifier);
179+
const resolvedPath = normalizedSpecifier.startsWith(".")
180+
? path.posix.normalize(path.posix.join(path.posix.dirname(filePath), normalizedSpecifier))
181+
: normalizedSpecifier;
182+
return stripKnownExtension(resolvedPath) === stripKnownExtension(TEMP_DIR_HELPER_PATH);
183+
}
184+
185+
function scriptKindForFile(filePath) {
186+
if (/\.[cm]?tsx$/u.test(filePath)) {
187+
return ts.ScriptKind.TSX;
188+
}
189+
if (/\.[cm]?jsx$/u.test(filePath)) {
190+
return ts.ScriptKind.JSX;
191+
}
192+
if (/\.[cm]?js$/u.test(filePath)) {
193+
return ts.ScriptKind.JS;
194+
}
195+
return ts.ScriptKind.TS;
196+
}
197+
198+
function createSourceFile(filePath, sourceText) {
199+
return ts.createSourceFile(
200+
filePath,
201+
sourceText,
202+
ts.ScriptTarget.Latest,
203+
true,
204+
scriptKindForFile(filePath),
205+
);
206+
}
207+
208+
function lineForNode(sourceFile, node) {
209+
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
210+
}
211+
212+
function sourceLineText(sourceFile, line) {
213+
const lineStarts = sourceFile.getLineStarts();
214+
const start = lineStarts[line - 1] ?? 0;
215+
const end = lineStarts[line] ?? sourceFile.text.length;
216+
return sourceFile.text.slice(start, end).trim();
217+
}
218+
219+
function nodeOverlapsAddedLine(sourceFile, node, addedLineNumbers) {
220+
const startLine = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
221+
const endLine = sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line + 1;
222+
for (let line = startLine; line <= endLine; line += 1) {
223+
if (addedLineNumbers.has(line)) {
224+
return true;
225+
}
226+
}
227+
return false;
228+
}
229+
230+
function normalizeFileTextMap(fileTextByPath) {
231+
if (!fileTextByPath) {
232+
return null;
233+
}
234+
if (fileTextByPath instanceof Map) {
235+
return fileTextByPath;
236+
}
237+
return new Map(Object.entries(fileTextByPath));
238+
}
239+
240+
function readCurrentSource(filePath, options, fileTextByPath) {
241+
if (fileTextByPath?.has(filePath)) {
242+
return fileTextByPath.get(filePath) ?? "";
243+
}
244+
if (typeof options.readFile === "function") {
245+
return options.readFile(filePath) ?? "";
246+
}
247+
return "";
248+
}
249+
250+
function collectManualTempDirHelperImports(sourceFile, filePath, addedLineNumbers = null) {
251+
const imports = [];
252+
const localNames = new Set();
253+
for (const statement of sourceFile.statements) {
254+
if (
255+
!ts.isImportDeclaration(statement) ||
256+
!statement.importClause?.namedBindings ||
257+
!ts.isStringLiteral(statement.moduleSpecifier) ||
258+
!isTempDirHelperImportSpec(filePath, statement.moduleSpecifier.text) ||
259+
!ts.isNamedImports(statement.importClause.namedBindings)
260+
) {
261+
continue;
262+
}
263+
let importWarningLine = null;
264+
for (const element of statement.importClause.namedBindings.elements) {
265+
const imported = element.propertyName?.text ?? element.name.text;
266+
if (!MANUAL_TEMP_DIR_HELPERS.has(imported)) {
267+
continue;
268+
}
269+
localNames.add(element.name.text);
270+
if (
271+
importWarningLine === null &&
272+
(!addedLineNumbers || nodeOverlapsAddedLine(sourceFile, element, addedLineNumbers))
273+
) {
274+
importWarningLine = lineForNode(sourceFile, element);
275+
}
276+
}
277+
if (importWarningLine !== null) {
278+
imports.push({
279+
line: importWarningLine,
280+
source: statement.getText(sourceFile).trim().replace(/\s+/gu, " "),
281+
});
282+
}
283+
}
284+
return { imports, localNames };
285+
}
286+
287+
function findManualHelperUsageFindings(filePath, sourceText, addedLines) {
288+
const addedLineNumbers = new Set(addedLines.map((line) => line.line));
289+
const sourceFile = createSourceFile(filePath, sourceText);
290+
const { imports, localNames } = collectManualTempDirHelperImports(
291+
sourceFile,
292+
filePath,
293+
addedLineNumbers,
294+
);
295+
const findings = imports.map((manualImport) => ({
296+
file: filePath,
297+
line: manualImport.line,
298+
reason: "new manual temp-dir helper import",
299+
source: manualImport.source,
300+
}));
301+
if (localNames.size === 0) {
302+
return findings;
303+
}
304+
const visit = (node) => {
305+
if (
306+
ts.isCallExpression(node) &&
307+
ts.isIdentifier(node.expression) &&
308+
localNames.has(node.expression.text) &&
309+
nodeOverlapsAddedLine(sourceFile, node.expression, addedLineNumbers)
310+
) {
311+
findings.push({
312+
file: filePath,
313+
line: lineForNode(sourceFile, node.expression),
314+
reason: "new manual temp-dir helper usage",
315+
source: sourceLineText(sourceFile, lineForNode(sourceFile, node.expression)),
316+
});
317+
}
318+
ts.forEachChild(node, visit);
319+
};
320+
visit(sourceFile);
321+
return findings;
322+
}
323+
324+
function collectAddedLinesByFile(diffText) {
325+
const addedLinesByFile = new Map();
326+
let currentFile = null;
327+
let currentLine = 0;
328+
329+
for (const line of diffText.split(/\r?\n/u)) {
330+
const fileMatch = line.match(/^\+\+\+ b\/(.+)$/u);
331+
if (fileMatch) {
332+
currentFile = normalizePath(fileMatch[1]);
333+
continue;
334+
}
335+
if (line === "+++ /dev/null") {
336+
currentFile = null;
337+
continue;
338+
}
339+
340+
const hunkMatch = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/u);
341+
if (hunkMatch) {
342+
currentLine = Number.parseInt(hunkMatch[1], 10);
343+
continue;
344+
}
345+
346+
if (line.startsWith("+") && !line.startsWith("+++")) {
347+
if (currentFile && shouldInspectFile(currentFile)) {
348+
const lines = addedLinesByFile.get(currentFile) ?? [];
349+
lines.push({ line: currentLine, source: line.slice(1) });
350+
addedLinesByFile.set(currentFile, lines);
351+
}
352+
currentLine += 1;
353+
continue;
354+
}
355+
356+
if (line.startsWith(" ") || line === "") {
357+
currentLine += 1;
358+
}
359+
}
360+
361+
return addedLinesByFile;
362+
}
363+
364+
export function collectTempCreationFindingsFromDiff(diffText, options = {}) {
137365
const findings = [];
366+
const addedLinesByFile = collectAddedLinesByFile(diffText);
367+
const fileTextByPath = normalizeFileTextMap(options.fileTextByPath);
138368
let currentFile = null;
139369
let currentLine = 0;
140370
let allowNextLine = null;
@@ -192,6 +422,17 @@ export function collectTempCreationFindingsFromDiff(diffText) {
192422
}
193423
}
194424

425+
for (const [file, addedLines] of addedLinesByFile) {
426+
if (!shouldInspectManualHelperUsage(file)) {
427+
continue;
428+
}
429+
const sourceText = readCurrentSource(file, options, fileTextByPath);
430+
if (!sourceText) {
431+
continue;
432+
}
433+
findings.push(...findManualHelperUsageFindings(file, sourceText, addedLines));
434+
}
435+
195436
return findings;
196437
}
197438

@@ -205,21 +446,28 @@ export async function main(argv, io) {
205446
return 0;
206447
}
207448

208-
const findings = collectTempCreationFindingsFromDiff(readDiff(args));
449+
const cwd = process.cwd();
450+
const findings = collectTempCreationFindingsFromDiff(readDiff(args, cwd), {
451+
readFile(filePath) {
452+
return readSourceForDiff(filePath, args, cwd);
453+
},
454+
});
209455
if (args.json) {
210456
stdout.write(`${JSON.stringify(findings, null, 2)}\n`);
211457
} else if (findings.length === 0) {
212-
stderr.write("No new bare test temp-directory creation patterns found.\n");
458+
stderr.write("No new test temp-directory migration warnings found.\n");
213459
} else if (isTruthyEnvFlag(env.GITHUB_ACTIONS)) {
214460
for (const finding of findings) {
215461
stderr.write(`${formatGithubWarning(finding)}\n`);
216462
}
217463
} else {
218-
stderr.write("New bare test temp-directory creation patterns:\n");
464+
stderr.write("New test temp-directory migration warnings:\n");
219465
for (const finding of findings) {
220466
stderr.write(`- ${finding.file}:${finding.line} ${finding.reason}: ${finding.source}\n`);
221467
}
222-
stderr.write("Prefer test/helpers/temp-dir.ts for new test-owned temp directories.\n");
468+
stderr.write(
469+
"Prefer useAutoCleanupTempDirTracker() from test/helpers/temp-dir.ts for new test-owned temp directories.\n",
470+
);
223471
}
224472

225473
return args.failOnFindings && findings.length > 0 ? 1 : 0;

0 commit comments

Comments
 (0)