Skip to content

Commit

Permalink
refactor: use p-map instead of co-parallel
Browse files Browse the repository at this point in the history
and also use fs-extra instead of co-fs-extra,
because it support async/await by default
  • Loading branch information
fengmk2 committed May 8, 2019
1 parent 313dcb9 commit 3fbb871
Show file tree
Hide file tree
Showing 29 changed files with 316 additions and 349 deletions.
34 changes: 16 additions & 18 deletions bin/install.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
'use strict';

const debug = require('debug')('npminstall:bin:install');
const co = require('co');
const npa = require('npm-package-arg');
const chalk = require('chalk');
const path = require('path');
Expand Down Expand Up @@ -86,8 +85,7 @@ if (argv.version) {
}

if (argv.help) {
console.log(
`
console.log(`
Usage:
npminstall
Expand Down Expand Up @@ -201,11 +199,11 @@ for (const key in argv) {

debug('argv: %j, env: %j', argv, env);

co(function* () {
(async () => {
let binaryMirrors = {};

if (inChina) {
binaryMirrors = yield utils.getBinaryMirrors(registry, { proxy });
binaryMirrors = await utils.getBinaryMirrors(registry, { proxy });
if (customChinaMirrorUrl) {
for (const key in binaryMirrors) {
const item = binaryMirrors[key];
Expand Down Expand Up @@ -264,7 +262,7 @@ co(function* () {
}

if (argv['fix-bug-versions']) {
const packageVersionMapping = yield utils.getBugVersions(registry, { proxy });
const packageVersionMapping = await utils.getBugVersions(registry, { proxy });
config.autoFixVersion = function autoFixVersion(name, version) {
const fixVersions = packageVersionMapping[name];
return fixVersions && fixVersions[version] || null;
Expand Down Expand Up @@ -294,27 +292,27 @@ co(function* () {
const meta = utils.getGlobalInstallMeta(argv.prefix);
config.targetDir = meta.targetDir;
config.binDir = meta.binDir;
yield installGlobal(config);
await installGlobal(config);
} else {
if (pkgs.length === 0) {
if (config.production) {
// warning when `${root}/node_modules` exists
const nodeModulesDir = path.join(root, 'node_modules');
if (yield fs.exists(nodeModulesDir)) {
const dirs = yield fs.readdir(nodeModulesDir);
if (await fs.exists(nodeModulesDir)) {
const dirs = await fs.readdir(nodeModulesDir);
// ignore [ '.bin', 'node' ], it will install first by https://github.com/cnpm/nodeinstall
if (!(dirs.length === 2 && dirs.indexOf('.bin') >= 0 && dirs.indexOf('node') >= 0)) {
console.error(chalk.yellow(`npminstall WARN node_modules exists: ${nodeModulesDir}, contains ${dirs.length} dirs`));
}
}
}
const pkgFile = path.join(root, 'package.json');
const exists = yield fs.exists(pkgFile);
const exists = await fs.exists(pkgFile);
if (!exists) {
console.warn(chalk.yellow(`npminstall WARN package.json not exists: ${pkgFile}`));
} else {
// try to read npminstall config from package.json
const pkg = yield utils.readJSON(pkgFile);
const pkg = await utils.readJSON(pkgFile);
pkg.config = pkg.config || {};
pkg.config.npminstall = pkg.config.npminstall || {};
// {
Expand Down Expand Up @@ -362,7 +360,7 @@ co(function* () {
}
}
}
yield installLocal(config);
await installLocal(config);
if (pkgs.length > 0) {
// support --save, --save-dev, --save-optional, --save-client, --save-build and --save-isomorphic
const map = {
Expand All @@ -374,7 +372,7 @@ co(function* () {
'save-isomorphic': 'isomorphicDependencies',
};
for (const key in map) {
if (argv[key]) yield updateDependencies(root, pkgs, map[key], argv['save-exact'], config.remoteNames);
if (argv[key]) await updateDependencies(root, pkgs, map[key], argv['save-exact'], config.remoteNames);
}
}
}
Expand All @@ -384,7 +382,7 @@ co(function* () {
fs.writeFileSync(path.join(root, 'npminstall-debug.log'), util.inspect(config, { depth: 2 }));
}
});
}).catch(err => {
})().catch(err => {
console.error(chalk.red(err.stack));
console.error(chalk.yellow('npminstall version: %s'), require('../package.json').version);
console.error(chalk.yellow('npminstall args: %s'), process.argv.join(' '));
Expand Down Expand Up @@ -420,10 +418,10 @@ function getIgnoreScripts() {
}
}

function* updateDependencies(root, pkgs, propName, saveExact, remoteNames) {
async function updateDependencies(root, pkgs, propName, saveExact, remoteNames) {
const savePrefix = saveExact ? '' : getVersionSavePrefix();
const pkgFile = path.join(root, 'package.json');
const pkg = yield utils.readJSON(pkgFile);
const pkg = await utils.readJSON(pkgFile);
const deps = pkg[propName] = pkg[propName] || {};
for (const item of pkgs) {
if ([ 'remote', 'hosted', 'git' ].indexOf(item.type) >= 0) {
Expand All @@ -434,7 +432,7 @@ function* updateDependencies(root, pkgs, propName, saveExact, remoteNames) {
: deps[remoteNames[item.version]] = item.version;
} else {
const pkgDir = item.type === 'local' ? item.version : path.join(root, 'node_modules', item.name);
const itemPkg = yield utils.readJSON(path.join(pkgDir, 'package.json'));
const itemPkg = await utils.readJSON(path.join(pkgDir, 'package.json'));
deps[itemPkg.name] = `${savePrefix}${itemPkg.version}`;
}
}
Expand All @@ -444,5 +442,5 @@ function* updateDependencies(root, pkgs, propName, saveExact, remoteNames) {
newDeps[key] = deps[key];
}
pkg[propName] = newDeps;
yield fs.writeFile(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
await fs.writeFile(pkgFile, JSON.stringify(pkg, null, 2) + '\n');
}
33 changes: 15 additions & 18 deletions bin/link.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
const debug = require('debug')('npminstall:bin:link');
const npa = require('npm-package-arg');
const semver = require('semver');
const co = require('co');
const assert = require('assert');
const chalk = require('chalk');
const path = require('path');
Expand All @@ -31,8 +30,7 @@ if (argv.version) {
}

if (argv.help) {
console.log(
`
console.log(`
Usage:
npmlink <folder>
Expand All @@ -50,7 +48,7 @@ const globalModuleDir = path.join(globalMeta.targetDir, 'node_modules');

const folders = argv._.map(name => utils.formatPath(name));

co(function* npmlink() {
(async () => {
const installArgs = [];
for (const arg of orignalArgv) {
if (arg.startsWith('--root')) {
Expand All @@ -67,18 +65,18 @@ co(function* npmlink() {
// 2. link CWD to targetDir/node_modules/{name}
// 3. link bins to binDir
const pkgFile = path.join(root, 'package.json');
const pkg = yield utils.readJSON(pkgFile);
const pkg = await utils.readJSON(pkgFile);
assert(pkg.name, `package.name not eixsts on ${pkgFile}`);
const linkDir = path.join(globalMeta.targetDir, 'node_modules', pkg.name);

console.info(chalk.gray(`\`$ npminstall ${installArgs.join(' ')}\` on ${root}`));
const installBin = path.join(__dirname, 'install.js');
yield utils.fork(installBin, installArgs, {
await utils.fork(installBin, installArgs, {
cwd: root,
});
yield utils.forceSymlink(root, linkDir);
await utils.forceSymlink(root, linkDir);
console.info(`link ${chalk.magenta(linkDir)}@ -> ${root}`);
yield bin(root, pkg, linkDir, {
await bin(root, pkg, linkDir, {
console,
binDir: globalMeta.binDir,
targetDir: root,
Expand Down Expand Up @@ -111,8 +109,7 @@ co(function* npmlink() {
if (pkgInfo.name) {
debug('link source %s is a npm module', folder);
folder = path.join(globalModuleDir, pkgInfo.name);
pkg = yield utils.readJSON(path.join(globalModuleDir, pkgInfo.name, 'package.json'));

pkg = await utils.readJSON(path.join(globalModuleDir, pkgInfo.name, 'package.json'));

// when these situations need install
// 1. pkg not exist in global module directory
Expand All @@ -128,43 +125,43 @@ co(function* npmlink() {
debug('%s not satisfies with requirement, try to install %s from npm', folder, pkgInfo.raw);
// try install from npm registry
console.info(chalk.gray(`\`$ npminstall --global ${pkgInfo.raw}`));
yield utils.fork(installBin, installArgs.concat([ '-g', pkgInfo.raw ]), {
await utils.fork(installBin, installArgs.concat([ '-g', pkgInfo.raw ]), {
env,
});
}

const pkgFile = path.join(folder, 'package.json');
pkg = yield utils.readJSON(pkgFile);
pkg = await utils.readJSON(pkgFile);
assert(pkg.name, `package.name not eixsts on ${pkgFile}`);
} else {
if (!path.isAbsolute(folder)) {
folder = path.join(root, folder);
}
// read from folder
if (!(yield fs.exists(folder))) {
if (!(await fs.exists(folder))) {
throw new Error(`${folder} not exists`);
}

const pkgFile = path.join(folder, 'package.json');
pkg = yield utils.readJSON(pkgFile);
pkg = await utils.readJSON(pkgFile);
assert(pkg.name, `package.name not eixsts on ${pkgFile}`);

// install dependencies
console.info(chalk.gray(`\`$ npminstall ${installArgs.join(' ')}\` on ${folder}`));
yield utils.fork(installBin, installArgs, {
await utils.fork(installBin, installArgs, {
cwd: folder,
env,
});
}

// link folder to CWD/node_modules/{name}
const linkDir = path.join(targetDir, pkg.name);
yield utils.forceSymlink(folder, linkDir);
await utils.forceSymlink(folder, linkDir);
// link bins
console.info(`link ${chalk.magenta(linkDir)}@ -> ${folder}`);
yield bin(root, pkg, linkDir, { console });
await bin(root, pkg, linkDir, { console });
}
}).catch(err => {
})().catch(err => {
console.error(chalk.red(err.stack));
console.error(chalk.yellow('npmlink version: %s'), require('../package.json').version);
console.error(chalk.yellow('npmlink args: %s'), process.argv.join(' '));
Expand Down
24 changes: 11 additions & 13 deletions bin/uninstall.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

const debug = require('debug')('npminstall:bin:uninstall');
const npa = require('npm-package-arg');
const co = require('co');
const path = require('path');
const fs = require('mz/fs');
const parseArgs = require('minimist');
Expand Down Expand Up @@ -54,7 +53,7 @@ for (const name of argv._) {

if (!pkgs.length) help();

co(function* () {
(async () => {
const root = argv.root || process.cwd();
const config = {
root,
Expand All @@ -76,40 +75,39 @@ co(function* () {
}
}
debug('uninstall in %s with pkg: $j, config: %j', root, pkgs, config);
const uninstalled = yield uninstall(config);
const uninstalled = await uninstall(config);
if (uninstalled.length > 0) {
// support --save, --save-dev and --save-optional
if (argv.save) {
yield updateDependencies(root, pkgs, 'dependencies');
await updateDependencies(root, pkgs, 'dependencies');
} else if (argv['save-dev']) {
yield updateDependencies(root, pkgs, 'devDependencies');
await updateDependencies(root, pkgs, 'devDependencies');
} else if (argv['save-optional']) {
yield updateDependencies(root, pkgs, 'optionalDependencies');
await updateDependencies(root, pkgs, 'optionalDependencies');
}
}
yield updateDependencies(root, uninstalled);
}).catch(function(err) {
await updateDependencies(root, uninstalled);
})().catch(err => {
console.error(chalk.red(err));
console.error(chalk.red(err.stack));
process.exit(1);
});

function* updateDependencies(root, pkgs, propName) {
async function updateDependencies(root, pkgs, propName) {
const pkgFile = path.join(root, 'package.json');
const pkg = yield utils.readJSON(pkgFile);
const pkg = await utils.readJSON(pkgFile);
const deps = pkg[propName];
if (!deps) return;

for (const pkg of pkgs) {
delete deps[pkg.name];
}

yield fs.writeFile(pkgFile, JSON.stringify(pkg, null, 2));
await fs.writeFile(pkgFile, JSON.stringify(pkg, null, 2));
}

function help() {
console.log(
`
console.log(`
Usage:
npmuninstall <pkg>
Expand Down
3 changes: 1 addition & 2 deletions bin/update.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ process.env.NPMINSTALL_BY_UPDATE = 'true';
require('./install');

function help() {
console.log(
`
console.log(`
Usage:
npmupdate [--root=${root}]
Expand Down
12 changes: 6 additions & 6 deletions lib/bin.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const utils = require('./utils');

module.exports = bin;

function* bin(parentDir, pkg, pkgDir, options) {
async function bin(parentDir, pkg, pkgDir, options) {
let bins = pkg.bin || {};
if (typeof bins === 'string') {
bins = {};
Expand All @@ -30,13 +30,13 @@ function* bin(parentDir, pkg, pkgDir, options) {
} else {
binDir = path.join(parentDir, 'node_modules', '.bin');
}
yield utils.mkdirp(binDir);
await utils.mkdirp(binDir);

for (const name of names) {
const srcBin = path.join(pkgDir, bins[name]);
const destBin = path.join(binDir, name);
yield fs.chmod(srcBin, 0o755);
yield linkBin(srcBin, destBin);
await fs.chmod(srcBin, 0o755);
await linkBin(srcBin, destBin);
if (showBinLog) {
options.console.info('[%s] link %s@ -> %s',
chalk.green(pkg.name + '@' + pkg.version), chalk.magenta(destBin), srcBin);
Expand All @@ -47,7 +47,7 @@ function* bin(parentDir, pkg, pkgDir, options) {
}
}

function* linkBin(src, dest) {
async function linkBin(src, dest) {
if (process.platform === 'win32') {
return new Promise((resolve, reject) => {
cmdShim.ifExists(src, dest, err => {
Expand All @@ -57,5 +57,5 @@ function* linkBin(src, dest) {
});
}

return yield utils.forceSymlink(src, dest);
return await utils.forceSymlink(src, dest);
}
Loading

0 comments on commit 3fbb871

Please sign in to comment.