Skip to content
Myr

Add override to allow throw instead of process.exit (#1040)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Add TypeScript for exitOverride * Switch from _exitOveride to exitOveride * Add exitOverride to README

authored by John Gee · committed by GitHub · parent d7f9cd4 · Browse files · 12 files+90 added−37 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+90 added−37 removed

  • tests:+30 added−30 removed
  • other:+60 added−7 removed

12 files+90 added−37 removed

modified:tests/args.variadic.test.js+2 added-2 removed
modified:tests/command.allowUnknownOptions.test.js+4 added-4 removed
modified:tests/command.executableSubcommand.test.js+1 added-1 removed
modified:tests/command.exitOverride.test.js+10 added-10 removed
34 unmodified lines
3536 test('when specify unknown program option then throw CommanderError', () => {37 const program = new commander.Command();38 program39 ._exitOverride();39 .exitOverride();4041 let caughtErr;42 try {43 program.parse(['node', 'test', '-m']);
9 unmodified lines
53 test('when supply custom handler then throw custom error', () => {54 const customError = new commander.CommanderError(123, 'custom-code', 'custom-message');55 const program = new commander.Command();56 program57 ._exitOverride((_err) => {57 .exitOverride((_err) => {58 throw customError;59 });6061 let caughtErr;
9 unmodified lines
71 test('when specify option without required value then throw CommanderError', () => {72 const optionFlags = '-p, --pepper <type>';73 const program = new commander.Command();74 program75 ._exitOverride()75 .exitOverride()76 .option(optionFlags, 'add pepper');7778 let caughtErr;79 try {
8 unmodified lines
8889 test('when specify command without required argument then throw CommanderError', () => {90 const program = new commander.Command();91 program92 ._exitOverride()92 .exitOverride()93 .command('compress <arg-name>')94 .action(() => { });9596 let caughtErr;
9 unmodified lines
106107 test('when specify --help then throw CommanderError', () => {108 const program = new commander.Command();109 program110 ._exitOverride();110 .exitOverride();111112 let caughtErr;113 try {114 program.parse(['node', 'test', '--help']);
7 unmodified lines
122123 test('when executable subcommand and no command specified then throw CommanderError', () => {124 const program = new commander.Command();125 program126 ._exitOverride()126 .exitOverride()127 .command('compress', 'compress description');128129 let caughtErr;130 try {
10 unmodified lines
141 test('when specify --version then throw CommanderError', () => {142 const myVersion = '1.2.3';143 const program = new commander.Command();144 program145 ._exitOverride()145 .exitOverride()146 .version(myVersion);147148 let caughtErr;149 try {
9 unmodified lines
159 test('when program variadic argument not last then throw CommanderError', () => {160 // Note: this error is notified during parse, although could have been detected at declaration.161 const program = new commander.Command();162 program163 ._exitOverride()163 .exitOverride()164 .arguments('<myVariadicArg...> [optionalArg]')165 .action(jest.fn);166167 let caughtErr;
10 unmodified lines
178 test('when executableSubcommand succeeds then call exitOverride', (done) => {179 const pm = path.join(__dirname, 'fixtures/pm');180 const program = new commander.Command();181 program182 ._exitOverride((err) => {182 .exitOverride((err) => {183 expectCommanderError(err, 0, 'commander.executeSubCommandAsync', '(close)');184 done();185 })186 .command('silent', 'description');
14 unmodified lines
201 });202 const pm = path.join(__dirname, 'fixtures/pm');203 const program = new commander.Command();204 program205 ._exitOverride(exitCallback)205 .exitOverride(exitCallback)206 .command('does-not-exist', 'fail');207208 program.parse(['node', pm, 'does-not-exist']);209 });
1 unmodified line
modified:tests/command.help.test.js+3 added-3 removed
38 unmodified lines
39 // Optional. Suppress normal output to keep test output clean.40 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });41 const program = new commander.Command();42 program43 ._exitOverride();43 .exitOverride();44 expect(() => {45 program.help();46 }).toThrow('(outputHelp)');47 writeSpy.mockClear();
3 unmodified lines
51 // Optional. Suppress normal output to keep test output clean.52 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });53 const program = new commander.Command();54 program55 ._exitOverride();55 .exitOverride();56 expect(() => {57 program.parse(['node', 'test', '--help']);58 }).toThrow('(outputHelp)');59 writeSpy.mockClear();
4 unmodified lines
64 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });65 const helpReplacement = 'reformatted help';66 const program = new commander.Command();67 program68 ._exitOverride();68 .exitOverride();69 expect(() => {70 program.help((helpInformation) => {71 return helpReplacement;72 });
24 unmodified lines
modified:tests/command.helpOption.test.js+1 added-1 removed
3 unmodified lines
4 // Optional. Suppress normal output to keep test output clean.5 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });6 const program = new commander.Command();7 program8 ._exitOverride()8 .exitOverride()9 .helpOption('--custom-help', 'custom help output');10 expect(() => {11 program.parse(['node', 'test', '--custom-help']);12 }).toThrow('(outputHelp)');
10 unmodified lines
modified:tests/openIssues.test.js.skip+3 added-3 removed
5 unmodified lines
6 // https://github.com/tj/commander.js/issues/10397 test('#1039: when unknown option then unknown option detected', () => {8 const program = new commander.Command();9 program10 ._exitOverride();10 .exitOverride();11 expect(() => {12 program.parse(['node', 'text', '--bug']);13 }).toThrow();14 });1516 test('#1039: when unknown option and multiple arguments then unknown option detected', () => {17 const program = new commander.Command();18 program19 ._exitOverride();19 .exitOverride();20 expect(() => {21 program.parse(['node', 'text', '--bug', '0', '1', '2', '3']);22 }).toThrow();23 });
24 unmodified lines
48 // https://github.com/tj/commander.js/issues/56149 test('#561: when specify argument and unknown option then error', () => {50 const program = new commander.Command();51 program52 ._exitOverride()52 .exitOverride()53 .option('-x, --x-flag', 'A flag')54 .arguments('<file>');5556 expect(() => {
13 unmodified lines
modified:tests/options.version.test.js+6 added-6 removed
1const commander = require('../');23// Test .version. Using _exitOverride to check behaviour (instead of mocking process.exit).3// Test .version. Using exitOverride to check behaviour (instead of mocking process.exit).45describe('.version', () => {6 // Optional. Suppress normal output to keep test output clean.7 let writeSpy;
33 unmodified lines
41 test('when specify default short flag then display version', () => {42 const myVersion = '1.2.3';43 const program = new commander.Command();44 program45 ._exitOverride()45 .exitOverride()46 .version(myVersion);4748 expect(() => {49 program.parse(['node', 'test', '-V']);
6 unmodified lines
56 test('when specify default long flag then display version', () => {57 const myVersion = '1.2.3';58 const program = new commander.Command();59 program60 ._exitOverride()60 .exitOverride()61 .version(myVersion);6263 expect(() => {64 program.parse(['node', 'test', '--version']);
15 unmodified lines
80 test('when specify custom short flag then display version', () => {81 const myVersion = '1.2.3';82 const program = new commander.Command();83 program84 ._exitOverride()84 .exitOverride()85 .version(myVersion, '-r, --revision');8687 expect(() => {88 program.parse(['node', 'test', '-r']);
3 unmodified lines
92 test('when specify custom long flag then display version', () => {93 const myVersion = '1.2.3';94 const program = new commander.Command();95 program96 ._exitOverride()96 .exitOverride()97 .version(myVersion, '-r, --revision');9899 expect(() => {100 program.parse(['node', 'test', '--revision']);
30 unmodified lines
131 test('when have .version+version and specify --version then version displayed', () => {132 const myVersion = '1.2.3';133 const program = new commander.Command();134 program135 ._exitOverride()135 .exitOverride()136 .version(myVersion)137 .command('version')138 .action(() => {});139
5 unmodified lines
modified:typings/commander-tests.ts+19 added
4 unmodified lines
5}67const commandInstance = new program.Command('-f');8const optionsInstance = new program.Option('-f');9const errorInstance = new program.CommanderError(1, 'code', 'message');1011const name = program.name();1213program
85 unmodified lines
99program100 .command("name1", "description")101 .command("name2", "description", { isDefault:true })102103program104 .exitOverride();105106program.exitOverride((err):never => {107 console.log(err.code);108 console.log(err.message);109 console.log(err.nestedError);110 return process.exit(err.exitCode);111});112113program.exitOverride((err):void => {114 if (err.code !== 'commander.executeSubCommandAsync') {115 throw err;116 } else {117 // Async callback from spawn events, not useful to throw.118 }119});120121program.parse(process.argv);122123console.log('stuff');
modified:typings/index.d.ts+19 added-4 removed
5 unmodified lines
6///<reference types="node" />78declare namespace local {910 class CommanderError extends Error {11 code: string;12 exitCode: number;13 message: string;14 nestedError?: string;1516 constructor(exitCode: number, code: string, message: string);17 }1819 class Option {20 flags: string;21 required: boolean;22 optional: boolean;
11 unmodified lines
34 constructor(flags: string, description?: string);35 }3637 class Command extends NodeJS.EventEmitter {29 [key: string]: any;38 [key: string]: any; // options as properties3940 args: string[];4142 /**
63 unmodified lines
106 */107 arguments(desc: string): Command;108109 /**101 * Parse expected `args`.110 * Parse expected `args`.111 *112 * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.113 *114 * @param {string[]} args115 * @returns {Command} for chaining116 */108 parseExpectedArgs(args: string[]): Command;117 parseExpectedArgs(args: string[]): Command;118119 /**120 * Register callback to use as replacement for calling process.exit.121 */122 exitOverride(callback?: (err: CommanderError) => never|void): Command;123124 /**125 * Register callback `fn` for the command.126 *127 * @example128 * program
176 unmodified lines
305 Command: typeof local.Command;306 Option: typeof local.Option;307 CommandOptions: CommandOptions;308 ParseOptionsResult: ParseOptionsResult;309 CommanderError : typeof local.CommanderError;295 }310 }311312}313314declare const commander: commander.CommanderStatic;
1 unmodified line
modified:index.js+3 added-3 removed
253 unmodified lines
254 return this;255};256257/**258 * Register callback `fn` to use as replacement for calling process.exit.258 * Register callback to use as replacement for calling process.exit.259 *260 * @param {Function} fn callback which will be passed a CommanderError260 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing261 * @return {Command} for chaining262 * @api public263 */264265Command.prototype._exitOverride = function(fn) {265Command.prototype.exitOverride = function(fn) {266 if (fn) {267 this._exitCallback = fn;268 } else {269 this._exitCallback = function(err) {
1155 unmodified lines
modified:Readme.md+19 added
29 unmodified lines
30 - [Bits and pieces](#bits-and-pieces)31 - [TypeScript](#typescript)32 - [Node options such as `--harmony`](#node-options-such-as---harmony)33 - [Node debugging](#node-debugging)34 - [Override exit handling](#override-exit-handling)35 - [Examples](#examples)36 - [License](#license)37 - [Support](#support)38
515 unmodified lines
554555If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) git-style executable (sub)commands using `node --inspect` et al,556the inspector port is incremented by 1 for the spawned subcommand.557558### Override exit handling559560By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override561this behaviour and optionally supply a callback. The default override throws a `CommanderError`.562563The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help564is not affected by the override which is called after the display.565566``` js567program.exitOverride();568569try {570 program.parse(process.argv);571} catch (err) {572 // custom processing...573}574```575576## Examples577578```js579const program = require('commander');
52 unmodified lines