Add a way to override help and version help message #963
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Minor edits from John Gee to typings added during squash.
authored by Ivan · committed by John Gee · parent 1c1ffca · Browse files · 8 files·+248 added−17 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+248 added−17 removed
- tests:+133 added−0 removed
- other:+115 added−17 removed
Provenance
- Commit
c61d724- Tree
4404b5f- Author
Ivan <ivan.montiel@nextiva.com>- Committer
John Gee <john@ruru.gen.nz>- Parent
1c1ffca
8 files changed+248 added−17 removed
added:examples/custom-help-description+21 added
1+#!/usr/bin/env node2+3+/**4+ * Module dependencies.5+ */6+7+var program = require('../');8+9+program10+ .helpOption('-c, --HELP', 'custom help message')11+ .option('-s, --sessions', 'add session support')12+ .option('-t, --template <engine>', 'specify template engine (jade|ejs) [jade]', 'jade');13+14+program15+ .command('child')16+ .option('--gender', 'specific gender of child')17+ .action((cmd) => {18+ console.log('Childsubcommand...');19+ });20+21+program.parse(process.argv);added:examples/custom-version+13 added
1+#!/usr/bin/env node2+3+/**4+ * Module dependencies.5+ */6+7+var program = require('../');8+9+program10+ .version('0.0.1', '-v, --VERSION', 'new version message')11+ .option('-s, --sessions', 'add session support')12+ .option('-t, --template <engine>', 'specify template engine (jade|ejs) [jade]', 'jade')13+ .parse(process.argv);added:test/test.command.helpInformation.custom.js+46 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546var program = require('../') , sinon = require('sinon').sandbox.create() , should = require('should');
sinon.stub(process, 'exit');sinon.stub(process.stdout, 'write');
program.helpOption('-c, --HELP', 'custom help output');program.command('somecommand');program.command('anothercommand [options]');
var expectedHelpInformation = [ 'Usage: [options] [command]', '', 'Options:', ' -c, --HELP custom help output', '', 'Commands:', ' somecommand', ' anothercommand [options]', ''].join('\n');
program.helpInformation().should.equal(expectedHelpInformation);
// Test argumentsvar expectedCommandHelpInformation = [ 'Usage: test [options] [command]', '', 'Options:', ' -c, --HELP custom help output', '', 'Commands:', ' somecommand', ' anothercommand [options]', ''].join('\n');
program.parse(['node', 'test', '--HELP']);
process.stdout.write.called.should.equal(true);
var output = process.stdout.write.args[0];output[0].should.equal(expectedCommandHelpInformation);
sinon.restore();added:test/test.command.helpSubCommand.customFlags.js+65 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465var program = require('../'), sinon = require('sinon').sandbox.create(), should = require('should');
sinon.stub(process, 'exit');sinon.stub(process.stdout, 'write');
// Test that subcommands inherit the help flags// but can also override help flagsprogram .helpOption('-i, --ihelp', 'foo foo');
program .command('child') .option('--gender', 'specific gender of child') .action((cmd) => { console.log('Childsubcommand...'); });
program .command('family') .helpOption('-h, --help') .action((cmd) => { console.log('Familysubcommand...'); });
// Test argumentsvar expectedCommandHelpInformation = [ 'Usage: child [options]', '', 'Options:', ' --gender specific gender of child', ' -i, --ihelp foo foo', ''].join('\n');
program.parse(['node', 'test', 'child', '-i']);
process.stdout.write.called.should.equal(true);
var output = process.stdout.write.args[0];output[0].should.equal(expectedCommandHelpInformation);
// Test other commandsinon.restore();
sinon.stub(process, 'exit');sinon.stub(process.stdout, 'write');
var expectedFamilyCommandHelpInformation = [ 'Usage: family [options]', '', 'Options:', ' -h, --help foo foo', ''].join('\n');
program.parse(['node', 'test', 'family', '-h']);
process.stdout.write.called.should.equal(true);
var output2 = process.stdout.write.args[0];output2[0].should.equal(expectedFamilyCommandHelpInformation);
sinon.restore();added:test/test.options.version.customHelpDescription.js+22 added
12345678910111213141516171819202122var program = require('../') , sinon = require('sinon').sandbox.create() , should = require('should');
program.version('1.0.0', undefined, 'custom version output');program.command('somecommand');program.command('anothercommand [options]');
var expectedHelpInformation = [ 'Usage: [options] [command]', '', 'Options:', ' -V, --version custom version output', ' -h, --help output usage information', '', 'Commands:', ' somecommand', ' anothercommand [options]', ''].join('\n');
program.helpInformation().should.equal(expectedHelpInformation);modified:typings/index.d.ts+15 added-8 removed
34 unmodified lines35 */36 constructor(name?: string);37 38 /**39- * Set the program version to `str`.39+ * Set the program version to `str`. 40 *41 * This method auto-registers the "-V, --version" flag42 * which will print the version number when passed.43+ * 44+ * You can optionally supply the flags and description to override the defaults.45 *44- * @param {string} str45- * @param {string} [flags]46- * @returns {Command} for chaining46 */48- version(str: string, flags?: string): Command;47+ version(str: string, flags?: string, description?: string): Command;48 49 /**50 * Add command `name`.51 *214 unmodified lines266 267 /**268 * Output help information for this command.269 *270+ * When listener(s) are available for the helpLongFlag271+ * those callbacks are invoked.272+ * 273 * @param {(str: string) => string} [cb]274 */275 outputHelp(cb?: (str: string) => string): void;276 275- /** Output help information and exit.276- *277- * @param {(str: string) => string} [cb]277+ /**278+ * You can pass in flags and a description to override the help279+ * flags and help description for your command.280 */281+ helpOption(flags?: string, description?: string): Command;282+283+ /** 284+ * Output help information and exit.285+ */286 help(cb?: (str: string) => string): never;287 }288 289 }28 unmodified linesmodified:index.js+51 added-9 removed
101 unmodified lines102 this._execs = {};103 this._allowUnknownOption = false;104 this._args = [];105 this._name = name || '';106+107+ this._helpFlags = '-h, --help';108+ this._helpDescription = 'output usage information';109+ this._helpShortFlag = '-h';110+ this._helpLongFlag = '--help';111 }112 113 /**114 * Add command `name`.71 unmodified lines186 this._execs[cmd._name] = true;187 if (opts.isDefault) this.defaultExecutable = cmd._name;188 }189 cmd._noHelp = !!opts.noHelp;190+ cmd._helpFlags = this._helpFlags;191+ cmd._helpDescription = this._helpDescription;192+ cmd._helpShortFlag = this._helpShortFlag;193+ cmd._helpLongFlag = this._helpLongFlag;194 this.commands.push(cmd);195 cmd.parseExpectedArgs(args);196 cmd.parent = this;197 276 unmodified lines474 475 // github-style sub-commands with no sub-command476 if (this.executables && argv.length < 3 && !this.defaultExecutable) {477 // this user needs help469- argv.push('--help');478+ argv.push(this._helpLongFlag);479 }480 481 // process argv482 var parsed = this.parseOptions(this.normalize(argv.slice(2)));44 unmodified lines527 528 // <cmd> --help529 if (args[0] === 'help') {530 args[0] = args[1];522- args[1] = '--help';531+ args[1] = this._helpLongFlag;532 }533 534 // executable535 var f = argv[1];318 unmodified lines854 *855 * This method auto-registers the "-V, --version" flag856 * which will print the version number when passed.857 *858+ * You can optionally supply the flags and description to override the defaults.859+ *860 * @param {String} str861 * @param {String} [flags]862+ * @param {String} [description]863 * @return {Command} for chaining864 * @api public865 */866 855-Command.prototype.version = function(str, flags) {867+Command.prototype.version = function(str, flags, description) {868 if (arguments.length === 0) return this._version;869 this._version = str;870 flags = flags || '-V, --version';871+ description = description || 'output the version number';859- var versionOption = new Option(flags, 'output the version number');872+ var versionOption = new Option(flags, description);873 this._versionOptionName = versionOption.long.substr(2) || 'version';874 this.options.push(versionOption);875 this.on('option:' + this._versionOptionName, function() {876 process.stdout.write(str + '\n');125 unmodified lines1002 1003 Command.prototype.largestOptionLength = function() {1004 var options = [].slice.call(this.options);1005 options.push({993- flags: '-h, --help'1006+ flags: this._helpFlags1007 });1008+1009 return options.reduce(function(max, option) {1010 return Math.max(max, option.flags.length);1011 }, 0);1012 };48 unmodified lines1061 // Append the help information1062 return this.options.map(function(option) {1063 return pad(option.flags, width) + ' ' + option.description +1064 ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');1051- }).concat([pad('-h, --help', width) + ' ' + 'output usage information'])1065+ }).concat([pad(this._helpFlags, width) + ' ' + this._helpDescription])1066 .join('\n');1067 };1068 1069 /**72 unmodified lines1142 .join('\n');1143 };1144 1145 /**1132- * Output help information for this command1146+ * Output help information for this command.1147 *1148+ * When listener(s) are available for the helpLongFlag1149+ * those callbacks are invoked.1150+ *1151 * @api public1152 */1153 1154 Command.prototype.outputHelp = function(cb) {6 unmodified lines1161 if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) {1162 throw new Error('outputHelp callback must return a string or a Buffer');1163 }1164 process.stdout.write(cbOutput);1148- this.emit('--help');1165+ this.emit(this._helpLongFlag);1166 };1167 1168 /**1169+ * You can pass in flags and a description to override the help1170+ * flags and help description for your command.1171+ *1172+ * @param {String} [flags]1173+ * @param {String} [description]1174+ * @return {Command}1175+ * @api public1176+ */1177+1178+Command.prototype.helpOption = function(flags, description) {1179+ this._helpFlags = flags || this._helpFlags;1180+ this._helpDescription = description || this._helpDescription;1181+1182+ var splitFlags = this._helpFlags.split(/[ ,|]+/);1183+1184+ if (splitFlags.length > 1) this._helpShortFlag = splitFlags.shift();1185+1186+ this._helpLongFlag = splitFlags.shift();1187+1188+ return this;1189+};1190+1191+/**1192 * Output help information and exit.1193 *1194+ * @param {Function} [cb]1195 * @api public1196 */1197 1198 Command.prototype.help = function(cb) {38 unmodified lines1237 */1238 1239 function outputHelpIfNecessary(cmd, options) {1240 options = options || [];1241+1242 for (var i = 0; i < options.length; i++) {1201- if (options[i] === '--help' || options[i] === '-h') {1243+ if (options[i] === cmd._helpLongFlag || options[i] === cmd._helpShortFlag) {1244 cmd.outputHelp();1245 process.exit(0);1246 }1247 }28 unmodified linesmodified:Readme.md+15 added
222 unmodified lines223 ```js224 program.version('0.0.1', '-v, --version');225 ```226 227+You can also override the help description for the version command.228 229+```js230+program.version('0.0.1', '-v, --version', 'output the current version');231+```232 233+234+235 ## Command-specific options236 237 You can attach options to a command.238 199 unmodified lines438 return colors.red(txt); //display the help text in red on the console439 }440 ```441 442+## .helpOption(flags, description)443+444+ Override the default help flags and description.445+446+```js447+program448+ .helpOption('-e, --HELP', 'read more information');449+```450+451 ## .help(cb)452 453 Output help information and exit immediately.454 Optional callback cb allows post-processing of help text before it is displayed.84 unmodified lines