/
check-outdated.js
647 lines (561 loc) · 19.1 KB
/
check-outdated.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
#!/usr/bin/env node
/**
* @file The CLI entry point.
*/
/**
* @external NodeModule
*/
const parseArguments = require('./helper/args');
const colorize = require('./helper/colorize');
const { getOutdatedDependencies, compareByName, compareByType } = require('./helper/dependencies');
const { getChangelogPath, getDependencyPackageJSON, getParentPackageJSONPath, readFile } = require('./helper/files');
const generateKeyValueList = require('./helper/list');
const { getRegExpPosition, escapeRegExp } = require('./helper/regexp');
const { semverDiff, semverDiffType, semverInRange } = require('./helper/semver');
const prettifyTable = require('./helper/table');
const { getNpmJSLink, getPackageAuthor, getPackageHomepage, getPackageRepository } = require('./helper/urls');
const pkg = require('./package.json');
/**
* @typedef {import('./helper/dependencies').NpmOptions} NpmOptions
* @typedef {import('./helper/dependencies').OutdatedDependencies} OutdatedDependencies
* @typedef {import('./helper/dependencies').OutdatedDependency} OutdatedDependency
* @typedef {import('./helper/files').PackageJSON} PackageJSON
* @typedef {import('./helper/table').Table} Table
* @typedef {import('./helper/table').TableColumn} TableColumn
* @typedef {import('./helper/args').AvailableArguments} AvailableArguments
*/
/**
* The options based on the CLI arguments.
*
* @typedef {object} CheckOutdatedOptions
* @property {string[]} [ignorePackages]
* @property {boolean} [ignoreDevDependencies]
* @property {boolean} [ignorePreReleases]
* @property {boolean} [preferWanted]
* @property {string[]} [columns]
* @property {string[]} [types]
*/
/** @typedef {CheckOutdatedOptions & NpmOptions} Options */
/**
* Array of outdated dependencies.
*
* @typedef {OutdatedDependency[]} Dependencies
*/
/**
* The details change can be used to share data between columns.
* For example, if the first column reads the package.json, the next column can rely of this data, without to acquire it again.
*
* @typedef {object} DependencyDetailsCache
* @property {[string, string]} [semverDiff]
* @property {PackageJSON} [packageJSON]
*/
const DEFAULT_COLUMNS = ['package', 'current', 'wanted', 'latest', 'reference', 'changes', 'location'];
/**
* @typedef {object} Column
* @property {TableColumn | string} caption;
* @property {(dependency: OutdatedDependency, options: Options, detailsCache: DependencyDetailsCache) => Promise<TableColumn | string>} getValue
*/
/** @type {{ [filePath: string]: string }} */
const packageJsonCache = {};
/** @type {{ readonly [columnName: string]: Column; }} */
const AVAILABLE_COLUMNS = {
package: {
caption: colorize.underline('Package'),
getValue: async (dependency, options) => {
switch (semverDiffType(dependency.current, getWantedOrLatest(dependency, options))) {
case 'major':
return colorize.yellow(dependency.name);
case 'minor':
return colorize.cyan(dependency.name);
case 'patch':
return colorize.green(dependency.name);
case 'revert':
return colorize.red(dependency.name);
default:
return dependency.name;
}
}
},
current: {
caption: {
text: colorize.underline('Current'),
alignRight: true
},
getValue: async (dependency, options) => {
if (dependency.current === '') {
return {
text: colorize.gray('-'),
alignRight: true
};
}
const diff = semverDiff(
[dependency.current, getWantedOrLatest(dependency, options)],
[colorize, colorize.magenta],
[colorize.underline, colorize.magenta.underline]
);
return {
text: diff[0],
alignRight: true
};
}
},
wanted: {
caption: {
text: colorize.underline('Wanted'),
alignRight: true
},
getValue: async (dependency) => {
if (dependency.wanted === '') {
return {
text: colorize.gray('-'),
alignRight: true
};
}
const diff = semverDiff(
[dependency.current, dependency.wanted],
[colorize, colorize.green],
[colorize.underline, colorize.green.underline]
);
return {
text: diff[1],
alignRight: true
};
}
},
latest: {
caption: {
text: colorize.underline('Latest'),
alignRight: true
},
getValue: async (dependency) => {
if (dependency.latest === '') {
return {
text: colorize.gray('-'),
alignRight: true
};
}
const diff = semverDiff(
[dependency.current, dependency.latest],
[colorize, colorize.magenta],
[colorize.underline, colorize.magenta.underline]
);
return {
text: diff[1],
alignRight: true
};
}
},
type: {
caption: colorize.underline('Type'),
getValue: async (dependency, options) => (semverDiffType(dependency.current, getWantedOrLatest(dependency, options)) || colorize.gray('-'))
},
location: {
caption: colorize.underline('Location'),
getValue: async (dependency) => dependency.location || colorize.gray('-')
},
packageType: {
caption: colorize.underline('Package Type'),
getValue: async (dependency) => dependency.type || colorize.gray('-')
},
reference: {
caption: colorize.underline('Reference'),
getValue: async (dependency) => {
const filePath = getParentPackageJSONPath(dependency.location);
let fileContent = packageJsonCache[filePath] || readFile(filePath);
if (fileContent !== undefined) {
fileContent = fileContent.replace(/\r\n|\r/gu, '\n');
if (!('filePath' in packageJsonCache)) {
packageJsonCache[filePath] = fileContent;
}
const json = JSON.parse(fileContent);
const actualVersion = (dependency.type && dependency.type in json ? json[dependency.type][dependency.name] : undefined);
const needle = new RegExp(`"${escapeRegExp(dependency.name)}"[^:]*:[^"]*"[^"]*${(actualVersion ? escapeRegExp(actualVersion) : '')}"`, 'u');
const [line, column] = getRegExpPosition(fileContent, needle);
if (line && column) {
return `${filePath}:${line}:${column}`;
}
}
return colorize.gray('-');
}
},
changes: {
caption: colorize.underline('Changes'),
getValue: async (dependency, _options, detailsCache) => {
detailsCache.packageJSON = detailsCache.packageJSON || getDependencyPackageJSON(dependency.location);
return (
await getPackageRepository(detailsCache.packageJSON, true) ||
getPackageHomepage(detailsCache.packageJSON) ||
getNpmJSLink(dependency.name) ||
colorize.gray('-')
);
}
},
changesPreferLocal: {
caption: colorize.underline('Changes'),
getValue: async (dependency, _options, detailsCache) => {
const changelogFile = getChangelogPath(dependency.location);
if (changelogFile) {
return changelogFile;
}
detailsCache.packageJSON = detailsCache.packageJSON || getDependencyPackageJSON(dependency.location);
return (
await getPackageRepository(detailsCache.packageJSON, true) ||
getPackageHomepage(detailsCache.packageJSON) ||
getNpmJSLink(dependency.name) ||
colorize.gray('-')
);
}
},
homepage: {
caption: colorize.underline('Homepage'),
getValue: async (dependency, _options, detailsCache) => {
detailsCache.packageJSON = detailsCache.packageJSON || getDependencyPackageJSON(dependency.location);
return (
dependency.homepage ||
getPackageHomepage(detailsCache.packageJSON) ||
await getPackageRepository(detailsCache.packageJSON) ||
getPackageAuthor(detailsCache.packageJSON) ||
getNpmJSLink(dependency.name) ||
colorize.gray('-')
);
}
},
npmjs: {
caption: colorize.underline('npmjs.com'),
getValue: async (dependency) => getNpmJSLink(dependency.name) || colorize.gray('-')
}
};
/**
* @deprecated `name` has been replaced by `package` in version 2.8.0.
*/
// @ts-expect-error -- That's the easiest way the clone the `package` property values
AVAILABLE_COLUMNS.name = AVAILABLE_COLUMNS.package;
/** @type {AvailableArguments} */
const AVAILABLE_ARGUMENTS = {
'--help': () => help(),
'-h': () => help(),
'--ignore-pre-releases': {
ignorePreReleases: true
},
'--ignore-dev-dependencies': {
ignoreDevDependencies: true
},
'--ignore-packages': (value) => {
const ignorePackages = value.split(',');
if (ignorePackages.length === 1 && (ignorePackages[0] === '' || ignorePackages[0].startsWith('-'))) {
return help('Invalid value of --ignore-packages');
}
return { ignorePackages };
},
'--prefer-wanted': {
preferWanted: true
},
'--columns': (value) => {
const columns = value.split(',');
const availableColumnsNames = Object.keys(AVAILABLE_COLUMNS);
if (columns.length === 1 && (columns[0] === '' || columns[0].startsWith('-'))) {
return help('Invalid value of --columns');
}
const invalidColumn = columns.find((name) => !availableColumnsNames.includes(name));
if (invalidColumn) {
return help(`Invalid column name "${invalidColumn}" in --columns\nAvailable columns are:\n${availableColumnsNames.join(', ')}`);
}
return { columns };
},
'--types': (value) => {
const types = value.split(',');
const availableTypesNames = ['major', 'minor', 'patch', 'prerelease', 'build', 'reverted'];
if (types.length === 1 && (types[0] === '' || types[0].startsWith('-'))) {
return help('Invalid value of --types');
}
const invalidType = types.find((name) => !availableTypesNames.includes(name));
if (invalidType) {
return help(`Invalid type name "${invalidType}" in --types\nAvailable types are:\n${availableTypesNames.join(', ')}`);
}
return { types };
},
'--global': {
global: true
},
'--depth': (value) => {
const depth = Number.parseInt(value, 10);
if (!Number.isFinite(depth)) {
return help('Invalid value of --depth');
}
return { depth };
}
};
if (require.main === /** @type {NodeModule} */(/** @type {any} */(module))) {
process.title = pkg.name;
const argv = process.argv.slice(2);
void (async () => {
process.exitCode = await checkOutdated(argv);
})();
}
else {
module.exports = checkOutdated;
}
/**
* The main functionality of the tool.
*
* @public
* @param {string[]} argv - Arguments given in the command line (`process.argv.slice(2)`).
* @returns {Promise<number>} A number which shall used as process exit code.
*/
async function checkOutdated (argv) {
/** @type {Options | string} */
let args;
try {
args = /** @type {Options | string} */(parseArguments(argv, AVAILABLE_ARGUMENTS));
}
catch (error) {
if (error instanceof Error) {
args = help(error.message);
}
else {
args = help();
}
}
if (typeof args === 'string') {
process.stdout.write(args);
return 1;
}
try {
const outdatedDependencies = Object.values(await getOutdatedDependencies(args));
const filteredDependencies = getFilteredDependencies(outdatedDependencies, args);
if (filteredDependencies.length === 0) {
process.stdout.write('All dependencies are up-to-date.\n');
return 0;
}
if (filteredDependencies.length === 1) {
process.stdout.write('1 outdated dependency found:\n\n');
}
else {
process.stdout.write(`${filteredDependencies.length} outdated dependencies found:\n\n`);
}
const visibleColumns = (args.columns === undefined || args.columns.length === 0 ? DEFAULT_COLUMNS : args.columns);
await writeOutdatedDependenciesToStdout(visibleColumns, filteredDependencies, args);
writeUnnecessaryIgnoredPackagesToStdout(filteredDependencies, args);
}
catch (error) {
if (typeof error === 'object' && error !== null) {
// Required for TypeScript to ensure the type is an `object` instead of `unknown`.
/** @type {Record<string, any>} */
const errorObject = error;
const out = generateKeyValueList(Object.getOwnPropertyNames(errorObject).map((property) => [colorize.magenta(property), errorObject[property]]));
process.stdout.write(`${colorize.red('Error while gathering outdated dependencies:')}\n\n${out}\n`);
}
else {
process.stdout.write(`${colorize.red('Unknown error while gathering outdated dependencies.')}\n`);
}
}
return 1;
}
/**
* Returns the help text of the CLI tool.
*
* @private
* @param {string[]} additionalLines - Additional text (error messages etc.) which shall be shown after the help.
* @returns {string} Multiline text containing the whole help text.
*/
function help (...additionalLines) {
return [
`${pkg.name} v${pkg.version} - ${pkg.description}`,
'Usage: ',
[
'[--ignore-pre-releases]',
'[--ignore-dev-dependencies]',
'[--ignore-packages <comma-separated-list-of-package-names>]',
'[--prefer-wanted]',
'[--columns <comma-separated-list-of-columns>]',
'[--types <comma-separated-list-of-update-types>]',
'[--global]',
'[--depth <number>]'
].join(' '),
'',
'Arguments:',
prettifyTable([
[
'--help, -h',
'Show this help.'
],
[
'--ignore-pre-releases',
'Don\'t recommend to update to versions which contain a hyphen (e.g. "2.1.0-alpha", "2.1.0-beta", "2.1.0-rc.1").'
],
[
'--ignore-dev-dependencies',
'Do not warn if devDependencies are outdated.'
],
[
'--ignore-packages <comma-separated-list-of-package-names>',
'Ignore the listed packages, even if they are outdated.'
],
[
'--prefer-wanted',
'Compare the "Current" version to the "Wanted" version, instead of the "Latest" version.'
],
[
'--columns <comma-separated-list-of-columns>',
'Defines which columns should be shown in which order.'
],
[
// Follow-up line for '--columns' description
'',
`Possible values: ${Object.keys(AVAILABLE_COLUMNS).join(',')}`
],
[
'--types <comma-separated-list-of-update-types>',
'Restrict the update type (e.g. only show minor updates, or reverted versions)'
],
[
// Follow-up line for '--types' description
'',
'Possible values: major,minor,patch,prerelease,build,reverted'
],
[
'--global',
'Check packages in the global install prefix instead of in the current project (equal to the npm outdated-option).'
],
[
'--depth <number>',
'Max depth for checking dependency tree (equal to the npm outdated-option).'
]
]),
...(Array.isArray(additionalLines) ? [''].concat(additionalLines) : []),
''
].join('\n');
}
/**
* Filters dependencies by the given filter `options`.
*
* @private
* @param {Dependencies} dependencies - Array of dependency objects which shall be filtered.
* @param {Options} options - Options to configure the filtering.
* @returns {Dependencies} Array with of the filtered dependency objects.
*/
function getFilteredDependencies (dependencies, options) {
let filteredDependencies = dependencies.filter((dependency) => (
!['git', 'linked', 'remote'].includes(getWantedOrLatest(dependency, options))
));
if (options.ignorePackages) {
const ignorePackages = options.ignorePackages;
const packageVersionRegExp = /^(.+?)@(.*)$/u;
filteredDependencies = filteredDependencies.filter((dependency) => {
for (const ignoredPackage of ignorePackages) {
const match = packageVersionRegExp.exec(ignoredPackage);
if (match === null) {
if (ignoredPackage === dependency.name) {
return false;
}
}
else {
if (match[1] === dependency.name) {
if (semverInRange(getWantedOrLatest(dependency, options), match[2])) {
return false;
}
}
}
}
return true;
});
}
if (options.ignoreDevDependencies) {
filteredDependencies = filteredDependencies.filter(({ type }) => (
type !== 'devDependencies'
));
}
if (options.ignorePreReleases) {
filteredDependencies = filteredDependencies.filter((dependency) => (
!dependency.current.includes('-') && !getWantedOrLatest(dependency, options).includes('-')
));
}
if (options.preferWanted) {
filteredDependencies = filteredDependencies.filter(({ current, wanted }) => current !== wanted);
}
if (options.types) {
filteredDependencies = filteredDependencies.filter(({ current, latest }) => options.types && options.types.includes(semverDiffType(current, latest) || ''));
}
return filteredDependencies;
}
/**
* Depending on the `preferWanted` option, either the `wanted` or the `latest` property of a dependency is returned.
*
* @param {OutdatedDependency} dependency - A specific outdated dependency.
* @param {Options} options - The arguments which the user provided.
* @returns {string} `wanted` or `latest`
*/
function getWantedOrLatest (dependency, options) {
return (options.preferWanted ? dependency.wanted : dependency.latest);
}
/**
* Show the version information of outdated dependencies in a styled way on the terminal (stdout).
*
* @private
* @param {string[]} visibleColumns - The columns which should be shown in the given order.
* @param {Dependencies} dependencies - Array of dependency objects, which shall be formatted and shown in the terminal.
* @param {Options} options - The arguments which the user provided.
* @returns {Promise<void>}
*/
async function writeOutdatedDependenciesToStdout (visibleColumns, dependencies, options) {
/** @type {(string | (string | TableColumn)[] | Promise<string | (string | TableColumn)[]>)[]} */
const table = [
visibleColumns.map((columnName) => AVAILABLE_COLUMNS[columnName].caption)
];
const groupByPackageType = !visibleColumns.includes('packageType');
/** @type {undefined | string} */
let previousPackageTypeGroup;
dependencies.sort((groupByPackageType ? compareByType : compareByName));
for (const dependency of dependencies) {
if (groupByPackageType && previousPackageTypeGroup !== dependency.type) {
table.push(`\n${colorize.underline(dependency.type || colorize.gray('unknown'))}`);
previousPackageTypeGroup = dependency.type;
}
table.push((async () => {
/** @type {DependencyDetailsCache} */
const dependencyDetailsCache = {};
return Promise.all(visibleColumns.map(async (columnName) => AVAILABLE_COLUMNS[columnName].getValue(dependency, options, dependencyDetailsCache)));
})());
}
process.stdout.write([
prettifyTable(await Promise.all(table)),
'',
colorize.underline('Color legend'),
`${colorize.yellow('Major update')}: backward-incompatible updates`,
`${colorize.cyan('Minor update')}: backward-compatible features`,
`${colorize.green('Patch update')}: backward-compatible bug fixes`,
`${colorize.red('Reverted')}: latest available version is lower than the installed version`,
'',
''
].join('\n'));
}
/**
* Show information about packages which are ignored by `--ignore-packages` with version number, but where the `latest` version differs.
*
* Example:
* Current "module" version: 2.0.0
* Latest "module" version: 2.0.2
* --ignore-packages module@^1
* --ignore-packages module@2.0.1
* In these cases, the ignore-statements have no effect, because version ^1 and 2.0.1 are outdated. That means, the ignore-statement can be removed.
*
* @private
* @param {Dependencies} filteredDependencies - Array of dependency objects, which will be shown in the terminal.
* @param {Options} options - The arguments which the user provided.
* @returns {void}
*/
function writeUnnecessaryIgnoredPackagesToStdout (filteredDependencies, options) {
const packageVersionRegExp = /^(.+?)@(.*)$/u;
if (!options.ignorePackages) {
return;
}
for (const ignoredPackage of options.ignorePackages) {
const match = packageVersionRegExp.exec(ignoredPackage);
if (match !== null) {
const dependency = filteredDependencies.find(({ name }) => name === match[1]);
if (dependency) {
process.stdout.write(`The --ignore-packages filter "${ignoredPackage}" has no effect, the latest version is ${dependency.latest}.\n\n`);
}
}
}
}