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
import "npm:@babel/parser";
import { NodePath } from "npm:ast-types";
import recast from "npm:recast";
import typescriptParser from "npm:recast/parsers/typescript.js";
run();
async function run() {
if (!import.meta.main) return;
const flags = {
dry: false,
};
const args = Deno.args.slice();
const fileArgs = args.filter((d) => {
if (d.startsWith("--")) {
if (d === "--") {
return false;
}
const flag = d.replace(/^[-]{2}/, "") as keyof typeof flags;
if (!(flag in flags)) {
throw new Error(`Invalid flag --${flag}`);
}
flags[flag] = true;
return false;
}
return true;
});
for (const file of fileArgs) {
const fileData = await Deno.readTextFile(file);
const tranformed = transform(fileData, { typescript: true });
if (!flags.dry) {
await Deno.writeTextFile(file, tranformed);
}
}
}
export function transform(code: string, { typescript = false } = {}) {
const parserOptions: Partial<recast.Options> = {};
if (typescript) {
parserOptions.parser = typescriptParser;
}
const ast = recast.parse(code, parserOptions);
const asserts = recast.types.namedTypes;
const builder = recast.types.builders;
let tapImportIdentifier = "t";
const testUtils = [
"describe",
"before",
"beforeEach",
"afterEach",
"after",
"it",
];
const nodeTestImports = Object.fromEntries(testUtils.map((d) => [d, false]));
recast.visit(ast, {
visitImportDeclaration(path) {
if (path.node.source.value === "node:test") {
path.node.specifiers?.forEach((spec) => {
const name = spec.local?.name.toString() || "";
if (name && testUtils.includes(name)) {
nodeTestImports[name] = true;
}
});
nodeTestImports;
}
if (
!(
path.node.source.value === "tap" &&
path.node.specifiers?.length &&
asserts.ImportDefaultSpecifier.check(path.node.specifiers[0])
)
) {
return false;
}
const specifier = path.node.specifiers[0];
if (specifier && specifier.local) {
tapImportIdentifier = specifier.local.name.toString();
}
return false;
},
});
recast.visit(ast, {
visitExpressionStatement(path) {
removeMochaGlobal(path as NodePath, tapImportIdentifier, {
asserts,
});