Support showing global options in help (#1828)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add help configuration to show the global options.
authored by John Gee · committed by GitHub · parent 198c6e4 · Browse files · 11 files·+274 added−82 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+274 added−82 removed
- tests:+120 added−0 removed
- other:+154 added−82 removed
Provenance
- Commit
0ae5b2f- Tree
9c34ea2- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
198c6e4
11 files changed+274 added−82 removed
added:examples/global-options-added.js+51 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#!/usr/bin/env node
// This example shows a couple of ways to add a "global" option to all of the subcommands.// The first approach is to use a subclass and add the option as the subcommand is created.// The second approach is to loop over the subcommands after they have been created.//// The code in this example assumes there is just one level of subcommands.//// (A different pattern for a "global" option is to add it to the root command, rather// than to the subcommand. See global-options-nested.js.)
// const { Command } = require('commander'); // (normal include)const { Command } = require('../'); // include commander in git clone of commander repo
// Common options can be added when subcommands are created by using a custom subclass.// If the options are unsorted in the help, these will appear first.class MyRootCommand extends Command { createCommand(name) { const cmd = new Command(name); cmd.option('-v, --verbose', 'use verbose logging'); return cmd; }}
const program = new MyRootCommand();
program.command('print') .option('--a4', 'Use A4 sized paper') .action((options) => { console.log('print options: %O', options); });
program.command('serve') .option('-p, --port <number>', 'port number for server') .action((options) => { console.log('serve options: %O', options); });
// Common options can be added manually after setting up program and subcommands.// If the options are unsorted in the help, these will appear last.program.commands.forEach((cmd) => { cmd.option('-d, --debug');});
program.parse();
// Try the following:// node global-options-added.js --help// node global-options-added.js print --help// node global-options-added.js serve --help// node global-options-added.js serve --debug --verboseadded:examples/global-options-nested.js+32 added
1234567891011121314151617181920212223242526272829303132#!/usr/bin/env node
// This example shows global options on the program which affect all the subcommands.// See how to work with global options in the subcommand and display them in the help.//// (A different pattern for a "global" option is to add it to the subcommands, rather// than to the program. See global-options-added.js.)
// const { Command } = require('commander'); // (normal include)const { Command } = require('../'); // include commander in git clone of commander repo
const program = new Command();
program .configureHelp({ showGlobalOptions: true }) .option('-g, --global');
program .command('sub') .option('-l, --local') .action((options, cmd) => { console.log({ opts: cmd.opts(), optsWithGlobals: cmd.optsWithGlobals() }); });
program.parse();
// Try the following:// node global-options-nested.js --global sub --local// node global-options-nested.js sub --helpdeleted:examples/global-options.js-51 removed
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#!/usr/bin/env node
// This example shows a couple of ways to add a "global" option to all of the subcommands.// The first approach is to use a subclass and add the option as the subcommand is created.// The second approach is to loop over the subcommands after they have been created.//// The code in this example assumes there is just one level of subcommands.//// (A different pattern for a "global" option is to add it to the root command, rather// than to the subcommand. That is not shown here.)
// const { Command } = require('commander'); // (normal include)const { Command } = require('../'); // include commander in git clone of commander repo
// Common options can be added when subcommands are created by using a custom subclass.// If the options are unsorted in the help, these will appear first.class MyRootCommand extends Command { createCommand(name) { const cmd = new Command(name); cmd.option('-v, --verbose', 'use verbose logging'); return cmd; }}
const program = new MyRootCommand();
program.command('print') .option('--a4', 'Use A4 sized paper') .action((options) => { console.log('print options: %O', options); });
program.command('serve') .option('-p, --port <number>', 'port number for server') .action((options) => { console.log('serve options: %O', options); });
// Common options can be added manually after setting up program and subcommands.// If the options are unsorted in the help, these will appear last.program.commands.forEach((cmd) => { cmd.option('-d, --debug');});
program.parse();
// Try the following:// node common-options.js --help// node common-options.js print --help// node common-options.js serve --help// node common-options.js serve --debug --verbosedeleted:examples/optsWithGlobals.js-24 removed
123456789101112131415161718192021222324// const { Command } = require('commander'); // (normal include)const { Command } = require('../'); // include commander in git clone of commander repo
// Show use of .optsWithGlobals(), and compare with .opts().
const program = new Command();
program .option('-g, --global');
program .command('sub') .option('-l, --local') .action((options, cmd) => { console.log({ opts: cmd.opts(), optsWithGlobals: cmd.optsWithGlobals() }); });
program.parse();
// Try the following:// node optsWithGlobals.js --global sub --localmodified:lib/help.js+62 added-7 removed
14 unmodified lines15 constructor() {16 this.helpWidth = undefined;17 this.sortSubcommands = false;18 this.sortOptions = false;19+ this.showGlobalOptions = false;20 }21 22 /**23 * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.22 unmodified lines46 return visibleCommands;47 }48 49 /**50+ * Compare options for sort.51+ *52+ * @param {Option} a53+ * @param {Option} b54+ * @returns number55+ */56+ compareOptions(a, b) {57+ const getSortKey = (option) => {58+ // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.59+ return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '');60+ };61+ return getSortKey(a).localeCompare(getSortKey(b));62+ }63+64+ /**65 * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.66 *67 * @param {Command} cmd68 * @returns {Option[]}15 unmodified lines84 }85 visibleOptions.push(helpOption);86 }87 if (this.sortOptions) {72- const getSortKey = (option) => {73- // WYSIWYG for order displayed in help with short before long, no special handling for negated.74- return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '');75- };76- visibleOptions.sort((a, b) => {77- return getSortKey(a).localeCompare(getSortKey(b));78- });88+ visibleOptions.sort(this.compareOptions);89 }90 return visibleOptions;91 }92 93 /**94+ * Get an array of the visible global options. (Not including help.)95+ *96+ * @param {Command} cmd97+ * @returns {Option[]}98+ */99+100+ visibleGlobalOptions(cmd) {101+ if (!this.showGlobalOptions) return [];102+103+ const globalOptions = [];104+ for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {105+ const visibleOptions = parentCmd.options.filter((option) => !option.hidden);106+ globalOptions.push(...visibleOptions);107+ }108+ if (this.sortOptions) {109+ globalOptions.sort(this.compareOptions);110+ }111+ return globalOptions;112+ }113+114+ /**115 * Get an array of the arguments if any have a description.116 *117 * @param {Command} cmd118 * @returns {Argument[]}80 unmodified lines199 }, 0);200 }201 202 /**203+ * Get the longest global option term length.204+ *205+ * @param {Command} cmd206+ * @param {Help} helper207+ * @returns {number}208+ */209+210+ longestGlobalOptionTermLength(cmd, helper) {211+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {212+ return Math.max(max, helper.optionTerm(option).length);213+ }, 0);214+ }215+216+ /**217 * Get the longest argument term length.218 *219 * @param {Command} cmd220 * @param {Help} helper164 unmodified lines385 if (optionList.length > 0) {386 output = output.concat(['Options:', formatList(optionList), '']);387 }388 389+ if (this.showGlobalOptions) {390+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {391+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));392+ });393+ if (globalOptionList.length > 0) {394+ output = output.concat(['Global Options:', formatList(globalOptionList), '']);395+ }396+ }397+398 // Commands399 const commandList = helper.visibleCommands(cmd).map((cmd) => {400 return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));401 });14 unmodified lines416 417 padWidth(cmd, helper) {418 return Math.max(419 helper.longestOptionTermLength(cmd, helper),420+ helper.longestGlobalOptionTermLength(cmd, helper),421 helper.longestSubcommandTermLength(cmd, helper),422 helper.longestArgumentTermLength(cmd, helper)423 );424 }37 unmodified linesmodified:tests/help.padWidth.test.js+13 added
26 unmodified lines2728293031323334353637383940414243444546478 unmodified lines26 unmodified lines const helper = new commander.Help(); expect(helper.padWidth(program, helper)).toEqual(longestThing.length); });
test('when global option term longest return global option length', () => { const longestThing = '--very-long-thing-bigger-than-others'; const program = new commander.Command(); program .argument('<file>', 'desc') .option(longestThing) .configureHelp({ showGlobalOptions: true }); const sub = program .command('sub'); const helper = sub.createHelp(); expect(helper.padWidth(sub, helper)).toEqual(longestThing.length); });
test('when command term longest return command length', () => { const longestThing = 'very-long-thing-bigger-than-others'; const program = new commander.Command(); program8 unmodified linesadded:tests/help.showGlobalOptions.test.js+62 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162const commander = require('../');
test('when default configuration then global options hidden', () => { const program = new commander.Command(); program .option('--global'); const sub = program.command('sub'); expect(sub.helpInformation()).not.toContain('global');});
test('when showGlobalOptions:true then program options shown', () => { const program = new commander.Command(); program .option('--global') .configureHelp({ showGlobalOptions: true }); const sub = program.command('sub'); expect(sub.helpInformation()).toContain('global');});
test('when showGlobalOptions:true and no global options then global options header not shown', () => { const program = new commander.Command(); program .configureHelp({ showGlobalOptions: true }); const sub = program.command('sub'); expect(sub.helpInformation()).not.toContain('Global');});
test('when showGlobalOptions:true and nested commands then combined nested options shown program last', () => { const program = new commander.Command(); program .option('--global') .configureHelp({ showGlobalOptions: true }); const sub1 = program.command('sub1') .option('--sub1'); const sub2 = sub1.command('sub2'); expect(sub2.helpInformation()).toContain(`Global Options: --sub1 --global`);});
test('when showGlobalOptions:true and sortOptions: true then global options sorted', () => { const program = new commander.Command(); program .option('-3') .option('-4') .option('-2') .configureHelp({ showGlobalOptions: true, sortOptions: true }); const sub1 = program.command('sub1') .option('-6') .option('-1') .option('-5'); const sub2 = sub1.command('sub2'); expect(sub2.helpInformation()).toContain(`Global Options: -1 -2 -3 -4 -5 -6`);});added:tests/help.visibleGlobalOptions.test.js+45 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445const commander = require('../');
test('when default configuration then return empty array', () => { const program = new commander.Command(); program .option('--global'); const sub = program.command('sub'); const helper = sub.createHelp(); expect(helper.visibleGlobalOptions(program)).toEqual([]);});
test('when showGlobalOptions:true then return program options', () => { const program = new commander.Command(); program .option('--global') .configureHelp({ showGlobalOptions: true }); const sub = program.command('sub'); const helper = sub.createHelp(); const visibleOptionNames = helper.visibleGlobalOptions(sub).map(option => option.name()); expect(visibleOptionNames).toEqual(['global']);});
test('when showGlobalOptions:true and program has version then return version', () => { const program = new commander.Command(); program .configureHelp({ showGlobalOptions: true }) .version('1.2.3'); const sub = program.command('sub'); const helper = sub.createHelp(); const visibleOptionNames = helper.visibleGlobalOptions(sub).map(option => option.name()); expect(visibleOptionNames).toEqual(['version']);});
test('when showGlobalOptions:true and nested commands then return combined global options', () => { const program = new commander.Command(); program .configureHelp({ showGlobalOptions: true }) .option('--global'); const sub1 = program.command('sub1') .option('--sub1'); const sub2 = sub1.command('sub2'); const helper = sub2.createHelp(); const visibleOptionNames = helper.visibleGlobalOptions(sub2).map(option => option.name()); expect(visibleOptionNames).toEqual(['sub1', 'global']);});modified:typings/index.d.ts+5 added
197 unmodified lines198 /** output helpWidth, long lines are wrapped to fit */199 helpWidth?: number;200 sortSubcommands: boolean;201 sortOptions: boolean;202+ showGlobalOptions: boolean;203 204 constructor();205 206 /** Get the command term to show in the list of subcommands. */17 unmodified lines224 /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */225 visibleCommands(cmd: Command): Command[];226 /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */227 visibleOptions(cmd: Command): Option[];228+ /** Get an array of the visible global options. (Not including help.) */229+ visibleGlobalOptions(cmd: Command): Option[];230 /** Get an array of the arguments which have descriptions. */231 visibleArguments(cmd: Command): Argument[];232 233 /** Get the longest command term length. */234 longestSubcommandTermLength(cmd: Command, helper: Help): number;235 /** Get the longest option term length. */236 longestOptionTermLength(cmd: Command, helper: Help): number;237+ /** Get the longest global option term length. */238+ longestGlobalOptionTermLength(cmd: Command, helper: Help): number;239 /** Get the longest argument term length. */240 longestArgumentTermLength(cmd: Command, helper: Help): number;241 /** Calculate the pad width from the maximum term length. */242 padWidth(cmd: Command, helper: Help): number;644 unmodified linesmodified:typings/index.test-d.ts+3 added
364 unmodified lines365 366 expectType<number | undefined>(helper.helpWidth);367 expectType<boolean>(helper.sortSubcommands);368 expectType<boolean>(helper.sortOptions);369+expectType<boolean>(helper.showGlobalOptions);370 371 expectType<string>(helper.subcommandTerm(helperCommand));372 expectType<string>(helper.commandUsage(helperCommand));373 expectType<string>(helper.commandDescription(helperCommand));4 unmodified lines378 expectType<string>(helper.argumentDescription(helperArgument));379 380 expectType<commander.Command[]>(helper.visibleCommands(helperCommand));381 expectType<commander.Option[]>(helper.visibleOptions(helperCommand));382+expectType<commander.Option[]>(helper.visibleGlobalOptions(helperCommand));383 expectType<commander.Argument[]>(helper.visibleArguments(helperCommand));384 385 expectType<number>(helper.longestSubcommandTermLength(helperCommand, helper));386 expectType<number>(helper.longestOptionTermLength(helperCommand, helper));387+expectType<number>(helper.longestGlobalOptionTermLength(helperCommand, helper));388 expectType<number>(helper.longestArgumentTermLength(helperCommand, helper));389 expectType<number>(helper.padWidth(helperCommand, helper));390 391 expectType<string>(helper.wrap('a b c', 50, 3));86 unmodified linesmodified:Readme.md+1 added
913 unmodified lines914 915 - `helpWidth`: specify the wrap width, useful for unit tests916 - `sortSubcommands`: sort the subcommands alphabetically917 - `sortOptions`: sort the options alphabetically918+- `showGlobalOptions`: show a section with the global options from the parent command(s)919 920 There are methods getting the visible lists of arguments, options, and subcommands. There are methods for formatting the items in the lists, with each item having a _term_ and _description_. Take a look at `.formatHelp()` to see how they are used.921 922 Example file: [configure-help.js](./examples/configure-help.js)205 unmodified lines