/
check-dependencies.js
345 lines (294 loc) · 10 KB
/
check-dependencies.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
'use strict';
const fs = require('fs');
const path = require('path');
const pico = require('picocolors');
const semver = require('semver');
const spawn = require('child_process').spawn;
const spawnSync = require('child_process').spawnSync;
const findup = fileName => {
let dir = process.cwd();
while (true) {
const filePath = path.resolve(dir, fileName);
if (fs.existsSync(filePath)) {
return filePath;
}
const nextDir = path.dirname(dir);
if (dir === nextDir) {
// top level => not found
return null;
}
dir = nextDir;
}
};
const checkDependenciesHelper = (syncOrAsync, config) => {
const output = { log: [], error: [] };
let packageJson;
let installPromise = Promise.resolve();
let success = true;
let installNeeded = false;
const log = message => {
output.log.push(message);
if (options.verbose) {
options.log(message);
}
};
const error = message => {
output.error.push(message);
if (options.verbose) {
options.error(message);
}
};
const finish = () => {
output.status = success ? 0 : 1;
if (syncOrAsync === 'async') {
return Promise.resolve(output);
}
return output;
};
const missingPackageJson = () => {
success = false;
error('Missing package.json!');
return finish();
};
const options = {
packageManager: 'npm',
onlySpecified: false,
install: false,
scopeList: ['dependencies', 'devDependencies'],
optionalScopeList: ['optionalDependencies'],
verbose: false,
checkGitUrls: false,
log: console.log.bind(console),
error: console.error.bind(console),
...config,
};
if (!/^[a-z][a-z0-9-]*$/i.test(options.packageManager)) {
success = false;
error(
'The packageManager field value must match the regex ' +
`\`/^[a-z][a-z0-9-]*$/i\`; got: "${options.packageManager}"`,
);
return finish();
}
const packageJsonRegex = /package\.json$/;
options.packageDir = options.packageDir || findup('package.json');
if (!options.packageDir) {
return missingPackageJson();
}
options.packageDir = path.resolve(
options.packageDir.replace(packageJsonRegex, ''),
);
packageJson = `${options.packageDir}/package.json`;
if (!fs.existsSync(packageJson)) {
return missingPackageJson();
}
packageJson = require(packageJson);
const depsDir = `${options.packageDir}/node_modules`;
const getDepsMappingsFromScopeList = scopeList =>
// Get names of all packages specified in `package.json` at keys from
// `scopeList` together with specified version numbers.
scopeList.reduce(
(result, scope) => Object.assign(result, packageJson[scope]),
{},
);
// Make sure each package from `scopeList` is present and matches the specified version range.
// Packages from `optionalScopeList` may not be present but if they are, they are required
// to match the specified version range.
const checkPackage = pkg => {
const name = pkg.name;
let versionString = pkg.versionString;
const depDir = `${depsDir}/${name}`;
const depJsonPath = `${depDir}/package.json`;
if (!fs.existsSync(depDir) || !fs.existsSync(depJsonPath)) {
if (pkg.isOptional) {
log(`${name}: ${pico.red('not installed!')}`);
} else {
error(`${name}: ${pico.red('not installed!')}`);
success = false;
}
return;
}
// Let's look if we can get a valid version from a Git URL
if (options.checkGitUrls && /\.git.*#v?(.+)$/.test(versionString)) {
versionString = /#v?(.+)$/.exec(versionString)[1];
if (!semver.valid(versionString)) {
return;
}
}
// Quick and dirty check - make sure we're not dealing with a URL
if (/\//.test(versionString)) {
return;
}
// If we are dealing with a custom package name, semver check won't work - skip it
if (/#/.test(versionString)) {
return;
}
// Skip version checks for 'latest' - the semver module won't help here and the check
// would have to consult the npm server, making the operation slow.
if (versionString === 'latest') {
return;
}
const depJson = require(depJsonPath);
// Support package aliases
if (/npm:(.+)@(.+)/.test(versionString)) {
const [, depName, version] = versionString.match(/npm:(.+)@(.+)/);
versionString = version;
if (depJson.name !== depName) {
success = false;
error(
`${name}: installed: ${pico.red(
depName,
)}, expected: ${pico.green(depJson.name)}`,
);
}
}
const depVersion = depJson.version;
if (semver.satisfies(depVersion, versionString)) {
log(
`${name}: installed: ${pico.green(
depVersion,
)}, expected: ${pico.green(versionString)}`,
);
} else {
success = false;
error(
`${name}: installed: ${pico.red(
depVersion,
)}, expected: ${pico.green(versionString)}`,
);
}
};
const depsMappings = getDepsMappingsFromScopeList(options.scopeList);
const optionalDepsMappings = getDepsMappingsFromScopeList(
options.optionalScopeList,
);
const fullDepsMappings = {
...depsMappings,
...optionalDepsMappings,
};
Object.keys(depsMappings).forEach(name => {
checkPackage({
name,
versionString: depsMappings[name],
isOptional: false,
});
});
Object.keys(optionalDepsMappings).forEach(name => {
checkPackage({
name,
versionString: optionalDepsMappings[name],
isOptional: true,
});
});
installNeeded = !success;
if (options.onlySpecified) {
fs.readdirSync(depsDir)
// Ignore hidden directories
.filter(depName => depName[0] !== '.')
// Ignore files
.filter(depName =>
fs.lstatSync(`${depsDir}/${depName}`).isDirectory(),
)
.forEach(depName => {
let depSubDirName;
// Scoped packages
if (depName[0] === '@') {
depName = fs.readdirSync(`${depsDir}/${depName}`)[0];
// Ignore weird directories - if it just looks like a scoped package but
// isn't one, just skip it.
if (depSubDirName && !fullDepsMappings[depName]) {
success = false;
installNeeded = true;
error(
`Package ${depName} installed, though it shouldn't be`,
);
}
return;
}
// Regular packages
if (!fullDepsMappings[depName]) {
success = false;
installNeeded = true;
error(
`Package ${depName} installed, though it shouldn't be`,
);
}
});
}
if (success) {
output.depsWereOk = true;
return finish();
}
output.depsWereOk = false;
if (!options.install) {
error(
`Invoke ${pico.green(
`${options.packageManager} install`,
)} to install missing packages${
options.onlySpecified ? ' and remove excessive ones' : ''
}`,
);
return finish();
}
const install = () => {
log(`Invoking ${pico.green(`${options.packageManager} install`)}...`);
// If we're using a direct path, on Windows we need to invoke it via `node path`, not
// `cmd /c path`. In UNIX systems we can execute the command directly so no need to wrap.
let msg;
const method = syncOrAsync === 'sync' ? spawnSync : spawn;
const spawnReturn = method(`${options.packageManager} install`, {
cwd: options.packageDir,
stdio: 'inherit',
shell: true,
});
if (syncOrAsync === 'sync') {
if (spawnReturn.status !== 0) {
msg = `${
options.packageManager
} install failed with code: ${pico.red(spawnReturn.status)}`;
throw new Error(msg);
}
return null;
}
return new Promise((resolve, reject) => {
spawnReturn.on('close', code => {
if (code === 0) {
resolve();
return;
}
msg = `${
options.packageManager
} install failed with code: ${pico.red(code)}`;
error(msg);
reject(msg);
});
});
};
const installMissing = () => install();
if (syncOrAsync === 'sync') {
try {
if (installNeeded) {
installMissing();
}
success = true;
} catch (error) {
success = false;
}
return finish();
}
// Async scenario
if (installNeeded) {
installPromise = installPromise.then(installMissing);
}
return installPromise
.then(() => {
success = true;
return finish();
})
.catch(() => {
success = false;
return finish();
});
};
module.exports = cfg => checkDependenciesHelper('async', cfg);
module.exports.sync = cfg => checkDependenciesHelper('sync', cfg);