|
| 1 | +const { prompt } = require("inquirer"); |
| 2 | + |
| 3 | +class ExternalCommand { |
| 4 | + static async runCommand(command, args = []) { |
| 5 | + const cp = require("child_process"); |
| 6 | + const executedCommand = await cp.spawn(command, args, { |
| 7 | + stdio: "inherit", |
| 8 | + shell: true |
| 9 | + }); |
| 10 | + return new Promise((resolve, reject) => { |
| 11 | + executedCommand.on("error", error => { |
| 12 | + reject(error); |
| 13 | + }); |
| 14 | + |
| 15 | + executedCommand.on("exit", code => { |
| 16 | + resolve(); |
| 17 | + }); |
| 18 | + }); |
| 19 | + } |
| 20 | + |
| 21 | + static validateEnv(extName) { |
| 22 | + let packageIsInstalled; |
| 23 | + try { |
| 24 | + const path = require("path"); |
| 25 | + const pathForCmd = path.resolve(process.cwd(), "node_modules", "@webpack-cli", extName); |
| 26 | + require.resolve(pathForCmd); |
| 27 | + packageIsInstalled = pathForCmd; |
| 28 | + } catch (err) { |
| 29 | + packageIsInstalled = false; |
| 30 | + } |
| 31 | + return packageIsInstalled; |
| 32 | + } |
| 33 | + static async promptInstallation(scopeName, name) { |
| 34 | + const path = require("path"); |
| 35 | + const fs = require("fs"); |
| 36 | + const isYarn = fs.existsSync(path.resolve(process.cwd(), "yarn.lock")); |
| 37 | + |
| 38 | + const packageManager = isYarn ? "yarn" : "npm"; |
| 39 | + const options = ["install", "-D", scopeName]; |
| 40 | + |
| 41 | + if (isYarn) { |
| 42 | + options[0] = "add"; |
| 43 | + } |
| 44 | + |
| 45 | + const commandToBeRun = `${packageManager} ${options.join(" ")}`; |
| 46 | + process.cliLogger.error(`The command moved into a separate package: ${name}`); |
| 47 | + const question = `Would you like to install ${name}? (That will run ${commandToBeRun})`; |
| 48 | + const answer = await prompt([ |
| 49 | + { |
| 50 | + type: "confirm", |
| 51 | + name: "installConfirm", |
| 52 | + message: question, |
| 53 | + default: "Y", |
| 54 | + choices: ["Yes", "No", "Y", "N", "y", "n"] |
| 55 | + } |
| 56 | + ]); |
| 57 | + if (answer.installConfirm === true) { |
| 58 | + await ExternalCommand.runCommand(commandToBeRun); |
| 59 | + return ExternalCommand.validateEnv(name); |
| 60 | + } |
| 61 | + process.exitCode = -1; |
| 62 | + } |
| 63 | + |
| 64 | + static async run(name, ...args) { |
| 65 | + let pkgLoc = ExternalCommand.validateEnv(name); |
| 66 | + const scopeName = "@webpack-cli/" + name; |
| 67 | + if (!pkgLoc) { |
| 68 | + pkgLoc = await ExternalCommand.promptInstallation(scopeName, name); |
| 69 | + } |
| 70 | + // Serve needs to be checked for |
| 71 | + if (name === "serve") { |
| 72 | + return pkgLoc ? require(pkgLoc).serve(args) : null; |
| 73 | + } |
| 74 | + return pkgLoc ? require(pkgLoc).default(args) : null; |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +module.exports = ExternalCommand; |
0 commit comments