UNPKG

npscripts

Version:

A simple module to list and run scripts in your package.json

105 lines (94 loc) 2.7 kB
const fs = require("fs"); const ora = require("ora"); const npm = require("npm"); const path = require("path"); const inquirer = require("inquirer"); const { projectInstallSync } = require("pkg-install"); class NPScripts { constructor() { if (!fs.existsSync(path.resolve(process.cwd(), "package.json"))) { console.error(`No package.json file could be found at ${process.cwd()}`); process.exit(0); } else { this.package = require(path.resolve(process.cwd(), "package.json")); } if (!this.package || !this.package.hasOwnProperty("scripts")) { console.error(`[${this.package.name.toUpperCase()}] does not have any scripts`); process.exit(0); } let { name, description, scripts} = this.package; return { name, scripts, description, package: this.package, dependencies: this.dependencies() } } dependencies () { let { dependencies = {}, devDependencies = {} } = this.package; let all = Object.assign({}, dependencies, devDependencies); let packages = Object.keys(all); let installed = fs.existsSync( path.resolve(process.cwd(), "node_modules") ); let install = async (shouldInstall) => { return new Promise(async (res, rej) => { let spinner = ora(); if (!installed) { spinner.start("Installing Dependencies"); let installDeps = await projectInstallSync({ verbose: true, dev: true, prefer: "npm", stdio: "inherit", }) } res(spinner.succeed()); }) } return { all, install, packages, installed, } } } let npscripts = new NPScripts(); const questions = { install: { type: "list", name: "install", message: "Package dpendencies have not been installed, would you like to install them?", choices: ["Yes", "No"], when: !npscripts.dependencies.installed }, scripts: { type: "list", name: "script", message: `\n[${npscripts.name}]\n${npscripts.description}\nWhich script would you like to run?`, choices: Object.keys(npscripts.scripts) }, }; Object.assign(questions.install, { }) inquirer.prompt(questions.install) .then((answers) => { return npscripts.dependencies.install(); }) .then(() => { inquirer.prompt(questions.scripts) .then((answers) => { return new Promise(() => { npm.load(() => { try { console.log(`[RUNNING::${answers.script}]`); npm.run(answers.script); } catch (e) { console.warn(e); } }); }); }); });