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
Provenance
- Commit
082717f- Tree
7b7ec8b- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
5ddc41b
9 files changed+180 added−25 removed
modified:lib/command.js+22 added-7 removed
40 unmodified lines41 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;47 48 // see .configureOutput() for docs49 this._outputConfiguration = {50 writeOut: (str) => process.stdout.write(str),75 unmodified lines126 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;127 cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;128 cmd._allowExcessArguments = this._allowExcessArguments;129 cmd._enablePositionalOptions = this._enablePositionalOptions;130+ cmd._showHelpAfterError = this._showHelpAfterError;131 132 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 lines204 return this;205 }206 207 /**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+ }218+219+ /**220 * Add a prepared subcommand.221 *222 * See .command() for creating an attached subcommand which inherits settings from its parent.223 *1160 unmodified lines1384 * @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 }1396 1397 /**68 unmodified lines1466 * @api private1467 */1468 1469 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 };1473 1474 /**351 unmodified linesmodified:tests/command.chain.test.js+6 added
175 unmodified linesExpand all176177178179180181182183184185186175 unmodified linesExpand all const program = new Command(); const result = program.setOptionValue(); expect(result).toBe(program); });
test('when call .showHelpAfterError() then returns this', () => { const program = new Command(); const result = program.showHelpAfterError(); expect(result).toBe(program); });});modified:tests/command.exitOverride.test.js+1 added-1 removed
60 unmodified lines61 caughtErr = err;62 }63 64 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 });67 68 // Same error as above, but with custom handler.69 test('when supply custom handler then throw custom error', () => {288 unmodified linesmodified:tests/command.helpOption.test.js+1 added-1 removed
126 unmodified lines127 .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
1+const commander = require('../');2+3+describe('showHelpAfterError with message', () => {4+ const customHelpMessage = 'See --help';5+6+ function makeProgram() {7+ const writeMock = jest.fn();8+ const program = new commander.Command();9+ program10+ .exitOverride()11+ .showHelpAfterError(customHelpMessage)12+ .configureOutput({ writeErr: writeMock });13+14+ return { program, writeMock };15+ }16+17+ 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+ });29+30+ 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+ });42+43+ 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+ });55+56+ 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+ });67+68+ 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+ });81+82+ 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+ });94+95+ 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+});108+109+test('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 });116+117+ 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 lines77 caughtErr = err;78 }79 expect(caughtErr.code).toBe('commander.unknownCommand');80 });81-82- 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 lines388 /** Get configuration */389 configureOutput(): OutputConfiguration;390 391 /**392+ * Display the help or a custom message after an error occurs.393+ */394+ showHelpAfterError(displayHelp?: boolean | string): this;395+396+ /**397 * Register callback `fn` for the command.398 *399 * @example400 * program331 unmodified linesmodified:typings/index.test-d.ts+5 added
281 unmodified lines282 visibleCommands: () => [] // override method283 }));284 expectType<commander.HelpConfiguration>(program.configureHelp());285 286+// showHelpAfterError287+expectType<commander.Command>(program.showHelpAfterError());288+expectType<commander.Command>(program.showHelpAfterError(true));289+expectType<commander.Command>(program.showHelpAfterError('See --help'));290+291 // configureOutput292 expectType<commander.Command>(program.configureOutput({ }));293 expectType<commander.OutputConfiguration>(program.configureOutput());294 101 unmodified linesmodified:Readme.md+18 added
28 unmodified lines29 - [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 lines668 669 - error: a boolean for whether the help is being displayed due to a usage error670 - command: the Command which is displaying the help671 672+### Display help after errors673+674+The default behaviour for usage errors is to just display a short error message. 675+You can change the behaviour to show the full help or a custom help message after an error.676+677+```js678+program.showHelpAfterError();679+// or680+program.showHelpAfterError('(add --help for additional information)');681+```682+683+```sh684+$ pizza --unknown685+error: unknown option '--unknown'686+(add --help for additional information)687+```688+689 ### Display help from code690 691 `.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