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
Provenance
- Commit
8df692e- Tree
8363aa3- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
d7f9cd4
12 files changed+90 added−37 removed
modified:tests/args.variadic.test.js+2 added-2 removed
69 unmodified lines707172737474757677783 unmodified lines828384858686878889904 unmodified lines69 unmodified lines
test('when program variadic argument not last then error', () => { const program = new commander.Command(); program ._exitOverride() .exitOverride() .arguments('<variadicArg...> [optionalArg]') .action(jest.fn);
expect(() => {3 unmodified lines
test('when command variadic argument not last then error', () => { const program = new commander.Command(); program ._exitOverride() .exitOverride() .command('sub <variadicArg...> [optionalArg]') .action(jest.fn);
expect(() => {4 unmodified linesmodified:tests/command.allowUnknownOptions.test.js+4 added-4 removed
19 unmodified lines202122232424252627282 unmodified lines313233343535363738393 unmodified lines434445464747484950514 unmodified lines565758596060616263646 unmodified lines19 unmodified lines
test('when specify unknown program option then error', () => { const program = new commander.Command(); program ._exitOverride() .exitOverride() .option('-p, --pepper', 'add pepper');
expect(() => { program.parse(['node', 'test', '-m']);2 unmodified lines
test('when specify unknown program option and allowUnknownOption then no error', () => { const program = new commander.Command(); program ._exitOverride() .exitOverride() .allowUnknownOption() .option('-p, --pepper', 'add pepper');
expect(() => {3 unmodified lines
test('when specify unknown command option then error', () => { const program = new commander.Command(); program ._exitOverride() .exitOverride() .command('sub') .option('-p, --pepper', 'add pepper') .action(() => { });
4 unmodified lines
test('when specify unknown command option and allowUnknownOption then no error', () => { const program = new commander.Command(); program ._exitOverride() .exitOverride() .command('sub') .allowUnknownOption() .option('-p, --pepper', 'add pepper') .action(() => { });6 unmodified linesmodified:tests/command.executableSubcommand.test.js+1 added-1 removed
6 unmodified lines789101111121314152 unmodified lines6 unmodified lines // Optional. Suppress normal output to keep test output clean. const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { }); const program = new commander.Command(); program ._exitOverride((err) => { throw err; }) .exitOverride((err) => { throw err; }) .command('install', 'install description'); expect(() => { program.parse(['node', 'test']); }).toThrow('(outputHelp)');2 unmodified linesmodified:tests/command.exitOverride.test.js+10 added-10 removed
34 unmodified lines35 36 test('when specify unknown program option then throw CommanderError', () => {37 const program = new commander.Command();38 program39- ._exitOverride();39+ .exitOverride();40 41 let caughtErr;42 try {43 program.parse(['node', 'test', '-m']);9 unmodified lines53 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 });60 61 let caughtErr;9 unmodified lines71 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');77 78 let caughtErr;79 try {8 unmodified lines88 89 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(() => { });95 96 let caughtErr;9 unmodified lines106 107 test('when specify --help then throw CommanderError', () => {108 const program = new commander.Command();109 program110- ._exitOverride();110+ .exitOverride();111 112 let caughtErr;113 try {114 program.parse(['node', 'test', '--help']);7 unmodified lines122 123 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');128 129 let caughtErr;130 try {10 unmodified lines141 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);147 148 let caughtErr;149 try {9 unmodified lines159 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);166 167 let caughtErr;10 unmodified lines178 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 lines201 });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');207 208 program.parse(['node', pm, 'does-not-exist']);209 });1 unmodified linemodified:tests/command.help.test.js+3 added-3 removed
38 unmodified lines39 // 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 lines51 // 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 lines64 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 linesmodified:tests/command.helpOption.test.js+1 added-1 removed
3 unmodified lines4 // 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 linesmodified:tests/openIssues.test.js.skip+3 added-3 removed
5 unmodified lines6 // 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 });15 16 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 lines48 // 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>');55 56 expect(() => {13 unmodified linesmodified:tests/options.version.test.js+6 added-6 removed
1 const commander = require('../');2 3-// 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).4 5 describe('.version', () => {6 // Optional. Suppress normal output to keep test output clean.7 let writeSpy;33 unmodified lines41 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);47 48 expect(() => {49 program.parse(['node', 'test', '-V']);6 unmodified lines56 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);62 63 expect(() => {64 program.parse(['node', 'test', '--version']);15 unmodified lines80 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');86 87 expect(() => {88 program.parse(['node', 'test', '-r']);3 unmodified lines92 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');98 99 expect(() => {100 program.parse(['node', 'test', '--revision']);30 unmodified lines131 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 linesmodified:typings/commander-tests.ts+19 added
4 unmodified lines5 }6 7 const commandInstance = new program.Command('-f');8 const optionsInstance = new program.Option('-f');9+const errorInstance = new program.CommanderError(1, 'code', 'message');10 11 const name = program.name();12 13 program85 unmodified lines99 program100 .command("name1", "description")101 .command("name2", "description", { isDefault:true })102 103+program104+ .exitOverride();105+106+program.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+});112+113+program.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+});120+121 program.parse(process.argv);122 123 console.log('stuff');modified:typings/index.d.ts+19 added-4 removed
5 unmodified lines6 ///<reference types="node" />7 8 declare namespace local {9 10+ class CommanderError extends Error {11+ code: string;12+ exitCode: number;13+ message: string;14+ nestedError?: string;15+16+ constructor(exitCode: number, code: string, message: string);17+ }18+19 class Option {20 flags: string;21 required: boolean;22 optional: boolean;11 unmodified lines34 constructor(flags: string, description?: string);35 }36 37 class Command extends NodeJS.EventEmitter {29- [key: string]: any;38+ [key: string]: any; // options as properties39 40 args: string[];41 42 /**63 unmodified lines106 */107 arguments(desc: string): Command;108 109 /**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;118 119 /**120+ * Register callback to use as replacement for calling process.exit.121+ */122+ exitOverride(callback?: (err: CommanderError) => never|void): Command;123+124+ /**125 * Register callback `fn` for the command.126 *127 * @example128 * program176 unmodified lines305 Command: typeof local.Command;306 Option: typeof local.Option;307 CommandOptions: CommandOptions;308 ParseOptionsResult: ParseOptionsResult;309+ CommanderError : typeof local.CommanderError;295- }310+ }311 312 }313 314 declare const commander: commander.CommanderStatic;1 unmodified linemodified:index.js+3 added-3 removed
253 unmodified lines254 return this;255 };256 257 /**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 */264 265-Command.prototype._exitOverride = function(fn) {265+Command.prototype.exitOverride = function(fn) {266 if (fn) {267 this._exitCallback = fn;268 } else {269 this._exitCallback = function(err) {1155 unmodified linesmodified:Readme.md+19 added
29 unmodified lines30 - [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 lines554 555 If 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,556 the inspector port is incremented by 1 for the spawned subcommand.557 558+### Override exit handling559+560+By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override561+this behaviour and optionally supply a callback. The default override throws a `CommanderError`.562+563+The 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 help564+is not affected by the override which is called after the display.565+566+``` js567+program.exitOverride();568+569+try {570+ program.parse(process.argv);571+} catch (err) {572+ // custom processing...573+}574+```575+576 ## Examples577 578 ```js579 const program = require('commander');52 unmodified lines