Skip to content
Myr

Add support for groups of options and commands in the help (#2328)

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

authored by John Gee · committed by GitHub · parent 00af603 · Browse files · 9 files+556 added−47 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+556 added−47 removed

  • tests:+292 added−0 removed
  • other:+264 added−47 removed

9 files+556 added−47 removed

added:examples/help-groups.js+75 added
modified:lib/command.js+99 added-9 removed
78 unmodified lines
79 this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited80 /** @type {Command} */81 this._helpCommand = undefined; // lazy initialised, inherited82 this._helpConfiguration = {};83 /** @type {string | undefined} */84 this._helpGroupHeading = undefined; // soft initialised when added to parent85 /** @type {string | undefined} */86 this._defaultCommandGroup = undefined;87 /** @type {string | undefined} */88 this._defaultOptionGroup = undefined;89 }9091 /**92 * Copy settings that are useful to have in common across root command and subcommands.
316 unmodified lines
409410 helpCommand(enableOrNameAndArgs, description) {411 if (typeof enableOrNameAndArgs === 'boolean') {412 this._addImplicitHelpCommand = enableOrNameAndArgs;413 if (enableOrNameAndArgs && this._defaultCommandGroup) {414 // make the command to store the group415 this._initCommandGroup(this._getHelpCommand());416 }417 return this;418 }419410 enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';411 const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);420 const nameAndArgs = enableOrNameAndArgs ?? 'help [command]';421 const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);422 const helpDescription = description ?? 'display help for command';423424 const helpCommand = this.createCommand(helpName);425 helpCommand.helpOption(false);
1 unmodified line
427 if (helpDescription) helpCommand.description(helpDescription);428429 this._addImplicitHelpCommand = true;430 this._helpCommand = helpCommand;431 // init group unless lazy create432 if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);433434 return this;435 }436
13 unmodified lines
450 }451452 this._addImplicitHelpCommand = true;453 this._helpCommand = helpCommand;454 this._initCommandGroup(helpCommand);455 return this;456 }457458 /**
170 unmodified lines
629 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'630- already used by option '${matchingOption.flags}'`);631 }632633 this._initOptionGroup(option);634 this.options.push(option);635 }636637 /**
19 unmodified lines
657 `cannot add command '${newCmd}' as already have command '${existingCmd}'`,658 );659 }660661 this._initCommandGroup(command);662 this.commands.push(command);663 }664665 /**
1669 unmodified lines
2335 return this;2336 }23372338 /**2339 * Set/get the help group heading for this subcommand in parent command's help.2340 *2341 * @param {string} [heading]2342 * @return {Command | string}2343 */23442345 helpGroup(heading) {2346 if (heading === undefined) return this._helpGroupHeading ?? '';2347 this._helpGroupHeading = heading;2348 return this;2349 }23502351 /**2352 * Set/get the default help group heading for subcommands added to this command.2353 * (This does not override a group set directly on the subcommand using .helpGroup().)2354 *2355 * @example2356 * program.commandsGroup('Development Commands:);2357 * program.command('watch')...2358 * program.command('lint')...2359 * ...2360 *2361 * @param {string} [heading]2362 * @returns {Command | string}2363 */2364 commandsGroup(heading) {2365 if (heading === undefined) return this._defaultCommandGroup ?? '';2366 this._defaultCommandGroup = heading;2367 return this;2368 }23692370 /**2371 * Set/get the default help group heading for options added to this command.2372 * (This does not override a group set directly on the option using .helpGroup().)2373 *2374 * @example2375 * program2376 * .optionsGroup('Development Options:')2377 * .option('-d, --debug', 'output extra debugging')2378 * .option('-p, --profile', 'output profiling information')2379 *2380 * @param {string} [heading]2381 * @returns {Command | string}2382 */2383 optionsGroup(heading) {2384 if (heading === undefined) return this._defaultOptionGroup ?? '';2385 this._defaultOptionGroup = heading;2386 return this;2387 }23882389 /**2390 * @param {Option} option2391 * @private2392 */2393 _initOptionGroup(option) {2394 if (this._defaultOptionGroup && !option.helpGroupHeading)2395 option.helpGroup(this._defaultOptionGroup);2396 }23972398 /**2399 * @param {Command} cmd2400 * @private2401 */2402 _initCommandGroup(cmd) {2403 if (this._defaultCommandGroup && !cmd.helpGroup())2404 cmd.helpGroup(this._defaultCommandGroup);2405 }24062407 /**2408 * Set the name of the command from script filename, such as process.argv[1],2409 * or require.main.filename, or __filename.2410 *2411 * (Used internally and public although not documented in README.)
145 unmodified lines
2557 * @return {Command} `this` command for chaining2558 */25592560 helpOption(flags, description) {2477 // Support disabling built-in help option.2561 // Support enabling/disabling built-in help option.2562 if (typeof flags === 'boolean') {2479 // true is not an expected value. Do something sensible but no unit-test.2480 // istanbul ignore if2563 if (flags) {2482 this._helpOption = this._helpOption ?? undefined; // preserve existing option2564 if (this._helpOption === null) this._helpOption = undefined; // reenable2565 if (this._defaultOptionGroup) {2566 // make the option to store the group2567 this._initOptionGroup(this._getHelpOption());2568 }2569 } else {2570 this._helpOption = null; // disable2571 }2572 return this;2573 }25742575 // Customise flags and description.2490 flags = flags ?? '-h, --help';2491 description = description ?? 'display help for command';2492 this._helpOption = this.createOption(flags, description);2576 this._helpOption = this.createOption(2577 flags ?? '-h, --help',2578 description ?? 'display help for command',2579 );2580 // init group unless lazy create2581 if (flags || description) this._initOptionGroup(this._helpOption);25822583 return this;2584 }2585
20 unmodified lines
2606 * @return {Command} `this` command for chaining2607 */2608 addHelpOption(option) {2609 this._helpOption = option;2610 this._initOptionGroup(option);2611 return this;2612 }26132614 /**
164 unmodified lines
modified:lib/help.js+69 added-38 removed
391 unmodified lines
392 return argument.description;393 }394395 /**396 * @param {string} heading397 * @param {string[]} items398 * @param {Help} helper399 * @returns string[]400 */401 formatItemList(heading, items, helper) {402 if (items.length === 0) return [];403404 return [helper.styleTitle(heading), ...items, ''];405 }406407 /**408 *409 * @param {Command[] | Option[]} unsortedItems410 * @param {Command[] | Option[]} visibleItems411 * @param {Function} getGroup412 * @returns {Map<string, Command[] | Option[]>}413 */414 groupItems(unsortedItems, visibleItems, getGroup) {415 const result = new Map();416 // Add groups in order of appearance in unsortedItems.417 unsortedItems.forEach((item) => {418 const group = getGroup(item);419 if (!result.has(group)) result.set(group, []);420 });421 // Add items in order of appearance in visibleItems.422 visibleItems.forEach((item) => {423 const group = getGroup(item);424 if (!result.has(group)) {425 result.set(group, []);426 }427 result.get(group).push(item);428 });429 return result;430 }431432 /**433 * Generate the built-in help text.434 *435 * @param {Command} cmd436 * @param {Help} helper
32 unmodified lines
469 helper.styleArgumentTerm(helper.argumentTerm(argument)),470 helper.styleArgumentDescription(helper.argumentDescription(argument)),471 );472 });436 if (argumentList.length > 0) {437 output = output.concat([438 helper.styleTitle('Arguments:'),439 ...argumentList,440 '',441 ]);442 }473 output = output.concat(474 this.formatItemList('Arguments:', argumentList, helper),475 );476477 // Options478 const optionGroups = this.groupItems(479 cmd.options,480 helper.visibleOptions(cmd),481 (option) => option.helpGroupHeading ?? 'Options:',482 );483 optionGroups.forEach((options, group) => {445 const optionList = helper.visibleOptions(cmd).map((option) => {446 return callFormatItem(447 helper.styleOptionTerm(helper.optionTerm(option)),448 helper.styleOptionDescription(helper.optionDescription(option)),449 );484 const optionList = options.map((option) => {485 return callFormatItem(486 helper.styleOptionTerm(helper.optionTerm(option)),487 helper.styleOptionDescription(helper.optionDescription(option)),488 );489 });490 output = output.concat(this.formatItemList(group, optionList, helper));491 });451 if (optionList.length > 0) {452 output = output.concat([453 helper.styleTitle('Options:'),454 ...optionList,455 '',456 ]);457 }492493 if (helper.showGlobalOptions) {494 const globalOptionList = helper495 .visibleGlobalOptions(cmd)
2 unmodified lines
498 helper.styleOptionTerm(helper.optionTerm(option)),499 helper.styleOptionDescription(helper.optionDescription(option)),500 );501 });468 if (globalOptionList.length > 0) {469 output = output.concat([470 helper.styleTitle('Global Options:'),471 ...globalOptionList,472 '',473 ]);474 }502 output = output.concat(503 this.formatItemList('Global Options:', globalOptionList, helper),504 );505 }506507 // Commands508 const commandGroups = this.groupItems(509 cmd.commands,510 helper.visibleCommands(cmd),511 (sub) => sub.helpGroup() || 'Commands:',512 );513 commandGroups.forEach((commands, group) => {478 const commandList = helper.visibleCommands(cmd).map((cmd) => {479 return callFormatItem(480 helper.styleSubcommandTerm(helper.subcommandTerm(cmd)),481 helper.styleSubcommandDescription(helper.subcommandDescription(cmd)),482 );514 const commandList = commands.map((sub) => {515 return callFormatItem(516 helper.styleSubcommandTerm(helper.subcommandTerm(sub)),517 helper.styleSubcommandDescription(helper.subcommandDescription(sub)),518 );519 });520 output = output.concat(this.formatItemList(group, commandList, helper));521 });484 if (commandList.length > 0) {485 output = output.concat([486 helper.styleTitle('Commands:'),487 ...commandList,488 '',489 ]);490 }522523 return output.join('\n');524 }525
219 unmodified lines
modified:lib/option.js+12 added
31 unmodified lines
32 this.hidden = false;33 this.argChoices = undefined;34 this.conflictsWith = [];35 this.implied = undefined;36 this.helpGroupHeading = undefined; // soft initialised when option added to command37 }3839 /**40 * Set the default value, and optionally supply the description to be displayed in the help.
179 unmodified lines
220 return camelcase(this.name());221 }222223 /**224 * Set the help group heading.225 *226 * @param {string} heading227 * @return {Option}228 */229 helpGroup(heading) {230 this.helpGroupHeading = heading;231 return this;232 }233234 /**235 * Check if `arg` matches the short or long flag.236 *237 * @param {string} arg238 * @return {boolean}
141 unmodified lines
modified:tests/command.chain.test.js+18 added
255 unmodified lines
256 const program = new Command();257 const result = program.nameFromFilename('name');258 expect(result).toBe(program);259 });260261 test('when set .helpGroup(heading) then returns this', () => {262 const program = new Command();263 const result = program.helpGroup('Commands:');264 expect(result).toBe(program);265 });266267 test('when set .commandsGroup(heading) then returns this', () => {268 const program = new Command();269 const result = program.commandsGroup('Commands:');270 expect(result).toBe(program);271 });272273 test('when set .optionsGroup(heading) then returns this', () => {274 const program = new Command();275 const result = program.optionsGroup('Options:');276 expect(result).toBe(program);277 });278});
modified:tests/command.helpOption.test.js+16 added
added:tests/helpGroup.test.js+252 added
1const { Command, Option } = require('../');23// Similar tests for Option.helpGroup() and Command.helpGroup(),4// and for Command.optionsGroup() and Command.commandsGroup().56describe('Option.helpGroup', () => {7 test('when add one option with helpGroup then help contains group', () => {8 const program = new Command();9 program.addOption(new Option('--alpha').helpGroup('Greek:'));10 const helpInfo = program.helpInformation();11 expect(helpInfo).toMatch(/Greek:\n *--alpha/);12 });1314 test('when add two options with helpGroup then help contains group', () => {15 const program = new Command();16 program.addOption(new Option('--alpha').helpGroup('Greek:'));17 program.addOption(new Option('--beta').helpGroup('Greek:'));18 const helpInfo = program.helpInformation();19 expect(helpInfo).toMatch(/Greek:\n *--alpha\n *--beta/);20 });21});2223describe('Command.helpGroup', () => {24 test('when add one command with helpGroup then help contains group', () => {25 const program = new Command();26 program.command('alpha').helpGroup('Greek:');27 const helpInfo = program.helpInformation();28 expect(helpInfo).toMatch(/Greek:\n *alpha/);29 });3031 test('when add two commands with helpGroup then help contains group', () => {32 const program = new Command();33 program.command('alpha').helpGroup('Greek:');34 program.command('beta').helpGroup('Greek:');35 const helpInfo = program.helpInformation();36 expect(helpInfo).toMatch(/Greek:\n *alpha\n *beta/);37 });38});3940describe('.optionsGroup', () => {41 test('when add one option then help contains group', () => {42 const program = new Command();43 program.optionsGroup('Greek:');44 program.option('--alpha');45 const helpInfo = program.helpInformation();46 expect(helpInfo).toMatch(/Greek:\n *--alpha/);47 });4849 test('when add two options then help contains group with two options', () => {50 const program = new Command();51 program.optionsGroup('Greek:');52 program.option('--alpha');53 program.option('--beta');54 const helpInfo = program.helpInformation();55 expect(helpInfo).toMatch(/Greek:\n *--alpha\n *--beta/);56 });5758 test('when add options with different groups then help contains two groups', () => {59 const program = new Command();60 program.optionsGroup('Greek:');61 program.option('--alpha');62 program.optionsGroup('Latin:');63 program.option('--unus');64 const helpInfo = program.helpInformation();65 expect(helpInfo).toMatch(/Greek:\n *--alpha/);66 expect(helpInfo).toMatch(/Latin:\n *--unus/);67 });6869 test('when implicit help option then help option not affected', () => {70 const program = new Command();71 program.optionsGroup('Greek:');72 program.option('--alpha');73 const helpInfo = program.helpInformation();74 expect(helpInfo).toMatch(/Options:\n *-h, --help/);75 });7677 test('when option with helpGroup then helpGroup wins', () => {78 const program = new Command();79 program.optionsGroup('Greek:');80 program.addOption(new Option('--unus').helpGroup('Latin:'));81 const helpInfo = program.helpInformation();82 expect(helpInfo).toMatch(/Latin:\n *--unus/);83 });8485 test('when add no options with heading then heading does not appear', () => {86 const program = new Command();87 program.optionsGroup('Greek:');88 const helpInfo = program.helpInformation();89 expect(helpInfo).not.toMatch(/Greek/);90 });9192 test('when add no visible options with heading then heading does not appear', () => {93 const program = new Command();94 program.optionsGroup('Greek:');95 program.addOption(new Option('--alpha').hideHelp());96 const helpInfo = program.helpInformation();97 expect(helpInfo).not.toMatch(/Greek/);98 });99100 test('when .helpOption(flags) then help option in group', () => {101 const program = new Command();102 program.optionsGroup('Greek:');103 program.helpOption('--assist');104 const helpInfo = program.helpInformation();105 expect(helpInfo).toMatch(/Greek:\n *--assist/);106 });107108 test('when .helpOption(true) then help option in group', () => {109 const program = new Command();110 program.optionsGroup('Greek:');111 program.helpOption(true);112 const helpInfo = program.helpInformation();113 expect(helpInfo).toMatch(/Greek:\n *-h, --help/);114 });115116 test('when .version(str) then version option in group', () => {117 const program = new Command();118 program.optionsGroup('Greek:');119 program.version('1.2.3');120 const helpInfo = program.helpInformation();121 expect(helpInfo).toMatch(/Greek:\n *-V, --version/);122 });123124 test('when set sortOptions then options are sorted within groups', () => {125 const program = new Command();126 program.configureHelp({ sortOptions: true });127 program.optionsGroup('Latin:');128 program.option('--unus');129 program.option('--duo');130 program.optionsGroup('Greek:');131 program.option('--beta');132 program.option('--alpha');133 const helpInfo = program.helpInformation();134 expect(helpInfo).toMatch(/Latin:\n *--duo\n *--unus/);135 expect(helpInfo).toMatch(/Greek:\n *--alpha\n *--beta/);136 });137138 test('when set sortOptions then groups are in order added not sorted', () => {139 const program = new Command();140 program.configureHelp({ sortOptions: true });141 program.addOption(new Option('--bbb').helpGroup('BBB:'));142 program.addOption(new Option('--ccc').helpGroup('CCC:'));143 program.addOption(new Option('--aaa').helpGroup('AAA:'));144 const helpInfo = program.helpInformation();145 expect(helpInfo).toMatch(146 /BBB:\n *--bbb.*\n\nCCC:\n *--ccc.*\n\nAAA:\n *--aaa/,147 );148 });149});150151describe('.commandsGroup', () => {152 test('when add one command then help contains group', () => {153 const program = new Command();154 program.commandsGroup('Greek:');155 program.command('alpha');156 const helpInfo = program.helpInformation();157 expect(helpInfo).toMatch(/Greek:\n *alpha/);158 });159160 test('when add two commands then help contains group with two commands', () => {161 const program = new Command();162 program.commandsGroup('Greek:');163 program.command('alpha');164 program.command('beta');165 const helpInfo = program.helpInformation();166 expect(helpInfo).toMatch(/Greek:\n *alpha\n *beta/);167 });168169 test('when add commands with different groups then help contains two groups', () => {170 const program = new Command();171 program.commandsGroup('Greek:');172 program.command('alpha');173 program.commandsGroup('Latin:');174 program.command('unus');175 const helpInfo = program.helpInformation();176 expect(helpInfo).toMatch(/Greek:\n *alpha/);177 expect(helpInfo).toMatch(/Latin:\n *unus/);178 });179180 test('when implicit help command then help command not affected', () => {181 const program = new Command();182 program.commandsGroup('Greek:');183 program.command('alpha');184 const helpInfo = program.helpInformation();185 expect(helpInfo).toMatch(/Commands:\n *help/);186 });187188 test('when command with custom helpGroup then helpGroup wins', () => {189 const program = new Command();190 program.commandsGroup('Greek:');191 program.command('unus').helpGroup('Latin:');192 const helpInfo = program.helpInformation();193 expect(helpInfo).toMatch(/Latin:\n *unus/);194 });195196 test('when add no commands with heading then heading does not appear', () => {197 const program = new Command();198 program.commandsGroup('Greek:');199 const helpInfo = program.helpInformation();200 expect(helpInfo).not.toMatch(/Greek/);201 });202203 test('when add no visible command with heading then heading does not appear', () => {204 const program = new Command();205 program.commandsGroup('Greek:');206 program.command('alpha', { hidden: true });207 const helpInfo = program.helpInformation();208 expect(helpInfo).not.toMatch(/Greek/);209 });210211 test('when .helpCommand(name) then help command in group', () => {212 const program = new Command();213 program.command('foo');214 program.commandsGroup('Greek:');215 program.helpCommand('assist');216 const helpInfo = program.helpInformation();217 expect(helpInfo).toMatch(/Greek:\n *assist/);218 });219220 test('when .helpCommand(true) then help command in group', () => {221 const program = new Command();222 program.command('foo');223 program.commandsGroup('Greek:');224 program.helpCommand(true);225 const helpInfo = program.helpInformation();226 expect(helpInfo).toMatch(/Greek:\n *help/);227 });228229 test('when set sortCommands then commands are sorted within groups', () => {230 const program = new Command();231 program.configureHelp({ sortSubcommands: true });232 program.commandsGroup('Latin:');233 program.command('unus');234 program.command('duo');235 program.commandsGroup('Greek:');236 program.command('beta');237 program.command('alpha');238 const helpInfo = program.helpInformation();239 expect(helpInfo).toMatch(/Latin:\n *duo\n *unus/);240 expect(helpInfo).toMatch(/Greek:\n *alpha\n *beta/);241 });242243 test('when set sortOptions then groups are in order added not sorted', () => {244 const program = new Command();245 program.configureHelp({ sortSubcommands: true });246 program.command('bbb').helpGroup('BBB:');247 program.command('ccc').helpGroup('CCC:');248 program.command('aaa').helpGroup('AAA:');249 const helpInfo = program.helpInformation();250 expect(helpInfo).toMatch(/BBB:\n *bbb.*\n\nCCC:\n *ccc.*\n\nAAA:\n *aaa/);251 });252});
modified:tests/option.chain.test.js+6 added
40 unmodified lines
41 const option = new Option('-e,--example <value>');42 const result = option.conflicts(['a']);43 expect(result).toBe(option);44 });4546 test('when call .helpGroup(heading) then returns this', () => {47 const option = new Option('-e,--example <value>');48 const result = option.helpGroup('Options:');49 expect(result).toBe(option);50 });51});
modified:Readme.md+9 added
36 unmodified lines
37 - [.usage](#usage)38 - [.description and .summary](#description-and-summary)39 - [.helpOption(flags, description)](#helpoptionflags-description)40 - [.helpCommand()](#helpcommand)41 - [Help Groups](#help-groups)42 - [More configuration](#more-configuration-2)43 - [Custom event listeners](#custom-event-listeners)44 - [Bits and pieces](#bits-and-pieces)45 - [.parse() and .parseAsync()](#parse-and-parseasync)
881 unmodified lines
927```928929(Or use `.addHelpCommand()` to add a command you construct yourself.)930931### Help Groups932933The help by default lists options under the the heading `Options:` and commands under `Commands:`. You can create your own groups934with different headings. The high-level way is to set the desired group heading while adding the options and commands,935using `.optionsGroup()` and `.commandsGroup()`. The low-level way is using `.helpGroup()` on an individual `Option` or `Command`936937Example file: [help-groups.js](./examples/help-groups.js)938939### More configuration940941The built-in help is formatted using the Help class.942You can configure the help by modifying data properties and methods using `.configureHelp()`, or by subclassing Help using `.createHelp()` .
217 unmodified lines