Skip to content

Commit

Permalink
fix: simplify promisification
Browse files Browse the repository at this point in the history
Use `pify` with `multiArgs` instead of `new Promise` with callback.
  • Loading branch information
pvdlg committed Apr 9, 2018
1 parent 790563d commit 9390ab7
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 56 deletions.
10 changes: 6 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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",
Expand All @@ -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",
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -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});
Expand Down Expand Up @@ -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;
Expand Down
74 changes: 39 additions & 35 deletions src/lib/npm.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
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');
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}) {
Expand All @@ -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) {
Expand All @@ -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) {
Expand Down
28 changes: 13 additions & 15 deletions src/lib/travis.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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;
}
Expand All @@ -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
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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);
};

0 comments on commit 9390ab7

Please sign in to comment.