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
Provenance
- Commit
6b2e42c- Tree
242ded9- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
a71d592
7 files changed+146 added−18 removed
modified:tests/command.help.test.js+9 added
128 unmodified linesExpand all129130131132133134135136137138139140141128 unmodified linesExpand all .option('-h, --help', 'custom'); const helpInformation = program.helpInformation(); expect(helpInformation).not.toMatch('display help');});
test('when no options then Options not includes in helpInformation', () => { const program = new commander.Command(); // No custom options, no version option, no help option program .helpOption(false); const helpInformation = program.helpInformation(); expect(helpInformation).not.toMatch('Options');});modified:tests/command.helpOption.test.js+52 added-1 removed
1 const commander = require('../');2 3 describe('helpOption', () => {4 let writeSpy;5+ let consoleErrorSpy;6 7 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 });12 13 afterEach(() => {14 writeSpy.mockClear();15+ consoleErrorSpy.mockClear();16 });17 18 afterAll(() => {19 writeSpy.mockRestore();20+ consoleErrorSpy.mockRestore();21 });22 23 test('when helpOption has custom flags then custom short flag invokes help', () => {24 const program = new commander.Command();41 unmodified lines66 .helpOption('-C,--custom-help', 'custom help output');67 const helpInformation = program.helpInformation();68 expect(helpInformation).toMatch(/-C,--custom-help +custom help output/);69 });70+71+ 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+ });78+79+ 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+ });92+93+ 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+ });106+107+ 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 lines43 const helpInformation = subCommand.helpInformation();44 45 expect(helpInformation).toMatch(new RegExp(`^Usage: test info ${myUsage}`));46 });47+48+test('when has option then [options] included in usage', () => {49+ const program = new commander.Command();50+51+ program52+ .option('--foo');53+54+ expect(program.usage()).toMatch('[options]');55+});56+57+test('when no options then [options] not included in usage', () => {58+ const program = new commander.Command();59+60+ program61+ .helpOption(false);62+63+ expect(program.usage()).not.toMatch('[options]');64+});65+66+test('when has command then [command] included in usage', () => {67+ const program = new commander.Command();68+69+ program70+ .command('foo');71+72+ expect(program.usage()).toMatch('[command]');73+});74+75+test('when no commands then [command] not included in usage', () => {76+ const program = new commander.Command();77+78+ expect(program.usage()).not.toMatch('[command]');79+});80+81+test('when arguments then arguments included in usage', () => {82+ const program = new commander.Command();83+84+ program85+ .arguments('<file>');86+87+ expect(program.usage()).toMatch('<file>');88+});89+90+test('when options and command and arguments then all three included in usage', () => {91+ const program = new commander.Command();92+93+ program94+ .arguments('<file>')95+ .option('--alpha')96+ .command('beta');97+98+ expect(program.usage()).toEqual('[options] [command] <file>');99+});modified:typings/commander-tests.ts+1 added
194 unmodified lines195 // helpOption196 const helpOptionThis1: commander.Command = program.helpOption('-h,--help');197 const helpOptionThis2: commander.Command = program.helpOption('-h,--help', 'custom description');198 const helpOptionThis3: commander.Command = program.helpOption(undefined, 'custom description');199+const helpOptionThis4: commander.Command = program.helpOption(false);200 201 // on202 const onThis: commander.Command = program.on('--help', () => {203 // do nothing.20 unmodified linesmodified:typings/index.d.ts+3 added-2 removed
333 unmodified lines334 helpInformation(): string;335 336 /**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;342 343 /**344 * Output help information and exit.345 */42 unmodified linesmodified:index.js+27 added-14 removed
127 unmodified lines128 this._exitCallback = null;129 this._aliases = [];130 131 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 lines184 }185 if (opts.isDefault) this._defaultCommandName = cmd._name;186 187 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 lines1237 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 lines1347 1348 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 }1357 1358 this._usage = str;1359 return this;134 unmodified lines1494 return padOptionDetails(option.flags, fullDesc);1495 });1496 1497 // 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 lines1581 let cmds = [];1582 const commandHelp = this.commandHelp();1583 if (commandHelp) cmds = [commandHelp];1584 1585+ 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+ }1593 1594 return usage1595 .concat(desc)1596 .concat(options)25 unmodified lines1622 };1623 1624 /**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 */1634 1635 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;1642 1643 const helpFlags = _parseOptionFlags(this._helpFlags);124 unmodified lines1768 * @api private1769 */1770 1771 function 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 linesmodified:Readme.md+1 added-1 removed
557 unmodified lines558 from `--help` listeners.)559 560 ### .helpOption(flags, description)561 562-Override the default help flags and description.562+Override the default help flags and description. Pass false to disable the built-in help option.563 564 ```js565 program566 .helpOption('-e, --HELP', 'read more information');210 unmodified lines