Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add publish command #182

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions actions.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const open = require('open');
const chalk = require('chalk');
const { fetch } = require('undici');
const { execSync } = require('child_process');

const {
exit,
readFile,
Expand All @@ -13,6 +15,7 @@ const {
isLowerCaseEqual,
isRegistryNotFound,
isInternalRegistry,
printError,
} = require('./helpers');

const { NRMRC, NPMRC, AUTH, EMAIL, ALWAYS_AUTH, REPOSITORY, REGISTRY, HOME } = require('./constants');
Expand Down Expand Up @@ -277,6 +280,34 @@ async function onTest(target) {
return messages;
}

async function onPublish(name) {
const npmrc = await readFile(NPMRC);
const currentRegistry = npmrc[REGISTRY];
const currentRepositry = npmrc[REPOSITORY];
let publishRepositry = currentRepositry;

if(name && !(await isRegistryNotFound(name))) {
const registries = await getRegistries();;
const customRegistry = registries?.[name];
const customRepositry = customRegistry?.[REPOSITORY] ?? customRegistry?.[REGISTRY];
if(customRepositry) {
publishRepositry = customRepositry;
}
}

try {
execSync(`npm config set registry ${publishRepositry}`);
printMessages([`Publishing to ${publishRepositry}...`]);
execSync(`npm publish`, { stdio: 'inherit' });
printSuccess('Package published successfully.');
} catch (error) {
printError(`Failed to publish package: ${error.message}`);
} finally {
execSync(`npm config set registry ${currentRegistry}`);
}
}


module.exports = {
onList,
onCurrent,
Expand All @@ -291,4 +322,5 @@ module.exports = {
onSetAttribute,
onTest,
onLogin,
onPublish,
};
5 changes: 5 additions & 0 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ program
.description('Show response time for specific or all registries')
.action(actions.onTest);

program
.command('publish [name]')
.description('Publish package to current registry if current registry is a custom registry. The field "repository" of current custom registry is required running this command. If you\'re not using custom registry, this command will run npm publish directly. If you want to publish to a specific registry, you can use the registry name to specify the registry.')
.action(actions.onPublish);

program
.parse(process.argv);

Expand Down
99 changes: 88 additions & 11 deletions tests/cli.test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const coffee = require('coffee');
const open = require('open');
const chalk = require('chalk');

const { onHome, onTest } = require('.././actions.js');
const { getRegistries, printSuccess, printMessages } = require('../helpers.js');
const { onHome, onTest, onPublish } = require('../actions.js');

const isWin = process.platform === 'win32';

Expand All @@ -19,12 +19,43 @@ jest.mock('undici', () => {
return new Promise(resolve => {
setTimeout(
() => resolve({ ok: !url.includes('error.com') }),
(Math.random() + 1)*1000,
(Math.random() + 1) * 1000,
);
});
})
}
});
jest.mock('child_process', () => {
const originalModule = jest.requireActual('child_process')

return {
...originalModule,
execSync: jest.fn((command, options) => {
if (command.includes('npm publish')) {
return jest.fn();
}

return originalModule.execSync(command, options);
})
};
});

jest.mock('../helpers', () => {
const originalModule = jest.requireActual('../helpers');
return {
...originalModule,
printMessages: jest.fn(
(message) => {
originalModule.printMessages(message);
}
),
printSuccess: jest.fn(
(message) => {
originalModule.printSuccess(message);
}
),
}
});

beforeAll(async () => {
const { stdout } = await coffee.spawn('nrm', ['-V'], { shell: isWin }).end();
Expand All @@ -34,7 +65,7 @@ beforeAll(async () => {

afterAll(async () => {
await coffee.spawn('npm', ['unlink', 'nrm', '-g'], { shell: isWin }).end();
if(__NRM_VERSION__ !== null) {
if (__NRM_VERSION__ !== null) {
await coffee.spawn('npm', [`install -g nrm@${__NRM_VERSION__}`], { shell: isWin }).end();
}
});
Expand Down Expand Up @@ -86,7 +117,7 @@ describe('nrm command which needs to add a custom registry', () => {
});

afterEach(async () => {
await coffee.spawn('nrm', ['del',`${__REGISTRY__}`], { shell: isWin })
await coffee.spawn('nrm', ['del', `${__REGISTRY__}`], { shell: isWin })
.expect('stdout', /has been deleted successfully/g)
.expect('code', 0)
.end();
Expand All @@ -97,7 +128,7 @@ describe('nrm command which needs to add a custom registry', () => {
__REGISTRY__ = newName;
const match = new RegExp(`The registry '${customName}' has been renamed to '${newName}'`, 'g');

await coffee.spawn('nrm', ['rename',`${customName}`, `${newName}`], { shell: isWin })
await coffee.spawn('nrm', ['rename', `${customName}`, `${newName}`], { shell: isWin })
.expect('stdout', match)
.expect('code', 0)
.end();
Expand All @@ -124,12 +155,12 @@ describe('nrm command which needs to add a custom registry', () => {
const scopeName = 'nrm';
const url = 'https://scope.example.org';

await coffee.spawn('nrm', ['set-scope',`${scopeName}`, `${url}`], { shell: isWin })
await coffee.spawn('nrm', ['set-scope', `${scopeName}`, `${url}`], { shell: isWin })
.expect('stdout', /success/g)
.expect('code', 0)
.end();

await coffee.spawn('nrm', ['del-scope',`${scopeName}`], { shell: isWin })
await coffee.spawn('nrm', ['del-scope', `${scopeName}`], { shell: isWin })
.expect('stdout', /success/g)
.expect('code', 0)
.end();
Expand All @@ -139,7 +170,7 @@ describe('nrm command which needs to add a custom registry', () => {
const repo = 'repo';
const match = new RegExp(`Set the repository of registry '${__REGISTRY__}' successfully`, 'g');

await coffee.spawn('nrm', ['set-hosted-repo',`${__REGISTRY__}`, `${repo}`], { shell: isWin })
await coffee.spawn('nrm', ['set-hosted-repo', `${__REGISTRY__}`, `${repo}`], { shell: isWin })
.expect('stdout', match)
.expect('code', 0)
.end();
Expand All @@ -149,15 +180,61 @@ describe('nrm command which needs to add a custom registry', () => {
const username = 'username';
const password = 'password';

await coffee.spawn('nrm', ['login',`${__REGISTRY__}`,'-u', `${username}`, '-p', `${password}`], { shell: isWin })
await coffee.spawn('nrm', ['login', `${__REGISTRY__}`, '-u', `${username}`, '-p', `${password}`], { shell: isWin })
.expect('stdout', /success/g)
.expect('code', 0)
.end();

await coffee.spawn('nrm', ['login',`${__REGISTRY__}`], { shell: isWin })
await coffee.spawn('nrm', ['login', `${__REGISTRY__}`], { shell: isWin })
.expect('stderr', /Authorization information in base64 format or username & password is required/g)
.end();
});


describe('nrm publish [name]', () => {
const matchSuccess = 'Package published successfully.';

beforeEach(async () => {
jest.clearAllMocks();
});

it('publish to registry if there is not repository', async () => {
const matchMessage = [`Publishing to ${url}...`];

await onPublish(__REGISTRY__);
expect(printMessages).toHaveBeenCalledWith(matchMessage);
expect(printSuccess).toHaveBeenCalledWith(matchSuccess);
});

describe('publish to repository if there is repository', () => {
const repo = 'repo';
const matchMessage = [`Publishing to ${repo}...`];

beforeEach(async () => {
const match = new RegExp(`Set the repository of registry '${__REGISTRY__}' successfully`, 'g');
await coffee.spawn('nrm', ['set-hosted-repo', `${__REGISTRY__}`, `${repo}`], { shell: isWin })
.expect('stdout', match)
.expect('code', 0)
.end();
})

it('publish without name', async () => {
await coffee.spawn('nrm', ['use', __REGISTRY__], { shell: isWin }).end();

await onPublish();
expect(printMessages).toHaveBeenCalledWith(matchMessage);
expect(printSuccess).toHaveBeenCalledWith(matchSuccess);
})

it('publish with name', async () => {
await coffee.spawn('nrm', ['use', 'cnpm'], { shell: isWin }).end();

await onPublish(__REGISTRY__);
expect(printMessages).toHaveBeenCalledWith(matchMessage);
expect(printSuccess).toHaveBeenCalledWith(matchSuccess);
})
});
})
});

it('nrm home <registry> [browser]', async () => {
Expand Down
Loading