Skip to content
Myr

Add showHelpAfterError (#1534)

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

* First cut at displayHelpWithError * Rename method * Rename * Add typings * Simplify unknownCommand message to match others * Add chain test * Add JSDoc typing for TypeScript --checkJS * Inherit behaviour to subcommands * Add tests * Add README * Tweak wording * Add test for invalid argument showing help

authored by John Gee · committed by GitHub · parent 5ddc41b · Browse files · 9 files+180 added−25 removed
This commit

State

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

Diff stats

9 files+180 added−25 removed

  • tests:+130 added−18 removed
  • other:+50 added−7 removed

9 files+180 added−25 removed

modified:lib/command.js+22 added-7 removed
40 unmodified lines
41 this._argsDescription = undefined; // legacy42 this._enablePositionalOptions = false;43 this._passThroughOptions = false;44 this._lifeCycleHooks = {}; // a hash of arrays45 /** @type {boolean | string} */46 this._showHelpAfterError = false;4748 // see .configureOutput() for docs49 this._outputConfiguration = {50 writeOut: (str) => process.stdout.write(str),
75 unmodified lines
126 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;127 cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;128 cmd._allowExcessArguments = this._allowExcessArguments;129 cmd._enablePositionalOptions = this._enablePositionalOptions;130 cmd._showHelpAfterError = this._showHelpAfterError;131132 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor133 if (args) cmd.arguments(args);134 this.commands.push(cmd);
69 unmodified lines
204 return this;205 }206207 /**208 * Display the help or a custom message after an error occurs.209 *210 * @param {boolean|string} [displayHelp]211 * @return {Command} `this` command for chaining212 */213 showHelpAfterError(displayHelp = true) {214 if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;215 this._showHelpAfterError = displayHelp;216 return this;217 }218219 /**220 * Add a prepared subcommand.221 *222 * See .command() for creating an attached subcommand which inherits settings from its parent.223 *
1160 unmodified lines
1384 * @api private1385 */1386 _displayError(exitCode, code, message) {1387 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);1388 if (typeof this._showHelpAfterError === 'string') {1389 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1390 } else if (this._showHelpAfterError) {1391 this._outputConfiguration.writeErr('\n');1392 this.outputHelp({ error: true });1393 }1394 this._exit(exitCode, code, message);1395 }13961397 /**
68 unmodified lines
1466 * @api private1467 */14681469 unknownCommand() {1449 const partCommands = [this.name()];1450 for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {1451 partCommands.unshift(parentCmd.name());1452 }1453 const fullCommand = partCommands.join(' ');1454 const message = `error: unknown command '${this.args[0]}'.` +1470 const message = `error: unknown command '${this.args[0]}'`;1455 (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : '');1471 this._displayError(1, 'commander.unknownCommand', message);1472 };14731474 /**
351 unmodified lines
modified:tests/command.chain.test.js+6 added
modified:tests/command.exitOverride.test.js+1 added-1 removed
60 unmodified lines
61 caughtErr = err;62 }6364 expect(stderrSpy).toHaveBeenCalled();65 expectCommanderError(caughtErr, 1, 'commander.unknownCommand', "error: unknown command 'oops'. See 'prog --help'.");65 expectCommanderError(caughtErr, 1, 'commander.unknownCommand', "error: unknown command 'oops'");66 });6768 // Same error as above, but with custom handler.69 test('when supply custom handler then throw custom error', () => {
288 unmodified lines
modified:tests/command.helpOption.test.js+1 added-1 removed
126 unmodified lines
127 .helpOption(false)128 .command('foo');129 expect(() => {130 program.parse(['UNKNOWN'], { from: 'user' });131 }).toThrow("error: unknown command 'UNKNOWN'.");131 }).toThrow("error: unknown command 'UNKNOWN'");132 });133});
added:tests/command.showHelpAfterError.test.js+122 added
1const commander = require('../');23describe('showHelpAfterError with message', () => {4 const customHelpMessage = 'See --help';56 function makeProgram() {7 const writeMock = jest.fn();8 const program = new commander.Command();9 program10 .exitOverride()11 .showHelpAfterError(customHelpMessage)12 .configureOutput({ writeErr: writeMock });1314 return { program, writeMock };15 }1617 test('when missing command-argument then shows help', () => {18 const { program, writeMock } = makeProgram();19 program.argument('<file>');20 let caughtErr;21 try {22 program.parse([], { from: 'user' });23 } catch (err) {24 caughtErr = err;25 }26 expect(caughtErr.code).toBe('commander.missingArgument');27 expect(writeMock).toHaveBeenLastCalledWith(`${customHelpMessage}\n`);28 });2930 test('when missing option-argument then shows help', () => {31 const { program, writeMock } = makeProgram();32 program.option('--output <file>');33 let caughtErr;34 try {35 program.parse(['--output'], { from: 'user' });36 } catch (err) {37 caughtErr = err;38 }39 expect(caughtErr.code).toBe('commander.optionMissingArgument');40 expect(writeMock).toHaveBeenLastCalledWith(`${customHelpMessage}\n`);41 });4243 test('when missing mandatory option then shows help', () => {44 const { program, writeMock } = makeProgram();45 program.requiredOption('--password <cipher>');46 let caughtErr;47 try {48 program.parse([], { from: 'user' });49 } catch (err) {50 caughtErr = err;51 }52 expect(caughtErr.code).toBe('commander.missingMandatoryOptionValue');53 expect(writeMock).toHaveBeenLastCalledWith(`${customHelpMessage}\n`);54 });5556 test('when unknown option then shows help', () => {57 const { program, writeMock } = makeProgram();58 let caughtErr;59 try {60 program.parse(['--unknown-option'], { from: 'user' });61 } catch (err) {62 caughtErr = err;63 }64 expect(caughtErr.code).toBe('commander.unknownOption');65 expect(writeMock).toHaveBeenLastCalledWith(`${customHelpMessage}\n`);66 });6768 test('when too many command-arguments then shows help', () => {69 const { program, writeMock } = makeProgram();70 program71 .allowExcessArguments(false);72 let caughtErr;73 try {74 program.parse(['surprise'], { from: 'user' });75 } catch (err) {76 caughtErr = err;77 }78 expect(caughtErr.code).toBe('commander.excessArguments');79 expect(writeMock).toHaveBeenLastCalledWith(`${customHelpMessage}\n`);80 });8182 test('when unknown command then shows help', () => {83 const { program, writeMock } = makeProgram();84 program.command('sub1');85 let caughtErr;86 try {87 program.parse(['sub2'], { from: 'user' });88 } catch (err) {89 caughtErr = err;90 }91 expect(caughtErr.code).toBe('commander.unknownCommand');92 expect(writeMock).toHaveBeenLastCalledWith(`${customHelpMessage}\n`);93 });9495 test('when invalid option choice then shows help', () => {96 const { program, writeMock } = makeProgram();97 program.addOption(new commander.Option('--color').choices(['red', 'blue']));98 let caughtErr;99 try {100 program.parse(['--color', 'pink'], { from: 'user' });101 } catch (err) {102 caughtErr = err;103 }104 expect(caughtErr.code).toBe('commander.invalidArgument');105 expect(writeMock).toHaveBeenLastCalledWith(`${customHelpMessage}\n`);106 });107});108109test('when showHelpAfterError() and error and then shows full help', () => {110 const writeMock = jest.fn();111 const program = new commander.Command();112 program113 .exitOverride()114 .showHelpAfterError()115 .configureOutput({ writeErr: writeMock });116117 try {118 program.parse(['--unknown-option'], { from: 'user' });119 } catch (err) {120 }121 expect(writeMock).toHaveBeenLastCalledWith(program.helpInformation());122});
modified:tests/command.unknownCommand.test.js-16 removed
76 unmodified lines
77 caughtErr = err;78 }79 expect(caughtErr.code).toBe('commander.unknownCommand');80 });8182 test('when unknown subcommand then help suggestion includes command path', () => {83 const program = new commander.Command();84 program85 .exitOverride()86 .command('sub')87 .command('subsub');88 let caughtErr;89 try {90 program.parse('node test.js sub unknown'.split(' '));91 } catch (err) {92 caughtErr = err;93 }94 expect(caughtErr.code).toBe('commander.unknownCommand');95 expect(writeErrorSpy.mock.calls[0][0]).toMatch('test sub');96 });81});
modified:typings/index.d.ts+5 added
387 unmodified lines
388 /** Get configuration */389 configureOutput(): OutputConfiguration;390391 /**392 * Display the help or a custom message after an error occurs.393 */394 showHelpAfterError(displayHelp?: boolean | string): this;395396 /**397 * Register callback `fn` for the command.398 *399 * @example400 * program
331 unmodified lines
modified:typings/index.test-d.ts+5 added
281 unmodified lines
282 visibleCommands: () => [] // override method283}));284expectType<commander.HelpConfiguration>(program.configureHelp());285286// showHelpAfterError287expectType<commander.Command>(program.showHelpAfterError());288expectType<commander.Command>(program.showHelpAfterError(true));289expectType<commander.Command>(program.showHelpAfterError('See --help'));290291// configureOutput292expectType<commander.Command>(program.configureOutput({ }));293expectType<commander.OutputConfiguration>(program.configureOutput());294
101 unmodified lines
modified:Readme.md+18 added
28 unmodified lines
29 - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)30 - [Life cycle hooks](#life-cycle-hooks)31 - [Automated help](#automated-help)32 - [Custom help](#custom-help)33 - [Display help after errors](#display-help-after-errors)34 - [Display help from code](#display-help-from-code)35 - [.usage and .name](#usage-and-name)36 - [.helpOption(flags, description)](#helpoptionflags-description)37 - [.addHelpCommand()](#addhelpcommand)
630 unmodified lines
668669- error: a boolean for whether the help is being displayed due to a usage error670- command: the Command which is displaying the help671672### Display help after errors673674The default behaviour for usage errors is to just display a short error message. 675You can change the behaviour to show the full help or a custom help message after an error.676677```js678program.showHelpAfterError();679// or680program.showHelpAfterError('(add --help for additional information)');681```682683```sh684$ pizza --unknown685error: unknown option '--unknown'686(add --help for additional information)687```688689### Display help from code690691`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.692
312 unmodified lines