From 9390ab75ceb869f8ee53b4f08e782eac1f6465ba Mon Sep 17 00:00:00 2001 From: Pierre Vanduynslager Date: Fri, 6 Apr 2018 23:24:15 -0400 Subject: [PATCH] fix: simplify promisification Use `pify` with `multiArgs` instead of `new Promise` with callback. --- package.json | 10 ++++--- src/index.js | 4 +-- src/lib/npm.js | 74 +++++++++++++++++++++++++---------------------- src/lib/travis.js | 28 +++++++++--------- 4 files changed, 60 insertions(+), 56 deletions(-) diff --git a/package.json b/package.json index 465ffda..84d91e0 100644 --- a/package.json +++ b/package.json @@ -37,7 +37,6 @@ "babel-preset-env": "^1.6.1", "babel-register": "^6.26.0", "base32": "0.0.6", - "bluebird": "^3.4.6", "clipboardy": "^1.2.2", "git-config-path": "^1.0.1", "github-url-from-git": "^1.4.0", @@ -52,6 +51,7 @@ "p-retry": "^1.0.0", "parse-git-config": "^2.0.0", "parse-github-repo-url": "^1.0.0", + "pify": "^3.0.0", "request": "^2.85.0", "request-debug": "^0.2.0", "request-promise": "^4.1.1", @@ -66,8 +66,9 @@ "cz-conventional-changelog": "^2.0.0", "nyc": "^11.2.1", "rimraf": "^2.4.2", - "semantic-release": "^15.0.0", - "xo": "^0.20.0" + "semantic-release": "^15.1.5", + "xo": "^0.20.0", + "travis-deploy-once": "^4.4.1" }, "engines": { "node": ">=4", @@ -119,7 +120,8 @@ "lint": "xo", "pretest": "npm run lint", "semantic-release": "semantic-release", - "test": "nyc ava -v" + "test": "nyc ava -v", + "travis-deploy-once": "travis-deploy-once" }, "xo": { "prettier": true, diff --git a/src/index.js b/src/index.js index 0fdb4a6..5111e53 100644 --- a/src/index.js +++ b/src/index.js @@ -1,6 +1,6 @@ const {readFileSync, writeFileSync} = require('fs'); const _ = require('lodash'); -const {promisify} = require('bluebird'); +const pify = require('pify'); const nopt = require('nopt'); const npm = require('npm'); const request = require('request-promise').defaults({json: true}); @@ -68,7 +68,7 @@ Aliases: let config; try { - config = (await promisify(npm.load.bind(npm))({progress: false})).config; + config = (await pify(npm.load)({progress: false})).config; } catch (err) { console.log('Failed to load npm config.', err); process.exitCode = 1; diff --git a/src/lib/npm.js b/src/lib/npm.js index 1044395..01a3efb 100644 --- a/src/lib/npm.js +++ b/src/lib/npm.js @@ -1,6 +1,6 @@ const url = require('url'); const _ = require('lodash'); -const {promisifyAll} = require('bluebird'); +const pify = require('pify'); const inquirer = require('inquirer'); const npm = require('npm'); const RegClient = require('npm-registry-client'); @@ -8,7 +8,7 @@ const validator = require('validator'); const log = require('npmlog'); const passwordStorage = require('./password-storage')('npm'); -const client = promisifyAll(new RegClient({log})); +const client = new RegClient({log}); const DEFAULT_REGISTRY = 'https://registry.npmjs.org/'; async function getNpmToken({npm, options}) { @@ -22,32 +22,36 @@ async function getNpmToken({npm, options}) { }; const uri = url.resolve(npm.registry, '-/user/org.couchdb.user:' + encodeURIComponent(npm.username)); + let token; - const {err, token} = await new Promise(resolve => { - client.request(uri, {method: 'PUT', body}, async (err, parsed, raw, response) => { - if (err && err.code === 'E401' && response.headers['www-authenticate'] === 'OTP') { - await askForOTP(uri, body, npm); - resolve({token: npm.token}); - } else if (err && err.code === 'E409') { - // Some registries (Sinopia) return 409 for existing users, retry using authenticated call - return client - .requestAsync(uri, { - authed: true, - method: 'PUT', - auth: {username: npm.username, password: npm.password}, - body, - }) - .then(res => resolve(res)) - .catch(err => resolve({err})); - } else if (err) { - resolve({err}); - } else { - resolve(parsed); - } + try { + [{token}] = await pify(client.request.bind(client), {multiArgs: true})(uri, { + method: 'PUT', + body, }); - }); + } catch (err) { + const [error, , , response] = err; + + if (error.code === 'E401' && response.headers['www-authenticate'] === 'OTP') { + await askForOTP(uri, body, npm); + ({token} = npm); + } else if (error.code === 'E409') { + // Some registries (Sinopia) return 409 for existing users, retry using authenticated call + try { + ({token} = await pify(client.request.bind(client))(uri, { + authed: true, + method: 'PUT', + auth: {username: npm.username, password: npm.password}, + body, + })); + } catch (err) { + log.verbose(`Error: ${err}`); + } + } else { + log.verbose(`Error: ${error}`); + } + } - if (err) log.verbose(`Error: ${err}`); if (!token) throw new Error(`Could not login to npm.`); if (options.keychain) { @@ -71,16 +75,16 @@ async function validateToken(otp, uri, body, npm) { return false; } - return new Promise(resolve => { - client.request(uri, {method: 'PUT', auth: {otp}, body}, (err, parsed) => { - if (err || !parsed || !parsed.ok) { - resolve('Invalid authentication code'); - } else { - npm.token = parsed.token; - resolve(true); - } - }); - }); + try { + const response = await pify(client.request.bind(client))(uri, {method: 'PUT', auth: {otp}, body}); + if (response && response.ok) { + npm.token = response.token; + return true; + } + } catch (err) { + // Invalid 2FA token + } + return 'Invalid authentication code'; } function getRegistry(pkg, conf) { diff --git a/src/lib/travis.js b/src/lib/travis.js index ee19acb..e2eee5b 100644 --- a/src/lib/travis.js +++ b/src/lib/travis.js @@ -2,7 +2,7 @@ const {readFileSync, writeFileSync, accessSync} = require('fs'); const {join} = require('path'); const _ = require('lodash'); -const {promisify} = require('bluebird'); +const pify = require('pify'); const pRetry = require('p-retry'); const home = require('user-home'); const inquirer = require('inquirer'); @@ -36,7 +36,7 @@ async function isSyncing(travis) { async function syncTravis(travis) { try { - await promisify(travis.users.sync.post.bind(travis))(); + await pify(travis.users.sync.post)(); } catch (err) { if (err.message !== 'Sync already in progress. Try again later.') throw err; } @@ -45,15 +45,13 @@ async function syncTravis(travis) { } async function setEnvVar(travis, name, value) { - const tagent = travis.agent; - const response = await promisify(tagent.request.bind(tagent))( - 'GET', - `/settings/env_vars?repository_id=${travis.repoid}` - ); + const request = pify(travis.agent.request.bind(travis.agent)); + + const response = await request('GET', `/settings/env_vars?repository_id=${travis.repoid}`); let envid = _.get(_.find(response.env_vars, ['name', name]), 'id'); envid = envid ? `/${envid}` : ''; - await await promisify(tagent.request.bind(tagent))( + await request( envid ? 'PATCH' : 'POST', `/settings/env_vars${envid}?repository_id=${travis.repoid}`, {env_var: {name, value, public: false}} // eslint-disable-line camelcase @@ -94,14 +92,11 @@ async function setUpTravis(pkg, info) { log.info('Syncing repositories...'); await syncTravis(travis); - travis.repoid = _.get( - await promisify(travis.repos(info.ghrepo.slug[0], info.ghrepo.slug[1]).get.bind(travis))(), - 'repo.id' - ); + travis.repoid = _.get(await pify(travis.repos(info.ghrepo.slug[0], info.ghrepo.slug[1]).get)(), 'repo.id'); if (!travis.repoid) throw new Error('Could not get repo id'); - const {result} = await promisify(travis.hooks(travis.repoid).put.bind(travis))({ + const {result} = await pify(travis.hooks(travis.repoid).put)({ hook: {active: true}, }); if (!result) throw new Error('Could not enable hook on Travis CI'); @@ -155,8 +150,11 @@ module.exports = async function(endpoint, pkg, info) { info.travis = travis; travis.agent._endpoint = endpoint; - if (token) travis.agent.setAccessToken(token); - else await promisify(travis.authenticate.bind(travis))({github_token: info.github.token}); // eslint-disable-line camelcase + if (token) { + travis.agent.setAccessToken(token); + } else { + await pify(travis.authenticate)({github_token: info.github.token}); // eslint-disable-line camelcase + } await setUpTravis(pkg, info); };