Skip to content
Myr

Opt-in behaviour to avoid name pollution (#1102)

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

* Add object to hold option values separately from properties on command. Return directly from .opts(). * Add configureCommand, and support for passing options rather than command to action handler * Restore original opts() implementation when using old configuration * Use either/or new/old option storage, not both * Turn version test on again, old behaviour restored * Add tests for configureCommand, and fix bugs * Expand .opts tests to include modern configuration * Add TypeScript and inline documentation for configureCommand * Switch from modern:boolean to combo:string * Rework new behaviour with matching named routines. * Add example files for storeOptionsAsProperties * Add usage error, and make value default to true for new routines (so simpler call for that case) * Simpify description * Add section on avoiding option name clashes * Do not use else after a return

authored by John Gee · committed by GitHub · parent df6284c · Browse files · 11 files+407 added−49 removed
This commit

State

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

Diff stats

11 files+407 added−49 removed

  • tests:+136 added−31 removed
  • other:+271 added−18 removed

11 files+407 added−49 removed

added:examples/storeOptionsAsProperties-action.js+40 added
added:examples/storeOptionsAsProperties-opts.js+38 added
added:examples/storeOptionsAsProperties-problem.js+35 added
added:tests/commander.configureCommand.test.js+87 added
1const commander = require('../');23// Mostly testing direct on program, limited check that (sub)command working same.45// Default behaviours67test('when default then options stored on command', () => {8 const program = new commander.Command();9 program10 .option('--foo <value>', 'description');11 program.parse(['node', 'test', '--foo', 'bar']);12 expect(program.foo).toBe('bar');13});1415test('when default then command passed to action', () => {16 const program = new commander.Command();17 const callback = jest.fn();18 program19 .arguments('<value>')20 .action(callback);21 program.parse(['node', 'test', 'value']);22 expect(callback).toHaveBeenCalledWith('value', program);23});2425// storeOptionsAsProperties2627test('when storeOptionsAsProperties() then options stored on command', () => {28 const program = new commander.Command();29 program30 .storeOptionsAsProperties()31 .option('--foo <value>', 'description');32 program.parse(['node', 'test', '--foo', 'bar']);33 expect(program.foo).toBe('bar');34});3536test('when storeOptionsAsProperties(true) then options stored on command', () => {37 const program = new commander.Command();38 program39 .storeOptionsAsProperties(true)40 .option('--foo <value>', 'description');41 program.parse(['node', 'test', '--foo', 'bar']);42 expect(program.foo).toBe('bar');43});4445test('when storeOptionsAsProperties(false) then options not stored on command', () => {46 const program = new commander.Command();47 program48 .storeOptionsAsProperties(false)49 .option('--foo <value>', 'description');50 program.parse(['node', 'test', '--foo', 'bar']);51 expect(program.foo).toBeUndefined();52});5354// passCommandToAction5556test('when passCommandToAction() then command passed to action', () => {57 const program = new commander.Command();58 const callback = jest.fn();59 program60 .passCommandToAction()61 .arguments('<value>')62 .action(callback);63 program.parse(['node', 'test', 'value']);64 expect(callback).toHaveBeenCalledWith('value', program);65});6667test('when passCommandToAction(true) then command passed to action', () => {68 const program = new commander.Command();69 const callback = jest.fn();70 program71 .passCommandToAction(true)72 .arguments('<value>')73 .action(callback);74 program.parse(['node', 'test', 'value']);75 expect(callback).toHaveBeenCalledWith('value', program);76});7778test('when passCommandToAction(false) then options passed to action', () => {79 const program = new commander.Command();80 const callback = jest.fn();81 program82 .passCommandToAction(false)83 .arguments('<value>')84 .action(callback);85 program.parse(['node', 'test', 'value']);86 expect(callback).toHaveBeenCalledWith('value', program.opts());87});
modified:tests/options.opts.test.js+49 added-31 removed
modified:typings/commander-tests.ts+3 added
8 unmodified lines
9const errorInstance = new program.CommanderError(1, 'code', 'message');1011const name = program.name();1213program.storeOptionsAsProperties(true);14program.passCommandToAction(true);1516program17 .name('set name')18 .version('0.0.1')19 .option('-p, --peppers', 'Add peppers')
117 unmodified lines
modified:typings/index.d.ts+17 added
169 unmodified lines
170 */171 requiredOption(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command;172 requiredOption(flags: string, description?: string, defaultValue?: any): Command;173174175 /**176 * Whether to store option values as properties on command object,177 * or store separately (specify false). In both cases the option values can be accessed using .opts().178 *179 * @return Command for chaining180 */181 storeOptionsAsProperties(value?: boolean): Command;182183 /**184 * Whether to pass command to action handler,185 * or just the options (specify false).186 * 187 * @return Command for chaining188 */189 passCommandToAction(value?: boolean): Command;190191 /**192 * Allow unknown options on the command line.193 *194 * @param [arg] if `true` or omitted, no error will be thrown for unknown options.195 * @returns Command for chaining
107 unmodified lines
added:.eslintignore+2 added
1# We have not configured eslint for TypeScript so avoid bogus error messages in the test file and typings file.2**/*.ts
modified:.eslintrc.json+2 added-1 removed
modified:index.js+94 added-17 removed
124 unmodified lines
125 this._execs = new Set();126 this._allowUnknownOption = false;127 this._args = [];128 this._name = name || '';129 this._optionValues = {};130 this._storeOptionsAsProperties = true; // backwards compatible by default131 this._passCommandToAction = true; // backwards compatible by default132133 this._helpFlags = '-h, --help';134 this._helpDescription = 'output usage information';135 this._helpShortFlag = '-h';
49 unmodified lines
185 cmd._helpDescription = this._helpDescription;186 cmd._helpShortFlag = this._helpShortFlag;187 cmd._helpLongFlag = this._helpLongFlag;188 cmd._exitCallback = this._exitCallback;189 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;190 cmd._passCommandToAction = this._passCommandToAction;191192 cmd._executableFile = opts.executableFile; // Custom name for executable file193 this.commands.push(cmd);194 cmd.parseExpectedArgs(args);
160 unmodified lines
355356 // The .action callback takes an extra parameter which is the command itself.357 var expectedArgsCount = self._args.length;358 var actionArgs = args.slice(0, expectedArgsCount);359 if (self._passCommandToAction) {354 actionArgs[expectedArgsCount] = self;360 actionArgs[expectedArgsCount] = self;361 } else {362 actionArgs[expectedArgsCount] = self.opts();363 }364 // Add the extra arguments so available too.365 if (args.length > expectedArgsCount) {366 actionArgs.push(args.slice(expectedArgsCount));367 }
45 unmodified lines
413 // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value414 if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {415 // when --no-foo we make sure default is true, unless a --foo option is already defined416 if (option.negate) {408 var opts = self.opts();409 defaultValue = Object.prototype.hasOwnProperty.call(opts, name) ? opts[name] : true;417 const positiveLongFlag = option.long.replace(/^--no-/, '--');418 defaultValue = self.optionFor(positiveLongFlag) ? self._getOptionValue(name) : true;419 }420 // preassign only if we have a default421 if (defaultValue !== undefined) {413 self[name] = defaultValue;422 self._setOptionValue(name, defaultValue);423 option.defaultValue = defaultValue;424 }425 }426
4 unmodified lines
431 // and conditionally invoke the callback432 this.on('option:' + oname, function(val) {433 // coercion434 if (val !== null && fn) {426 val = fn(val, self[name] === undefined ? defaultValue : self[name]);435 val = fn(val, self._getOptionValue(name) === undefined ? defaultValue : self._getOptionValue(name));436 }437438 // unassigned or boolean value430 if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') {439 if (typeof self._getOptionValue(name) === 'boolean' || typeof self._getOptionValue(name) === 'undefined') {440 // if no value, negate false, and we have a default, then use it!441 if (val == null) {433 self[name] = option.negate442 self._setOptionValue(name, option.negate443 ? false435 : defaultValue || true;444 : defaultValue || true);445 } else {437 self[name] = val;446 self._setOptionValue(name, val);447 }448 } else if (val !== null) {449 // reassign441 self[name] = option.negate ? false : val;450 self._setOptionValue(name, option.negate ? false : val);451 }452 });453454 return this;
85 unmodified lines
540 return this;541};542543/**544 * Whether to store option values as properties on command object,545 * or store separately (specify false). In both cases the option values can be accessed using .opts().546 *547 * @param {boolean} value548 * @return {Command} Command for chaining549 * @api public550 */551552Command.prototype.storeOptionsAsProperties = function(value) {553 this._storeOptionsAsProperties = (value === undefined) || value;554 if (this.options.length) {555 // This is for programmer, not end user.556 console.error('Commander usage error: call storeOptionsAsProperties before adding options');557 }558 return this;559};560561/**562 * Whether to pass command to action handler,563 * or just the options (specify false).564 *565 * @param {boolean} value566 * @return {Command} Command for chaining567 * @api public568 */569570Command.prototype.passCommandToAction = function(value) {571 this._passCommandToAction = (value === undefined) || value;572 return this;573};574575/**576 * Store option value577 *578 * @param {String} key579 * @param {Object} value580 * @api private581 */582583Command.prototype._setOptionValue = function(key, value) {584 if (this._storeOptionsAsProperties) {585 this[key] = value;586 } else {587 this._optionValues[key] = value;588 }589};590591/**592 * Retrieve option value593 *594 * @param {String} key595 * @return {Object} value596 * @api private597 */598599Command.prototype._getOptionValue = function(key) {600 if (this._storeOptionsAsProperties) {601 return this[key];602 }603 return this._optionValues[key];604};605606/**607 * Parse `argv`, settings options and invoking commands when defined.608 *609 * @param {Array} argv610 * @return {Command} for chaining
303 unmodified lines
914Command.prototype._checkForMissingMandatoryOptions = function() {915 // Walk up hierarchy so can call from action handler after checking for displaying help.916 for (var cmd = this; cmd; cmd = cmd.parent) {917 cmd.options.forEach((anOption) => {846 if (anOption.mandatory && (cmd[anOption.attributeName()] === undefined)) {918 if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {919 cmd.missingMandatoryOptionValue(anOption);920 }921 });922 }
84 unmodified lines
1007 * @return {Object}1008 * @api public1009 */1010Command.prototype.opts = function() {1011 if (this._storeOptionsAsProperties) {1012 // Preserve original behaviour so backwards compatible when still using properties939 var result = {},940 len = this.options.length;1013 var result = {},1014 len = this.options.length;1015942 for (var i = 0; i < len; i++) {943 var key = this.options[i].attributeName();944 result[key] = key === this._versionOptionName ? this._version : this[key];1016 for (var i = 0; i < len; i++) {1017 var key = this.options[i].attributeName();1018 result[key] = key === this._versionOptionName ? this._version : this[key];1019 }1020 return result;1021 }946 return result;10221023 return this._optionValues;1024};10251026/**1027 * Argument `name` is missing.
601 unmodified lines
modified:Readme.md+40 added
29 unmodified lines
30 - [.helpOption(flags, description)](#helpoptionflags-description)31 - [.help(cb)](#helpcb)32 - [Custom event listeners](#custom-event-listeners)33 - [Bits and pieces](#bits-and-pieces)34 - [Avoiding option name clashes](#avoiding-option-name-clashes)35 - [TypeScript](#typescript)36 - [Node options such as `--harmony`](#node-options-such-as---harmony)37 - [Node debugging](#node-debugging)38 - [Override exit handling](#override-exit-handling)
31 unmodified lines
70Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space.7172The options can be accessed as properties on the Command object. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. Multiple short flags may be combined as a single arg, for example `-abc` is equivalent to `-a -b -c`.7374See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes).7576### Common option types, boolean and value7778The two most used option types are a boolean flag, and an option which takes a value (declared using angle brackets). Both are `undefined` unless specified on command line.79
472 unmodified lines
552```553554## Bits and pieces555556### Avoiding option name clashes557558The original and default behaviour is that the option values are stored559as properties on the program, and the action handler is passed a560command object with the options values stored as properties.561This is very convenient to code, but the downside is possible clashes with562existing properties of Command.563564There are two new routines to change the behaviour, and the default behaviour may change in the future:565566- `storeOptionsAsProperties`: whether to store option values as properties on command object, or store separately (specify false) and access using `.opts()`567- `passCommandToAction`: whether to pass command to action handler,568or just the options (specify false)569570```js571// file: ./examples/storeOptionsAsProperties.action.js572program573 .storeOptionsAsProperties(false)574 .passCommandToAction(false);575576program577 .name('my-program-name')578 .option('-n,--name <name>');579580program581 .command('show')582 .option('-a,--action <action>')583 .action((options) => {584 console.log(options.action);585 });586587program.parse(process.argv);588589const programOptions = program.opts();590console.log(programOptions.name);591```592593### TypeScript594595The Commander package includes its TypeScript Definition file, but also requires the node types which you need to install yourself. e.g.596
104 unmodified lines