Skip to content

Commit e096fe1

Browse files
committed
chore(cli-repl): add run-Node.js-script execution mode
1 parent a0adcf0 commit e096fe1

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

packages/cli-repl/src/run.spec.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import childProcess from 'child_process';
2+
import path from 'path';
3+
import { promisify } from 'util';
4+
import { expect } from 'chai';
5+
const execFile = promisify(childProcess.execFile);
6+
7+
describe('CLI entry point', () => {
8+
async function run(args: string[], env?: Record<string, string>): Promise<{ stdout: string, stderr: string }> {
9+
// Use ts-node to run the .ts files directly so nyc can pick them up for
10+
// coverage.
11+
return await execFile(
12+
process.execPath,
13+
['-r', 'ts-node/register', path.resolve(__dirname, 'run.ts'), ...args],
14+
{ env: { ...process.env, ...(env ?? {}) } });
15+
}
16+
17+
it('prints the version if --version is being used', async() => {
18+
const { stdout } = await run(['--version']);
19+
expect(stdout).to.match(/^\d+\.\d+\.\d+/);
20+
});
21+
22+
it('prints the help text if --help is being used', async() => {
23+
const { stdout } = await run(['--help']);
24+
expect(stdout).to.include('$ mongosh [options]');
25+
});
26+
27+
it('runs regular mongosh code otherwise', async() => {
28+
const { stdout } = await run(['--nodb', '--norc', '--eval', '55 + 89']);
29+
expect(stdout).to.include('144');
30+
});
31+
32+
it('runs Node.js scripts if MONGOSH_RUN_NODE_SCRIPT is passed', async() => {
33+
const { stdout } = await run([path.resolve(__dirname, '..', 'test', 'fixtures', 'nodescript.js')], { MONGOSH_RUN_NODE_SCRIPT: '1' });
34+
expect(stdout).to.include('works!');
35+
});
36+
});

packages/cli-repl/src/run.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,18 @@
11
import { CliRepl, parseCliArgs, mapCliToDriver, getStoragePaths, getMongocryptdPaths, runSmokeTests, USAGE } from './index';
22
import { generateUri } from '@mongosh/service-provider-server';
33
import { redactCredentials } from '@mongosh/history';
4+
import { runMain } from 'module';
45

56
(async() => {
7+
if (process.env.MONGOSH_RUN_NODE_SCRIPT) {
8+
if (process.execPath !== process.argv[1]) {
9+
// node /path/to/this/file script ... -> node script ...
10+
process.argv.splice(1, 1);
11+
}
12+
(runMain as any)(process.argv[1]);
13+
return;
14+
}
15+
616
let repl;
717
try {
818
const options = parseCliArgs(process.argv);
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
const assert = require('assert');
2+
assert.strictEqual(typeof print, 'undefined');
3+
console.log('works!');

0 commit comments

Comments
 (0)