Skip to content

Instantly share code, notes, and snippets.

@maecapozzi
Created April 5, 2020 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maecapozzi/10f261931193411e8b7feee4cf325dfd to your computer and use it in GitHub Desktop.
Save maecapozzi/10f261931193411e8b7feee4cf325dfd to your computer and use it in GitHub Desktop.
Script for a cli tool that lets users generate a new package from an example package
const fs = require('fs');
const path = require('path');
const inquirer = require('inquirer');
const { exec } = require('child_process');
// Pull the arguments off of the command
let args = process.argv.slice(2);
// Write your own custom questions that the script will ask
const cliQuestions = [
{
type: 'input',
name: 'description',
message: 'What should the package.json description be?',
},
{
type: 'input',
name: 'version',
message: 'What should the package.json version be?',
},
];
// Find the path in the `/packages` directory where the package
// is going to live
const getPathToFile = packagesDir => {
return fs
.readdirSync(packagesDir)
.map(filename => path.join(packagesDir, filename))
.filter(filePath => filePath.includes('package.json'))[0];
};
// Update the example package's package.json file with the
// user's responses to the cliQuestions
const editPackageJson = packageName => {
inquirer.prompt(cliQuestions).then(answers => {
const packagesDir = path.resolve(`./packages/${packageName}`);
const content = {
name: `@maecapozzi/${packageName}`,
description: answers.description,
version: answers.version,
};
const pathToFile = getPathToFile(packagesDir);
const file = require(pathToFile);
const editedFile = JSON.stringify(
Object.assign(file, {
...content,
})
);
return fs.writeFileSync(pathToFile, editedFile, err => {
if (err) {
console.error(err);
return;
}
console.log('You successfully update the package.json file.');
});
});
};
const execute = packageName => {
if (packageName[0] === undefined) {
throw Error('Please provide a package name');
}
if (packageName.length > 1) {
throw Error('Please only provide a single package name');
}
if (fs.existsSync(`./packages/${packageName[0]}`)) {
throw Error('Please provide a package name that does not already exist');
}
// copy the example package to the new path
exec(
`cp -r ./examples/example-package ./packages/${packageName}`,
(err, stdout, stderr) => {
if (err) {
throw err;
}
console.log(stdout);
console.log(stderr);
console.log(`${packageName} has been successfully created`);
editPackageJson(packageName);
}
);
};
execute(args);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment