-
Notifications
You must be signed in to change notification settings - Fork 109
/
rename-kebabs-to-pascal-case.js
executable file
·79 lines (69 loc) · 2.44 KB
/
rename-kebabs-to-pascal-case.js
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
#!/usr/bin/env node
/*
* Rename kebab-case files into PascalCase files and update references
*
* Basic working:
* 1. Find all kebab case files
* 2. Rename them
* 3. Use the `git grep` to get all filenames with indexed hits of the old file name
* 4. Loop through the hits and update
*/
const argv = require('yargs').argv;
const {isEmpty, flowRight} = require('lodash');
const {promisify} = require('util');
const fs = require('fs');
const cp = require('child_process');
const {basename} = require('path');
const exec = promisify(cp.exec);
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const moveFile = promisify(fs.rename);
const debug = require('debug')('info');
const usage = `
USAGE: rename-kebab --dir src --dir test --dir some-other
Will rename all kebab-case files to PascalCase and update references in the mentioned directories
`;
let dirs = '';
if (isEmpty(argv.dir)) {
// eslint-disable-next-line no-console
console.error(usage);
process.exit(1);
}
if (!Array.isArray(argv.dir)) {
dirs = [argv.dir];
} else {
dirs = argv.dir;
}
async function main() {
const kebabs = await execAndParseList(`find ${dirs.join(' ')} -name '*-*.js' -type f `);
const pascalify = flowRight(
fromKebabToCamel,
fromCamelToPascal
);
for (const fullKebabPath of kebabs) {
const oldNameWithoutExtension = basename(fullKebabPath, '.js');
const newName = pascalify(basename(fullKebabPath));
const newNameWithoutExtension = basename(newName, '.js');
const filesWithReferences = await execAndParseList(`grep -r -l ${oldNameWithoutExtension} ${dirs.join(' ')}`);
debug(`${oldNameWithoutExtension} is referenced by:\n${filesWithReferences.join('\n')}`);
await moveFile(fullKebabPath, fullKebabPath.replace(oldNameWithoutExtension, newNameWithoutExtension));
for (const file of filesWithReferences) {
const buffer = await readFile(file);
const newFileContent = buffer
.toString()
.replace(new RegExp(oldNameWithoutExtension, 'm'), newNameWithoutExtension);
await writeFile(file, newFileContent);
}
}
}
function fromCamelToPascal(camel) {
return camel.replace(/^(.)/, (_, char) => char.toUpperCase());
}
function fromKebabToCamel(kebab) {
return kebab.replace(/\b-([a-z])/g, (_, char) => char.toUpperCase());
}
async function execAndParseList(cmd) {
const tmp = await exec(cmd).catch(_ => ({stdout: ''}));
return tmp.stdout.split('\n').filter(e => e);
}
main();