Skip to content
Myr

Refactor help internals into separate interface/class (#1365)

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

* Start filling out HelpUtils to try pattern * Shift the largestFoo routines into helper * Update generation of Commands section of help * Rework helpInformation in consistent new style * Remove unused routines * Make columns part of HelpUtils * Offer a light weight override to HelpUtils * Tweak comment * Add chain test for helpUtilOverrides * Add itemIndent as another proof of concept of allowing overrides * Avoid Utils contraction * Update comments * Switch columns from function to data property * Remove itemIndent(), not useful enough alone or as a pattern for now * Make _helpToolsOverrides inherited * Improve naming for termWidth * Move usage into HelpTools * Add term and description routines to HelpTools so symmetrical pattern * Name the magic numbers * More consistent naming * Remove reference to removed routine * Move help formatting into HelpTools * Fix typescript-checkJS errors * Simpler naming * Slightly simplify code * Add getter/setter to assist overrides * Add sort overrides * First cut at TypeScript definitions for Help, no TSDoc yet * Replace pad and low level indents with modern calls * Rename and rework type for HelpConfiguration * Combine optionalWrap and wrap * Add createHelp to TypeScript definition * Add test-all script * More carefully make concrete help option for displaying * Fix test with valid parameters for custom help * Start adding Help tests * Add largestCommandTermLength tests * Add more Help tests * Add commandUsage tests * Add test for commandDescription * Add missing Command properties, and default description to empty string * Add tests for optionDescription * Add padWidth tests * Add sort tests * Add columns and wrap tests * Add test for legacy commandTerm behaviour * Add TypeScript usage tests for Help * Refactor Help tests into separate files * Add tests for createHelp and configureHelp * Add JSDoc for Help. Rename methods. Delete @api public as default. * Add TSDoc for Help * Test special caes of implicit help flags * Clarify method naming * Shift the Usage prefix into formatHelp * Add Help class mention and reorder help * Add simple configure-help example * Add example file to README * Rename to sortSubcommands to match other naming * Do not weaken configuration type, user can extend as required * Do not cache implicit help command calculation so safer (no need, not being thrashed) * Add JSDoc for configureHelp * Add TSDoc * Add missing TSDoc * Switch option sort to use attributeName, with negative after positive * No need for string template literal * No need for string template literal

authored by John Gee · committed by GitHub · parent b0c5884 · Browse files · 28 files+1439 added−585 removed
This commit

State

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

Diff stats

28 files+1439 added−585 removed

  • tests:+821 added−132 removed
  • other:+618 added−453 removed

28 files+1439 added−585 removed

added:examples/configure-help.js+24 added
modified:tests/command.chain.test.js+6 added
modified:tests/command.commandHelp.test.js+5 added-5 removed
added:tests/command.configureHelp.test.js+31 added
added:tests/command.createHelp.test.js+18 added
modified:tests/command.helpCommand.test.js+2 added-2 removed
29 unmodified lines
30 });3132 test('when add custom help command then custom help command', () => {33 const program = new commander.Command();34 program.addHelpCommand('help command', 'help description');34 program.addHelpCommand('myHelp', 'help description');35 const helpInformation = program.helpInformation();36 expect(helpInformation).toMatch(/help command +help description/);36 expect(helpInformation).toMatch(/myHelp +help description/);37 });38});3940describe('help command processed on correct command', () => {
60 unmodified lines
added:tests/help.columns.test.js+22 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('columns', () => {7 test('when default then columns from stdout', () => {8 const hold = process.stdout.columns;9 process.stdout.columns = 123;10 const program = new commander.Command();11 const helper = program.createHelp();12 expect(helper.columns).toEqual(123);13 process.stdout.columns = hold;14 });1516 test('when configure columns then value from user', () => {17 const program = new commander.Command();18 program.configureHelp({ columns: 321 });19 const helper = program.createHelp();20 expect(helper.columns).toEqual(321);21 });22});
added:tests/help.commandDescription.test.js+20 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('subcommandDescription', () => {7 test('when program has no description then empty string', () => {8 const program = new commander.Command();9 const helper = new commander.Help();10 expect(helper.subcommandDescription(program)).toEqual('');11 });1213 test('when program has description then return description', () => {14 const description = 'description';15 const program = new commander.Command();16 program.description(description);17 const helper = new commander.Help();18 expect(helper.subcommandDescription(program)).toEqual(description);19 });20});
added:tests/help.commandTerm.test.js+43 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56// subcommandTerm does not currently respect helpOption or ignore hidden options, so not testing those.7describe('subcommandTerm', () => {8 test('when plain command then returns name', () => {9 const command = new commander.Command('program');10 const helper = new commander.Help();11 expect(helper.subcommandTerm(command)).toEqual('program');12 });1314 test('when command has alias then returns name|alias', () => {15 const command = new commander.Command('program')16 .alias('alias');17 const helper = new commander.Help();18 expect(helper.subcommandTerm(command)).toEqual('program|alias');19 });2021 test('when command has options then returns name [options]', () => {22 const command = new commander.Command('program')23 .option('-a,--all');24 const helper = new commander.Help();25 expect(helper.subcommandTerm(command)).toEqual('program [options]');26 });2728 test('when command has <argument> then returns name <argument>', () => {29 const command = new commander.Command('program')30 .arguments('<argument>');31 const helper = new commander.Help();32 expect(helper.subcommandTerm(command)).toEqual('program <argument>');33 });3435 test('when command has everything then returns name|alias [options] <argument>', () => {36 const command = new commander.Command('program')37 .alias('alias')38 .option('-a,--all')39 .arguments('<argument>');40 const helper = new commander.Help();41 expect(helper.subcommandTerm(command)).toEqual('program|alias [options] <argument>');42 });43});
added:tests/help.commandUsage.test.js+49 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('commandUsage', () => {7 test('when single program then "program [options]"', () => {8 const program = new commander.Command();9 program.name('program');10 const helper = new commander.Help();11 expect(helper.commandUsage(program)).toEqual('program [options]');12 });1314 test('when multi program then "program [options] [command]"', () => {15 const program = new commander.Command();16 program.name('program');17 program.command('sub');18 const helper = new commander.Help();19 expect(helper.commandUsage(program)).toEqual('program [options] [command]');20 });2122 test('when program has alias then usage includes alias', () => {23 const program = new commander.Command();24 program25 .name('program')26 .alias('alias');27 const helper = new commander.Help();28 expect(helper.commandUsage(program)).toEqual('program|alias [options]');29 });3031 test('when help for subcommand then usage includes hierarchy', () => {32 const program = new commander.Command();33 program34 .name('program');35 const sub = program.command('sub')36 .name('sub');37 const helper = new commander.Help();38 expect(helper.commandUsage(sub)).toEqual('program sub [options]');39 });4041 test('when program has argument then usage includes argument', () => {42 const program = new commander.Command();43 program44 .name('program')45 .arguments('<file>');46 const helper = new commander.Help();47 expect(helper.commandUsage(program)).toEqual('program [options] <file>');48 });49});
added:tests/help.longestArgumentTermLength.test.js+32 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('longestArgumentTermLength', () => {7 test('when no arguments then returns zero', () => {8 const program = new commander.Command();9 const helper = new commander.Help();10 expect(helper.longestArgumentTermLength(program, helper)).toEqual(0);11 });1213 test('when has argument description then returns argument length', () => {14 const program = new commander.Command();15 program.arguments('<wonder>');16 program.description('dummy', { wonder: 'wonder description' });17 const helper = new commander.Help();18 expect(helper.longestArgumentTermLength(program, helper)).toEqual('wonder'.length);19 });2021 test('when has multiple argument descriptions then returns longest', () => {22 const program = new commander.Command();23 program.arguments('<alpha> <longest> <beta>');24 program.description('dummy', {25 alpha: 'x',26 longest: 'x',27 beta: 'x'28 });29 const helper = new commander.Help();30 expect(helper.longestArgumentTermLength(program, helper)).toEqual('longest'.length);31 });32});
added:tests/help.longestCommandTermLength.test.js+52 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('longestSubcommandTermLength', () => {7 test('when no commands then returns zero', () => {8 const program = new commander.Command();9 const helper = new commander.Help();10 expect(helper.longestSubcommandTermLength(program, helper)).toEqual(0);11 });1213 test('when command and no help then returns length of term', () => {14 const sub = new commander.Command('sub');15 const program = new commander.Command();16 program17 .addHelpCommand(false)18 .addCommand(sub);19 const helper = new commander.Help();20 expect(helper.longestSubcommandTermLength(program, helper)).toEqual(helper.subcommandTerm(sub).length);21 });2223 test('when command with arg and no help then returns length of term', () => {24 const sub = new commander.Command('sub <file)');25 const program = new commander.Command();26 program27 .addHelpCommand(false)28 .addCommand(sub);29 const helper = new commander.Help();30 expect(helper.longestSubcommandTermLength(program, helper)).toEqual(helper.subcommandTerm(sub).length);31 });3233 test('when multiple commands then returns longest length', () => {34 const longestCommandName = 'alphabet-soup <longer_than_help>';35 const program = new commander.Command();36 program37 .addHelpCommand(false)38 .command('before', 'desc')39 .command(longestCommandName, 'desc')40 .command('after', 'desc');41 const helper = new commander.Help();42 expect(helper.longestSubcommandTermLength(program, helper)).toEqual(longestCommandName.length);43 });4445 test('when just help command then returns length of help term', () => {46 const program = new commander.Command();47 program48 .addHelpCommand(true);49 const helper = new commander.Help();50 expect(helper.longestSubcommandTermLength(program, helper)).toEqual('help [command]'.length);51 });52});
added:tests/help.longestOptionTermLength.test.js+30 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('longestOptionTermLength', () => {7 test('when no option then returns zero', () => {8 const program = new commander.Command();9 program.helpOption(false);10 const helper = new commander.Help();11 expect(helper.longestOptionTermLength(program, helper)).toEqual(0);12 });1314 test('when just implicit help option returns length of help flags', () => {15 const program = new commander.Command();16 const helper = new commander.Help();17 expect(helper.longestOptionTermLength(program, helper)).toEqual('-h, --help'.length);18 });1920 test('when multiple option then returns longest length', () => {21 const longestOptionFlags = '-l, --longest <value>';22 const program = new commander.Command();23 program24 .option('--before', 'optional description of flags')25 .option(longestOptionFlags)26 .option('--after');27 const helper = new commander.Help();28 expect(helper.longestOptionTermLength(program, helper)).toEqual(longestOptionFlags.length);29 });30});
added:tests/help.optionDescription.test.js+42 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('optionDescription', () => {7 test('when option has no description then empty string', () => {8 const option = new commander.Option('-a');9 const helper = new commander.Help();10 expect(helper.optionDescription(option)).toEqual('');11 });1213 test('when option has description then return description', () => {14 const description = 'description';15 const option = new commander.Option('-a', description);16 const helper = new commander.Help();17 expect(helper.optionDescription(option)).toEqual(description);18 });1920 test('when option has default value then return description and default value', () => {21 const description = 'description';22 const option = new commander.Option('-a', description).default('default');23 const helper = new commander.Help();24 expect(helper.optionDescription(option)).toEqual('description (default: "default")');25 });2627 test('when option has default value description then return description and custom default description', () => {28 const description = 'description';29 const defaultValueDescription = 'custom';30 const option = new commander.Option('-a', description).default('default value', defaultValueDescription);31 const helper = new commander.Help();32 expect(helper.optionDescription(option)).toEqual(`description (default: ${defaultValueDescription})`);33 });3435 test('when option has choices then return description and choices', () => {36 const description = 'description';37 const choices = ['one', 'two'];38 const option = new commander.Option('-a', description).choices(choices);39 const helper = new commander.Help();40 expect(helper.optionDescription(option)).toEqual('description (choices: "one", "two")');41 });42});
added:tests/help.optionTerm.test.js+34 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('optionTerm', () => {7 test('when -s flags then returns flags', () => {8 const flags = '-s';9 const option = new commander.Option(flags);10 const helper = new commander.Help();11 expect(helper.optionTerm(option)).toEqual(flags);12 });1314 test('when --short flags then returns flags', () => {15 const flags = '--short';16 const option = new commander.Option(flags);17 const helper = new commander.Help();18 expect(helper.optionTerm(option)).toEqual(flags);19 });2021 test('when -s,--short flags then returns flags', () => {22 const flags = '-s,--short';23 const option = new commander.Option(flags);24 const helper = new commander.Help();25 expect(helper.optionTerm(option)).toEqual(flags);26 });2728 test('when -s|--short flags then returns flags', () => {29 const flags = '-s|--short';30 const option = new commander.Option(flags);31 const helper = new commander.Help();32 expect(helper.optionTerm(option)).toEqual(flags);33 });34});
added:tests/help.padWidth.test.js+45 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('padWidth', () => {7 test('when argument term longest return argument length', () => {8 const longestThing = 'veryLongThingBiggerThanOthers';9 const program = new commander.Command();10 program11 .arguments(`<${longestThing}>`)12 .description('description', { veryLongThingBiggerThanOthers: 'desc' })13 .option('-o');14 program15 .command('sub');16 const helper = new commander.Help();17 expect(helper.padWidth(program, helper)).toEqual(longestThing.length);18 });1920 test('when option term longest return option length', () => {21 const longestThing = '--very-long-thing-bigger-than-others';22 const program = new commander.Command();23 program24 .arguments('<file}>')25 .description('description', { file: 'desc' })26 .option(longestThing);27 program28 .command('sub');29 const helper = new commander.Help();30 expect(helper.padWidth(program, helper)).toEqual(longestThing.length);31 });3233 test('when command term longest return command length', () => {34 const longestThing = 'very-long-thing-bigger-than-others';35 const program = new commander.Command();36 program37 .arguments('<file}>')38 .description('description', { file: 'desc' })39 .option('-o');40 program41 .command(longestThing);42 const helper = new commander.Help();43 expect(helper.padWidth(program, helper)).toEqual(longestThing.length);44 });45});
added:tests/help.sortCommands.test.js+29 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('sortSubcommands', () => {7 test('when unsorted then commands in order added', () => {8 const program = new commander.Command();9 program10 .command('ccc', 'desc')11 .command('aaa', 'desc')12 .command('bbb', 'desc');13 const helper = program.createHelp();14 const visibleCommandNames = helper.visibleCommands(program).map(cmd => cmd.name());15 expect(visibleCommandNames).toEqual(['ccc', 'aaa', 'bbb', 'help']);16 });1718 test('when sortSubcommands:true then commands sorted', () => {19 const program = new commander.Command();20 program21 .configureHelp({ sortSubcommands: true })22 .command('ccc', 'desc')23 .command('aaa', 'desc')24 .command('bbb', 'desc');25 const helper = program.createHelp();26 const visibleCommandNames = helper.visibleCommands(program).map(cmd => cmd.name());27 expect(visibleCommandNames).toEqual(['aaa', 'bbb', 'ccc', 'help']);28 });29});
added:tests/help.sortOptions.test.js+67 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('sortOptions', () => {7 test('when unsorted then options in order added', () => {8 const program = new commander.Command();9 program10 .option('--zzz', 'desc')11 .option('--aaa', 'desc')12 .option('--bbb', 'desc');13 const helper = program.createHelp();14 const visibleOptionNames = helper.visibleOptions(program).map(option => option.name());15 expect(visibleOptionNames).toEqual(['zzz', 'aaa', 'bbb', 'help']);16 });1718 test('when sortOptions:true then options sorted alphabetically', () => {19 const program = new commander.Command();20 program21 .configureHelp({ sortOptions: true })22 .option('--zzz', 'desc')23 .option('--aaa', 'desc')24 .option('--bbb', 'desc');25 const helper = program.createHelp();26 const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name());27 expect(visibleOptionNames).toEqual(['aaa', 'bbb', 'help', 'zzz']);28 });2930 test('when short and long flags then sort on long flag (name)', () => {31 const program = new commander.Command();32 program33 .configureHelp({ sortOptions: true })34 .option('-m,--zzz', 'desc')35 .option('-n,--aaa', 'desc')36 .option('-o,--bbb', 'desc');37 const helper = program.createHelp();38 const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name());39 expect(visibleOptionNames).toEqual(['aaa', 'bbb', 'help', 'zzz']);40 });4142 test('when negated option with positive then sort together with negative after positive', () => {43 const program = new commander.Command();44 program45 .configureHelp({ sortOptions: true })46 .option('--bbb', 'desc')47 .option('--ccc', 'desc')48 .option('--no-bbb', 'desc')49 .option('--aaa', 'desc');50 const helper = program.createHelp();51 const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name());52 expect(visibleOptionNames).toEqual(['aaa', 'bbb', 'no-bbb', 'ccc', 'help']);53 });5455 test('when negated option without positive then still sorts using attribute name', () => {56 // Sorting '--no-foo' as 'foo' (mainly for when also 'foo' so sort together)!57 const program = new commander.Command();58 program59 .configureHelp({ sortOptions: true })60 .option('--ccc', 'desc')61 .option('--aaa', 'desc')62 .option('--no-bbb', 'desc');63 const helper = program.createHelp();64 const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name());65 expect(visibleOptionNames).toEqual(['aaa', 'no-bbb', 'ccc', 'help']);66 });67});
added:tests/help.visibleArgumnets.test.js+27 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('visibleArguments', () => {7 test('when no arguments then empty array', () => {8 const program = new commander.Command();9 const helper = new commander.Help();10 expect(helper.visibleArguments(program)).toEqual([]);11 });1213 test('when argument but no argument description then empty array', () => {14 const program = new commander.Command();15 program.arguments('<file>');16 const helper = new commander.Help();17 expect(helper.visibleArguments(program)).toEqual([]);18 });1920 test('when argument and argument description then returned', () => {21 const program = new commander.Command();22 program.arguments('<file>');23 program.description('dummy', { file: 'file description' });24 const helper = new commander.Help();25 expect(helper.visibleArguments(program)).toEqual([{ term: 'file', description: 'file description' }]);26 });27});
added:tests/help.visibleCommands.test.js+33 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('visibleCommands', () => {7 test('when no subcommands then empty array', () => {8 const program = new commander.Command();9 const helper = new commander.Help();10 expect(helper.visibleCommands(program)).toEqual([]);11 });1213 test('when add command then visible (with help)', () => {14 const program = new commander.Command();15 program16 .command('sub');17 const helper = new commander.Help();18 const visibleCommandNames = helper.visibleCommands(program).map(cmd => cmd.name());19 expect(visibleCommandNames).toEqual(['sub', 'help']);20 });2122 test('when commands hidden then not visible', () => {23 const program = new commander.Command();24 program25 .command('visible', 'desc')26 .command('invisible executable', 'desc', { hidden: true });27 program28 .command('invisible action', { hidden: true });29 const helper = new commander.Help();30 const visibleCommandNames = helper.visibleCommands(program).map(cmd => cmd.name());31 expect(visibleCommandNames).toEqual(['visible', 'help']);32 });33});
added:tests/help.visibleOptions.test.js+70 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('visibleOptions', () => {7 test('when no options then just help visible', () => {8 const program = new commander.Command();9 const helper = new commander.Help();10 const visibleOptionNames = helper.visibleOptions(program).map(option => option.name());11 expect(visibleOptionNames).toEqual(['help']);12 });1314 test('when no options and no help option then empty array', () => {15 const program = new commander.Command();16 program.helpOption(false);17 const helper = new commander.Help();18 expect(helper.visibleOptions(program)).toEqual([]);19 });2021 test('when add option then visible (with help)', () => {22 const program = new commander.Command();23 program.option('-v,--visible');24 const helper = new commander.Help();25 const visibleOptionNames = helper.visibleOptions(program).map(option => option.name());26 expect(visibleOptionNames).toEqual(['visible', 'help']);27 });2829 test('when option hidden then not visible', () => {30 const program = new commander.Command();31 program32 .option('-v,--visible')33 .addOption(new commander.Option('--invisible').hideHelp());34 const helper = new commander.Help();35 const visibleOptionNames = helper.visibleOptions(program).map(option => option.name());36 expect(visibleOptionNames).toEqual(['visible', 'help']);37 });38});3940describe('implicit help', () => {41 test('when default then help term is -h, --help', () => {42 const program = new commander.Command();43 const helper = new commander.Help();44 const implicitHelp = helper.visibleOptions(program)[0];45 expect(helper.optionTerm(implicitHelp)).toEqual('-h, --help');46 });4748 test('when short flag obscured then help term is --help', () => {49 const program = new commander.Command();50 program.addOption(new commander.Option('-h, --huge').hideHelp());51 const helper = new commander.Help();52 const implicitHelp = helper.visibleOptions(program)[0];53 expect(helper.optionTerm(implicitHelp)).toEqual('--help');54 });5556 test('when long flag obscured then help term is --h', () => {57 const program = new commander.Command();58 program.addOption(new commander.Option('-H, --help').hideHelp());59 const helper = new commander.Help();60 const implicitHelp = helper.visibleOptions(program)[0];61 expect(helper.optionTerm(implicitHelp)).toEqual('-h');62 });6364 test('when help flags obscured then implicit help hidden', () => {65 const program = new commander.Command();66 program.addOption(new commander.Option('-h, --help').hideHelp());67 const helper = new commander.Help();68 expect(helper.visibleOptions(program)).toEqual([]);69 });70});
added:tests/help.wrap.test.js+164 added
1const commander = require('../');23// These are tests of the Help class, not of the Command help.4// There is some overlap with the higher level Command tests (which predate Help).56describe('wrap', () => {7 test('when string fits into width then no wrap', () => {8 const text = 'a '.repeat(24) + 'a';9 const helper = new commander.Help();10 const wrapped = helper.wrap(text, 50, 3);11 expect(wrapped).toEqual(text);12 });1314 test('when string exceeds width then wrap', () => {15 const text = 'a '.repeat(30) + 'a';16 const helper = new commander.Help();17 const wrapped = helper.wrap(text, 50, 0);18 expect(wrapped).toEqual(`${'a '.repeat(24)}a19${'a '.repeat(5)}a`);20 });2122 test('when string exceeds width then wrap and indent', () => {23 const text = 'a '.repeat(30) + 'a';24 const helper = new commander.Help();25 const wrapped = helper.wrap(text, 50, 10);26 expect(wrapped).toEqual(`${'a '.repeat(24)}a27${' '.repeat(10)}${'a '.repeat(5)}a`);28 });2930 test('when width < 40 then do not wrap', () => {31 const text = 'a '.repeat(30) + 'a';32 const helper = new commander.Help();33 const wrapped = helper.wrap(text, 39, 0);34 expect(wrapped).toEqual(text);35 });3637 test('when text has line breaks then respect and indent', () => {38 const text = 'foo\nbar';39 const helper = new commander.Help();40 const wrapped = helper.wrap(text, 50, 3);41 expect(wrapped).toEqual('foo\n bar');42 });4344 test('when text already formatted with line breaks and indent then do not touch', () => {45 const text = 'a '.repeat(25) + '\n ' + 'a '.repeat(25) + 'a';46 const helper = new commander.Help();47 const wrapped = helper.wrap(text, 39, 0);48 expect(wrapped).toEqual(text);49 });50});5152describe('wrapping by formatHelp', () => {53 // Test auto wrap and indent with some manual strings.54 // Fragile tests with complete help output.5556 test('when long option description then wrap and indent', () => {57 const program = new commander.Command();58 program59 .configureHelp({ columns: 80 })60 .option('-x --extra-long-option-switch', 'kjsahdkajshkahd kajhsd akhds kashd kajhs dkha dkh aksd ka dkha kdh kasd ka kahs dkh sdkh askdh aksd kashdk ahsd kahs dkha skdh');6162 const expectedOutput =63`Usage: [options]6465Options:66 -x --extra-long-option-switch kjsahdkajshkahd kajhsd akhds kashd kajhs dkha67 dkh aksd ka dkha kdh kasd ka kahs dkh sdkh68 askdh aksd kashdk ahsd kahs dkha skdh69 -h, --help display help for command70`;7172 expect(program.helpInformation()).toBe(expectedOutput);73 });7475 test('when long option description and default then wrap and indent', () => {76 const program = new commander.Command();77 program78 .configureHelp({ columns: 80 })79 .option('-x --extra-long-option <value>', 'kjsahdkajshkahd kajhsd akhds', 'aaa bbb ccc ddd eee fff ggg');8081 const expectedOutput =82`Usage: [options]8384Options:85 -x --extra-long-option <value> kjsahdkajshkahd kajhsd akhds (default: "aaa86 bbb ccc ddd eee fff ggg")87 -h, --help display help for command88`;8990 expect(program.helpInformation()).toBe(expectedOutput);91 });9293 test('when long command description then wrap and indent', () => {94 const program = new commander.Command();95 program96 .configureHelp({ columns: 80 })97 .option('-x --extra-long-option-switch', 'x')98 .command('alpha', 'Lorem mollit quis dolor ex do eu quis ad insa a commodo esse.');99100 const expectedOutput =101`Usage: [options] [command]102103Options:104 -x --extra-long-option-switch x105 -h, --help display help for command106107Commands:108 alpha Lorem mollit quis dolor ex do eu quis ad insa109 a commodo esse.110 help [command] display help for command111`;112113 expect(program.helpInformation()).toBe(expectedOutput);114 });115116 test('when not enough room then help not wrapped', () => {117 // Not wrapping if less than 40 columns available for wrapping.118 const program = new commander.Command();119 const commandDescription = 'description text of very long command which should not be automatically be wrapped. Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu.';120 program121 .configureHelp({ columns: 60 })122 .command('1234567801234567890x', commandDescription);123124 const expectedOutput =125`Usage: [options] [command]126127Options:128 -h, --help display help for command129130Commands:131 1234567801234567890x ${commandDescription}132 help [command] display help for command133`;134135 expect(program.helpInformation()).toBe(expectedOutput);136 });137138 test('when option descripton preformatted then only add small indent', () => {139 // #396: leave custom format alone, apart from space-space indent140 const optionSpec = '-t, --time <HH:MM>';141 const program = new commander.Command();142 program143 .configureHelp({ columns: 80 })144 .option(optionSpec, `select time145146Time can also be specified using special values:147 "dawn" - From night to sunrise.148`);149150 const expectedOutput =151`Usage: [options]152153Options:154 ${optionSpec} select time155 156 Time can also be specified using special values:157 "dawn" - From night to sunrise.158 159 -h, --help display help for command160`;161162 expect(program.helpInformation()).toBe(expectedOutput);163 });164});
deleted:tests/helpwrap.test.js-125 removed
1const commander = require('../');23// Test auto wrap and indent with some manual strings.4// Fragile tests with complete help output.56test('when long option description then wrap and indent', () => {7 const oldColumns = process.stdout.columns;8 process.stdout.columns = 80;9 const program = new commander.Command();10 program11 .option('-x --extra-long-option-switch', 'kjsahdkajshkahd kajhsd akhds kashd kajhs dkha dkh aksd ka dkha kdh kasd ka kahs dkh sdkh askdh aksd kashdk ahsd kahs dkha skdh');1213 const expectedOutput =14`Usage: [options]1516Options:17 -x --extra-long-option-switch kjsahdkajshkahd kajhsd akhds kashd kajhs dkha18 dkh aksd ka dkha kdh kasd ka kahs dkh sdkh19 askdh aksd kashdk ahsd kahs dkha skdh20 -h, --help display help for command21`;2223 expect(program.helpInformation()).toBe(expectedOutput);24 process.stdout.columns = oldColumns;25});2627test('when long option description and default then wrap and indent', () => {28 const oldColumns = process.stdout.columns;29 process.stdout.columns = 80;30 const program = new commander.Command();31 program32 .option('-x --extra-long-option <value>', 'kjsahdkajshkahd kajhsd akhds', 'aaa bbb ccc ddd eee fff ggg');3334 const expectedOutput =35`Usage: [options]3637Options:38 -x --extra-long-option <value> kjsahdkajshkahd kajhsd akhds (default: "aaa39 bbb ccc ddd eee fff ggg")40 -h, --help display help for command41`;4243 expect(program.helpInformation()).toBe(expectedOutput);44 process.stdout.columns = oldColumns;45});4647test('when long command description then wrap and indent', () => {48 const oldColumns = process.stdout.columns;49 process.stdout.columns = 80;50 const program = new commander.Command();51 program52 .option('-x --extra-long-option-switch', 'x')53 .command('alpha', 'Lorem mollit quis dolor ex do eu quis ad insa a commodo esse.');5455 const expectedOutput =56`Usage: [options] [command]5758Options:59 -x --extra-long-option-switch x60 -h, --help display help for command6162Commands:63 alpha Lorem mollit quis dolor ex do eu quis ad64 insa a commodo esse.65 help [command] display help for command66`;6768 expect(program.helpInformation()).toBe(expectedOutput);69 process.stdout.columns = oldColumns;70});7172test('when not enough room then help not wrapped', () => {73 // Not wrapping if less than 40 columns available for wrapping.74 const oldColumns = process.stdout.columns;75 process.stdout.columns = 60;76 const program = new commander.Command();77 const commandDescription = 'description text of very long command which should not be automatically be wrapped. Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu.';78 program79 .command('1234567801234567890x', commandDescription);8081 const expectedOutput =82`Usage: [options] [command]8384Options:85 -h, --help display help for command8687Commands:88 1234567801234567890x ${commandDescription}89 help [command] display help for command90`;9192 expect(program.helpInformation()).toBe(expectedOutput);93 process.stdout.columns = oldColumns;94});9596test('when option descripton preformatted then only add small indent', () => {97 const oldColumns = process.stdout.columns;98 process.stdout.columns = 80;99 // #396: leave custom format alone, apart from space-space indent100 const optionSpec = '-t, --time <HH:MM>';101 const program = new commander.Command();102 program103 .option(optionSpec, `select time104105Time can also be specified using special values:106 "dawn" - From night to sunrise.107`);108109 const expectedOutput =110`Usage: [options]111112Options:113 ${optionSpec} select time114 115 Time can also be specified using special values:116 "dawn" - From night to sunrise.117 118 -h, --help display help for command119`;120121 expect(program.helpInformation()).toBe(expectedOutput);122 process.stdout.columns = oldColumns;123});124125// test for argsDescription passed to command ????
modified:typings/commander-tests.ts+38 added
242 unmodified lines
243myProgram.myFunction();244const mySub = myProgram.command('sub');245mySub.myFunction();246247// configureHelp248249const createHelpInstance: commander.Help = program.createHelp();250const configureHelpThis: commander.Command = program.configureHelp({251 sortSubcommands: true, // override property252 visibleCommands: (cmd: commander.Command) => [] // override method253});254const helpConfiguration: commander.HelpConfiguration = program.configureHelp();255256// Help257const helper = new commander.Help();258const helperCommand = new commander.Command();259const helperOption = new commander.Option('-a, --all');260261helper.columns = 3;262helper.sortSubcommands = true;263helper.sortOptions = false;264265const subcommandTermStr: string = helper.subcommandTerm(helperCommand);266const commandUsageStr: string = helper.commandUsage(helperCommand);267const commandDescriptionStr: string = helper.commandDescription(helperCommand);268const subcommandDescriptionStr: string = helper.subcommandDescription(helperCommand);269const optionTermStr: string = helper.optionTerm(helperOption);270const optionDescriptionStr: string = helper.optionDescription(helperOption);271272const visibleCommands: commander.Command[] = helper.visibleCommands(helperCommand);273const visibleOptions: commander.Option[] = helper.visibleOptions(helperCommand);274const visibleArguments: Array<{ term: string; description: string}> = helper.visibleArguments(helperCommand);275276const widestCommand: number = helper.longestSubcommandTermLength(helperCommand, helper);277const widestOption: number = helper.longestOptionTermLength(helperCommand, helper);278const widestArgument: number = helper.longestArgumentTermLength(helperCommand, helper);279const widest: number = helper.padWidth(helperCommand, helper);280281const wrapped: string = helper.wrap('a b c', 50, 3);282283const formatted: string = helper.formatHelp(helperCommand, helper);284285// Option methods286287const baseOption = new commander.Option('-f,--foo', 'foo description');288
30 unmodified lines
modified:typings/index.d.ts+64 added
70 unmodified lines
71 name(): string;72 }73 type OptionConstructor = new (flags: string, description?: string) => Option;7475 interface Help {76 /** output columns, long lines are wrapped to fit */77 columns: number;78 sortSubcommands: boolean;79 sortOptions: boolean;8081 /** Get the command term to show in the list of subcommands. */82 subcommandTerm(cmd: Command): string;83 /** Get the command description to show in the list of subcommands. */84 subcommandDescription(cmd: Command): string;85 /** Get the option term to show in the list of options. */86 optionTerm(option: Option): string;87 /** Get the option description to show in the list of options. */88 optionDescription(option: Option): string;8990 /** Get the command usage to be displayed at the top of the built-in help. */91 commandUsage(cmd: Command): string;92 /** Get the description for the command. */93 commandDescription(cmd: Command): string;9495 /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */96 visibleCommands(cmd: Command): Command[];97 /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */98 visibleOptions(cmd: Command): Option[];99 /** Get an array of the arguments which have descriptions. */100 visibleArguments(cmd: Command): Array<{ term: string; description: string}>;101102 /** Get the longest command term length. */103 longestSubcommandTermLength(cmd: Command, helper: Help): number;104 /** Get the longest option term length. */105 longestOptionTermLength(cmd: Command, helper: Help): number;106 /** Get the longest argument term length. */107 longestArgumentTermLength(cmd: Command, helper: Help): number;108 /** Calculate the pad width from the maximum term length. */109 padWidth(cmd: Command, helper: Help): number;110111 /**112 * Optionally wrap the given str to a max width of width characters per line113 * while indenting with indent spaces. Do not wrap if insufficient width or114 * string is manually formatted.115 */116 wrap(str: string, width: number, indent: number): string;117118 /** Generate the built-in help text. */119 formatHelp(cmd: Command, helper: Help): string;120 }121 type HelpConstructor = new () => Help;122 type HelpConfiguration = Partial<Help>;123124 interface ParseOptions {125 from: 'node' | 'electron' | 'user';126 }127 interface HelpContext { // optional parameter for .help() and .outputHelp()
93 unmodified lines
221 */222 exitOverride(callback?: (err: CommanderError) => never|void): this;223224 /**225 * You can customise the help with a subclass of Help by overriding createHelp,226 * or by overriding Help properties using configureHelp().227 */228 createHelp(): Help;229230 /**231 * You can customise the help by overriding Help properties using configureHelp(),232 * or with a subclass of Help by overriding createHelp().233 */234 configureHelp(configuration: HelpConfiguration): this;235 /** Get configuration */236 configureHelp(): HelpConfiguration;237238 /**239 * Register callback `fn` for the command.240 *241 * @example242 * program
285 unmodified lines
528 program: Command;529 Command: CommandConstructor;530 Option: OptionConstructor;531 CommanderError: CommanderErrorConstructor;532 Help: HelpConstructor;533 }534535}536
4 unmodified lines
modified:index.js+381 added-360 removed
7 unmodified lines
8const fs = require('fs');910// @ts-check1112// Although this is a class, methods are static in style to allow override using subclass or just functions.13class Help {14 constructor() {15 this.columns = process.stdout.columns || 80;16 this.sortSubcommands = false;17 this.sortOptions = false;18 }1920 /**21 * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.22 *23 * @param {Command} cmd24 * @returns {Command[]}25 */2627 visibleCommands(cmd) {28 const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);29 if (cmd._hasImplicitHelpCommand()) {30 // Create a command matching the implicit help command.31 const args = cmd._helpCommandnameAndArgs.split(/ +/);32 const helpCommand = cmd.createCommand(args.shift())33 .helpOption(false);34 helpCommand.description(cmd._helpCommandDescription);35 helpCommand._parseExpectedArgs(args);36 visibleCommands.push(helpCommand);37 }38 if (this.sortSubcommands) {39 visibleCommands.sort((a, b) => {40 return a.name().localeCompare(b.name());41 });42 }43 return visibleCommands;44 }4546 /**47 * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.48 *49 * @param {Command} cmd50 * @returns {Option[]}51 */5253 visibleOptions(cmd) {54 const visibleOptions = cmd.options.filter((option) => !option.hidden);55 // Implicit help56 const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);57 const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);58 if (showShortHelpFlag || showLongHelpFlag) {59 let helpOption;60 if (!showShortHelpFlag) {61 helpOption = new Option(cmd._helpLongFlag, cmd._helpDescription);62 } else if (!showLongHelpFlag) {63 helpOption = new Option(cmd._helpShortFlag, cmd._helpDescription);64 } else {65 helpOption = new Option(cmd._helpFlags, cmd._helpDescription);66 }67 visibleOptions.push(helpOption);68 }69 if (this.sortOptions) {70 visibleOptions.sort((a, b) => {71 const compare = a.attributeName().localeCompare(b.attributeName());72 if (compare === 0) {73 return (a.negate) ? +1 : -1;74 }75 return compare;76 });77 }78 return visibleOptions;79 }8081 /**82 * Get an array of the arguments which have descriptions.83 *84 * @param {Command} cmd85 * @returns {{ term: string, description:string }[]}86 */8788 visibleArguments(cmd) {89 if (cmd._argsDescription && cmd._args.length) {90 return cmd._args.map((argument) => {91 return { term: argument.name, description: cmd._argsDescription[argument.name] || '' };92 }, 0);93 }94 return [];95 }9697 /**98 * Get the command term to show in the list of subcommands.99 *100 * @param {Command} cmd101 * @returns {string}102 */103104 subcommandTerm(cmd) {105 // Legacy. Ignores custom usage string, and nested commands.106 const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' ');107 return cmd._name +108 (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +109 (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option110 (args ? ' ' + args : '');111 }112113 /**114 * Get the option term to show in the list of options.115 *116 * @param {Option} option117 * @returns {string}118 */119120 optionTerm(option) {121 return option.flags;122 }123124 /**125 * Get the longest command term length.126 *127 * @param {Command} cmd128 * @param {Help} helper129 * @returns {number}130 */131132 longestSubcommandTermLength(cmd, helper) {133 return helper.visibleCommands(cmd).reduce((max, command) => {134 return Math.max(max, helper.subcommandTerm(command).length);135 }, 0);136 };137138 /**139 * Get the longest option term length.140 *141 * @param {Command} cmd142 * @param {Help} helper143 * @returns {number}144 */145146 longestOptionTermLength(cmd, helper) {147 return helper.visibleOptions(cmd).reduce((max, option) => {148 return Math.max(max, helper.optionTerm(option).length);149 }, 0);150 };151152 /**153 * Get the longest argument term length.154 *155 * @param {Command} cmd156 * @param {Help} helper157 * @returns {number}158 */159160 longestArgumentTermLength(cmd, helper) {161 return helper.visibleArguments(cmd).reduce((max, argument) => {162 return Math.max(max, argument.term.length);163 }, 0);164 };165166 /**167 * Get the command usage to be displayed at the top of the built-in help.168 *169 * @param {Command} cmd170 * @returns {string}171 */172173 commandUsage(cmd) {174 // Usage175 let cmdName = cmd._name;176 if (cmd._aliases[0]) {177 cmdName = cmdName + '|' + cmd._aliases[0];178 }179 let parentCmdNames = '';180 for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {181 parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;182 }183 return parentCmdNames + cmdName + ' ' + cmd.usage();184 }185186 /**187 * Get the description for the command.188 *189 * @param {Command} cmd190 * @returns {string}191 */192193 commandDescription(cmd) {194 // @ts-ignore: overloaded return type195 return cmd.description();196 }197198 /**199 * Get the command description to show in the list of subcommands.200 *201 * @param {Command} cmd202 * @returns {string}203 */204205 subcommandDescription(cmd) {206 // @ts-ignore: overloaded return type207 return cmd.description();208 }209210 /**211 * Get the option description to show in the list of options.212 *213 * @param {Option} option214 * @return {string}215 */216217 optionDescription(option) {218 if (option.negate) {219 return option.description;220 }221 const extraInfo = [];222 if (option.argChoices) {223 extraInfo.push(224 // use stringify to match the display of the default value225 `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);226 }227 if (option.defaultValue !== undefined) {228 extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);229 }230 if (extraInfo.length > 0) {231 return `${option.description} (${extraInfo.join(', ')})`;232 }233 return option.description;234 };235236 /**237 * Generate the built-in help text.238 *239 * @param {Command} cmd240 * @param {Help} helper241 * @returns {string}242 */243244 formatHelp(cmd, helper) {245 const termWidth = helper.padWidth(cmd, helper);246 const columns = helper.columns;247 const itemIndentWidth = 2;248 const itemSeparatorWidth = 2;249 // itemIndent term itemSeparator description250 const descriptionWidth = columns - termWidth - itemIndentWidth - itemSeparatorWidth;251 function formatItem(term, description) {252 if (description) {253 return term.padEnd(termWidth + itemSeparatorWidth) + helper.wrap(description, descriptionWidth, termWidth + itemSeparatorWidth);254 }255 return term;256 };257 function formatList(textArray) {258 return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));259 }260261 // Usage262 let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];263264 // Description265 const commandDescription = helper.commandDescription(cmd);266 if (commandDescription.length > 0) {267 output = output.concat([commandDescription, '']);268 }269270 // Arguments271 const argumentList = helper.visibleArguments(cmd).map((argument) => {272 return formatItem(argument.term, argument.description);273 });274 if (argumentList.length > 0) {275 output = output.concat(['Arguments:', formatList(argumentList), '']);276 }277278 // Options279 const optionList = helper.visibleOptions(cmd).map((option) => {280 return formatItem(helper.optionTerm(option), helper.optionDescription(option));281 });282 if (optionList.length > 0) {283 output = output.concat(['Options:', formatList(optionList), '']);284 }285286 // Commands287 const commandList = helper.visibleCommands(cmd).map((cmd) => {288 return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));289 });290 if (commandList.length > 0) {291 output = output.concat(['Commands:', formatList(commandList), '']);292 }293294 return output.join('\n');295 }296297 /**298 * Calculate the pad width from the maximum term length.299 *300 * @param {Command} cmd301 * @param {Help} helper302 * @returns {number}303 */304305 padWidth(cmd, helper) {306 return Math.max(307 helper.longestOptionTermLength(cmd, helper),308 helper.longestSubcommandTermLength(cmd, helper),309 helper.longestArgumentTermLength(cmd, helper)310 );311 };312313 /**314 * Optionally wrap the given str to a max width of width characters per line315 * while indenting with indent spaces. Do not wrap if insufficient width or316 * string is manually formatted.317 *318 * @param {string} str319 * @param {number} width320 * @param {number} indent321 * @return {string}322 */323324 wrap(str, width, indent) {325 // Detect manually wrapped and indented strings by searching for line breaks326 // followed by multiple spaces/tabs.327 if (str.match(/[\n]\s+/)) return str;328 // Do not wrap to narrow columns (or can end up with a word per line).329 const minWidth = 40;330 if (width < minWidth) return str;331332 const indentString = ' '.repeat(indent);333 const regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');334 const lines = str.match(regex) || [];335 return lines.map((line, i) => {336 if (line.slice(-1) === '\n') {337 line = line.slice(0, line.length - 1);338 }339 return ((i > 0 && indent) ? indentString : '') + line.trimRight();340 }).join('\n');341 }342}343344class Option {345 /**346 * Initialize a new `Option` with the given `flags` and `description`.347 *348 * @param {string} flags349 * @param {string} [description]18 * @api public350 */351352 constructor(flags, description) {353 this.flags = flags;
23 unmodified lines
377 *378 * @param {any} value379 * @param {string} [description]380 * @return {Option}50 * @api public381 */382383 default(value, description) {384 this.defaultValue = value;
1 unmodified line
386 return this;387 };388389 /**60 * Calculate the full description, including defaultValue etc.61 *62 * @return {string}63 * @api public64 */6566 fullDescription() {67 if (this.negate) {68 return this.description;69 }70 const extraInfo = [];71 if (this.argChoices) {72 extraInfo.push(73 // use stringify to match the display of the default value74 `choices: ${this.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);75 }76 if (this.defaultValue !== undefined) {77 extraInfo.push(`default: ${this.defaultValueDescription || JSON.stringify(this.defaultValue)}`);78 }79 if (extraInfo.length > 0) {80 return `${this.description} (${extraInfo.join(', ')})`;81 }82 return this.description;83 };8485 /**390 * Set the custom handler for processing CLI option arguments into option values.391 *392 * @param {Function} [fn]393 * @return {Option}90 * @api public394 */395396 argParser(fn) {397 this.parseArg = fn;
4 unmodified lines
402 * Whether the option is mandatory and must have a value after parsing.403 *404 * @param {boolean} [value]405 * @return {Option}103 * @api public406 */407408 makeOptionMandatory(value) {409 this.mandatory = (value === undefined) || value;
4 unmodified lines
414 * Hide option in help.415 *416 * @param {boolean} [value]417 * @return {Option}116 * @api public418 */419420 hideHelp(value) {421 this.hidden = (value === undefined) || value;
4 unmodified lines
426 * Validation of option argument failed.427 * Intended for use from custom argument processing functions.428 *429 * @param {string} message129 * @api public430 */431 argumentRejected(message) {432 throw new CommanderError(1, 'commander.optionArgumentRejected', message);433 }
2 unmodified lines
436 * Only allow option value to be one of choices.437 *438 * @param {string[]} values439 * @return {Option}140 * @api public440 */441442 choices(values) {443 this.argChoices = values;
9 unmodified lines
453 /**454 * Return option name.455 *456 * @return {string}158 * @api public457 */458459 name() {460 if (this.long) {
54 unmodified lines
515 /**516 * Initialize a new `Command`.517 *518 * @param {string} [name]221 * @api public519 */520521 constructor(name) {522 super();
16 unmodified lines
539 this._defaultCommandName = null;540 this._exitCallback = null;541 this._aliases = [];542 this._combineFlagAndOptionalValue = true;543 this._description = '';544 this._argsDescription = undefined;545546 this._hidden = false;547 this._hasHelpOption = true;548 this._helpFlags = '-h, --help';549 this._helpDescription = 'display help for command';550 this._helpShortFlag = '-h';551 this._helpLongFlag = '--help';253 this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false552 this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false553 this._helpCommandName = 'help';554 this._helpCommandnameAndArgs = 'help [command]';555 this._helpCommandDescription = 'display help for command';556 this._helpConfiguration = {};557 }558559 /**560 * Define a command.
18 unmodified lines
579 * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`580 * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)581 * @param {Object} [execOpts] - configuration options (for executable)582 * @return {Command} returns new command for action handler, or `this` for executable command283 * @api public583 */584585 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {586 let desc = actionOptsOrExecDesc;
20 unmodified lines
607 cmd._helpLongFlag = this._helpLongFlag;608 cmd._helpCommandName = this._helpCommandName;609 cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;610 cmd._helpCommandDescription = this._helpCommandDescription;611 cmd._helpConfiguration = this._helpConfiguration;612 cmd._exitCallback = this._exitCallback;613 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;614 cmd._passCommandToAction = this._passCommandToAction;615 cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;
14 unmodified lines
630 * create the command. You can override createCommand to customise subcommands.631 *632 * @param {string} [name]633 * @return {Command} new command334 * @api public634 */635636 createCommand(name) {637 return new Command(name);638 };639640 /**641 * You can customise the help with a subclass of Help by overriding createHelp,642 * or by overriding Help properties using configureHelp().643 *644 * @return {Help}645 */646647 createHelp() {648 return Object.assign(new Help(), this.configureHelp());649 };650651 /**652 * You can customise the help by overriding Help properties using configureHelp(),653 * or with a subclass of Help by overriding createHelp().654 *655 * @param {Object} [configuration] - configuration options656 * @return {Command|Object} `this` command for chaining, or stored configuration657 */658659 configureHelp(configuration) {660 if (configuration === undefined) return this._helpConfiguration;661662 this._helpConfiguration = configuration;663 return this;664 }665666 /**667 * Add a prepared subcommand.668 *669 * See .command() for creating an attached subcommand which inherits settings from its parent.670 *671 * @param {Command} cmd - new subcommand672 * @param {Object} [opts] - configuration options673 * @return {Command} `this` command for chaining349 * @api public674 */675676 addCommand(cmd, opts) {677 if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');
20 unmodified lines
698 };699700 /**701 * Define argument syntax for the command.378 *379 * @api public702 */703704 arguments(desc) {705 return this._parseExpectedArgs(desc.split(/ +/));
6 unmodified lines
712 * addHelpCommand(false); // force off713 * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details714 *715 * @return {Command} `this` command for chaining394 * @api public716 */717718 addHelpCommand(enableOrNameAndArgs, description) {719 if (enableOrNameAndArgs === false) {399 this._hasImplicitHelpCommand = false;720 this._addImplicitHelpCommand = false;721 } else {401 this._hasImplicitHelpCommand = true;722 this._addImplicitHelpCommand = true;723 if (typeof enableOrNameAndArgs === 'string') {724 this._helpCommandName = enableOrNameAndArgs.split(' ')[0];725 this._helpCommandnameAndArgs = enableOrNameAndArgs;726 }
6 unmodified lines
733 * @return {boolean}734 * @api private735 */736416 _lazyHasImplicitHelpCommand() {417 if (this._hasImplicitHelpCommand === undefined) {418 this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help');737 _hasImplicitHelpCommand() {738 if (this._addImplicitHelpCommand === undefined) {739 return this.commands.length && !this._actionHandler && !this._findCommand('help');740 }420 return this._hasImplicitHelpCommand;741 return this._addImplicitHelpCommand;742 };743744 /**745 * Parse expected `args`.
44 unmodified lines
790 * Register callback to use as replacement for calling process.exit.791 *792 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing793 * @return {Command} `this` command for chaining473 * @api public794 */795796 exitOverride(fn) {797 if (fn) {
41 unmodified lines
839 * });840 *841 * @param {Function} fn842 * @return {Command} `this` command for chaining523 * @api public843 */844845 action(fn) {846 const listener = (args) => {
211 unmodified lines
1058 * @param {string} description1059 * @param {Function|*} [fn] - custom option processing function or default value1060 * @param {*} [defaultValue]1061 * @return {Command} `this` command for chaining743 * @api public1062 */10631064 option(flags, description, fn, defaultValue) {1065 return this._optionEx({}, flags, description, fn, defaultValue);
9 unmodified lines
1075 * @param {string} description1076 * @param {Function|*} [fn] - custom option processing function or default value1077 * @param {*} [defaultValue]1078 * @return {Command} `this` command for chaining761 * @api public1079 */10801081 requiredOption(flags, description, fn, defaultValue) {1082 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
8 unmodified lines
1091 * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour1092 * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`1093 *1094 * @param {Boolean} [arg] - if `true` or omitted, an optional value can be specified directly after the flag.778 * @api public1095 */1096 combineFlagAndOptionalValue(arg) {1097 this._combineFlagAndOptionalValue = (arg === undefined) || arg;1098 return this;
3 unmodified lines
1102 * Allow unknown options on the command line.1103 *1104 * @param {Boolean} [arg] - if `true` or omitted, no error will be thrown1105 * for unknown options.790 * @api public1106 */1107 allowUnknownOption(arg) {1108 this._allowUnknownOption = (arg === undefined) || arg;1109 return this;
4 unmodified lines
1114 * or store separately (specify false). In both cases the option values can be accessed using .opts().1115 *1116 * @param {boolean} value1117 * @return {Command} `this` command for chaining803 * @api public1118 */11191120 storeOptionsAsProperties(value) {1121 this._storeOptionsAsPropertiesCalled = true;
9 unmodified lines
1131 * or just the options (specify false).1132 *1133 * @param {boolean} value1134 * @return {Command} `this` command for chaining821 * @api public1135 */11361137 passCommandToAction(value) {1138 this._passCommandToAction = (value === undefined) || value;
46 unmodified lines
1185 * @param {string[]} [argv] - optional, defaults to process.argv1186 * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron1187 * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'1188 * @return {Command} `this` command for chaining876 * @api public1189 */11901191 parse(argv, parseOptions) {1192 if (argv !== undefined && !Array.isArray(argv)) {
3 unmodified lines
11961197 // Default to using process.argv1198 if (argv === undefined) {1199 argv = process.argv;888 // @ts-ignore1200 // @ts-ignore: unknown property1201 if (process.versions && process.versions.electron) {1202 parseOptions.from = 'electron';1203 }1204 }
7 unmodified lines
1212 this._scriptPath = argv[1];1213 userArgs = argv.slice(2);1214 break;1215 case 'electron':904 // @ts-ignore1216 // @ts-ignore: unknown property1217 if (process.defaultApp) {1218 this._scriptPath = argv[1];1219 userArgs = argv.slice(2);1220 } else {
5 unmodified lines
1226 break;1227 default:1228 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);1229 }918 // @ts-ignore1230 // @ts-ignore: unknown property1231 if (!this._scriptPath && process.mainModule) {920 // @ts-ignore1232 // @ts-ignore: unknown property1233 this._scriptPath = process.mainModule.filename;1234 }12351236 // Guess name, used in usage in help.
22 unmodified lines
1259 * @param {string[]} [argv]1260 * @param {Object} [parseOptions]1261 * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'1262 * @return {Promise}951 * @api public1263 */12641265 parseAsync(argv, parseOptions) {1266 this.parse(argv, parseOptions);
16 unmodified lines
12831284 // Want the entry script as the reference for command name and directory for searching for other files.1285 let scriptPath = this._scriptPath;1286 // Fallback in case not set, due to how Command created or called.976 // @ts-ignore1287 // @ts-ignore: unknown property1288 if (!scriptPath && process.mainModule) {978 // @ts-ignore1289 // @ts-ignore: unknown property1290 scriptPath = process.mainModule.filename;1291 }12921293 let baseDir;
113 unmodified lines
1407 this.args = operands.concat(unknown);14081409 if (operands && this._findCommand(operands[0])) {1410 this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1100 } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1411 } else if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {1412 if (operands.length === 1) {1413 this.help();1414 } else {1415 this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
95 unmodified lines
1511 * sub -- --unknown uuu op => [sub --unknown uuu op], []1512 *1513 * @param {String[]} argv1514 * @return {{operands: String[], unknown: String[]}}1204 * @api public1515 */15161517 parseOptions(argv) {1518 const operands = []; // operands, not options or values
87 unmodified lines
1606 /**1607 * Return an object containing options as key-value pairs1608 *1609 * @return {Object}1300 * @api public1610 */1611 opts() {1612 if (this._storeOptionsAsProperties) {1613 // Preserve original behaviour so backwards compatible when still using properties
98 unmodified lines
1712 * @param {string} str1713 * @param {string} [flags]1714 * @param {string} [description]1715 * @return {this | string} `this` command for chaining, or version string if no arguments1407 * @api public1716 */17171718 version(str, flags, description) {1719 if (str === undefined) return this._version;
12 unmodified lines
17321733 /**1734 * Set the description to `str`.1735 *1428 * @param {string} str1736 * @param {string} [str]1737 * @param {Object} [argsDescription]1738 * @return {string|Command}1431 * @api public1739 */14331740 description(str, argsDescription) {1741 if (str === undefined && argsDescription === undefined) return this._description;1742 this._description = str;1743 this._argsDescription = argsDescription;
6 unmodified lines
1750 * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.1751 *1752 * @param {string} [alias]1753 * @return {string|Command}1448 * @api public1754 */17551756 alias(alias) {1757 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
16 unmodified lines
1774 * Only the first alias is shown in the auto-generated help.1775 *1776 * @param {string[]} [aliases]1777 * @return {string[]|Command}1473 * @api public1778 */17791780 aliases(aliases) {1781 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
7 unmodified lines
1789 * Set / get the command usage `str`.1790 *1791 * @param {string} [str]1792 * @return {String|Command}1489 * @api public1793 */17941795 usage(str) {1796 if (str === undefined) {
16 unmodified lines
1813 /**1814 * Get or set the name of the command1815 *1816 * @param {string} [str]1514 * @return {String|Command}1515 * @api public1817 * @return {string|Command}1818 */18191820 name(str) {1821 if (str === undefined) return this._name;
1 unmodified line
1823 return this;1824 };18251826 /**1525 * Return prepared commands.1526 *1527 * @return {Array}1528 * @api private1529 */15301531 prepareCommands() {1532 const commandDetails = this.commands.filter((cmd) => {1533 return !cmd._hidden;1534 }).map((cmd) => {1535 const args = cmd._args.map((arg) => {1536 return humanReadableArgName(arg);1537 }).join(' ');15381539 return [1540 cmd._name +1541 (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +1542 (cmd.options.length ? ' [options]' : '') +1543 (args ? ' ' + args : ''),1544 cmd._description1545 ];1546 });15471548 if (this._lazyHasImplicitHelpCommand()) {1549 commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]);1550 }1551 return commandDetails;1552 };15531554 /**1555 * Return the largest command length.1556 *1557 * @return {number}1558 * @api private1559 */15601561 largestCommandLength() {1562 const commands = this.prepareCommands();1563 return commands.reduce((max, command) => {1564 return Math.max(max, command[0].length);1565 }, 0);1566 };15671568 /**1569 * Return the largest option length.1570 *1571 * @return {number}1572 * @api private1573 */15741575 largestOptionLength() {1576 const options = [].slice.call(this.options);1577 options.push({1578 flags: this._helpFlags1579 });15801581 return options.reduce((max, option) => {1582 return Math.max(max, option.flags.length);1583 }, 0);1584 };15851586 /**1587 * Return the largest arg length.1588 *1589 * @return {number}1590 * @api private1591 */15921593 largestArgLength() {1594 return this._args.reduce((max, arg) => {1595 return Math.max(max, arg.name.length);1596 }, 0);1597 };15981599 /**1600 * Return the pad width.1601 *1602 * @return {number}1603 * @api private1604 */16051606 padWidth() {1607 let width = this.largestOptionLength();1608 if (this._argsDescription && this._args.length) {1609 if (this.largestArgLength() > width) {1610 width = this.largestArgLength();1611 }1612 }16131614 if (this.commands && this.commands.length) {1615 if (this.largestCommandLength() > width) {1616 width = this.largestCommandLength();1617 }1618 }16191620 return width;1621 };16221623 /**1624 * Any visible options?1625 *1626 * @return {boolean}1627 * @api private1628 */1629 _hasVisibleOptions() {1630 return this._hasHelpOption || this.options.some((option) => !option.hidden);1631 }16321633 /**1634 * Return help for options.1635 *1636 * @return {string}1637 * @api private1638 */16391640 optionHelp() {1641 const width = this.padWidth();1642 const columns = process.stdout.columns || 80;1643 const descriptionWidth = columns - width - 4;1644 function padOptionDetails(flags, description) {1645 return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2);1646 };16471648 // Explicit options (including version)1649 const visibleOptions = this.options.filter((option) => !option.hidden);1650 const help = visibleOptions.map((option) => {1651 return padOptionDetails(option.flags, option.fullDescription());1652 });16531654 // Implicit help1655 const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag);1656 const showLongHelpFlag = this._hasHelpOption && !this._findOption(this._helpLongFlag);1657 if (showShortHelpFlag || showLongHelpFlag) {1658 let helpFlags = this._helpFlags;1659 if (!showShortHelpFlag) {1660 helpFlags = this._helpLongFlag;1661 } else if (!showLongHelpFlag) {1662 helpFlags = this._helpShortFlag;1663 }1664 help.push(padOptionDetails(helpFlags, this._helpDescription));1665 }16661667 return help.join('\n');1668 };16691670 /**1671 * Return command help documentation.1672 *1673 * @return {string}1674 * @api private1675 */16761677 commandHelp() {1678 if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return '';16791680 const commands = this.prepareCommands();1681 const width = this.padWidth();16821683 const columns = process.stdout.columns || 80;1684 const descriptionWidth = columns - width - 4;16851686 return [1687 'Commands:',1688 commands.map((cmd) => {1689 const desc = cmd[1] ? ' ' + cmd[1] : '';1690 return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2);1691 }).join('\n').replace(/^/gm, ' '),1692 ''1693 ].join('\n');1694 };16951696 /**1827 * Return program help documentation.1828 *1829 * @return {string}1700 * @api public1830 */18311832 helpInformation() {1704 let desc = [];1705 if (this._description) {1706 desc = [1707 this._description,1708 ''1709 ];17101711 const argsDescription = this._argsDescription;1712 if (argsDescription && this._args.length) {1713 const width = this.padWidth();1714 const columns = process.stdout.columns || 80;1715 const descriptionWidth = columns - width - 5;1716 desc.push('Arguments:');1717 this._args.forEach((arg) => {1718 desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name] || '', descriptionWidth, width + 4));1719 });1720 desc.push('');1721 }1722 }17231724 let cmdName = this._name;1725 if (this._aliases[0]) {1726 cmdName = cmdName + '|' + this._aliases[0];1727 }1728 let parentCmdNames = '';1729 for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {1730 parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;1731 }1732 const usage = [1733 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(),1734 ''1735 ];17361737 let cmds = [];1738 const commandHelp = this.commandHelp();1739 if (commandHelp) cmds = [commandHelp];17401741 let options = [];1742 if (this._hasVisibleOptions()) {1743 options = [1744 'Options:',1745 '' + this.optionHelp().replace(/^/gm, ' '),1746 ''1747 ];1748 }17491750 return usage1751 .concat(desc)1752 .concat(options)1753 .concat(cmds)1754 .join('\n');1833 const helper = this.createHelp();1834 return helper.formatHelp(this, helper);1835 };18361837 /**1838 * @api private
18 unmodified lines
1857 *1858 * Outputs built-in help, and custom text added using `.addHelpText()`.1859 *1860 * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout1781 * @api public1861 */18621863 outputHelp(contextOptions) {1864 let deprecatedCallback;
34 unmodified lines
1899 *1900 * @param {string | boolean} [flags]1901 * @param {string} [description]1902 * @return {Command} `this` command for chaining1824 * @api public1903 */19041905 helpOption(flags, description) {1906 if (typeof flags === 'boolean') {
15 unmodified lines
1922 *1923 * Outputs built-in help, and custom text added using `.addHelpText()`.1924 *1925 * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout1848 * @api public1926 */19271928 help(contextOptions) {1929 this.outputHelp(contextOptions);
51 unmodified lines
19811982exports.Command = Command;1983exports.Option = Option;1984exports.CommanderError = CommanderError;1985exports.Help = Help;19861987/**1988 * Camel-case the given `flag`1989 *
8 unmodified lines
1998 });1999}20002001/**1924 * Pad `str` to `width`.1925 *1926 * @param {string} str1927 * @param {number} width1928 * @return {string}1929 * @api private1930 */19311932function pad(str, width) {1933 const len = Math.max(0, width - str.length);1934 return str + Array(len + 1).join(' ');1935}19361937/**1938 * Wraps the given string with line breaks at the specified width while breaking1939 * words and indenting every but the first line on the left.1940 *1941 * @param {string} str1942 * @param {number} width1943 * @param {number} indent1944 * @return {string}1945 * @api private1946 */1947function wrap(str, width, indent) {1948 const regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');1949 const lines = str.match(regex) || [];1950 return lines.map((line, i) => {1951 if (line.slice(-1) === '\n') {1952 line = line.slice(0, line.length - 1);1953 }1954 return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight();1955 }).join('\n');1956}19571958/**1959 * Optionally wrap the given str to a max width of width characters per line1960 * while indenting with indent spaces. Do not wrap if insufficient width or1961 * string is manually formatted.1962 *1963 * @param {string} str1964 * @param {number} width1965 * @param {number} indent1966 * @return {string}1967 * @api private1968 */1969function optionalWrap(str, width, indent) {1970 // Detect manually wrapped and indented strings by searching for line breaks1971 // followed by multiple spaces/tabs.1972 if (str.match(/[\n]\s+/)) return str;1973 // Do not wrap to narrow columns (or can end up with a word per line).1974 const minWidth = 40;1975 if (width < minWidth) return str;19761977 return wrap(str, width, indent);1978}19791980/**2002 * Output help information if help flags specified2003 *2004 * @param {Command} cmd - command to output help for2005 * @param {Array} args - array of options to search for help flags
96 unmodified lines
modified:package.json+2 added-1 removed
21 unmodified lines
22 "lint": "eslint index.js \"tests/**/*.js\"",23 "typescript-lint": "eslint typings/*.ts",24 "test": "jest && npm run test-typings",25 "test-typings": "tsc -p tsconfig.json",26 "typescript-checkJS": "tsc --allowJS --checkJS index.js --noEmit"26 "typescript-checkJS": "tsc --allowJS --checkJS index.js --noEmit",27 "test-all": "npm run test && npm run lint && npm run typescript-lint && npm run typescript-checkJS"28 },29 "main": "index",30 "files": [31 "index.js",
22 unmodified lines
modified:Readme.md+109 added-92 removed
14 unmodified lines
15 - [Options](#options)16 - [Common option types, boolean and value](#common-option-types-boolean-and-value)17 - [Default option value](#default-option-value)18 - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)19 - [Extra option features](#extra-option-features)20 - [Custom option processing](#custom-option-processing)19 - [Required option](#required-option)20 - [Variadic option](#variadic-option)21 - [Version option](#version-option)22 - [More configuration](#more-configuration)23 - [Custom option processing](#custom-option-processing)24 - [Commands](#commands)25 - [Specify the argument syntax](#specify-the-argument-syntax)26 - [Action handler (sub)commands](#action-handler-subcommands)27 - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)28 - [Automated help](#automated-help)29 - [Custom help](#custom-help)30 - [Display help from code](#display-help-from-code)31 - [.usage and .name](#usage-and-name)31 - [.help()](#help)32 - [.outputHelp()](#outputhelp)33 - [.helpInformation()](#helpinformation)32 - [.helpOption(flags, description)](#helpoptionflags-description)33 - [.addHelpCommand()](#addhelpcommand)34 - [More configuration](#more-configuration-1)35 - [Custom event listeners](#custom-event-listeners)36 - [Bits and pieces](#bits-and-pieces)37 - [.parse() and .parseAsync()](#parse-and-parseasync)38 - [Avoiding option name clashes](#avoiding-option-name-clashes)
167 unmodified lines
206```207208For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).209211### Extra option features210### Required option211212You may specify a required (mandatory) option using `.requiredOption`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing.213214Example file: [options-required.js](./examples/options-required.js)215216```js217program218 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');219220program.parse(process.argv);221```222223```bash224$ pizza225error: required option '-c, --cheese <type>' not specified226```227228### Variadic option229230You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you231can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments232are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value233is specified in the same argument as the option then no further values are read.234235Example file: [options-variadic.js](./examples/options-variadic.js)236237```js238program239 .option('-n, --number <numbers...>', 'specify numbers')240 .option('-l, --letter [letters...]', 'specify letters');241242program.parse();243244console.log('Options: ', program.opts());245console.log('Remaining arguments: ', program.args);246```247248```bash249$ collect -n 1 2 3 --letter a b c250Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }251Remaining arguments: []252$ collect --letter=A -n80 operand253Options: { number: [ '80' ], letter: [ 'A' ] }254Remaining arguments: [ 'operand' ]255$ collect --letter -n 1 -n 2 3 -- operand256Options: { number: [ '1', '2', '3' ], letter: true }257Remaining arguments: [ 'operand' ]258```259260For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).261262### Version option263264The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.265266```js267program.version('0.0.1');268```269270```bash271$ ./examples/pizza -V2720.0.1273```274275You may change the flags and description by passing additional parameters to the `version` method, using276the same syntax for flags as the `option` method.277278```js279program.version('0.0.1', '-v, --vers', 'output the current version');280```281282### More configuration283284You can add most options using the `.option()` method, but there are some additional features available285by constructing an `Option` explicitly for less common cases.286287Example file: [options-extra.js](./examples/options-extra.js)
76 unmodified lines
364$ custom --list x,y,z365[ 'x', 'y', 'z' ]366```367297### Required option298299You may specify a required (mandatory) option using `.requiredOption`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing.300301Example file: [options-required.js](./examples/options-required.js)302303```js304program305 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');306307program.parse(process.argv);308```309310```bash311$ pizza312error: required option '-c, --cheese <type>' not specified313```314315### Variadic option316317You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you318can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments319are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value320is specified in the same argument as the option then no further values are read.321322Example file: [options-variadic.js](./examples/options-variadic.js)323324```js325program326 .option('-n, --number <numbers...>', 'specify numbers')327 .option('-l, --letter [letters...]', 'specify letters');328329program.parse();330331console.log('Options: ', program.opts());332console.log('Remaining arguments: ', program.args);333```334335```bash336$ collect -n 1 2 3 --letter a b c337Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }338Remaining arguments: []339$ collect --letter=A -n80 operand340Options: { number: [ '80' ], letter: [ 'A' ] }341Remaining arguments: [ 'operand' ]342$ collect --letter -n 1 -n 2 3 -- operand343Options: { number: [ '1', '2', '3' ], letter: true }344Remaining arguments: [ 'operand' ]345```346347For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).348349### Version option350351The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.352353```js354program.version('0.0.1');355```356357```bash358$ ./examples/pizza -V3590.0.1360```361362You may change the flags and description by passing additional parameters to the `version` method, using363the same syntax for flags as the `option` method.364365```js366program.version('0.0.1', '-v, --vers', 'output the current version');367```368368## Commands369370You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)).371
208 unmodified lines
580581- error: a boolean for whether the help is being displayed due to a usage error582- command: the Command which is displaying the help583584### Display help from code585586`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.587588`.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.589590`.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.591592### .usage and .name593594These allow you to customise the usage description in the first line of the help. The name is otherwise595deduced from the (full) program arguments. Given:
9 unmodified lines
605```Text606Usage: my-command [global options] command607```608602### .help()603604Output help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.605606### .outputHelp()607608Output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.609610### .helpInformation()611612Get the built-in command help information as a string for processing or displaying yourself.613609### .helpOption(flags, description)610616Override the default help flags and description. Pass false to disable the built-in help option.611By default every command has a help option. Override the default help flags and description. Pass false to disable the built-in help option.612613```js614program615 .helpOption('-e, --HELP', 'read more information');616```617618### .addHelpCommand()619625You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.620A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.621622You can both turn on and customise the help command by supplying the name and description:623624```js625program.addHelpCommand('assist [command]', 'show assistance');626```627628### More configuration629630The built-in help is formatted using the Help class.631You can configure the Help behaviour by modifying data properties and methods using `.configureHelp()`, or by subclassing using `.createHelp()` if you prefer.632633The data properties are:634635- `columns`: specify the wrap width, useful for unit tests636- `sortSubcommands`: sort the subcommands alphabetically637- `sortOptions`: sort the options alphabetically638639There 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.640641Example file: [configure-help.js](./examples/configure-help.js)642643```644program.configureHelp({645 sortSubcommands: true,646 subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.647});648```649650## Custom event listeners651652You can execute custom actions by listening to command and option events.653
199 unmodified lines