-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenameFiles.mjs
More file actions
executable file
·65 lines (57 loc) · 1.89 KB
/
renameFiles.mjs
File metadata and controls
executable file
·65 lines (57 loc) · 1.89 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
#!/usr/bin/env node
import fs from 'node:fs/promises'
import path from 'node:path'
// Process a directory recursively, renaming files as needed
const extMap = {
esm: {
'.d.ts': '.d.mts',
'.js': '.mjs'
},
cjs: {
'.d.ts': '.d.cts',
'.js': '.cjs'
}
}
/**
* @param {string} dir Directory name
* @param {Record<string, string>} ext File extension map
*/
function processDirectory (dir, ext) {
fs.readdir(dir, { withFileTypes: true }).then((entries) => {
return Promise.all(entries.map(async (entry) => {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
// Recursively process subdirectories
return processDirectory(fullPath, ext)
} else if (entry.isFile() && Object.keys(ext).some(e => entry.name.endsWith(e))) {
// Generate the new file name
const curExt = Object.keys(ext).find(e => entry.name.endsWith(e))
if (!curExt) throw new Error('Extension not found')
const newExt = ext[curExt]
const newFullPath = fullPath.slice(0, -curExt.length) + newExt
if (ext['.js']) {
const jsNewExt = ext['.js']
await fs.readFile(fullPath, { encoding: 'utf8' }).then((content) => {
const newContent = content
.replace(/(?<=".*)\.js(?=")/g, jsNewExt)
.replace(/(?<='.*)\.js(?=')/g, jsNewExt)
return fs.writeFile(fullPath, newContent)
})
}
await fs.rename(fullPath, newFullPath).catch((err) => {
console.error(`Error renaming ${fullPath} to ${newFullPath}:`, err)
})
}
return null
}))
}).catch(err => {
console.error(`Error reading directory ${dir}:`, err)
})
}
if (process.argv[2] === 'esm') {
processDirectory('./dist/esm', extMap.esm)
} else if (process.argv[2] === 'cjs') {
processDirectory('./dist/cjs', extMap.cjs)
} else {
console.error('Invalid dist output')
}