Skip to content

Commit

Permalink
chore: update linter
Browse files Browse the repository at this point in the history
and make sure we are linting everything (**) in lib
  • Loading branch information
Artoria2e5 committed Oct 18, 2019
1 parent 01636e1 commit 07ff807
Show file tree
Hide file tree
Showing 13 changed files with 109 additions and 90 deletions.
85 changes: 44 additions & 41 deletions lib/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ const meow = require('meow');
const updateNotifier = require('update-notifier');
const isCI = require('is-ci');
const createCallsiteRecord = require('callsite-record');
const pkgDir = require('pkg-dir');
const detectPreferredPM = require('preferred-pm');
const execa = require('execa');
const pkg = require('../package.json');
const npmCheck = require('./index');
const staticOutput = require('./out/static-output');
const interactiveUpdate = require('./out/interactive-update');
const updateAll = require('./out/update-all');
const debug = require('./state/debug');
const pkgDir = require('pkg-dir');
const detectPreferredPM = require('preferred-pm');
const execa = require('execa');
const npmCheck = require('.');

updateNotifier({pkg}).notify();

Expand Down Expand Up @@ -44,39 +44,39 @@ const cli = meow({
$ npm-check ../foo # Check another path.
$ npm-check -gu # Update globally installed modules by picking which ones to upgrade.
`},
{
alias: {
u: 'update',
y: 'update-all',
g: 'global',
s: 'skip-unused',
p: 'production',
d: 'dev-only',
E: 'save-exact',
i: 'ignore'
},
default: {
dir: pkgDir.sync() || process.cwd(),
emoji: !isCI,
spinner: !isCI
},
boolean: [
'update',
'update-all',
'global',
'skip-unused',
'production',
'dev-only',
'save-exact',
'color',
'emoji',
'spinner'
],
string: [
'ignore',
'specials'
]
});
{
alias: {
u: 'update',
y: 'update-all',
g: 'global',
s: 'skip-unused',
p: 'production',
d: 'dev-only',
E: 'save-exact',
i: 'ignore'
},
default: {
dir: pkgDir.sync() || process.cwd(),
emoji: !isCI,
spinner: !isCI
},
boolean: [
'update',
'update-all',
'global',
'skip-unused',
'production',
'dev-only',
'save-exact',
'color',
'emoji',
'spinner'
],
string: [
'ignore',
'specials'
]
});

const options = {
cwd: cli.input[0] || cli.flags.dir,
Expand Down Expand Up @@ -116,19 +116,21 @@ Promise.resolve()
if (options.updateAll) {
return updateAll(currentState);
}

if (options.update) {
return interactiveUpdate(currentState);
}

return staticOutput(currentState);
})
.catch(err => {
console.log(err.message);
.catch(error => {
console.log(error.message);
if (options.debug) {
console.log(createCallsiteRecord(err).renderSync());
console.log(createCallsiteRecord(error).renderSync());
} else {
console.log('For more detail, add `--debug` to the command');
}

process.exit(1);
});

Expand All @@ -137,12 +139,13 @@ const SUPPORTED_INSTALLERS = ['npm', 'pnpm', 'ied', 'yarn'];
function detectPreferredInstaller(cwd) {
return detectPreferredPM(cwd)
.then(preferredPM => {
let pm = preferredPM && SUPPORTED_INSTALLERS.indexOf(preferredPM.name) !== -1 ?
let pm = preferredPM && SUPPORTED_INSTALLERS.includes(preferredPM.name) ?
preferredPM.name : 'npm';
// Suffix the major version for pnpm@4.
if (pm === 'pnpm' && preferredPM.version === '>=3') {
pm = 'pnpm@' + execa.sync('pnpm', ['--version']).stdout.toString().split('.')[0];
}

return pm;
});
}
24 changes: 12 additions & 12 deletions lib/in/create-package-summary.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
'use strict';

const readPackageJson = require('./read-package-json');
const getLatestFromRegistry = require('./get-latest-from-registry');
const findModulePath = require('./find-module-path');
const path = require('path');
const _ = require('lodash');
const semverDiff = require('semver-diff');
const pathExists = require('path-exists');
const path = require('path');
const semver = require('semver');
const minimatch = require('minimatch');
const findModulePath = require('./find-module-path');
const getLatestFromRegistry = require('./get-latest-from-registry');
const readPackageJson = require('./read-package-json');

function createPackageSummary(moduleName, currentState) {
const cwdPackageJson = currentState.get('cwdPackageJson');
Expand Down Expand Up @@ -72,14 +72,14 @@ function createPackageSummary(moduleName, currentState) {
const unused = _.includes(unusedDependencies, moduleName);

return {
// info
moduleName: moduleName,
// Info
moduleName,
homepage: fromRegistry.homepage,
regError: fromRegistry.error,
pkgError: modulePackageJson.error,

// versions
latest: latest,
// Versions
latest,
installed: versionToUse,
isInstalled: packageIsInstalled,
notInstalled: !packageIsInstalled,
Expand All @@ -89,10 +89,10 @@ function createPackageSummary(moduleName, currentState) {
// Missing from package json
notInPackageJson: foundIn(missingFromPackageJson[moduleName]),

// meta
// Meta
devDependency: _.has(cwdPackageJson.devDependencies, moduleName),
usedInScripts: _.findKey(cwdPackageJson.scripts, script => {
return script.indexOf(moduleName) !== -1;
return script.includes(moduleName);
}),
mismatch: semver.validRange(packageJsonVersion) &&
semver.valid(versionToUse) &&
Expand All @@ -103,9 +103,9 @@ function createPackageSummary(moduleName, currentState) {
semver.valid(versionToUse) &&
semver.satisfies(latest, packageJsonVersion) &&
bump !== 'major',
bump: bump,
bump,

unused: unused
unused
};
});
}
Expand Down
2 changes: 1 addition & 1 deletion lib/in/find-module-path.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ function findModulePath(moduleName, currentState) {
const possibleModulePaths = nodeModulesPaths.map(x => path.join(x, moduleName));
const modulePath = possibleModulePaths.find(pathExists.sync);

// if no existing path was found, return the first tried path anyway
// If no existing path was found, return the first tried path anyway
return modulePath || path.join(cwd, moduleName);
}

Expand Down
4 changes: 2 additions & 2 deletions lib/in/get-installed-packages.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
'use strict';
const path = require('path');
const _ = require('lodash');
const globby = require('globby');
const readPackageJson = require('./read-package-json');
const path = require('path');

module.exports = function (cwd) {
const GLOBBY_PACKAGE_JSON = '{*/package.json,@*/*/package.json}';
const installedPackages = globby.sync(GLOBBY_PACKAGE_JSON, {cwd: cwd});
const installedPackages = globby.sync(GLOBBY_PACKAGE_JSON, {cwd});

return _(installedPackages)
.map(pkgPath => {
Expand Down
12 changes: 6 additions & 6 deletions lib/in/get-latest-from-registry.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ const cpuCount = require('os').cpus().length;
const throat = require('throat')(cpuCount);

const _ = require('lodash');
const bestGuessHomepage = require('./best-guess-homepage');
const packageJson = require('package-json');
const semver = require('semver');
const bestGuessHomepage = require('./best-guess-homepage');

function getNpmInfo(packageName) {
return throat(() => packageJson(packageName, {fullMetadata: true, allVersions: true}))
Expand All @@ -19,19 +19,19 @@ function getNpmInfo(packageName) {
.sort(semver.compare)
.valueOf();

const latest = rawData['dist-tags'].latest;
const next = rawData['dist-tags'].next;
const {latest} = rawData['dist-tags'];
const {next} = rawData['dist-tags'];
const latestStableRelease = semver.satisfies(latest, '*') ?
latest :
semver.maxSatisfying(sortedVersions, '*');
return {
latest: latestStableRelease,
next: next,
next,
versions: sortedVersions,
homepage: bestGuessHomepage(rawData)
};
}).catch(err => {
const errorMessage = `Registry error ${err.message}`;
}).catch(error => {
const errorMessage = `Registry error ${error.message}`;
return {
error: errorMessage
};
Expand Down
21 changes: 12 additions & 9 deletions lib/in/get-unused-packages.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,26 @@ const ora = require('ora');
const _ = require('lodash');

function skipUnused(currentState) {
return currentState.get('skipUnused') || // manual option to ignore this
currentState.get('global') || // global modules
currentState.get('update') || // in the process of doing an update
!currentState.get('cwdPackageJson').name; // there's no package.json
return currentState.get('skipUnused') || // Manual option to ignore this
currentState.get('global') || // global modules
currentState.get('update') || // In the process of doing an update
!currentState.get('cwdPackageJson').name; // There's no package.json
}

function getSpecialParsers(currentState) {
const specialsInput = currentState.get('specials');
if (!specialsInput) return;
if (!specialsInput) {
return;
}

return specialsInput
.split(',')
.map((special) => depcheck.special[special])
.map(special => depcheck.special[special])
.filter(Boolean);
}

function checkUnused(currentState) {
const spinner = ora(`Checking for unused packages. --skip-unused if you don't want this.`);
const spinner = ora('Checking for unused packages. --skip-unused if you don\'t want this.');
spinner.enabled = spinner.enabled && currentState.get('spinner');
spinner.start();

Expand Down Expand Up @@ -65,9 +68,9 @@ function checkUnused(currentState) {

const cwdPackageJson = currentState.get('cwdPackageJson');

// currently missing will return devDependencies that aren't really missing
// Currently missing will return devDependencies that aren't really missing
const missingFromPackageJson = _.omit(depCheckResults.missing || {},
Object.keys(cwdPackageJson.dependencies), Object.keys(cwdPackageJson.devDependencies));
Object.keys(cwdPackageJson.dependencies), Object.keys(cwdPackageJson.devDependencies));
currentState.set('missingFromPackageJson', missingFromPackageJson);
return currentState;
});
Expand Down
4 changes: 2 additions & 2 deletions lib/in/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ const getUnusedPackages = require('./get-unused-packages');
const createPackageSummary = require('./create-package-summary');

module.exports = function (currentState) {
return co(function *() {
return co(function * () {
yield getUnusedPackages(currentState);

const spinner = ora(`Checking npm registries for updated packages.`);
const spinner = ora('Checking npm registries for updated packages.');
spinner.enabled = spinner.enabled && currentState.get('spinner');
spinner.start();

Expand Down
7 changes: 4 additions & 3 deletions lib/in/read-package-json.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ function readPackageJson(filename) {
let error;
try {
pkg = require(filename);
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
} catch (error_) {
if (error_.code === 'MODULE_NOT_FOUND') {
error = new Error(`A package.json was not found at ${filename}`);
} else {
error = new Error(`A package.json was found at ${filename}, but it is not valid.`);
}
}
return extend({devDependencies: {}, dependencies: {}, error: error}, pkg);

return extend({devDependencies: {}, dependencies: {}, error}, pkg);
}

module.exports = readPackageJson;
6 changes: 3 additions & 3 deletions lib/out/interactive-update.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ function createChoices(packages, options) {

const choicesAsATable = table(_.map(choices, 'name'), {
align: ['l', 'l', 'l'],
stringLength: function (str) {
stringLength(str) {
return chalk.stripColor(str).length;
}
}).split('\n');
Expand Down Expand Up @@ -144,9 +144,9 @@ function interactive(currentState) {
.then(currentState => pm.doInstall(currentState, installer, installArgs[1]))
.then(currentState => {
console.log('');
console.log(chalk.green(`[npm-check] Update complete!`));
console.log(chalk.green('[npm-check] Update complete!'));
console.log(chalk.green('[npm-check] ' + updatedPackages));
console.log(chalk.green(`[npm-check] You should re-run your tests to make sure everything works with the updates.`));
console.log(chalk.green('[npm-check] You should re-run your tests to make sure everything works with the updates.'));
return currentState;
});
});
Expand Down
4 changes: 2 additions & 2 deletions lib/state/debug.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
'use strict';
const chalk = require('chalk');

function debug() {
function debug(...args) {
console.log(chalk.green('[npm-check] debug'));
console.log.apply(console, arguments);
console.log(...args);
console.log(`${chalk.green('===============================')}`);
}

Expand Down
8 changes: 4 additions & 4 deletions lib/state/init.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
'use strict';
const _ = require('lodash');
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const globalModulesPath = require('global-modules');
const chalk = require('chalk');
const readPackageJson = require('../in/read-package-json');
const globalPackages = require('../in/get-installed-packages');
const emoji = require('../out/emoji');
const fs = require('fs');
const chalk = require('chalk');

function init(currentState, userOptions) {
return new Promise((resolve, reject) => {
Expand All @@ -16,7 +16,7 @@ function init(currentState, userOptions) {
let modulesPath = globalModulesPath;

if (process.env.NODE_PATH) {
if (process.env.NODE_PATH.indexOf(path.delimiter) !== -1) {
if (process.env.NODE_PATH.includes(path.delimiter)) {
modulesPath = process.env.NODE_PATH.split(path.delimiter)[0];
console.log(chalk.yellow('warning: Using the first of multiple paths specified in NODE_PATH'));
} else {
Expand Down
Loading

0 comments on commit 07ff807

Please sign in to comment.