Created
December 7, 2023 22:21
-
-
Save loraxx753/9e38c3c940526e8d90d1ead68316ddea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
const { Command } = require('commander'); | |
const program = new Command(); | |
function addStateToComponent(componentName, stateName, defaultValue) { | |
const directories = ['page', 'template', 'organisms', 'molecules', 'atoms']; | |
let filePath; | |
for (const dir of directories) { | |
const potentialPath = path.join(process.cwd(), 'src', 'atomic', dir, componentName, 'component.tsx'); | |
if (fs.existsSync(potentialPath)) { | |
filePath = potentialPath; | |
break; | |
} | |
} | |
if (!filePath) { | |
console.error(`Component ${componentName} not found in any atomic directory.`); | |
return; | |
} | |
let content = fs.readFileSync(filePath, 'utf8'); | |
if (!content.includes('import React, { useState }')) { | |
content = content.replace('import React', 'import React, { useState }'); | |
} | |
const stateInitialization = `const [${stateName}, set${stateName.charAt(0).toUpperCase() + stateName.slice(1)}] = useState(${defaultValue});\n`; | |
const componentFunctionStart = content.indexOf('const ' + componentName); | |
content = content.slice(0, componentFunctionStart) + stateInitialization + content.slice(componentFunctionStart); | |
fs.writeFileSync(filePath, content); | |
console.log(`${componentName} updated with new state: ${stateName}`); | |
} | |
program | |
.command('add-to <componentName>') | |
.option('--state <stateName>', 'Name of the state to add') | |
.option('--default <defaultValue>', 'Default value of the state') | |
.action((componentName, options) => { | |
addStateToComponent(componentName, options.state, options.default); | |
}); | |
program.parse(process.argv); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment