From e1966fcff33e95993a95bbaace4920077d7422fd Mon Sep 17 00:00:00 2001 From: John Gee Date: Tue, 21 Apr 2020 18:29:06 +1200 Subject: [PATCH] Omit the help flags from help that are masked by other options (#1247) --- index.js | 28 ++++++++++++++++++++++------ tests/command.help.test.js | 16 ++++++++++++++++ 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/index.js b/index.js index c36df5367..987b79f0d 100644 --- a/index.js +++ b/index.js @@ -1401,17 +1401,33 @@ class Command extends EventEmitter { optionHelp() { const width = this.padWidth(); - const columns = process.stdout.columns || 80; const descriptionWidth = columns - width - 4; + function padOptionDetails(flags, description) { + return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2); + }; - // Append the help information - return this.options.map((option) => { + // Explicit options (including version) + const help = this.options.map((option) => { const fullDesc = option.description + ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : ''); - return pad(option.flags, width) + ' ' + optionalWrap(fullDesc, descriptionWidth, width + 2); - }).concat([pad(this._helpFlags, width) + ' ' + optionalWrap(this._helpDescription, descriptionWidth, width + 2)]) - .join('\n'); + return padOptionDetails(option.flags, fullDesc); + }); + + // Implicit help + const showShortHelpFlag = this._helpShortFlag && !this._findOption(this._helpShortFlag); + const showLongHelpFlag = !this._findOption(this._helpLongFlag); + if (showShortHelpFlag || showLongHelpFlag) { + let helpFlags = this._helpFlags; + if (!showShortHelpFlag) { + helpFlags = this._helpLongFlag; + } else if (!showLongHelpFlag) { + helpFlags = this._helpShortFlag; + } + help.push(padOptionDetails(helpFlags, this._helpDescription)); + } + + return help.join('\n'); }; /** diff --git a/tests/command.help.test.js b/tests/command.help.test.js index f484254a7..58b146f07 100644 --- a/tests/command.help.test.js +++ b/tests/command.help.test.js @@ -114,3 +114,19 @@ test('when addCommand with hidden:true then not displayed in helpInformation', ( const helpInformation = program.helpInformation(); expect(helpInformation).not.toMatch('secret'); }); + +test('when help short flag masked then not displayed in helpInformation', () => { + const program = new commander.Command(); + program + .option('-h, --host', 'select host'); + const helpInformation = program.helpInformation(); + expect(helpInformation).not.toMatch(/\W-h\W.*display help/); +}); + +test('when both help flags masked then not displayed in helpInformation', () => { + const program = new commander.Command(); + program + .option('-h, --help', 'custom'); + const helpInformation = program.helpInformation(); + expect(helpInformation).not.toMatch('display help'); +});