From e8e15244c29c3122823b6382803dc53c9a0699e9 Mon Sep 17 00:00:00 2001 From: John Gee Date: Sat, 18 Apr 2020 17:43:46 +1200 Subject: [PATCH] Omit the help flags from help that are masked by other options --- 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 2ae841538..3a852981a 100644 --- a/index.js +++ b/index.js @@ -1381,17 +1381,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'); +});