Skip to content
Myr

Allow disabling the built-in help option (#1325)

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

* Allow disabling the built-in help option * Suppress Options section of help if no options * Fix suppressed options * Leave [options] out of usage if no options * Expand usage tests

authored by John Gee · committed by GitHub · parent a71d592 · Browse files · 7 files+146 added−18 removed
This commit

State

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

Diff stats

7 files+146 added−18 removed

  • tests:+114 added−1 removed
  • other:+32 added−17 removed

7 files+146 added−18 removed

modified:tests/command.help.test.js+9 added
modified:tests/command.helpOption.test.js+52 added-1 removed
1const commander = require('../');23describe('helpOption', () => {4 let writeSpy;5 let consoleErrorSpy;67 beforeAll(() => {7 // Optional. Suppress normal output to keep test output clean.8 // Optional. Suppress expected output to keep test output clean.9 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });10 consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });11 });1213 afterEach(() => {14 writeSpy.mockClear();15 consoleErrorSpy.mockClear();16 });1718 afterAll(() => {19 writeSpy.mockRestore();20 consoleErrorSpy.mockRestore();21 });2223 test('when helpOption has custom flags then custom short flag invokes help', () => {24 const program = new commander.Command();
41 unmodified lines
66 .helpOption('-C,--custom-help', 'custom help output');67 const helpInformation = program.helpInformation();68 expect(helpInformation).toMatch(/-C,--custom-help +custom help output/);69 });7071 test('when helpOption(false) then helpInformation does not include --help', () => {72 const program = new commander.Command();73 program74 .helpOption(false);75 const helpInformation = program.helpInformation();76 expect(helpInformation).not.toMatch('--help');77 });7879 test('when helpOption(false) then --help is an unknown option', () => {80 const program = new commander.Command();81 program82 .exitOverride()83 .helpOption(false);84 let caughtErr;85 try {86 program.parse(['--help'], { from: 'user' });87 } catch (err) {88 caughtErr = err;89 }90 expect(caughtErr.code).toBe('commander.unknownOption');91 });9293 test('when helpOption(false) then -h is an unknown option', () => {94 const program = new commander.Command();95 program96 .exitOverride()97 .helpOption(false);98 let caughtErr;99 try {100 program.parse(['-h'], { from: 'user' });101 } catch (err) {102 caughtErr = err;103 }104 expect(caughtErr.code).toBe('commander.unknownOption');105 });106107 test('when helpOption(false) then unknown command error does not suggest --help', () => {108 const program = new commander.Command();109 program110 .exitOverride()111 .helpOption(false)112 .command('foo');113 expect(() => {114 program.parse(['UNKNOWN'], { from: 'user' });115 }).toThrow("error: unknown command 'UNKNOWN'.");116 });117});
modified:tests/command.usage.test.js+53 added
42 unmodified lines
43 const helpInformation = subCommand.helpInformation();4445 expect(helpInformation).toMatch(new RegExp(`^Usage: test info ${myUsage}`));46});4748test('when has option then [options] included in usage', () => {49 const program = new commander.Command();5051 program52 .option('--foo');5354 expect(program.usage()).toMatch('[options]');55});5657test('when no options then [options] not included in usage', () => {58 const program = new commander.Command();5960 program61 .helpOption(false);6263 expect(program.usage()).not.toMatch('[options]');64});6566test('when has command then [command] included in usage', () => {67 const program = new commander.Command();6869 program70 .command('foo');7172 expect(program.usage()).toMatch('[command]');73});7475test('when no commands then [command] not included in usage', () => {76 const program = new commander.Command();7778 expect(program.usage()).not.toMatch('[command]');79});8081test('when arguments then arguments included in usage', () => {82 const program = new commander.Command();8384 program85 .arguments('<file>');8687 expect(program.usage()).toMatch('<file>');88});8990test('when options and command and arguments then all three included in usage', () => {91 const program = new commander.Command();9293 program94 .arguments('<file>')95 .option('--alpha')96 .command('beta');9798 expect(program.usage()).toEqual('[options] [command] <file>');99});
modified:typings/commander-tests.ts+1 added
194 unmodified lines
195// helpOption196const helpOptionThis1: commander.Command = program.helpOption('-h,--help');197const helpOptionThis2: commander.Command = program.helpOption('-h,--help', 'custom description');198const helpOptionThis3: commander.Command = program.helpOption(undefined, 'custom description');199const helpOptionThis4: commander.Command = program.helpOption(false);200201// on202const onThis: commander.Command = program.on('--help', () => {203 // do nothing.
20 unmodified lines
modified:typings/index.d.ts+3 added-2 removed
333 unmodified lines
334 helpInformation(): string;335336 /**337 * You can pass in flags and a description to override the help338 * flags and help description for your command.338 * flags and help description for your command. Pass in false339 * to disable the built-in help option.340 */340 helpOption(flags?: string, description?: string): this;341 helpOption(flags?: string | boolean, description?: string): this;342343 /**344 * Output help information and exit.345 */
42 unmodified lines
modified:index.js+27 added-14 removed
127 unmodified lines
128 this._exitCallback = null;129 this._aliases = [];130131 this._hidden = false;132 this._hasHelpOption = true;133 this._helpFlags = '-h, --help';134 this._helpDescription = 'display help for command';135 this._helpShortFlag = '-h';136 this._helpLongFlag = '--help';
47 unmodified lines
184 }185 if (opts.isDefault) this._defaultCommandName = cmd._name;186187 cmd._hidden = !!(opts.noHelp || opts.hidden);188 cmd._hasHelpOption = this._hasHelpOption;189 cmd._helpFlags = this._helpFlags;190 cmd._helpDescription = this._helpDescription;191 cmd._helpShortFlag = this._helpShortFlag;192 cmd._helpLongFlag = this._helpLongFlag;
1044 unmodified lines
1237 for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {1238 partCommands.unshift(parentCmd.name());1239 }1240 const fullCommand = partCommands.join(' ');1239 const message = `error: unknown command '${this.args[0]}'. See '${fullCommand} ${this._helpLongFlag}'.`;1241 const message = `error: unknown command '${this.args[0]}'.` +1242 (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : '');1243 console.error(message);1244 this._exit(1, 'commander.unknownCommand', message);1245 };1246
100 unmodified lines
13471348 const args = this._args.map((arg) => {1349 return humanReadableArgName(arg);1350 });1348 return '[options]' +1349 (this.commands.length ? ' [command]' : '') +1350 (this._args.length ? ' ' + args.join(' ') : '');1351 return [].concat(1352 (this.options.length || this._hasHelpOption ? '[options]' : []),1353 (this.commands.length ? '[command]' : []),1354 (this._args.length ? args : [])1355 ).join(' ');1356 }13571358 this._usage = str;1359 return this;
134 unmodified lines
1494 return padOptionDetails(option.flags, fullDesc);1495 });14961497 // Implicit help1493 const showShortHelpFlag = this._helpShortFlag && !this._findOption(this._helpShortFlag);1494 const showLongHelpFlag = !this._findOption(this._helpLongFlag);1498 const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag);1499 const showLongHelpFlag = this._hasHelpOption && !this._findOption(this._helpLongFlag);1500 if (showShortHelpFlag || showLongHelpFlag) {1501 let helpFlags = this._helpFlags;1502 if (!showShortHelpFlag) {1503 helpFlags = this._helpLongFlag;
77 unmodified lines
1581 let cmds = [];1582 const commandHelp = this.commandHelp();1583 if (commandHelp) cmds = [commandHelp];15841585 let options = [];1586 if (this._hasHelpOption || this.options.length > 0) {1580 const options = [1581 'Options:',1582 '' + this.optionHelp().replace(/^/gm, ' '),1583 ''1584 ];1587 options = [1588 'Options:',1589 '' + this.optionHelp().replace(/^/gm, ' '),1590 ''1591 ];1592 }15931594 return usage1595 .concat(desc)1596 .concat(options)
25 unmodified lines
1622 };16231624 /**1625 * You can pass in flags and a description to override the help1618 * flags and help description for your command.1626 * flags and help description for your command. Pass in false to1627 * disable the built-in help option.1628 *1620 * @param {string} [flags]1629 * @param {string | boolean} [flags]1630 * @param {string} [description]1631 * @return {Command} `this` command for chaining1632 * @api public1633 */16341635 helpOption(flags, description) {1636 if (typeof flags === 'boolean') {1637 this._hasHelpOption = flags;1638 return this;1639 }1640 this._helpFlags = flags || this._helpFlags;1641 this._helpDescription = description || this._helpDescription;16421643 const helpFlags = _parseOptionFlags(this._helpFlags);
124 unmodified lines
1768 * @api private1769 */17701771function outputHelpIfRequested(cmd, args) {1759 const helpOption = args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);1772 const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);1773 if (helpOption) {1774 cmd.outputHelp();1775 // (Do not have all displayed text available so only passing placeholder.)1776 cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');
87 unmodified lines
modified:Readme.md+1 added-1 removed
557 unmodified lines
558from `--help` listeners.)559560### .helpOption(flags, description)561562Override the default help flags and description.562Override the default help flags and description. Pass false to disable the built-in help option.563564```js565program566 .helpOption('-e, --HELP', 'read more information');
210 unmodified lines