massive update, probably broken
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / eslint / lib / init / npm-utils.js
1 /**
2  * @fileoverview Utility for executing npm commands.
3  * @author Ian VanSchooten
4  */
5
6 "use strict";
7
8 //------------------------------------------------------------------------------
9 // Requirements
10 //------------------------------------------------------------------------------
11
12 const fs = require("fs"),
13     spawn = require("cross-spawn"),
14     path = require("path"),
15     log = require("../shared/logging");
16
17 //------------------------------------------------------------------------------
18 // Helpers
19 //------------------------------------------------------------------------------
20
21 /**
22  * Find the closest package.json file, starting at process.cwd (by default),
23  * and working up to root.
24  * @param   {string} [startDir=process.cwd()] Starting directory
25  * @returns {string}                          Absolute path to closest package.json file
26  */
27 function findPackageJson(startDir) {
28     let dir = path.resolve(startDir || process.cwd());
29
30     do {
31         const pkgFile = path.join(dir, "package.json");
32
33         if (!fs.existsSync(pkgFile) || !fs.statSync(pkgFile).isFile()) {
34             dir = path.join(dir, "..");
35             continue;
36         }
37         return pkgFile;
38     } while (dir !== path.resolve(dir, ".."));
39     return null;
40 }
41
42 //------------------------------------------------------------------------------
43 // Private
44 //------------------------------------------------------------------------------
45
46 /**
47  * Install node modules synchronously and save to devDependencies in package.json
48  * @param   {string|string[]} packages Node module or modules to install
49  * @returns {void}
50  */
51 function installSyncSaveDev(packages) {
52     const packageList = Array.isArray(packages) ? packages : [packages];
53     const npmProcess = spawn.sync("npm", ["i", "--save-dev"].concat(packageList), { stdio: "inherit" });
54     const error = npmProcess.error;
55
56     if (error && error.code === "ENOENT") {
57         const pluralS = packageList.length > 1 ? "s" : "";
58
59         log.error(`Could not execute npm. Please install the following package${pluralS} with a package manager of your choice: ${packageList.join(", ")}`);
60     }
61 }
62
63 /**
64  * Fetch `peerDependencies` of the given package by `npm show` command.
65  * @param {string} packageName The package name to fetch peerDependencies.
66  * @returns {Object} Gotten peerDependencies. Returns null if npm was not found.
67  */
68 function fetchPeerDependencies(packageName) {
69     const npmProcess = spawn.sync(
70         "npm",
71         ["show", "--json", packageName, "peerDependencies"],
72         { encoding: "utf8" }
73     );
74
75     const error = npmProcess.error;
76
77     if (error && error.code === "ENOENT") {
78         return null;
79     }
80     const fetchedText = npmProcess.stdout.trim();
81
82     return JSON.parse(fetchedText || "{}");
83
84
85 }
86
87 /**
88  * Check whether node modules are include in a project's package.json.
89  * @param   {string[]} packages           Array of node module names
90  * @param   {Object}  opt                 Options Object
91  * @param   {boolean} opt.dependencies    Set to true to check for direct dependencies
92  * @param   {boolean} opt.devDependencies Set to true to check for development dependencies
93  * @param   {boolean} opt.startdir        Directory to begin searching from
94  * @returns {Object}                      An object whose keys are the module names
95  *                                        and values are booleans indicating installation.
96  */
97 function check(packages, opt) {
98     const deps = new Set();
99     const pkgJson = (opt) ? findPackageJson(opt.startDir) : findPackageJson();
100     let fileJson;
101
102     if (!pkgJson) {
103         throw new Error("Could not find a package.json file. Run 'npm init' to create one.");
104     }
105
106     try {
107         fileJson = JSON.parse(fs.readFileSync(pkgJson, "utf8"));
108     } catch (e) {
109         const error = new Error(e);
110
111         error.messageTemplate = "failed-to-read-json";
112         error.messageData = {
113             path: pkgJson,
114             message: e.message
115         };
116         throw error;
117     }
118
119     ["dependencies", "devDependencies"].forEach(key => {
120         if (opt[key] && typeof fileJson[key] === "object") {
121             Object.keys(fileJson[key]).forEach(dep => deps.add(dep));
122         }
123     });
124
125     return packages.reduce((status, pkg) => {
126         status[pkg] = deps.has(pkg);
127         return status;
128     }, {});
129 }
130
131 /**
132  * Check whether node modules are included in the dependencies of a project's
133  * package.json.
134  *
135  * Convenience wrapper around check().
136  * @param   {string[]} packages  Array of node modules to check.
137  * @param   {string}   rootDir   The directory containing a package.json
138  * @returns {Object}             An object whose keys are the module names
139  *                               and values are booleans indicating installation.
140  */
141 function checkDeps(packages, rootDir) {
142     return check(packages, { dependencies: true, startDir: rootDir });
143 }
144
145 /**
146  * Check whether node modules are included in the devDependencies of a project's
147  * package.json.
148  *
149  * Convenience wrapper around check().
150  * @param   {string[]} packages  Array of node modules to check.
151  * @returns {Object}             An object whose keys are the module names
152  *                               and values are booleans indicating installation.
153  */
154 function checkDevDeps(packages) {
155     return check(packages, { devDependencies: true });
156 }
157
158 /**
159  * Check whether package.json is found in current path.
160  * @param   {string} [startDir] Starting directory
161  * @returns {boolean} Whether a package.json is found in current path.
162  */
163 function checkPackageJson(startDir) {
164     return !!findPackageJson(startDir);
165 }
166
167 //------------------------------------------------------------------------------
168 // Public Interface
169 //------------------------------------------------------------------------------
170
171 module.exports = {
172     installSyncSaveDev,
173     fetchPeerDependencies,
174     findPackageJson,
175     checkDeps,
176     checkDevDeps,
177     checkPackageJson
178 };