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
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
Provenance
- Commit
19ae912- Tree
a0182b6- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
b0c5884
28 files changed+1439 added−585 removed
added:examples/configure-help.js+24 added
123456789101112131415161718192021222324// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repo
const program = new commander.Command();
// This example shows a simple use of configureHelp.// This is used as an example in the README.
program.configureHelp({ sortSubcommands: true, subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.});
program.command('zebra <herd-size>', 'African equines with distinctive black-and-white striped coats');program.command('aardvark [colour]', 'medium-sized, burrowing, nocturnal mammal');program .command('beaver', 'large, semiaquatic rodent') .option('--pond') .option('--river');
program.parse();
// Try the following:// node configure-help.js --helpmodified:tests/command.chain.test.js+6 added
127 unmodified linesExpand all128129130131132133134135136137138127 unmodified linesExpand all const program = new Command(); const result = program.addHelpText('before', 'example'); expect(result).toBe(program); });
test('when call .configureHelp() then returns this', () => { const program = new Command(); const result = program.configureHelp({ }); expect(result).toBe(program); });});modified:tests/command.commandHelp.test.js+5 added-5 removed
123345567899101112131314151617171819const commander = require('../');
// Note: .commandHelp is not currently documented in the README. This is a ported legacy test.// This is a ported legacy test.
test('when program has command then appears in commandHelp', () => {test('when program has command then appears in help', () => { const program = new commander.Command(); program .command('bare'); const commandHelp = program.commandHelp(); const commandHelp = program.helpInformation(); expect(commandHelp).toMatch(/Commands:\n +bare\n/);});
test('when program has command with optional arg then appears in commandHelp', () => {test('when program has command with optional arg then appears in help', () => { const program = new commander.Command(); program .command('bare [bare-arg]'); const commandHelp = program.commandHelp(); const commandHelp = program.helpInformation(); expect(commandHelp).toMatch(/Commands:\n +bare \[bare-arg\]\n/);});added:tests/command.configureHelp.test.js+31 added
12345678910111213141516171819202122232425262728293031const commander = require('../');
test('when configure program then affects program helpInformation', () => { const program = new commander.Command(); program.configureHelp({ formatHelp: () => { return 'custom'; } }); expect(program.helpInformation()).toEqual('custom');});
test('when configure program then affects subcommand helpInformation', () => { const program = new commander.Command(); program.configureHelp({ formatHelp: () => { return 'custom'; } }); const sub = program.command('sub'); expect(sub.helpInformation()).toEqual('custom');});
test('when configure with unknown property then createHelp has unknown property', () => { const program = new commander.Command(); program.configureHelp({ mySecretValue: 'secret' }); expect(program.createHelp().mySecretValue).toEqual('secret');});
test('when configure with unknown property then helper passed to formatHelp has unknown property', () => { const program = new commander.Command(); program.configureHelp({ mySecretValue: 'secret', formatHelp: (cmd, helper) => { return helper.mySecretValue; } }); expect(program.helpInformation()).toEqual('secret');});added:tests/command.createHelp.test.js+18 added
123456789101112131415161718const commander = require('../');
test('when override createCommand then affects help', () => { class MyHelp extends commander.Help { formatHelp(cmd, helper) { return 'custom'; } }
class MyCommand extends commander.Command { createHelp() { return Object.assign(new MyHelp(), this.configureHelp()); }; }
const program = new MyCommand(); expect(program.helpInformation()).toEqual('custom');});modified:tests/command.helpCommand.test.js+2 added-2 removed
29 unmodified lines30 });31 32 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 });39 40 describe('help command processed on correct command', () => {60 unmodified linesadded:tests/help.columns.test.js+22 added
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });15+16+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });12+13+ 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
1+const commander = require('../');2+3+// 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).5+6+// subcommandTerm does not currently respect helpOption or ignore hidden options, so not testing those.7+describe('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+ });13+14+ 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+ });20+21+ 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+ });27+28+ 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+ });34+35+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });13+14+ 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+ });21+22+ 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+ });30+31+ 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+ });40+41+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });12+13+ 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+ });20+21+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });12+13+ 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+ });22+23+ 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+ });32+33+ 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+ });44+45+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });13+14+ 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+ });19+20+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });12+13+ 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+ });19+20+ 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+ });26+27+ 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+ });34+35+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });13+14+ 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+ });20+21+ 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+ });27+28+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });19+20+ 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+ });32+33+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });17+18+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });17+18+ 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+ });29+30+ 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+ });41+42+ 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+ });54+55+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });12+13+ 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+ });19+20+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });12+13+ 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+ });21+22+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });13+14+ 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+ });20+21+ 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+ });28+29+ 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+});39+40+describe('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+ });47+48+ 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+ });55+56+ 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+ });63+64+ 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
1+const commander = require('../');2+3+// 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).5+6+describe('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+ });13+14+ 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+ });21+22+ 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+ });29+30+ 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+ });36+37+ 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+ });43+44+ 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+});51+52+describe('wrapping by formatHelp', () => {53+ // Test auto wrap and indent with some manual strings.54+ // Fragile tests with complete help output.55+56+ 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');61+62+ const expectedOutput =63+`Usage: [options]64+65+Options: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+`;71+72+ expect(program.helpInformation()).toBe(expectedOutput);73+ });74+75+ 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');80+81+ const expectedOutput =82+`Usage: [options]83+84+Options:85+ -x --extra-long-option <value> kjsahdkajshkahd kajhsd akhds (default: "aaa86+ bbb ccc ddd eee fff ggg")87+ -h, --help display help for command88+`;89+90+ expect(program.helpInformation()).toBe(expectedOutput);91+ });92+93+ 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.');99+100+ const expectedOutput =101+`Usage: [options] [command]102+103+Options:104+ -x --extra-long-option-switch x105+ -h, --help display help for command106+107+Commands:108+ alpha Lorem mollit quis dolor ex do eu quis ad insa109+ a commodo esse.110+ help [command] display help for command111+`;112+113+ expect(program.helpInformation()).toBe(expectedOutput);114+ });115+116+ 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);123+124+ const expectedOutput =125+`Usage: [options] [command]126+127+Options:128+ -h, --help display help for command129+130+Commands:131+ 1234567801234567890x ${commandDescription}132+ help [command] display help for command133+`;134+135+ expect(program.helpInformation()).toBe(expectedOutput);136+ });137+138+ 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 time145+146+Time can also be specified using special values:147+ "dawn" - From night to sunrise.148+`);149+150+ const expectedOutput =151+`Usage: [options]152+153+Options: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+`;161+162+ expect(program.helpInformation()).toBe(expectedOutput);163+ });164+});deleted:tests/helpwrap.test.js-125 removed
1-const commander = require('../');2-3-// Test auto wrap and indent with some manual strings.4-// Fragile tests with complete help output.5-6-test('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');12-13- const expectedOutput =14-`Usage: [options]15-16-Options: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-`;22-23- expect(program.helpInformation()).toBe(expectedOutput);24- process.stdout.columns = oldColumns;25-});26-27-test('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');33-34- const expectedOutput =35-`Usage: [options]36-37-Options:38- -x --extra-long-option <value> kjsahdkajshkahd kajhsd akhds (default: "aaa39- bbb ccc ddd eee fff ggg")40- -h, --help display help for command41-`;42-43- expect(program.helpInformation()).toBe(expectedOutput);44- process.stdout.columns = oldColumns;45-});46-47-test('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.');54-55- const expectedOutput =56-`Usage: [options] [command]57-58-Options:59- -x --extra-long-option-switch x60- -h, --help display help for command61-62-Commands:63- alpha Lorem mollit quis dolor ex do eu quis ad64- insa a commodo esse.65- help [command] display help for command66-`;67-68- expect(program.helpInformation()).toBe(expectedOutput);69- process.stdout.columns = oldColumns;70-});71-72-test('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);80-81- const expectedOutput =82-`Usage: [options] [command]83-84-Options:85- -h, --help display help for command86-87-Commands:88- 1234567801234567890x ${commandDescription}89- help [command] display help for command90-`;91-92- expect(program.helpInformation()).toBe(expectedOutput);93- process.stdout.columns = oldColumns;94-});95-96-test('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 time104-105-Time can also be specified using special values:106- "dawn" - From night to sunrise.107-`);108-109- const expectedOutput =110-`Usage: [options]111-112-Options: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-`;120-121- expect(program.helpInformation()).toBe(expectedOutput);122- process.stdout.columns = oldColumns;123-});124-125-// test for argsDescription passed to command ????modified:typings/commander-tests.ts+38 added
242 unmodified lines243 myProgram.myFunction();244 const mySub = myProgram.command('sub');245 mySub.myFunction();246 247+// configureHelp248+249+const createHelpInstance: commander.Help = program.createHelp();250+const configureHelpThis: commander.Command = program.configureHelp({251+ sortSubcommands: true, // override property252+ visibleCommands: (cmd: commander.Command) => [] // override method253+});254+const helpConfiguration: commander.HelpConfiguration = program.configureHelp();255+256+// Help257+const helper = new commander.Help();258+const helperCommand = new commander.Command();259+const helperOption = new commander.Option('-a, --all');260+261+helper.columns = 3;262+helper.sortSubcommands = true;263+helper.sortOptions = false;264+265+const subcommandTermStr: string = helper.subcommandTerm(helperCommand);266+const commandUsageStr: string = helper.commandUsage(helperCommand);267+const commandDescriptionStr: string = helper.commandDescription(helperCommand);268+const subcommandDescriptionStr: string = helper.subcommandDescription(helperCommand);269+const optionTermStr: string = helper.optionTerm(helperOption);270+const optionDescriptionStr: string = helper.optionDescription(helperOption);271+272+const visibleCommands: commander.Command[] = helper.visibleCommands(helperCommand);273+const visibleOptions: commander.Option[] = helper.visibleOptions(helperCommand);274+const visibleArguments: Array<{ term: string; description: string}> = helper.visibleArguments(helperCommand);275+276+const widestCommand: number = helper.longestSubcommandTermLength(helperCommand, helper);277+const widestOption: number = helper.longestOptionTermLength(helperCommand, helper);278+const widestArgument: number = helper.longestArgumentTermLength(helperCommand, helper);279+const widest: number = helper.padWidth(helperCommand, helper);280+281+const wrapped: string = helper.wrap('a b c', 50, 3);282+283+const formatted: string = helper.formatHelp(helperCommand, helper);284+285 // Option methods286 287 const baseOption = new commander.Option('-f,--foo', 'foo description');288 30 unmodified linesmodified:typings/index.d.ts+64 added
70 unmodified lines71 name(): string;72 }73 type OptionConstructor = new (flags: string, description?: string) => Option;74 75+ interface Help {76+ /** output columns, long lines are wrapped to fit */77+ columns: number;78+ sortSubcommands: boolean;79+ sortOptions: boolean;80+81+ /** 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;89+90+ /** 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;94+95+ /** 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}>;101+102+ /** 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;110+111+ /**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;117+118+ /** Generate the built-in help text. */119+ formatHelp(cmd: Command, helper: Help): string;120+ }121+ type HelpConstructor = new () => Help;122+ type HelpConfiguration = Partial<Help>;123+124 interface ParseOptions {125 from: 'node' | 'electron' | 'user';126 }127 interface HelpContext { // optional parameter for .help() and .outputHelp()93 unmodified lines221 */222 exitOverride(callback?: (err: CommanderError) => never|void): this;223 224 /**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;229+230+ /**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;237+238+ /**239 * Register callback `fn` for the command.240 *241 * @example242 * program285 unmodified lines528 program: Command;529 Command: CommandConstructor;530 Option: OptionConstructor;531 CommanderError: CommanderErrorConstructor;532+ Help: HelpConstructor;533 }534 535 }536 4 unmodified linesmodified:index.js+381 added-360 removed
7 unmodified lines8 const fs = require('fs');9 10 // @ts-check11 12+// Although this is a class, methods are static in style to allow override using subclass or just functions.13+class Help {14+ constructor() {15+ this.columns = process.stdout.columns || 80;16+ this.sortSubcommands = false;17+ this.sortOptions = false;18+ }19+20+ /**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+ */26+27+ 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+ }45+46+ /**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+ */52+53+ 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+ }80+81+ /**82+ * Get an array of the arguments which have descriptions.83+ *84+ * @param {Command} cmd85+ * @returns {{ term: string, description:string }[]}86+ */87+88+ 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+ }96+97+ /**98+ * Get the command term to show in the list of subcommands.99+ *100+ * @param {Command} cmd101+ * @returns {string}102+ */103+104+ 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+ }112+113+ /**114+ * Get the option term to show in the list of options.115+ *116+ * @param {Option} option117+ * @returns {string}118+ */119+120+ optionTerm(option) {121+ return option.flags;122+ }123+124+ /**125+ * Get the longest command term length.126+ *127+ * @param {Command} cmd128+ * @param {Help} helper129+ * @returns {number}130+ */131+132+ longestSubcommandTermLength(cmd, helper) {133+ return helper.visibleCommands(cmd).reduce((max, command) => {134+ return Math.max(max, helper.subcommandTerm(command).length);135+ }, 0);136+ };137+138+ /**139+ * Get the longest option term length.140+ *141+ * @param {Command} cmd142+ * @param {Help} helper143+ * @returns {number}144+ */145+146+ longestOptionTermLength(cmd, helper) {147+ return helper.visibleOptions(cmd).reduce((max, option) => {148+ return Math.max(max, helper.optionTerm(option).length);149+ }, 0);150+ };151+152+ /**153+ * Get the longest argument term length.154+ *155+ * @param {Command} cmd156+ * @param {Help} helper157+ * @returns {number}158+ */159+160+ longestArgumentTermLength(cmd, helper) {161+ return helper.visibleArguments(cmd).reduce((max, argument) => {162+ return Math.max(max, argument.term.length);163+ }, 0);164+ };165+166+ /**167+ * Get the command usage to be displayed at the top of the built-in help.168+ *169+ * @param {Command} cmd170+ * @returns {string}171+ */172+173+ 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+ }185+186+ /**187+ * Get the description for the command.188+ *189+ * @param {Command} cmd190+ * @returns {string}191+ */192+193+ commandDescription(cmd) {194+ // @ts-ignore: overloaded return type195+ return cmd.description();196+ }197+198+ /**199+ * Get the command description to show in the list of subcommands.200+ *201+ * @param {Command} cmd202+ * @returns {string}203+ */204+205+ subcommandDescription(cmd) {206+ // @ts-ignore: overloaded return type207+ return cmd.description();208+ }209+210+ /**211+ * Get the option description to show in the list of options.212+ *213+ * @param {Option} option214+ * @return {string}215+ */216+217+ 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+ };235+236+ /**237+ * Generate the built-in help text.238+ *239+ * @param {Command} cmd240+ * @param {Help} helper241+ * @returns {string}242+ */243+244+ 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+ }260+261+ // Usage262+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];263+264+ // Description265+ const commandDescription = helper.commandDescription(cmd);266+ if (commandDescription.length > 0) {267+ output = output.concat([commandDescription, '']);268+ }269+270+ // 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+ }277+278+ // 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+ }285+286+ // 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+ }293+294+ return output.join('\n');295+ }296+297+ /**298+ * Calculate the pad width from the maximum term length.299+ *300+ * @param {Command} cmd301+ * @param {Help} helper302+ * @returns {number}303+ */304+305+ padWidth(cmd, helper) {306+ return Math.max(307+ helper.longestOptionTermLength(cmd, helper),308+ helper.longestSubcommandTermLength(cmd, helper),309+ helper.longestArgumentTermLength(cmd, helper)310+ );311+ };312+313+ /**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+ */323+324+ 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;331+332+ 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+}343+344 class Option {345 /**346 * Initialize a new `Option` with the given `flags` and `description`.347 *348 * @param {string} flags349 * @param {string} [description]18- * @api public350 */351 352 constructor(flags, description) {353 this.flags = flags;23 unmodified lines377 *378 * @param {any} value379 * @param {string} [description]380 * @return {Option}50- * @api public381 */382 383 default(value, description) {384 this.defaultValue = value;1 unmodified line386 return this;387 };388 389 /**60- * Calculate the full description, including defaultValue etc.61- *62- * @return {string}63- * @api public64- */65-66- 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- };84-85- /**390 * Set the custom handler for processing CLI option arguments into option values.391 *392 * @param {Function} [fn]393 * @return {Option}90- * @api public394 */395 396 argParser(fn) {397 this.parseArg = fn;4 unmodified lines402 * Whether the option is mandatory and must have a value after parsing.403 *404 * @param {boolean} [value]405 * @return {Option}103- * @api public406 */407 408 makeOptionMandatory(value) {409 this.mandatory = (value === undefined) || value;4 unmodified lines414 * Hide option in help.415 *416 * @param {boolean} [value]417 * @return {Option}116- * @api public418 */419 420 hideHelp(value) {421 this.hidden = (value === undefined) || value;4 unmodified lines426 * 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 lines436 * Only allow option value to be one of choices.437 *438 * @param {string[]} values439 * @return {Option}140- * @api public440 */441 442 choices(values) {443 this.argChoices = values;9 unmodified lines453 /**454 * Return option name.455 *456 * @return {string}158- * @api public457 */458 459 name() {460 if (this.long) {54 unmodified lines515 /**516 * Initialize a new `Command`.517 *518 * @param {string} [name]221- * @api public519 */520 521 constructor(name) {522 super();16 unmodified lines539 this._defaultCommandName = null;540 this._exitCallback = null;541 this._aliases = [];542 this._combineFlagAndOptionalValue = true;543+ this._description = '';544+ this._argsDescription = undefined;545 546 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 }558 559 /**560 * Define a command.18 unmodified lines579 * @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 */584 585 command(nameAndArgs, actionOptsOrExecDesc, execOpts) {586 let desc = actionOptsOrExecDesc;20 unmodified lines607 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 lines630 * create the command. You can override createCommand to customise subcommands.631 *632 * @param {string} [name]633 * @return {Command} new command334- * @api public634 */635 636 createCommand(name) {637 return new Command(name);638 };639 640 /**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+ */646+647+ createHelp() {648+ return Object.assign(new Help(), this.configureHelp());649+ };650+651+ /**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+ */658+659+ configureHelp(configuration) {660+ if (configuration === undefined) return this._helpConfiguration;661+662+ this._helpConfiguration = configuration;663+ return this;664+ }665+666+ /**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 */675 676 addCommand(cmd, opts) {677 if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');20 unmodified lines698 };699 700 /**701 * Define argument syntax for the command.378- *379- * @api public702 */703 704 arguments(desc) {705 return this._parseExpectedArgs(desc.split(/ +/));6 unmodified lines712 * 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 */717 718 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 lines733 * @return {boolean}734 * @api private735 */736 416- _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 };743 744 /**745 * Parse expected `args`.44 unmodified lines790 * 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 */795 796 exitOverride(fn) {797 if (fn) {41 unmodified lines839 * });840 *841 * @param {Function} fn842 * @return {Command} `this` command for chaining523- * @api public843 */844 845 action(fn) {846 const listener = (args) => {211 unmodified lines1058 * @param {string} description1059 * @param {Function|*} [fn] - custom option processing function or default value1060 * @param {*} [defaultValue]1061 * @return {Command} `this` command for chaining743- * @api public1062 */1063 1064 option(flags, description, fn, defaultValue) {1065 return this._optionEx({}, flags, description, fn, defaultValue);9 unmodified lines1075 * @param {string} description1076 * @param {Function|*} [fn] - custom option processing function or default value1077 * @param {*} [defaultValue]1078 * @return {Command} `this` command for chaining761- * @api public1079 */1080 1081 requiredOption(flags, description, fn, defaultValue) {1082 return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);8 unmodified lines1091 * .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 lines1102 * 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 lines1114 * 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 */1119 1120 storeOptionsAsProperties(value) {1121 this._storeOptionsAsPropertiesCalled = true;9 unmodified lines1131 * or just the options (specify false).1132 *1133 * @param {boolean} value1134 * @return {Command} `this` command for chaining821- * @api public1135 */1136 1137 passCommandToAction(value) {1138 this._passCommandToAction = (value === undefined) || value;46 unmodified lines1185 * @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 */1190 1191 parse(argv, parseOptions) {1192 if (argv !== undefined && !Array.isArray(argv)) {3 unmodified lines1196 1197 // 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 lines1212 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 lines1226 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 }1235 1236 // Guess name, used in usage in help.22 unmodified lines1259 * @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 */1264 1265 parseAsync(argv, parseOptions) {1266 this.parse(argv, parseOptions);16 unmodified lines1283 1284 // 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 }1292 1293 let baseDir;113 unmodified lines1407 this.args = operands.concat(unknown);1408 1409 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 lines1511 * sub -- --unknown uuu op => [sub --unknown uuu op], []1512 *1513 * @param {String[]} argv1514 * @return {{operands: String[], unknown: String[]}}1204- * @api public1515 */1516 1517 parseOptions(argv) {1518 const operands = []; // operands, not options or values87 unmodified lines1606 /**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 properties98 unmodified lines1712 * @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 */1717 1718 version(str, flags, description) {1719 if (str === undefined) return this._version;12 unmodified lines1732 1733 /**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 */1433-1740 description(str, argsDescription) {1741 if (str === undefined && argsDescription === undefined) return this._description;1742 this._description = str;1743 this._argsDescription = argsDescription;6 unmodified lines1750 * 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 */1755 1756 alias(alias) {1757 if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility16 unmodified lines1774 * Only the first alias is shown in the auto-generated help.1775 *1776 * @param {string[]} [aliases]1777 * @return {string[]|Command}1473- * @api public1778 */1779 1780 aliases(aliases) {1781 // Getter for the array of aliases is the main reason for having aliases() in addition to alias().7 unmodified lines1789 * Set / get the command usage `str`.1790 *1791 * @param {string} [str]1792 * @return {String|Command}1489- * @api public1793 */1794 1795 usage(str) {1796 if (str === undefined) {16 unmodified lines1813 /**1814 * Get or set the name of the command1815 *1816 * @param {string} [str]1514- * @return {String|Command}1515- * @api public1817+ * @return {string|Command}1818 */1819 1820 name(str) {1821 if (str === undefined) return this._name;1 unmodified line1823 return this;1824 };1825 1826 /**1525- * Return prepared commands.1526- *1527- * @return {Array}1528- * @api private1529- */1530-1531- 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(' ');1538-1539- return [1540- cmd._name +1541- (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +1542- (cmd.options.length ? ' [options]' : '') +1543- (args ? ' ' + args : ''),1544- cmd._description1545- ];1546- });1547-1548- if (this._lazyHasImplicitHelpCommand()) {1549- commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]);1550- }1551- return commandDetails;1552- };1553-1554- /**1555- * Return the largest command length.1556- *1557- * @return {number}1558- * @api private1559- */1560-1561- largestCommandLength() {1562- const commands = this.prepareCommands();1563- return commands.reduce((max, command) => {1564- return Math.max(max, command[0].length);1565- }, 0);1566- };1567-1568- /**1569- * Return the largest option length.1570- *1571- * @return {number}1572- * @api private1573- */1574-1575- largestOptionLength() {1576- const options = [].slice.call(this.options);1577- options.push({1578- flags: this._helpFlags1579- });1580-1581- return options.reduce((max, option) => {1582- return Math.max(max, option.flags.length);1583- }, 0);1584- };1585-1586- /**1587- * Return the largest arg length.1588- *1589- * @return {number}1590- * @api private1591- */1592-1593- largestArgLength() {1594- return this._args.reduce((max, arg) => {1595- return Math.max(max, arg.name.length);1596- }, 0);1597- };1598-1599- /**1600- * Return the pad width.1601- *1602- * @return {number}1603- * @api private1604- */1605-1606- padWidth() {1607- let width = this.largestOptionLength();1608- if (this._argsDescription && this._args.length) {1609- if (this.largestArgLength() > width) {1610- width = this.largestArgLength();1611- }1612- }1613-1614- if (this.commands && this.commands.length) {1615- if (this.largestCommandLength() > width) {1616- width = this.largestCommandLength();1617- }1618- }1619-1620- return width;1621- };1622-1623- /**1624- * Any visible options?1625- *1626- * @return {boolean}1627- * @api private1628- */1629- _hasVisibleOptions() {1630- return this._hasHelpOption || this.options.some((option) => !option.hidden);1631- }1632-1633- /**1634- * Return help for options.1635- *1636- * @return {string}1637- * @api private1638- */1639-1640- 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- };1647-1648- // 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- });1653-1654- // 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- }1666-1667- return help.join('\n');1668- };1669-1670- /**1671- * Return command help documentation.1672- *1673- * @return {string}1674- * @api private1675- */1676-1677- commandHelp() {1678- if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return '';1679-1680- const commands = this.prepareCommands();1681- const width = this.padWidth();1682-1683- const columns = process.stdout.columns || 80;1684- const descriptionWidth = columns - width - 4;1685-1686- 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- };1695-1696- /**1827 * Return program help documentation.1828 *1829 * @return {string}1700- * @api public1830 */1831 1832 helpInformation() {1704- let desc = [];1705- if (this._description) {1706- desc = [1707- this._description,1708- ''1709- ];1710-1711- 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- }1723-1724- 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- ];1736-1737- let cmds = [];1738- const commandHelp = this.commandHelp();1739- if (commandHelp) cmds = [commandHelp];1740-1741- let options = [];1742- if (this._hasVisibleOptions()) {1743- options = [1744- 'Options:',1745- '' + this.optionHelp().replace(/^/gm, ' '),1746- ''1747- ];1748- }1749-1750- 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 };1836 1837 /**1838 * @api private18 unmodified lines1857 *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 */1862 1863 outputHelp(contextOptions) {1864 let deprecatedCallback;34 unmodified lines1899 *1900 * @param {string | boolean} [flags]1901 * @param {string} [description]1902 * @return {Command} `this` command for chaining1824- * @api public1903 */1904 1905 helpOption(flags, description) {1906 if (typeof flags === 'boolean') {15 unmodified lines1922 *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 */1927 1928 help(contextOptions) {1929 this.outputHelp(contextOptions);51 unmodified lines1981 1982 exports.Command = Command;1983 exports.Option = Option;1984 exports.CommanderError = CommanderError;1985+exports.Help = Help;1986 1987 /**1988 * Camel-case the given `flag`1989 *8 unmodified lines1998 });1999 }2000 2001 /**1924- * Pad `str` to `width`.1925- *1926- * @param {string} str1927- * @param {number} width1928- * @return {string}1929- * @api private1930- */1931-1932-function pad(str, width) {1933- const len = Math.max(0, width - str.length);1934- return str + Array(len + 1).join(' ');1935-}1936-1937-/**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- */1947-function 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-}1957-1958-/**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- */1969-function 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;1976-1977- return wrap(str, width, indent);1978-}1979-1980-/**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 flags96 unmodified linesmodified:package.json+2 added-1 removed
21 unmodified lines22 "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 linesmodified:Readme.md+109 added-92 removed
14 unmodified lines15 - [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 lines206 ```207 208 For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).209 211-### Extra option features210+### Required option211 212+You 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.213+214+Example file: [options-required.js](./examples/options-required.js)215+216+```js217+program218+ .requiredOption('-c, --cheese <type>', 'pizza must have cheese');219+220+program.parse(process.argv);221+```222+223+```bash224+$ pizza225+error: required option '-c, --cheese <type>' not specified226+```227+228+### Variadic option229+230+You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you231+can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments232+are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value233+is specified in the same argument as the option then no further values are read.234+235+Example file: [options-variadic.js](./examples/options-variadic.js)236+237+```js238+program239+ .option('-n, --number <numbers...>', 'specify numbers')240+ .option('-l, --letter [letters...]', 'specify letters');241+242+program.parse();243+244+console.log('Options: ', program.opts());245+console.log('Remaining arguments: ', program.args);246+```247+248+```bash249+$ collect -n 1 2 3 --letter a b c250+Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }251+Remaining arguments: []252+$ collect --letter=A -n80 operand253+Options: { number: [ '80' ], letter: [ 'A' ] }254+Remaining arguments: [ 'operand' ]255+$ collect --letter -n 1 -n 2 3 -- operand256+Options: { number: [ '1', '2', '3' ], letter: true }257+Remaining arguments: [ 'operand' ]258+```259+260+For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).261+262+### Version option263+264+The 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.265+266+```js267+program.version('0.0.1');268+```269+270+```bash271+$ ./examples/pizza -V272+0.0.1273+```274+275+You may change the flags and description by passing additional parameters to the `version` method, using276+the same syntax for flags as the `option` method.277+278+```js279+program.version('0.0.1', '-v, --vers', 'output the current version');280+```281+282+### More configuration283+284 You can add most options using the `.option()` method, but there are some additional features available285 by constructing an `Option` explicitly for less common cases.286 287 Example file: [options-extra.js](./examples/options-extra.js)76 unmodified lines364 $ custom --list x,y,z365 [ 'x', 'y', 'z' ]366 ```367 297-### Required option298-299-You 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.300-301-Example file: [options-required.js](./examples/options-required.js)302-303-```js304-program305- .requiredOption('-c, --cheese <type>', 'pizza must have cheese');306-307-program.parse(process.argv);308-```309-310-```bash311-$ pizza312-error: required option '-c, --cheese <type>' not specified313-```314-315-### Variadic option316-317-You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you318-can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments319-are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value320-is specified in the same argument as the option then no further values are read.321-322-Example file: [options-variadic.js](./examples/options-variadic.js)323-324-```js325-program326- .option('-n, --number <numbers...>', 'specify numbers')327- .option('-l, --letter [letters...]', 'specify letters');328-329-program.parse();330-331-console.log('Options: ', program.opts());332-console.log('Remaining arguments: ', program.args);333-```334-335-```bash336-$ collect -n 1 2 3 --letter a b c337-Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }338-Remaining arguments: []339-$ collect --letter=A -n80 operand340-Options: { number: [ '80' ], letter: [ 'A' ] }341-Remaining arguments: [ 'operand' ]342-$ collect --letter -n 1 -n 2 3 -- operand343-Options: { number: [ '1', '2', '3' ], letter: true }344-Remaining arguments: [ 'operand' ]345-```346-347-For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).348-349-### Version option350-351-The 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.352-353-```js354-program.version('0.0.1');355-```356-357-```bash358-$ ./examples/pizza -V359-0.0.1360-```361-362-You may change the flags and description by passing additional parameters to the `version` method, using363-the same syntax for flags as the `option` method.364-365-```js366-program.version('0.0.1', '-v, --vers', 'output the current version');367-```368-368 ## Commands369 370 You 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 lines580 581 - error: a boolean for whether the help is being displayed due to a usage error582 - command: the Command which is displaying the help583 584+### Display help from code585+586+`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.587+588+`.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.589+590+`.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.591+592 ### .usage and .name593 594 These allow you to customise the usage description in the first line of the help. The name is otherwise595 deduced from the (full) program arguments. Given:9 unmodified lines605 ```Text606 Usage: my-command [global options] command607 ```608 602-### .help()603-604-Output help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.605-606-### .outputHelp()607-608-Output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.609-610-### .helpInformation()611-612-Get the built-in command help information as a string for processing or displaying yourself.613-609 ### .helpOption(flags, description)610 616-Override the default help flags and description. Pass false to disable the built-in help option.611+By default every command has a help option. Override the default help flags and description. Pass false to disable the built-in help option.612 613 ```js614 program615 .helpOption('-e, --HELP', 'read more information');616 ```617 618 ### .addHelpCommand()619 625-You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.620+A 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)`.621 622 You can both turn on and customise the help command by supplying the name and description:623 624 ```js625 program.addHelpCommand('assist [command]', 'show assistance');626 ```627 628+### More configuration629+630+The built-in help is formatted using the Help class.631+You can configure the Help behaviour by modifying data properties and methods using `.configureHelp()`, or by subclassing using `.createHelp()` if you prefer.632+633+The data properties are:634+635+- `columns`: specify the wrap width, useful for unit tests636+- `sortSubcommands`: sort the subcommands alphabetically637+- `sortOptions`: sort the options alphabetically638+639+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.640+641+Example file: [configure-help.js](./examples/configure-help.js)642+643+```644+program.configureHelp({645+ sortSubcommands: true,646+ subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.647+});648+```649+650 ## Custom event listeners651 652 You can execute custom actions by listening to command and option events.653 199 unmodified lines