UNPKG

3.13 kBJavaScriptView Raw
1'use strict';
2
3const depcheck = require('depcheck');
4const ora = require('ora');
5const _ = require('lodash');
6const { rcFile } = require('rc-config-loader');
7
8function skipUnused(currentState) {
9 return currentState.get('skipUnused') || // manual option to ignore this
10 currentState.get('global') || // global modules
11 currentState.get('update') || // in the process of doing an update
12 !currentState.get('cwdPackageJson').name; // there's no package.json
13}
14
15function loadRcFile(rcFileName) {
16 try {
17 const results = rcFile(rcFileName);
18 // Not Found
19 if (!results) {
20 return {};
21 }
22 return results.config;
23 } catch (error) {
24 console.error(`Error parsing rc file; skipping it; error: ${error.message}`);
25 return {}; // default value
26 }
27}
28
29function getSpecialParsers(currentState) {
30 const specialsInput = currentState.get('specials');
31 if (!specialsInput) return;
32 return specialsInput
33 .split(',')
34 .map((special) => depcheck.special[special])
35 .filter(Boolean);
36}
37
38function checkUnused(currentState) {
39 const spinner = ora(`Checking for unused packages. --skip-unused if you don't want this.`);
40 spinner.enabled = spinner.enabled && currentState.get('spinner');
41 spinner.start();
42
43 return new Promise(resolve => {
44 if (skipUnused(currentState)) {
45 resolve(currentState);
46 return;
47 }
48
49 const depcheckDefaults = {
50 ignoreDirs: [
51 'sandbox',
52 'dist',
53 'generated',
54 '.generated',
55 'build',
56 'fixtures',
57 'jspm_packages'
58 ],
59 ignoreMatches: [
60 'gulp-*',
61 'grunt-*',
62 'karma-*',
63 'angular-*',
64 'babel-*',
65 'metalsmith-*',
66 'eslint-plugin-*',
67 '@types/*',
68 'grunt',
69 'mocha',
70 'ava'
71 ],
72 specials: getSpecialParsers(currentState)
73 };
74
75 const npmCheckRc = loadRcFile('npmcheck');
76
77 const depcheckOptions = {
78 ...depcheckDefaults,
79 ...npmCheckRc.depcheck
80 };
81
82 depcheck(currentState.get('cwd'), depcheckOptions, resolve);
83 }).then(depCheckResults => {
84 spinner.stop();
85 const unusedDependencies = [].concat(depCheckResults.dependencies, depCheckResults.devDependencies);
86 currentState.set('unusedDependencies', unusedDependencies);
87
88 const cwdPackageJson = currentState.get('cwdPackageJson');
89
90 // currently missing will return devDependencies that aren't really missing
91 const missingFromPackageJson = _.omit(depCheckResults.missing || {},
92 Object.keys(cwdPackageJson.dependencies), Object.keys(cwdPackageJson.devDependencies));
93 currentState.set('missingFromPackageJson', missingFromPackageJson);
94 return currentState;
95 });
96}
97
98module.exports = checkUnused;