Skip to content

Commit

Permalink
refactor: use async/await instead of generator function
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed May 8, 2019
1 parent 322c5e0 commit 313dcb9
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 93 deletions.
12 changes: 0 additions & 12 deletions lib/patch_buffer.js

This file was deleted.

129 changes: 54 additions & 75 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,9 @@ const path = require('path');
const cp = require('child_process');
const urlparse = require('url').parse;
const querystring = require('querystring');

require('./patch_buffer');
const tar = require('tar');

const zlib = require('zlib');
const _rimraf = require('rimraf');
const rimraf = require('mz-modules/rimraf');
const _mkdirp = require('mkdirp');
const runscript = require('runscript');
const homedir = require('node-homedir');
Expand All @@ -24,84 +21,78 @@ const url = require('url');
const config = require('./config');
const get = require('./get');

exports.readJSON = function* readJSON(filepath) {
if (!(yield fs.exists(filepath))) {
exports.readJSON = async filepath => {
if (!(await fs.exists(filepath))) {
return {};
}
const content = yield fs.readFile(filepath, 'utf8');
const content = await fs.readFile(filepath, 'utf8');
try {
return JSON.parse(content.trim());
} catch (err) {
err.message += ` (file: ${filepath})`;
console.error('content buffer: %j', yield fs.readFile(filepath));
console.error('content buffer: %j', await fs.readFile(filepath));
throw err;
}
};

exports.readPackageJSON = function* readPackageJSON(root) {
const pkg = yield exports.readJSON(path.join(root, 'package.json'));
exports.readPackageJSON = async root => {
const pkg = await exports.readJSON(path.join(root, 'package.json'));
normalizeData(pkg);
return pkg;
};

const INSTALL_DONE_KEY = '__npminstall_done';

// 设置 pkg 安装完成的标记
exports.setInstallDone = function* setInstallDone(pkgRoot) {
yield exports.addMetaToJSONFile(path.join(pkgRoot, 'package.json'), {
exports.setInstallDone = async pkgRoot => {
await exports.addMetaToJSONFile(path.join(pkgRoot, 'package.json'), {
[INSTALL_DONE_KEY]: Date(),
});
};

exports.unsetInstallDone = function* setInstallDone(pkgRoot) {
yield exports.addMetaToJSONFile(path.join(pkgRoot, 'package.json'), {
exports.unsetInstallDone = async pkgRoot => {
await exports.addMetaToJSONFile(path.join(pkgRoot, 'package.json'), {
[INSTALL_DONE_KEY]: false,
});
};

// 判断 pkg 是否已经安装完成
exports.isInstallDone = function* isInstallDone(pkgRoot) {
const pkg = yield exports.readJSON(path.join(pkgRoot, 'package.json'));
exports.isInstallDone = async pkgRoot => {
const pkg = await exports.readJSON(path.join(pkgRoot, 'package.json'));
return !!pkg[INSTALL_DONE_KEY];
};

exports.addMetaToJSONFile = function* (filepath, meta) {
yield fs.chmod(filepath, '644');
const pkg = yield exports.readJSON(filepath);
exports.addMetaToJSONFile = async (filepath, meta) => {
await fs.chmod(filepath, '644');
const pkg = await exports.readJSON(filepath);
for (const key in meta) {
pkg[key] = meta[key];
}
yield fs.writeFile(filepath, JSON.stringify(pkg, null, 2));
await fs.writeFile(filepath, JSON.stringify(pkg, null, 2));
};

exports.mkdirp = function mkdirp(dir, mod) {
exports.mkdirp = (dir, mod) => {
return new Promise((resolve, reject) => {
_mkdirp(dir, mod, err => {
err ? reject(err) : resolve();
});
});
};

exports.rimraf = function rimraf(dir) {
return new Promise((resolve, reject) => {
_rimraf(dir, err => {
err ? reject(err) : resolve();
});
});
};
exports.rimraf = rimraf;

exports.relative = function relative(src, dest) {
exports.relative = (src, dest) => {
// Windows don't support relative path
if (process.platform === 'win32') return src;
return path.relative(path.dirname(dest), src);
};

exports.forceSymlink = function* forceSymlink(src, dest, type) {
exports.forceSymlink = async (src, dest, type) => {
const relative = exports.relative(src, dest);
type = type || 'junction';
// cleanup dest
try {
const linkString = yield fs.readlink(dest);
const linkString = await fs.readlink(dest);
// already linked
if (linkString === relative) {
return relative;
Expand All @@ -112,27 +103,15 @@ exports.forceSymlink = function* forceSymlink(src, dest, type) {

const destDir = path.dirname(dest);
// check if destDir is not exist
if (!(yield fs.exists(destDir))) {
yield exports.mkdirp(destDir);
if (!(await fs.exists(destDir))) {
await exports.mkdirp(destDir);
}

yield exports.rimraf(dest);
yield fs.symlink(relative, dest, type);
await rimraf(dest);
await fs.symlink(relative, dest, type);
return relative;
};

exports.forceStat = function* isSymbolicLink(linkPath) {
let stat;
try {
stat = yield fs.lstat(linkPath);
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
return stat;
};

function setNpmPackageEnv(env, key, value) {
const t = typeof value;
if (t === 'string' || t === 'number' || t === 'boolean') {
Expand All @@ -146,7 +125,7 @@ function setNpmPackageEnv(env, key, value) {
}
}

exports.formatPackageUrl = function formatUrl(registry, name) {
exports.formatPackageUrl = (registry, name) => {
if (name[0] === '@') {
// dont encodeURIComponent @ char, it will be 405
// https://registry.npmjs.com/%40rstacruz%2Ftap-spec/%3E%3D4.1.1
Expand All @@ -161,7 +140,7 @@ exports.formatPackageUrl = function formatUrl(registry, name) {
return url.format(parsed);
};

exports.parseTarballUrls = function parseTarballUrls(tarball) {
exports.parseTarballUrls = tarball => {
const urls = [ tarball ];
const parsed = urlparse(tarball);
const query = parsed.query && querystring.parse(parsed.query);
Expand All @@ -178,7 +157,7 @@ exports.parseTarballUrls = function parseTarballUrls(tarball) {
* Runs an npm script.
*/

exports.runScript = function* runScript(pkgDir, script, options) {
exports.runScript = async (pkgDir, script, options) => {
// merge config.env <= process.env <= options.env
const env = {};

Expand All @@ -203,7 +182,7 @@ exports.runScript = function* runScript(pkgDir, script, options) {
}

// set npm_package_* env from package.json
const pkg = yield exports.readJSON(path.join(pkgDir, 'package.json'));
const pkg = await exports.readJSON(path.join(pkgDir, 'package.json'));
for (const key in pkg) {
setNpmPackageEnv(env, key, pkg[key]);
}
Expand Down Expand Up @@ -232,7 +211,7 @@ exports.runScript = function* runScript(pkgDir, script, options) {
}

try {
return yield runscript(script, {
return await runscript(script, {
cwd: pkgDir,
env,
stdio: 'inherit',
Expand All @@ -246,15 +225,15 @@ exports.runScript = function* runScript(pkgDir, script, options) {
}
};

exports.getMaxRange = function(spec) {
exports.getMaxRange = spec => {
// >=1.0.0 <2.0.0
const r = /^>=.*?<(.*?)$/.exec(spec);
if (r) {
return r[1];
}
};

exports.findMaxSatisfyingVersion = function(spec, distTags, allVersions) {
exports.findMaxSatisfyingVersion = (spec, distTags, allVersions) => {
// try tag first
let realPkgVersion = distTags[spec];

Expand Down Expand Up @@ -286,14 +265,14 @@ exports.findMaxSatisfyingVersion = function(spec, distTags, allVersions) {
return realPkgVersion;
};

exports.getPackageStorePath = function(storeDir, pkg) {
exports.getPackageStorePath = (storeDir, pkg) => {
// name => _name@1.0.0@name
// @scope/name => _@scope_name@1.0.0@scope/name
// some packages need name: https://github.com/BenoitZugmeyer/eslint-plugin-html/blob/master/src/index.js#L24
return path.join(storeDir, `_${pkg.name.replace(/\//g, '_')}@${pkg.version}@${pkg.name}`);
};

exports.unpack = function(readstream, target, pkg) {
exports.unpack = (readstream, target, pkg) => {
return new Promise((resolve, reject) => {
const extracter = tar.extract({
cwd: target,
Expand Down Expand Up @@ -353,17 +332,17 @@ exports.unpack = function(readstream, target, pkg) {
});
};

exports.copyInstall = function* (src, options) {
exports.copyInstall = async (src, options) => {
// 1. make sure source folder has package.json, and package.json contains name
// 2. get the target directory: $storeDir/${pkg.name}/${pkg.version}
// 3. check if this package has been installed, and make sure only copy once.
// 4. if already installed, return with exists = true
// 5. if not installed, copy and return with exists = false
const pkgpath = path.join(src, 'package.json');
if (!(yield fs.exists(pkgpath))) {
if (!(await fs.exists(pkgpath))) {
throw new Error(`package.json missed(${pkgpath})`);
}
const realPkg = yield exports.readPackageJSON(src);
const realPkg = await exports.readPackageJSON(src);
if (!realPkg.name || !realPkg.version) {
throw new Error(`package.json must contains name and version(${pkgpath})`);
}
Expand All @@ -382,18 +361,18 @@ exports.copyInstall = function* (src, options) {
return result;
}
// wait copy finish
yield options.events.await(key);
await options.events.await(key);
return result;
}

options.cache[key] = {
done: false,
};

if (!(yield exports.isInstallDone(targetdir))) {
yield fse.emptydir(targetdir);
yield fse.copy(src, targetdir);
yield exports.setInstallDone(targetdir);
if (!(await exports.isInstallDone(targetdir))) {
await fse.emptydir(targetdir);
await fse.copy(src, targetdir);
await exports.setInstallDone(targetdir);
result.exists = false;
}

Expand All @@ -402,10 +381,10 @@ exports.copyInstall = function* (src, options) {
return result;
};

exports.getPkgFromPaths = function* (name, paths) {
exports.getPkgFromPaths = async (name, paths) => {
for (const p of paths) {
const tryPath = path.join(p, name, 'package.json');
const pkg = yield exports.readJSON(tryPath);
const pkg = await exports.readJSON(tryPath);
if (pkg.name && pkg.version) {
pkg.installPath = path.join(p, name);
return pkg;
Expand All @@ -414,8 +393,8 @@ exports.getPkgFromPaths = function* (name, paths) {
return null;
};

exports.getTarballStream = function* (url, options) {
const result = yield get(url, {
exports.getTarballStream = async (url, options) => {
const result = await get(url, {
timeout: options.streamingTimeout || options.timeout,
followRedirect: true,
streaming: true,
Expand All @@ -428,7 +407,7 @@ exports.getTarballStream = function* (url, options) {
return result.res;
};

function* getRemotePackage(name, registry, globalOptions) {
async function getRemotePackage(name, registry, globalOptions) {
const registries = [ registry ].concat([
'https://registry.npm.taobao.org',
'https://r.cnpmjs.org',
Expand All @@ -439,7 +418,7 @@ function* getRemotePackage(name, registry, globalOptions) {
for (const registry of registries) {
const binaryMirrorUrl = exports.formatPackageUrl(registry, name + '/latest');
try {
const res = yield get(binaryMirrorUrl, {
const res = await get(binaryMirrorUrl, {
dataType: 'json',
followRedirect: true,
// don't retry
Expand All @@ -459,17 +438,17 @@ function* getRemotePackage(name, registry, globalOptions) {
return pkg;
}

exports.getBinaryMirrors = function* getBinaryMirrors(registry, globalOptions) {
const pkg = yield getRemotePackage('binary-mirror-config', registry, globalOptions);
exports.getBinaryMirrors = async (registry, globalOptions) => {
const pkg = await getRemotePackage('binary-mirror-config', registry, globalOptions);
return pkg.mirrors.china;
};

exports.getBugVersions = function* getBugVersions(registry, globalOptions) {
const pkg = yield getRemotePackage('bug-versions', registry, globalOptions);
exports.getBugVersions = async (registry, globalOptions) => {
const pkg = await getRemotePackage('bug-versions', registry, globalOptions);
return pkg.config['bug-versions'];
};

exports.matchPlatform = function(current, osNames) {
exports.matchPlatform = (current, osNames) => {
if (!Array.isArray(osNames) || osNames.length === 0) {
return true;
}
Expand Down
12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"moment": "^2.24.0",
"ms": "^2.1.1",
"mz": "^2.7.0",
"mz-modules": "^2.1.0",
"node-gyp": "^4.0.0",
"node-homedir": "^1.1.1",
"normalize-git-url": "^3.0.2",
Expand All @@ -57,15 +58,14 @@
"devDependencies": {
"autod": "3",
"coffee": "^5.2.1",
"eslint": "3",
"eslint-config-egg": "3",
"http-proxy": "^1.16.2",
"eslint": "5",
"eslint-config-egg": "7",
"http-proxy": "1",
"intelli-espower-loader": "1",
"istanbul": "*",
"mm": "^2.5.0",
"mocha": "6",
"mz-modules": "^2.1.0",
"nyc": "^14.0.0",
"mz-modules": "2",
"nyc": "14",
"power-assert": "1"
},
"homepage": "https://github.com/cnpm/npminstall",
Expand Down

0 comments on commit 313dcb9

Please sign in to comment.