-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrename-cjs.mjs
43 lines (41 loc) · 1.17 KB
/
rename-cjs.mjs
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
/* eslint-env es6 */
//@ts-check
import * as fs from "node:fs/promises";
import { URL } from "node:url";
import * as console from "node:console";
/**
* @param {URL} file
* @returns {AsyncGenerator<URL>}
*/
export const listFiles = async function* (file) {
const stats = await fs.stat(file);
if (stats.isFile()) {
yield file;
return;
}
if (stats.isDirectory()) {
file.pathname = file.pathname.replace(/\/*$/, "/");
for (const name of await fs.readdir(file)) {
yield* listFiles(new URL(name, file));
}
}
};
/** @type {Array<[URL, URL]>} */
const renames = [];
const cjsDir = new URL("cjs/", import.meta.url);
for await (const file of listFiles(cjsDir)) {
if (/\.m[jt]s$/.test(file.pathname)) {
const renamed = new URL(file.href);
renamed.pathname = renamed.pathname.replace(/\.m([jt])s$/, ".c$1s");
renames.push([file, renamed]);
}
}
await Promise.all(
renames.map(async ([from, to]) => {
let code = await fs.readFile(from, "utf8");
code = code.replace(/\.m([jt])s(['"])/g, ".c$1s$2");
await fs.writeFile(to, code);
await fs.unlink(from);
console.info("renamed", to.pathname.slice(cjsDir.pathname.length));
}),
);