Skip to content

Commit

Permalink
Fix npm.isCollaborator() on npm v9 (#966)
Browse files Browse the repository at this point in the history
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]: npm/cli@9c32c6c
  • Loading branch information
indutny committed Dec 27, 2022
1 parent 2b484bf commit 3bd405a
Showing 1 changed file with 29 additions and 20 deletions.
49 changes: 29 additions & 20 deletions lib/plugin/npm/npm.js
Expand Up @@ -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() {
Expand Down

0 comments on commit 3bd405a

Please sign in to comment.