UNPKG

2.69 kBJavaScriptView Raw
1"use strict";
2
3const colors = require("colors/safe");
4const path = require("path");
5const program = require("commander");
6const Helper = require("../helper");
7const Utils = require("./utils");
8
9program
10 .command("uninstall <package>")
11 .description("Uninstall a theme or a package")
12 .on("--help", Utils.extraHelp)
13 .action(function(packageName) {
14 const fs = require("fs");
15 const child = require("child_process");
16
17 if (!fs.existsSync(Helper.getConfigPath())) {
18 log.error(`${Helper.getConfigPath()} does not exist.`);
19 return;
20 }
21
22 log.info(`Uninstalling ${colors.green(packageName)}...`);
23
24 const packagesPath = Helper.getPackagesPath();
25 const packagesConfig = path.join(packagesPath, "package.json");
26 const packageWasNotInstalled = `${colors.green(packageName)} was not installed.`;
27
28 if (!fs.existsSync(packagesConfig)) {
29 log.warn(packageWasNotInstalled);
30 process.exit(1);
31 }
32
33 const npm = process.platform === "win32" ? "npm.cmd" : "npm";
34 const errorHandler = (error) => {
35 log.error(
36 `Failed to uninstall ${colors.green(packageName)}. ` +
37 `${typeof x === "number" ? "Exit code" : "Error"}: ${error}`
38 );
39 process.exit(1);
40 };
41
42 // First, we check if the package is installed with `npm list`
43 const list = child.spawn(
44 npm,
45 [
46 "list",
47 "--depth",
48 "0",
49 "--prefix",
50 packagesPath,
51 packageName,
52 ],
53 {
54 // This is the same as `"inherit"` except:
55 // - `process.stdout` is piped so we can test if the output mentions the
56 // package was found
57 // - `process.stderr` is ignored to silence `npm ERR! extraneous` errors
58 stdio: [process.stdin, "pipe", "ignore"],
59 }
60 );
61
62 list.stdout.on("data", (data) => {
63 // If the package name does not appear in stdout, it means it was not
64 // installed. We cannot rely on exit code because `npm ERR! extraneous`
65 // causes a status of 1 even if package exists.
66 if (!data.toString().includes(packageName)) {
67 log.warn(packageWasNotInstalled);
68 process.exit(1);
69 }
70 });
71
72 list.on("error", errorHandler);
73
74 list.on("close", () => {
75 // If we get there, it means the package exists, so uninstall
76 const uninstall = child.spawn(
77 npm,
78 [
79 "uninstall",
80 "--save",
81 "--no-progress",
82 "--prefix",
83 packagesPath,
84 packageName,
85 ],
86 {
87 // This is the same as `"inherit"` except `process.stdout` is silenced
88 stdio: [process.stdin, "ignore", process.stderr],
89 }
90 );
91
92 uninstall.on("error", errorHandler);
93
94 uninstall.on("close", (code) => {
95 if (code !== 0) {
96 errorHandler(code);
97 }
98
99 log.info(`${colors.green(packageName)} has been successfully uninstalled.`);
100 });
101 });
102 });