Expand help customisation with .addHelpText (#1296)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Add new help events * Add context for new help events * Rename and use help context * Suppress help output * Slight tidy of legacy callback handling * Shift help contextOptions up to public API * Fix some spelling errors * Start adding tests. Fix groupHelp. * Test help event order * Add tests on context * Add missing semicolon * Add context.error tests * First cut at README adding events and removing callbacks * Add typings and parameter descriptions * Change from --help to postHelp event * Update and add custom help examples * Make help listener example more realistic * Update example * Call the old callback, deprecated * First cut at .addHelp() * Change name to addHelpText * First round of tests for addHelpText * Simplify help event context, remove log * Assign write directly * Add end-to-end and context checks for addHelpText * Put back write wrapper to fix unit test * Fix write mocks for help-as-error output * Ignore falsy values for AddHelpText * Remove the help override from addHelpText as not good fit * Convert example to addHelpText * Update README * Add info about new .help param * Remove excess space * Update more examples * Remove references to override * Update docs with .addHelpText
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+476 added−100 removed
- tests:+265 added−20 removed
- other:+211 added−80 removed
Provenance
- Commit
d26a26d- Tree
f497543- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
693a40f
13 files changed+476 added−100 removed
modified:examples/custom-help+9 added-7 removed
1 #!/usr/bin/env node2 3-// This example displays some custom help text after the built-in help.3+// This example shows a simple use of addHelpText.4+// This is used as an example in the README.5 6 // const { Command } = require('commander'); // (normal include)7 const { Command } = require('../'); // include commander in git clone of commander repo8 const program = new Command();9 10 program11 .option('-f, --foo', 'enable some foo');12 12-// must be before .parse()13-program.on('--help', () => {14- console.log('');15- console.log('Example call:');16- console.log(' $ custom-help --help');17-});13+program.addHelpText('after', `14 15+Example call:16+ $ custom-help --help`);17+18 program.parse(process.argv);19+20+// Try the following:21+// node custom-help --helpadded:examples/custom-help-text.js+33 added
123456789101112131415161718192021222324252627282930313233#!/usr/bin/env node
// This example shows using addHelpText.
// const { Command } = require('commander'); // (normal include)const { Command } = require('../'); // include commander in git clone of commander repoconst program = new Command();
program.name('awesome');
program .addHelpText('beforeAll', 'A W E S O M E\n') .addHelpText('afterAll', (context) => { if (context.error) { return '\nHelp being displayed for an error'; } return '\nSee web site for further help'; });
program .command('extra') .addHelpText('before', 'Note: the extra command does not do anything') .addHelpText('after', `Examples: awesome extra --help awesome help extra`);
program.parse();
// Try the following:// node custom-help-text.js --help// node custom-help-text.js extra --help// node custom-help-text.jsmodified:examples/deploy+6 added-8 removed
25 unmodified lines26 .description('execute the given remote cmd')27 .option('-e, --exec_mode <mode>', 'Which exec mode to use')28 .action(function(cmd, options) {29 console.log('exec "%s" using %s mode', cmd, options.exec_mode);30- }).on('--help', function() {31- console.log(' Examples:');32- console.log();33- console.log(' $ deploy exec sequential');34- console.log(' $ deploy exec async');35- console.log();36- });37-30+ }).addHelpText('after', `31+Examples:32+ $ deploy exec sequential33+ $ deploy exec async`34+ );35+ 36 program.parse(process.argv);modified:examples/storeOptionsAsProperties-action.js+1 added-1 removed
12345667891031 unmodified lines#!/usr/bin/env node
// To avoid possible name clashes, you can change the default behaviour// of storing the options values as properties on the command object.// In addition, you can pass just the options to the action handler// instead of a commmand object. This allows simpler code, and is more consistent// instead of a command object. This allows simpler code, and is more consistent// with the previous behaviour so less code changes from old code.//// Example output://31 unmodified linesadded:tests/command.addHelp.test.js+231 added
1+const commander = require('../');2+3+// Using outputHelp to simplify testing.4+5+describe('program calls to addHelpText', () => {6+ let writeSpy;7+8+ beforeAll(() => {9+ writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });10+ });11+12+ afterEach(() => {13+ writeSpy.mockClear();14+ });15+16+ afterAll(() => {17+ writeSpy.mockRestore();18+ });19+20+ test('when "before" string then string before built-in help', () => {21+ const program = new commander.Command();22+ program.addHelpText('before', 'text');23+ program.outputHelp();24+ expect(writeSpy).toHaveBeenNthCalledWith(1, 'text\n');25+ expect(writeSpy).toHaveBeenNthCalledWith(2, program.helpInformation());26+ });27+28+ test('when "before" function then function result before built-in help', () => {29+ const program = new commander.Command();30+ program.addHelpText('before', () => 'text');31+ program.outputHelp();32+ expect(writeSpy).toHaveBeenNthCalledWith(1, 'text\n');33+ expect(writeSpy).toHaveBeenNthCalledWith(2, program.helpInformation());34+ });35+36+ test('when "beforeAll" string then string before built-in help', () => {37+ const program = new commander.Command();38+ program.addHelpText('beforeAll', 'text');39+ program.outputHelp();40+ expect(writeSpy).toHaveBeenNthCalledWith(1, 'text\n');41+ expect(writeSpy).toHaveBeenNthCalledWith(2, program.helpInformation());42+ });43+44+ test('when "after" string then string after built-in help', () => {45+ const program = new commander.Command();46+ program.addHelpText('after', 'text');47+ program.outputHelp();48+ expect(writeSpy).toHaveBeenNthCalledWith(1, program.helpInformation());49+ expect(writeSpy).toHaveBeenNthCalledWith(2, 'text\n');50+ });51+52+ test('when "afterAll" string then string after built-in help', () => {53+ const program = new commander.Command();54+ program.addHelpText('afterAll', 'text');55+ program.outputHelp();56+ expect(writeSpy).toHaveBeenNthCalledWith(1, program.helpInformation());57+ expect(writeSpy).toHaveBeenNthCalledWith(2, 'text\n');58+ });59+60+ test('when all the simple positions then strings in order', () => {61+ const program = new commander.Command();62+ program.addHelpText('before', 'before');63+ program.addHelpText('after', 'after');64+ program.addHelpText('beforeAll', 'beforeAll');65+ program.addHelpText('afterAll', 'afterAll');66+ program.outputHelp();67+ expect(writeSpy).toHaveBeenNthCalledWith(1, 'beforeAll\n');68+ expect(writeSpy).toHaveBeenNthCalledWith(2, 'before\n');69+ expect(writeSpy).toHaveBeenNthCalledWith(3, program.helpInformation());70+ expect(writeSpy).toHaveBeenNthCalledWith(4, 'after\n');71+ expect(writeSpy).toHaveBeenNthCalledWith(5, 'afterAll\n');72+ });73+});74+75+describe('program and subcommand calls to addHelpText', () => {76+ let writeSpy;77+78+ beforeAll(() => {79+ writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });80+ });81+82+ afterEach(() => {83+ writeSpy.mockClear();84+ });85+86+ afterAll(() => {87+ writeSpy.mockRestore();88+ });89+90+ test('when "before" on program then not called on subcommand', () => {91+ const program = new commander.Command();92+ const sub = program.command('sub');93+ const testMock = jest.fn();94+ program.addHelpText('before', testMock);95+ sub.outputHelp();96+ expect(testMock).not.toHaveBeenCalled();97+ });98+99+ test('when "beforeAll" on program then is called on subcommand', () => {100+ const program = new commander.Command();101+ const sub = program.command('sub');102+ const testMock = jest.fn();103+ program.addHelpText('beforeAll', testMock);104+ sub.outputHelp();105+ expect(testMock).toHaveBeenCalled();106+ });107+108+ test('when "after" on program then not called on subcommand', () => {109+ const program = new commander.Command();110+ const sub = program.command('sub');111+ const testMock = jest.fn();112+ program.addHelpText('after', testMock);113+ sub.outputHelp();114+ expect(testMock).not.toHaveBeenCalled();115+ });116+117+ test('when "afterAll" on program then is called on subcommand', () => {118+ const program = new commander.Command();119+ const sub = program.command('sub');120+ const testMock = jest.fn();121+ program.addHelpText('afterAll', testMock);122+ sub.outputHelp();123+ expect(testMock).toHaveBeenCalled();124+ });125+});126+127+describe('context checks with full parse', () => {128+ let stdoutSpy;129+ let stderrSpy;130+131+ beforeAll(() => {132+ stdoutSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });133+ stderrSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });134+ });135+136+ afterEach(() => {137+ stdoutSpy.mockClear();138+ stderrSpy.mockClear();139+ });140+141+ afterAll(() => {142+ stdoutSpy.mockRestore();143+ stderrSpy.mockRestore();144+ });145+146+ test('when help requested then text is on stdout', () => {147+ const program = new commander.Command();148+ program149+ .exitOverride()150+ .addHelpText('before', 'text');151+ expect(() => {152+ program.parse(['--help'], { from: 'user' });153+ }).toThrow();154+ expect(stdoutSpy).toHaveBeenCalledWith('text\n');155+ });156+157+ test('when help for error then text is on stderr', () => {158+ const program = new commander.Command();159+ program160+ .exitOverride()161+ .addHelpText('before', 'text')162+ .command('sub');163+ expect(() => {164+ program.parse([], { from: 'user' });165+ }).toThrow();166+ expect(stderrSpy).toHaveBeenCalledWith('text\n');167+ });168+169+ test('when help requested then context.error is false', () => {170+ let context = {};171+ const program = new commander.Command();172+ program173+ .exitOverride()174+ .addHelpText('before', (contextParam) => { context = contextParam; });175+ expect(() => {176+ program.parse(['--help'], { from: 'user' });177+ }).toThrow();178+ expect(context.error).toBe(false);179+ });180+181+ test('when help for error then context.error is true', () => {182+ let context = {};183+ const program = new commander.Command();184+ program185+ .exitOverride()186+ .addHelpText('before', (contextParam) => { context = contextParam; })187+ .command('sub');188+ expect(() => {189+ program.parse([], { from: 'user' });190+ }).toThrow();191+ expect(context.error).toBe(true);192+ });193+194+ test('when help on program then context.command is program', () => {195+ let context = {};196+ const program = new commander.Command();197+ program198+ .exitOverride()199+ .addHelpText('before', (contextParam) => { context = contextParam; });200+ expect(() => {201+ program.parse(['--help'], { from: 'user' });202+ }).toThrow();203+ expect(context.command).toBe(program);204+ });205+206+ test('when help on subcommand and "before" subcommand then context.command is subcommand', () => {207+ let context = {};208+ const program = new commander.Command();209+ program210+ .exitOverride();211+ const sub = program.command('sub')212+ .addHelpText('before', (contextParam) => { context = contextParam; });213+ expect(() => {214+ program.parse(['sub', '--help'], { from: 'user' });215+ }).toThrow();216+ expect(context.command).toBe(sub);217+ });218+219+ test('when help on subcommand and "beforeAll" on program then context.command is subcommand', () => {220+ let context = {};221+ const program = new commander.Command();222+ program223+ .exitOverride()224+ .addHelpText('beforeAll', (contextParam) => { context = contextParam; });225+ const sub = program.command('sub');226+ expect(() => {227+ program.parse(['sub', '--help'], { from: 'user' });228+ }).toThrow();229+ expect(context.command).toBe(sub);230+ });231+});modified:tests/command.asterisk.test.js+2 added-11 removed
9 unmodified lines1011121314151617181920212223241415161718194 unmodified lines24252627282930313277 unmodified lines9 unmodified lines//// Historical: the event 'command:*' used to also be shared by the action handler on the program.
describe(".command('*')", () => { // Use internal knowledge to suppress output to keep test output clean. let writeMock;
beforeAll(() => { writeMock = jest.spyOn(process.stdout, 'write').mockImplementation(() => { }); });
afterAll(() => { writeMock.mockRestore(); });
test('when no arguments then asterisk action not called', () => { const writeMock = jest.spyOn(process.stderr, 'write').mockImplementation(() => { }); const mockAction = jest.fn(); const program = new commander.Command(); program .exitOverride() // to catch help4 unmodified lines } catch (err) { ; } expect(mockAction).not.toHaveBeenCalled(); writeMock.mockRestore(); });
test('when unrecognised argument then asterisk action called', () => { const mockAction = jest.fn();77 unmodified linesmodified:tests/command.executableSubcommand.test.js+2 added-2 removed
123456678891011125 unmodified linesconst commander = require('../');
// Executable subcommand tests that didn't fit in elsewhere.
// This is the default behaviour when no default command and no action handlerstest('when no command missing then display help', () => {test('when no command specified and executable then display help', () => { // Optional. Suppress normal output to keep test output clean. const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { }); const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { }); const program = new commander.Command(); program .exitOverride((err) => { throw err; }) .command('install', 'install description');5 unmodified linesmodified:tests/command.exitOverride.test.js+6 added-7 removed
16 unmodified lines17 18 describe('.exitOverride and error details', () => {19 // Use internal knowledge to suppress output to keep test output clean.20 let consoleErrorSpy;21- let writeSpy; // used for help [sic] and version21 22 beforeAll(() => {23 consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });25- writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });24 });25 26 afterEach(() => {27 consoleErrorSpy.mockClear();30- writeSpy.mockClear();28 });29 30 afterAll(() => {31 consoleErrorSpy.mockRestore();35- writeSpy.mockRestore();32 });33 34 test('when specify unknown program option then throw CommanderError', () => {35 const program = new commander.Command();84 unmodified lines120 expectCommanderError(caughtErr, 1, 'commander.missingArgument', "error: missing required argument 'arg-name'");121 });122 123 test('when specify --help then throw CommanderError', () => {124+ const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });125 const program = new commander.Command();126 program127 .exitOverride();128 3 unmodified lines132 } catch (err) {133 caughtErr = err;134 }135 139- expect(writeSpy).toHaveBeenCalled();136 expectCommanderError(caughtErr, 0, 'commander.helpDisplayed', '(outputHelp)');137+ writeSpy.mockRestore();138 });139 140 test('when executable subcommand and no command specified then throw CommanderError', () => {141+ const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });142 const program = new commander.Command();143 program144 .exitOverride()145 .command('compress', 'compress description');4 unmodified lines150 } catch (err) {151 caughtErr = err;152 }153 156- expect(writeSpy).toHaveBeenCalled();154 expectCommanderError(caughtErr, 1, 'commander.help', '(outputHelp)');155+ writeSpy.mockRestore();156 });157 158 test('when specify --version then throw CommanderError', () => {159+ const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });160 const myVersion = '1.2.3';161 const program = new commander.Command();162 program163 .exitOverride()5 unmodified lines169 } catch (err) {170 caughtErr = err;171 }172 174- expect(writeSpy).toHaveBeenCalled();173 expectCommanderError(caughtErr, 0, 'commander.version', myVersion);174+ writeSpy.mockRestore();175 });176 177 test('when executableSubcommand succeeds then call exitOverride', async() => {178 expect.hasAssertions();30 unmodified linesmodified:tests/command.help.test.js+24 added
129 unmodified lines130 const helpInformation = program.helpInformation();131 expect(helpInformation).not.toMatch('display help');132 });133 134+test('when call .help then output on stdout', () => {135+ const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });136+ const program = new commander.Command();137+ program138+ .exitOverride();139+ expect(() => {140+ program.help();141+ }).toThrow('(outputHelp)');142+ expect(writeSpy).toHaveBeenCalledWith(program.helpInformation());143+ writeSpy.mockClear();144+});145+146+test('when call .help with { error: true } then output on stderr', () => {147+ const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });148+ const program = new commander.Command();149+ program150+ .exitOverride();151+ expect(() => {152+ program.help({ error: true });153+ }).toThrow('(outputHelp)');154+ expect(writeSpy).toHaveBeenCalledWith(program.helpInformation());155+ writeSpy.mockClear();156+});157+158 test('when no options then Options not includes in helpInformation', () => {159 const program = new commander.Command();160 // No custom options, no version option, no help option161 program4 unmodified linesmodified:typings/commander-tests.ts+16 added-3 removed
185 unmodified lines186 const nameValue: string = program.name();187 188 // outputHelp189 program.outputHelp();190-program.outputHelp((str: string) => { return str; });190+program.outputHelp((str: string) => { return str; }); // deprecated191+program.outputHelp({ error: true });192 193 // help194 program.help();194-program.help((str: string) => { return str; });195+program.help((str: string) => { return str; }); // Deprecated196+program.help({ error: true });197 198 // helpInformation199 const helpInformnationValue: string = program.helpInformation();200 2 unmodified lines203 const helpOptionThis2: commander.Command = program.helpOption('-h,--help', 'custom description');204 const helpOptionThis3: commander.Command = program.helpOption(undefined, 'custom description');205 const helpOptionThis4: commander.Command = program.helpOption(false);206 207+// addHelpText208+const addHelpTextThis1: commander.Command = program.addHelpText('after', 'text');209+const addHelpTextThis2: commander.Command = program.addHelpText('afterAll', 'text');210+const addHelpTextThis3: commander.Command = program.addHelpText('before', () => 'before');211+const addHelpTextThis4: commander.Command = program.addHelpText('beforeAll', (context: commander.AddHelpTextContext) => {212+ if (context.error) {213+ return; // Can return nothing to skip display214+ }215+ return context.command.name();216+});217+218 // on206-const onThis: commander.Command = program.on('--help', () => {219+const onThis: commander.Command = program.on('command:foo', () => {220 // do nothing.221 });222 223 // createCommand17 unmodified linesmodified:typings/index.d.ts+26 added-10 removed
24 unmodified lines25 26 interface ParseOptions {27 from: 'node' | 'electron' | 'user';28 }29+ interface HelpContext { // optional parameter for .help() and .outputHelp()30+ error: boolean;31+ }32+ interface AddHelpTextContext { // passed to text function used with .addHelpText()33+ error: boolean;34+ command: Command;35+ }36 37+ type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';38+39 interface Command {40 [key: string]: any; // options as properties41 42 args: string[];300 unmodified lines343 344 /**345 * Output help information for this command.346 *338- * When listener(s) are available for the helpLongFlag339- * those callbacks are invoked.347+ * Outputs built-in help, and custom text added using `.addHelpText()`.348+ *349 */341- outputHelp(cb?: (str: string) => string): void;350+ outputHelp(context?: HelpContext): void;351+ outputHelp(cb?: (str: string) => string): void; // callback deprecated352 353 /**354 * Return command help documentation.355 */7 unmodified lines363 helpOption(flags?: string | boolean, description?: string): this;364 365 /**366 * Output help information and exit.367+ *368+ * Outputs built-in help, and custom text added using `.addHelpText()`.369 */358- help(cb?: (str: string) => string): never;370+ help(context?: HelpContext): never;371+ help(cb?: (str: string) => string): never; // callback deprecated372 373 /**361- * Add a listener (callback) for when events occur. (Implemented using EventEmitter.)374+ * Add additional text to be displayed with the built-in help.375 *363- * @example364- * program365- * .on('--help', () -> {366- * console.log('See web site for more information.');367- * });376+ * Position is 'before' or 'after' to affect just this command,377+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.378 */379+ addHelpText(position: AddHelpTextPosition, text: string): this;380+ addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string | void): this;381+382+ /**383+ * Add a listener (callback) for when events occur. (Implemented using EventEmitter.)384+ */385 on(event: string | symbol, listener: (...args: any[]) => void): this;386 }387 type CommandConstructor = new (name?: string) => Command;388 27 unmodified linesmodified:index.js+89 added-28 removed
943 unmodified lines944 * @api private945 */946 _dispatchSubcommand(commandName, operands, unknown) {947 const subCommand = this._findCommand(commandName);948- if (!subCommand) this._helpAndError();948+ if (!subCommand) this.help({ error: true });949 950 if (subCommand._executableHandler) {951 this._executeSubCommand(subCommand, operands.concat(unknown));952 } else {26 unmodified lines979 this._dispatchSubcommand(this._defaultCommandName, operands, unknown);980 } else {981 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {982 // probably missing subcommand and no handler, user needs help983- this._helpAndError();983+ this.help({ error: true });984 }985 986 outputHelpIfRequested(this, parsed.unknown);987 this._checkForMissingMandatoryOptions();22 unmodified lines1010 this.unknownCommand();1011 }1012 } else if (this.commands.length) {1013 // This command has subcommands and nothing hooked up at this level, so display help.1014- this._helpAndError();1014+ this.help({ error: true });1015 } else {1016 // fall through for caller to handle after calling .parse()1017 }1018 }598 unmodified lines1617 .join('\n');1618 };1619 1620 /**1621+ * @api private1622+ */1623+1624+ _getHelpContext(contextOptions) {1625+ contextOptions = contextOptions || {};1626+ const context = { error: !!contextOptions.error };1627+ let write;1628+ if (context.error) {1629+ write = (...args) => process.stderr.write(...args);1630+ } else {1631+ write = (...args) => process.stdout.write(...args);1632+ }1633+ context.write = contextOptions.write || write;1634+ context.command = this;1635+ return context;1636+ }1637+1638+ /**1639 * Output help information for this command.1640 *1623- * When listener(s) are available for the helpLongFlag1624- * those callbacks are invoked.1641+ * Outputs built-in help, and custom text added using `.addHelpText()`.1642 *1643 * @api public1644+ * @param {Object} [contextOptions] - Can optionally pass in `{ error: true }` to write to stderr1645 */1646 1629- outputHelp(cb) {1630- if (!cb) {1631- cb = (passthru) => {1632- return passthru;1633- };1647+ outputHelp(contextOptions) {1648+ let deprecatedCallback;1649+ if (typeof contextOptions === 'function') {1650+ deprecatedCallback = contextOptions;1651+ contextOptions = {};1652 }1635- const cbOutput = cb(this.helpInformation());1636- if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) {1637- throw new Error('outputHelp callback must return a string or a Buffer');1653+ const context = this._getHelpContext(contextOptions);1654+1655+ const groupListeners = [];1656+ let command = this;1657+ while (command) {1658+ groupListeners.push(command); // ordered from current command to root1659+ command = command.parent;1660 }1639- process.stdout.write(cbOutput);1640- this.emit(this._helpLongFlag);1661+1662+ groupListeners.slice().reverse().forEach(command => command.emit('beforeAllHelp', context));1663+ this.emit('beforeHelp', context);1664+1665+ let helpInformation = this.helpInformation();1666+ if (deprecatedCallback) {1667+ helpInformation = deprecatedCallback(helpInformation);1668+ if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {1669+ throw new Error('outputHelp callback must return a string or a Buffer');1670+ }1671+ }1672+ context.write(helpInformation);1673+1674+ this.emit(this._helpLongFlag); // deprecated1675+ this.emit('afterHelp', context);1676+ groupListeners.forEach(command => command.emit('afterAllHelp', context));1677 };1678 1679 /**1680 * You can pass in flags and a description to override the help23 unmodified lines1704 1705 /**1706 * Output help information and exit.1707 *1672- * @param {Function} [cb]1708+ * Outputs built-in help, and custom text added using `.addHelpText()`.1709+ *1710+ * @param {Object} [contextOptions] - optionally pass in `{ error: true }` to write to stderr1711 * @api public1712 */1713 1676- help(cb) {1677- this.outputHelp(cb);1678- // exitCode: preserving original behaviour which was calling process.exit()1714+ help(contextOptions) {1715+ this.outputHelp(contextOptions);1716+ let exitCode = process.exitCode || 0;1717+ if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {1718+ exitCode = 1;1719+ }1720 // message: do not have all displayed text available so only passing placeholder.1680- this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)');1721+ this._exit(exitCode, 'commander.help', '(outputHelp)');1722 };1723 1724 /**1684- * Output help information and exit. Display for error situations.1725+ * Add additional text to be displayed with the built-in help.1726 *1686- * @api private1727+ * Position is 'before' or 'after' to affect just this command,1728+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.1729+ *1730+ * @param {string} position - before or after built-in help1731+ * @param {string | Function} text - string to add, or a function returning a string1732+ * @return {Command} `this` command for chaining1733 */1688-1689- _helpAndError() {1690- this.outputHelp();1691- // message: do not have all displayed text available so only passing placeholder.1692- this._exit(1, 'commander.help', '(outputHelp)');1693- };1734+ addHelpText(position, text) {1735+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];1736+ if (!allowedValues.includes(position)) {1737+ throw new Error(`Unexpected value for position to addHelpText.1738+Expecting one of '${allowedValues.join("', '")}'`);1739+ }1740+ const helpEvent = `${position}Help`;1741+ this.on(helpEvent, (context) => {1742+ let helpStr;1743+ if (typeof text === 'function') {1744+ helpStr = text({ error: context.error, command: context.command });1745+ } else {1746+ helpStr = text;1747+ }1748+ // Ignore falsy value when nothing to output.1749+ if (helpStr) {1750+ context.write(`${helpStr}\n`);1751+ }1752+ });1753+ return this;1754+ }1755 };1756 1757 /**1758 * Expose the root command.185 unmodified linesmodified:Readme.md+31 added-23 removed
25 unmodified lines26 - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)27 - [Automated help](#automated-help)28 - [Custom help](#custom-help)29 - [.usage and .name](#usage-and-name)30- - [.help(cb)](#helpcb)31- - [.outputHelp(cb)](#outputhelpcb)30+ - [.help()](#help)31+ - [.outputHelp()](#outputhelp)32 - [.helpInformation()](#helpinformation)33 - [.helpOption(flags, description)](#helpoptionflags-description)34 - [.addHelpCommand()](#addhelpcommand)35 - [Custom event listeners](#custom-event-listeners)460 unmodified lines496 ```497 498 ### Custom help499 500-You can display extra information by listening for "--help".500+You can add extra text to be displayed along with the built-in help. 501 502 Example file: [custom-help](./examples/custom-help)503 504 ```js505 program506 .option('-f, --foo', 'enable some foo');507 508-// must be before .parse()509-program.on('--help', () => {510- console.log('');511- console.log('Example call:');512- console.log(' $ custom-help --help');513-});508+program.addHelpText('after', `509+510+Example call:511+ $ custom-help --help`);512 ```513 514 Yields the following help output:515 7 unmodified lines523 Example call:524 $ custom-help --help525 ```526 527+The positions in order displayed are:528+529+- `beforeAll`: add to the program for a global banner or header530+- `before`: display extra information before built-in help531+- `after`: display extra information after built-in help532+- `afterAll`: add to the program for a global footer (epilog)533+534+The positions "beforeAll" and "afterAll" apply to the command and all its subcommands. 535+536+The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are:537+538+- error: a boolean for whether the help is being displayed due to a usage error539+- command: the Command which is displaying the help540+541 ### .usage and .name542 543 These allow you to customise the usage description in the first line of the help. The name is otherwise544 deduced from the (full) program arguments. Given:9 unmodified lines554 ```Text555 Usage: my-command [global options] command556 ```557 546-### .help(cb)558+### .help()559 548-Output help information and exit immediately. Optional callback cb allows post-processing of help text before it is displayed.560+Output help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.561 550-### .outputHelp(cb)562+### .outputHelp()563 552-Output help information without exiting.553-Optional callback cb allows post-processing of help text before it is displayed.564+Output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.565 566 ### .helpInformation()567 557-Get the command help information as a string for processing or displaying yourself. (The text does not include the custom help558-from `--help` listeners.)568+Get the built-in command help information as a string for processing or displaying yourself.569 570 ### .helpOption(flags, description)571 572 Override the default help flags and description. Pass false to disable the built-in help option.185 unmodified lines758 .description('execute the given remote cmd')759 .option("-e, --exec_mode <mode>", "Which exec mode to use")760 .action(function(cmd, options){761 console.log('exec "%s" using %s mode', cmd, options.exec_mode);752- }).on('--help', function() {753- console.log('');754- console.log('Examples:');755- console.log('');756- console.log(' $ deploy exec sequential');757- console.log(' $ deploy exec async');758- });762+ }).addHelpText('after', `763+Examples:764+ $ deploy exec sequential765+ $ deploy exec async`766+ );767 768 program.parse(process.argv);769 ```770 14 unmodified lines