1 |
|
2 | const assert = require('assert');
|
3 | const chalk = require('chalk');
|
4 | const fs = require('fs');
|
5 | const path = require('path');
|
6 |
|
7 | const ensureEmptyFolder = require('./utils/ensure-empty-folder');
|
8 | const readFile = require('./utils/read-file');
|
9 | const renameFile = require('./utils/rename-file');
|
10 | const renameJSXTransform = require('./transforms/rename-jsx');
|
11 | const validateFilePath = require('./utils/validate-file-path');
|
12 | const writeFile = require('./utils/write-file');
|
13 |
|
14 | module.exports = function({ eslintConfig, filePath, newComponentName }) {
|
15 | return new Promise((resolve, reject) => {
|
16 | try {
|
17 | assert(newComponentName, 'No new component name provided.');
|
18 | validateFilePath(filePath);
|
19 |
|
20 | const componentName = path.basename(filePath, '.jsx');
|
21 | const folderPath = path.dirname(filePath);
|
22 | const jsxFilePath = filePath;
|
23 | const scssFilename = `${componentName}.scss`;
|
24 | const scssFilePath = path.join(folderPath, scssFilename);
|
25 |
|
26 | const hasScssfile = fs.existsSync(path.join(folderPath, scssFilename));
|
27 | const shouldRenameFolder = componentName === path.basename(folderPath);
|
28 |
|
29 | if (shouldRenameFolder) {
|
30 |
|
31 | const newFolderPath = path.join(
|
32 | path.dirname(folderPath),
|
33 | newComponentName
|
34 | );
|
35 | ensureEmptyFolder(newFolderPath);
|
36 | }
|
37 |
|
38 | const jsxFileContent = readFile(jsxFilePath);
|
39 |
|
40 | const newJsxFileContent = renameJSXTransform(
|
41 | jsxFileContent,
|
42 | componentName,
|
43 | newComponentName,
|
44 | eslintConfig
|
45 | );
|
46 |
|
47 | const messages = [];
|
48 |
|
49 | messages.push(
|
50 | writeFile(jsxFilePath, newJsxFileContent),
|
51 | renameFile(jsxFilePath, `${newComponentName}.jsx`)
|
52 | );
|
53 |
|
54 | if (hasScssfile) {
|
55 | const scssFileContent = readFile(scssFilePath);
|
56 | const newScssFileContent = scssFileContent.replace(
|
57 | new RegExp(`\\.${componentName}( |-)`, 'g'),
|
58 | `.${newComponentName}$1`
|
59 | );
|
60 | messages.push(
|
61 | writeFile(scssFilePath, newScssFileContent),
|
62 | renameFile(scssFilePath, `${newComponentName}.scss`)
|
63 | );
|
64 | }
|
65 |
|
66 | if (shouldRenameFolder) {
|
67 | messages.push(renameFile(folderPath, newComponentName, 'folder'));
|
68 | }
|
69 |
|
70 | resolve({
|
71 | messages: messages.concat({
|
72 | emoji: '🤖',
|
73 | text: `${chalk.green(`Beep boop, I'm done!`)}`
|
74 | })
|
75 | });
|
76 | } catch (error) {
|
77 | reject(error.message);
|
78 | }
|
79 | });
|
80 | };
|