From 3bd405a84cadbf1e4623bedf1d91152665e19de6 Mon Sep 17 00:00:00 2001 From: Fedor Indutny <238531+indutny@users.noreply.github.com> Date: Tue, 27 Dec 2022 13:38:31 -0800 Subject: [PATCH] Fix `npm.isCollaborator()` on npm v9 (#966) With v9.0.0 release [npm][] has changed the CLI commands for package access. While previously it was `npm access ls-collaborators` and the output was a JSON object, now it is `npm access list collaborators` and the output is plain text unless `--json` flag is provided. This commit adds support for npm v9.0.0 while keeping support for older npm versions. [npm]: https://github.com/npm/cli/commit/9c32c6c8d6fc5bdfd6af685731fe26920d7e5446 --- lib/plugin/npm/npm.js | 49 +++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/lib/plugin/npm/npm.js b/lib/plugin/npm/npm.js index c7c5d887..8b40fe21 100644 --- a/lib/plugin/npm/npm.js +++ b/lib/plugin/npm/npm.js @@ -132,34 +132,43 @@ class npm extends Plugin { ); } - isCollaborator() { + async isCollaborator() { const registry = this.getRegistry(); const registryArg = registry ? ` --registry ${registry}` : ''; const name = this.getName(); const { username } = this.getContext(); if (username === undefined) return true; if (username === null) return false; - return this.exec(`npm access ls-collaborators ${name}${registryArg}`, { options }).then( - output => { - try { - const collaborators = JSON.parse(output); - const permissions = collaborators[username]; - return permissions && permissions.includes('write'); - } catch (err) { - this.debug(err); - return false; - } - }, - err => { + + try { + let npmVersion = await this.exec('npm --version', { options }); + + let accessCommand; + if (semver.gt(npmVersion, '9.0.0')) { + accessCommand = 'npm access list collaborators --json'; + } else { + accessCommand = 'npm access ls-collaborators'; + } + + const output = await this.exec(`${accessCommand} ${name}${registryArg}`, { options }); + + try { + const collaborators = JSON.parse(output); + const permissions = collaborators[username]; + return permissions && permissions.includes('write'); + } catch (err) { this.debug(err); - if (/code E400/.test(err)) { - this.log.warn('Ignoring response from unsupported `npm access` command.'); - } else { - this.log.warn(`Unable to verify if user ${username} is a collaborator for ${name}.`); - } - return true; + return false; } - ); + } catch (err) { + this.debug(err); + if (/code E400/.test(err)) { + this.log.warn('Ignoring response from unsupported `npm access` command.'); + } else { + this.log.warn(`Unable to verify if user ${username} is a collaborator for ${name}.`); + } + return true; + } } async getLatestRegistryVersion() {