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
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
Provenance
- Commit
81c6e28- Tree
08859bc- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
df6284c
11 files changed+407 added−49 removed
added:examples/storeOptionsAsProperties-action.js+40 added
12345678910111213141516171819202122232425262728293031323334353637383940#!/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// with the previous behaviour so less code changes from old code.//// Example output://// $ node storeOptionsAsProperties-action.js show// undefined// undefined//// $ node storeOptionsAsProperties-action.js --name foo show --action jump// jump// foo
const commander = require('../');const program = new commander.Command();
program .storeOptionsAsProperties(false) // <--- change behaviour .passCommandToAction(false); // <--- change behaviour
program .name('my-program-name') .option('-n,--name <name>');
program .command('show') .option('-a,--action <action>') .action((options) => { // <--- passed options, not Command console.log(options.action); // <--- matches old code });
program.parse(process.argv);
const programOptions = program.opts(); // <--- use opts to access option valuesconsole.log(programOptions.name);added:examples/storeOptionsAsProperties-opts.js+38 added
1234567891011121314151617181920212223242526272829303132333435363738#!/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.// You access the option values using the .opts() function.//// Example output://// $ node storeOptionsAsProperties-opts.js show// undefined// undefined//// $ node storeOptionsAsProperties-opts.js --name foo show --action jump// jump// foo
const commander = require('../');const program = new commander.Command();
program .storeOptionsAsProperties(false); // <--- change behaviour
program .name('my-program-name') .option('-n,--name <name>');
program .command('show') .option('-a,--action <action>') .action((cmd) => { const options = cmd.opts(); // <--- use opts to access option values console.log(options.action); });
program.parse(process.argv);
const programOptions = program.opts(); // <--- use opts to access option valuesconsole.log(programOptions.name);added:examples/storeOptionsAsProperties-problem.js+35 added
1234567891011121314151617181920212223242526272829303132333435#!/usr/bin/env node
// The original and default behaviour is that the option values are stored// as properties on the program (Command). The action handler is passed a// command object (Command) with the options values also stored as properties.// This is very convenient to code, but the downside is possible clashes with// existing properties of Command.//// Example output, note the issues in the first call://// $ node storeOptionsAsProperties-problem.js show// [Function]// [Function]//// $ node storeOptionsAsProperties-problem.js --name foo show --action jump// jump// foo
const commander = require('../');const program = new commander.Command();
program .name('my-program-name') .option('-n,--name <name>'); // Oops, clash with .name()
program .command('show') .option('-a,--action <action>') // Oops, clash with .action() .action((cmd) => { console.log(cmd.action); });
program.parse(process.argv);
console.log(program.name);added:tests/commander.configureCommand.test.js+87 added
1+const commander = require('../');2+3+// Mostly testing direct on program, limited check that (sub)command working same.4+5+// Default behaviours6+7+test('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+});14+15+test('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+});24+25+// storeOptionsAsProperties26+27+test('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+});35+36+test('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+});44+45+test('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+});53+54+// passCommandToAction55+56+test('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+});66+67+test('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+});77+78+test('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
10 unmodified lines1112131415151617181918202122232425262723242526272829282930313233343531323334353637363738394041424344394041424344454645464748495051525348495051525354545556575859606162636465666768697071727310 unmodified lines program.parse(['node', 'test']); expect(program.opts()).toEqual({ version });});
test('when boolean flag not specified then not in opts', () => {test('when .version used with storeOptionsAsProperties(false) then version not in opts', () => { // New behaviour, stop storing version as an option value. const program = new commander.Command(); const version = '0.0.1'; program .option('--pepper', 'add pepper'); .storeOptionsAsProperties(false) .version(version); program.parse(['node', 'test']); expect(program.opts()).toEqual({ });});
describe.each([true, false])('storeOptionsAsProperties is %s', (storeOptionsAsProperties) => { test('when boolean flag not specified then not in opts', () => {test('when boolean flag specified then value true', () => { const program = new commander.Command(); program .option('--pepper', 'add pepper'); program.parse(['node', 'test', '--pepper']); expect(program.opts()).toEqual({ pepper: true });}); const program = new commander.Command(); program.storeOptionsAsProperties(storeOptionsAsProperties); program .option('--pepper', 'add pepper'); program.parse(['node', 'test']); expect(program.opts()).toEqual({ }); });
test('when option with required value not specified then not in opts', () => { const program = new commander.Command(); program .option('--pepper <flavour>', 'add pepper'); program.parse(['node', 'test']); expect(program.opts()).toEqual({ });}); test('when boolean flag specified then value true', () => { const program = new commander.Command(); program.storeOptionsAsProperties(storeOptionsAsProperties); program .option('--pepper', 'add pepper'); program.parse(['node', 'test', '--pepper']); expect(program.opts()).toEqual({ pepper: true }); });
test('when option with required value specified then value as specified', () => { const pepperValue = 'red'; const program = new commander.Command(); program .option('--pepper <flavour>', 'add pepper'); program.parse(['node', 'test', '--pepper', pepperValue]); expect(program.opts()).toEqual({ pepper: pepperValue });}); test('when option with required value not specified then not in opts', () => { const program = new commander.Command(); program.storeOptionsAsProperties(storeOptionsAsProperties); program .option('--pepper <flavour>', 'add pepper'); program.parse(['node', 'test']); expect(program.opts()).toEqual({ }); });
test('when option with default value not specified then default value in opts', () => { const pepperDefault = 'red'; const program = new commander.Command(); program .option('--pepper <flavour>', 'add pepper', pepperDefault); program.parse(['node', 'test']); expect(program.opts()).toEqual({ pepper: pepperDefault }); test('when option with required value specified then value as specified', () => { const pepperValue = 'red'; const program = new commander.Command(); program.storeOptionsAsProperties(storeOptionsAsProperties); program .option('--pepper <flavour>', 'add pepper'); program.parse(['node', 'test', '--pepper', pepperValue]); expect(program.opts()).toEqual({ pepper: pepperValue }); });
test('when option with default value not specified then default value in opts', () => { const pepperDefault = 'red'; const program = new commander.Command(); program.storeOptionsAsProperties(storeOptionsAsProperties); program .option('--pepper <flavour>', 'add pepper', pepperDefault); program.parse(['node', 'test']); expect(program.opts()).toEqual({ pepper: pepperDefault }); });});modified:typings/commander-tests.ts+3 added
8 unmodified lines9 const errorInstance = new program.CommanderError(1, 'code', 'message');10 11 const name = program.name();12 13+program.storeOptionsAsProperties(true);14+program.passCommandToAction(true);15+16 program17 .name('set name')18 .version('0.0.1')19 .option('-p, --peppers', 'Add peppers')117 unmodified linesmodified:typings/index.d.ts+17 added
169 unmodified lines170 */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;173 174+175 /**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;182+183+ /**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;190+191+ /**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 chaining107 unmodified linesadded:.eslintignore+2 added
1+# We have not configured eslint for TypeScript so avoid bogus error messages in the test file and typings file.2+**/*.tsmodified:.eslintrc.json+2 added-1 removed
2 unmodified lines34567789102 unmodified lines "plugins": ["jest"], "rules": { "one-var": "off", "semi": ["error", "always"], "space-before-function-paren": ["error", "never"] "space-before-function-paren": ["error", "never"], "no-else-return": ["error", { "allowElseIf": false }] }}modified:index.js+94 added-17 removed
124 unmodified lines125 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 default132 133 this._helpFlags = '-h, --help';134 this._helpDescription = 'output usage information';135 this._helpShortFlag = '-h';49 unmodified lines185 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;191 192 cmd._executableFile = opts.executableFile; // Custom name for executable file193 this.commands.push(cmd);194 cmd.parseExpectedArgs(args);160 unmodified lines355 356 // 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 lines413 // 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 lines431 // 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 }437 438 // 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 });453 454 return this;85 unmodified lines540 return this;541 };542 543 /**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+ */551+552+Command.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+};560+561+/**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+ */569+570+Command.prototype.passCommandToAction = function(value) {571+ this._passCommandToAction = (value === undefined) || value;572+ return this;573+};574+575+/**576+ * Store option value577+ *578+ * @param {String} key579+ * @param {Object} value580+ * @api private581+ */582+583+Command.prototype._setOptionValue = function(key, value) {584+ if (this._storeOptionsAsProperties) {585+ this[key] = value;586+ } else {587+ this._optionValues[key] = value;588+ }589+};590+591+/**592+ * Retrieve option value593+ *594+ * @param {String} key595+ * @return {Object} value596+ * @api private597+ */598+599+Command.prototype._getOptionValue = function(key) {600+ if (this._storeOptionsAsProperties) {601+ return this[key];602+ }603+ return this._optionValues[key];604+};605+606+/**607 * Parse `argv`, settings options and invoking commands when defined.608 *609 * @param {Array} argv610 * @return {Command} for chaining303 unmodified lines914 Command.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 lines1007 * @return {Object}1008 * @api public1009 */1010 Command.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;1015 942- 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;1022+1023+ return this._optionValues;1024 };1025 1026 /**1027 * Argument `name` is missing.601 unmodified linesmodified:Readme.md+40 added
29 unmodified lines30 - [.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 lines70 Options 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.71 72 The 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`.73 74+See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes).75+76 ### Common option types, boolean and value77 78 The 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 lines552 ```553 554 ## Bits and pieces555 556+### Avoiding option name clashes557+558+The original and default behaviour is that the option values are stored559+as properties on the program, and the action handler is passed a560+command object with the options values stored as properties.561+This is very convenient to code, but the downside is possible clashes with562+existing properties of Command.563+564+There are two new routines to change the behaviour, and the default behaviour may change in the future:565+566+- `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,568+or just the options (specify false)569+570+```js571+// file: ./examples/storeOptionsAsProperties.action.js572+program573+ .storeOptionsAsProperties(false)574+ .passCommandToAction(false);575+576+program577+ .name('my-program-name')578+ .option('-n,--name <name>');579+580+program581+ .command('show')582+ .option('-a,--action <action>')583+ .action((options) => {584+ console.log(options.action);585+ });586+587+program.parse(process.argv);588+589+const programOptions = program.opts();590+console.log(programOptions.name);591+```592+593 ### TypeScript594 595 The 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