Change to safe storage of options by default, and change action parameters (#1409)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* First cut at storing options safely by default * Pass command as options for legacy behaviour * Update examples for new patterns * Rework README on using storeOptionsAsProperties * Tweak wording * Updat example for options-common * Update options-defaults * Update options-negatable example * Update options-boolean-or-value example * Update options-custom-processing example * Turn on error for excess arguments, and update tests accordingly * Add first cut at migration tips * Second cut at migration tips * Migration wording tweaks * Reworking README for new patterns * Goodbye to option properties on Command * Add migration tip for excess arguments * Minor improvements to migrations tips * Update examples for arguments * Update example for action handler * Add allowUnknownOption and allowExcessArguments to README * Update pizza example * Reuse pizza as single command example. Tidy up pizza and deploy. * Word change
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
46 files+475 added−669 removed
- tests:+139 added−210 removed
- other:+336 added−459 removed
Provenance
- Commit
f76bc71- Tree
2fdd7ab- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
1db83b6
46 files changed+475 added−669 removed
added:examples/arguments.js+26 added
1234567891011121314151617181920212223242526#!/usr/bin/env node
// This example shows specifying the arguments for the program to pass to the action handler.
// const { Command } = require('commander'); // (normal include)const { Command } = require('../'); // include commander in git clone of commander repoconst program = new Command();
program .version('0.1.0') .arguments('<username> [password]') .description('test command', { username: 'user to login', password: 'password for user, if required' }) .action((username, password) => { console.log('username:', username); console.log('environment:', password || 'no password given'); });
program.parse();
// Try the following:// node arguments.js --help// node arguments.js user// node arguments.js user secretmodified:examples/custom-command-class.js+4 added-4 removed
16 unmodified lines17181920212221222324242526272828293031324 unmodified lines16 unmodified linesconst program = new MyCommand();program .command('serve') .option('--port <port-number>', 'specify port number', 80) .action((cmd) => { if (cmd.debug) { .action((options) => { if (options.debug) { console.log('Options:'); console.log(cmd.opts()); console.log(options); console.log(); }
console.log(`Start serve on port ${cmd.port}`); console.log(`Start serve on port ${options.port}`); });
program.parse();
4 unmodified linesmodified:examples/custom-command-function.js+4 added-4 removed
16 unmodified lines17181920212221222324242526272828293031324 unmodified lines16 unmodified lines
program .command('serve') .option('--port <port-number>', 'specify port number', 80) .action((cmd) => { if (cmd.debug) { .action((options) => { if (options.debug) { console.log('Options:'); console.log(cmd.opts()); console.log(options); console.log(); }
console.log(`Start serve on port ${cmd.port}`); console.log(`Start serve on port ${options.port}`); });
program.parse();
4 unmodified linesmodified:examples/custom-help-description+1 added-1 removed
12 unmodified lines13 14 program15 .command('child')16 .option('--gender', 'specific gender of child')17- .action((cmd) => {17+ .action((options) => {18 console.log('Childsubcommand...');19 });20 21 program.parse(process.argv);modified:examples/defaultCommand.js+2 added-2 removed
29 unmodified lines303132333435343536373829 unmodified linesprogram .command('serve', { isDefault: true }) .description('launch web server') .option('-p,--port <port_number>', 'web port') .action((opts) => { console.log(`server on port ${opts.port}`); .action((options) => { console.log(`server on port ${options.port}`); });
program.parse(process.argv);modified:examples/deploy+10 added-11 removed
4 unmodified lines5 const program = new Command();6 7 program8 .version('0.0.1')9- .option('-C, --chdir <path>', 'change the working directory')10- .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')11- .option('-T, --no-tests', 'ignore test hook');9+ .option('-c, --config <path>', 'set config path', './deploy.conf');10 11 program12 .command('setup [env]')13 .description('run setup commands for all envs')16- .option('-s, --setup_mode [mode]', 'Which setup mode to use')17- .action(function(env, options) {18- const mode = options.setup_mode || 'normal';14+ .option('-s, --setup_mode <mode>', 'Which setup mode to use', 'normal')15+ .action((env, options) => {16 env = env || 'all';17+ console.log('read config from %s', program.opts().config);20- console.log('setup for %s env(s) with %s mode', env, mode);18+ console.log('setup for %s env(s) with %s mode', env, options.setup_mode);19 });20 21 program24- .command('exec <cmd>')22+ .command('exec <script>')23 .alias('ex')24 .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);25+ .option('-e, --exec_mode <mode>', 'Which exec mode to use', 'fast')26+ .action((script, options) => {27+ console.log('read config from %s', program.opts().config);28+ console.log('exec "%s" using %s mode and config %s', script, options.exec_mode, program.opts().config);29 }).addHelpText('after', `30 Examples:31 $ deploy exec sequential32 $ deploy exec async`3 unmodified linesdeleted:examples/env-29 removed
1-#!/usr/bin/env node2-3-// This example shows specifying the arguments for the program to pass to the action handler.4-5-// const { Command } = require('commander'); // (normal include)6-const { Command } = require('../'); // include commander in git clone of commander repo7-const program = new Command();8-9-let cmdValue;10-let envValue;11-12-program13- .version('0.0.1')14- .arguments('<cmd> [env]')15- .description('test command', {16- cmd: 'command to run',17- env: 'environment to run test in'18- })19- .action(function(cmdValue, envValue) {20- console.log('command:', cmdValue);21- console.log('environment:', envValue || 'no environment given');22- });23-24-program.parse(process.argv);25-26-// Try the following:27-// node env --help28-// node env add29-// node env add browsermodified:examples/options-boolean-or-value.js+9 added-12 removed
123456789101112131467892 unmodified lines12131415162526271718192021222324#!/usr/bin/env node
// This is used as an example in the README for:// Other option types, flag|value// You can specify an option which functions as a flag but may also take a value (declared using square brackets).//// Example output pretending command called pizza-options (or try directly with `node options-flag-or-value.js`)//// $ pizza-options// no cheese// $ pizza-options --cheese// add cheese// $ pizza-options --cheese mozzarella// add cheese type mozzarella
// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repoconst program = new commander.Command();2 unmodified lines .option('-c, --cheese [type]', 'Add cheese with optional type');
program.parse(process.argv);
const options = program.opts();if (program.cheese === undefined) console.log('no cheese');else if (program.cheese === true) console.log('add cheese');else console.log(`add cheese type ${program.cheese}`);if (options.cheese === undefined) console.log('no cheese');else if (options.cheese === true) console.log('add cheese');else console.log(`add cheese type ${options.cheese}`);
// Try the following:// node options-boolean-or-value// node options-boolean-or-value --cheese// node options-boolean-or-value --cheese mozzarellamodified:examples/options-common.js+10 added-20 removed
1 #!/usr/bin/env node2 3 // This is used as an example in the README for:4 // Common option types, boolean and value5-// The two most used option types are a boolean flag, and an option which takes a value (declared using angle brackets).6-//7-// Example output pretending command called pizza-options (or try directly with `node options-common.js`)8-//9-// $ pizza-options -d10-// { debug: true, small: undefined, pizzaType: undefined }11-// pizza details:12-// $ pizza-options -p13-// error: option '-p, --pizza-type <type>' argument missing14-// $ pizza-options -ds -p vegetarian15-// { debug: true, small: true, pizzaType: 'vegetarian' }16-// pizza details:17-// - small pizza size18-// - vegetarian19-// $ pizza-options --pizza-type=cheese20-// pizza details:21-// - cheese5 6 // const commander = require('commander'); // (normal include)7 const commander = require('../'); // include commander in git clone of commander repo8 const program = new commander.Command();4 unmodified lines13 .option('-p, --pizza-type <type>', 'flavour of pizza');14 15 program.parse(process.argv);16 34-if (program.debug) console.log(program.opts());17+const options = program.opts();18+if (options.debug) console.log(options);19 console.log('pizza details:');36-if (program.small) console.log('- small pizza size');37-if (program.pizzaType) console.log(`- ${program.pizzaType}`);20+if (options.small) console.log('- small pizza size');21+if (options.pizzaType) console.log(`- ${options.pizzaType}`);22+23+// Try the following:24+// node options-common.js -d25+// node options-common.js -p26+// node options-common.js -ds -p vegetarian27+// node options-common.js --pizza-type=cheesemodified:examples/options-custom-processing.js+16 added-22 removed
1 #!/usr/bin/env node2 3 // This is used as an example in the README for:4 // Custom option processing5-// You may specify a function to do custom processing of option values. ...6-//7-// Example output pretending command called custom (or try directly with `node options-custom-processing.js`)8-//9-// $ custom -f 1e210-// float: 10011-// $ custom --integer 212-// integer: 213-// $ custom -v -v -v14-// verbose: 315-// $ custom -c a -c b -c c16-// [ 'a', 'b', 'c' ]17-// $ custom --list x,y,z18-// [ 'x', 'y', 'z' ]19-// $ custom --integer oops20-// error: option '-i, --integer <number>' argument 'oops' is invalid. Not a number.5+// You may specify a function to do custom processing of option values.6 7 // const commander = require('commander'); // (normal include)8 const commander = require('../'); // include commander in git clone of commander repo9 const program = new commander.Command();26 unmodified lines36 .option('-c, --collect <value>', 'repeatable value', collect, [])37 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)38 ;39 55-program.parse(process.argv);56-if (program.float !== undefined) console.log(`float: ${program.float}`);57-if (program.integer !== undefined) console.log(`integer: ${program.integer}`);58-if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);59-if (program.collect.length > 0) console.log(program.collect);60-if (program.list !== undefined) console.log(program.list);40+program.parse();41+42+const options = program.opts();43+if (options.float !== undefined) console.log(`float: ${options.float}`);44+if (options.integer !== undefined) console.log(`integer: ${options.integer}`);45+if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);46+if (options.collect.length > 0) console.log(options.collect);47+if (options.list !== undefined) console.log(options.list);48+49+// Try the following:50+// node options-custom-processing -f 1e251+// node options-custom-processing --integer 252+// node options-custom-processing -v -v -v53+// node options-custom-processing -c a -c b -c c54+// node options-custom-processing --list x,y,zmodified:examples/options-defaults.js+6 added-10 removed
1 #!/usr/bin/env node2 3 // This is used as an example in the README for:4 // Default option value5-// You can specify a default value for an option which takes a value.6-//7-// Example output pretending command called pizza-options (or try directly with `node options-defaults.js`)8-//9-// $ pizza-options10-// cheese: blue11-// $ pizza-options --cheese stilton12-// cheese: stilton5 6 // const commander = require('commander'); // (normal include)7 const commander = require('../'); // include commander in git clone of commander repo8 const program = new commander.Command();9 10 program11 .option('-c, --cheese <type>', 'Add the specified type of cheese', 'blue');12 21-program.parse(process.argv);13+program.parse();14 23-console.log(`cheese: ${program.cheese}`);15+console.log(`cheese: ${program.opts().cheese}`);16+17+// Try the following:18+// node options-defaults.js19+// node options-defaults.js --cheese stiltonmodified:examples/options-negatable.js+10 added-14 removed
1 unmodified line2 3 // This is used as an example in the README for:4 // Other option types, negatable boolean5 // You can specify a boolean option long name with a leading `no-` to make it true by default and able to be negated.6-//7-// Example output pretending command called pizza-options (or try directly with `node options-negatable.js`)8-//9-// $ pizza-options10-// You ordered a pizza with sauce and mozzarella cheese11-// $ pizza-options --sauce12-// error: unknown option '--sauce'13-// $ pizza-options --cheese=blue14-// You ordered a pizza with sauce and blue cheese15-// $ pizza-options --no-sauce --no-cheese16-// You ordered a pizza with no sauce and no cheese6 7 // const commander = require('commander'); // (normal include)8 const commander = require('../'); // include commander in git clone of commander repo9 const program = new commander.Command();2 unmodified lines12 .option('--no-sauce', 'Remove sauce')13 .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')14 .option('--no-cheese', 'plain with no cheese');15 27-program.parse(process.argv);16+program.parse();17 18+const options = program.opts();29-const sauceStr = program.sauce ? 'sauce' : 'no sauce';30-const cheeseStr = (program.cheese === false) ? 'no cheese' : `${program.cheese} cheese`;19+const sauceStr = options.sauce ? 'sauce' : 'no sauce';20+const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;21 console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);22+23+// Try the following:24+// node options-negatable.js25+// node options-negatable.js --sauce26+// node options-negatable.js --cheese=blue27+// node options-negatable.js --no-sauce --no-cheesemodified:examples/options-required.js+1 added-1 removed
15 unmodified lines16 17 program18 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');19 20-program.parse(process.argv);20+program.parse();modified:examples/pizza+5 added-10 removed
3 unmodified lines4 const { Command } = require('../'); // include commander in git clone of commander repo5 const program = new Command();6 7 program8- .version('0.0.1')9- .description('An application for pizzas ordering')8+ .description('An application for pizza ordering')9 .option('-p, --peppers', 'Add peppers')10 .option('-c, --cheese <type>', 'Add the specified type of cheese', 'marble')11 .option('-C, --no-cheese', 'You do not want any cheese');12 14-program.parse(process.argv);13+program.parse();14 15+const options = program.opts();16 console.log('you ordered a pizza with:');17-if (program.peppers) console.log(' - peppers');18-if (program.pineapple) console.log(' - pineapple');19-if (program.bbq) console.log(' - bbq');20-21-const cheese = !program.cheese ? 'no' : program.cheese;22-17+if (options.peppers) console.log(' - peppers');18+const cheese = !options.cheese ? 'no' : options.cheese;19 console.log(' - %s cheese', cheese);24-console.log(program.args);deleted:examples/storeOptionsAsProperties-action.js-41 removed
1-#!/usr/bin/env node2-3-// To avoid possible name clashes, you can change the default behaviour4-// of storing the options values as properties on the command object.5-// In addition, you can pass just the options to the action handler6-// instead of a command object. This allows simpler code, and is more consistent7-// with the previous behaviour so less code changes from old code.8-//9-// Example output:10-//11-// $ node storeOptionsAsProperties-action.js show12-// undefined13-// undefined14-//15-// $ node storeOptionsAsProperties-action.js --name foo show --action jump16-// jump17-// foo18-19-// const commander = require('commander'); // (normal include)20-const commander = require('../'); // include commander in git clone of commander repo21-const program = new commander.Command();22-23-program24- .storeOptionsAsProperties(false) // <--- change behaviour25- .passCommandToAction(false); // <--- change behaviour26-27-program28- .name('my-program-name')29- .option('-n,--name <name>');30-31-program32- .command('show')33- .option('-a,--action <action>')34- .action((options) => { // <--- passed options, not Command35- console.log(options.action); // <--- matches old code36- });37-38-program.parse(process.argv);39-40-const programOptions = program.opts(); // <--- use opts to access option values41-console.log(programOptions.name);deleted:examples/storeOptionsAsProperties-opts.js-39 removed
1-#!/usr/bin/env node2-3-// To avoid possible name clashes, you can change the default behaviour4-// of storing the options values as properties on the command object.5-// You access the option values using the .opts() function.6-//7-// Example output:8-//9-// $ node storeOptionsAsProperties-opts.js show10-// undefined11-// undefined12-//13-// $ node storeOptionsAsProperties-opts.js --name foo show --action jump14-// jump15-// foo16-17-// const commander = require('commander'); // (normal include)18-const commander = require('../'); // include commander in git clone of commander repo19-const program = new commander.Command();20-21-program22- .storeOptionsAsProperties(false); // <--- change behaviour23-24-program25- .name('my-program-name')26- .option('-n,--name <name>');27-28-program29- .command('show')30- .option('-a,--action <action>')31- .action((cmd) => {32- const options = cmd.opts(); // <--- use opts to access option values33- console.log(options.action);34- });35-36-program.parse(process.argv);37-38-const programOptions = program.opts(); // <--- use opts to access option values39-console.log(programOptions.name);deleted:examples/storeOptionsAsProperties-problem.js-36 removed
1-#!/usr/bin/env node2-3-// The original and default behaviour is that the option values are stored4-// as properties on the program (Command). The action handler is passed a5-// command object (Command) with the options values also stored as properties.6-// This is very convenient to code, but the downside is possible clashes with7-// existing properties of Command.8-//9-// Example output, note the issues in the first call:10-//11-// $ node storeOptionsAsProperties-problem.js show12-// [Function]13-// [Function]14-//15-// $ node storeOptionsAsProperties-problem.js --name foo show --action jump16-// jump17-// foo18-19-// const commander = require('commander'); // (normal include)20-const commander = require('../'); // include commander in git clone of commander repo21-const program = new commander.Command();22-23-program24- .name('my-program-name')25- .option('-n,--name <name>'); // Oops, clash with .name()26-27-program28- .command('show')29- .option('-a,--action <action>') // Oops, clash with .action()30- .action((cmd) => {31- console.log(cmd.action);32- });33-34-program.parse(process.argv);35-36-console.log(program.name);added:examples/thank.js+26 added
1+#!/usr/bin/env node2+3+// This example is used as an example in the README for the action handler.4+5+// const { Command } = require('commander'); // (normal include)6+const { Command } = require('../'); // include commander in git clone of commander repo7+const program = new Command();8+9+program10+ .arguments('<name>')11+ .option('-t, --title <honorific>', 'title to use before name')12+ .option('-d, --debug', 'display some debugging')13+ .action((name, options, command) => {14+ if (options.debug) {15+ console.error('Called %s with options %o', command.name(), options);16+ }17+ const title = options.title ? `${options.title} ` : '';18+ console.log(`Thank-you ${title}${name}`);19+ });20+21+program.parse();22+23+// Try the following:24+// node thank.js John25+// node thank.js Doe --title Mr26+// node thank.js --debug Doe --title Mrmodified:tests/args.literal.test.js+3 added-2 removed
10 unmodified lines11 .option('-f, --foo', 'add some foo')12 .option('-b, --bar', 'add some bar');13 program.parse(['node', 'test', '--foo', '--', '--bar', 'baz']);14 // More than one assert, ported from legacy test15+ const opts = program.opts();15- expect(program.foo).toBe(true);16- expect(program.bar).toBeUndefined();16+ expect(opts.foo).toBe(true);17+ expect(opts.bar).toBeUndefined();18 expect(program.args).toEqual(['--bar', 'baz']);19 });20 21 test('when arguments include -- then more literals are passed-through as args', () => {7 unmodified linesmodified:tests/args.variadic.test.js+4 added-4 removed
10 unmodified lines11 .action(actionMock);12 13 program.parse(['node', 'test', 'id']);14 15- expect(actionMock).toHaveBeenCalledWith('id', [], program);15+ expect(actionMock).toHaveBeenCalledWith('id', [], program.opts(), program);16 });17 18 test('when extra arguments specified for program then variadic arg is array of values', () => {19 const actionMock = jest.fn();4 unmodified lines24 const extraArguments = ['a', 'b', 'c'];25 26 program.parse(['node', 'test', 'id', ...extraArguments]);27 28- expect(actionMock).toHaveBeenCalledWith('id', extraArguments, program);28+ expect(actionMock).toHaveBeenCalledWith('id', extraArguments, program.opts(), program);29 });30 31 test('when no extra arguments specified for command then variadic arg is empty array', () => {32 const actionMock = jest.fn();3 unmodified lines36 .action(actionMock);37 38 program.parse(['node', 'test', 'sub']);39 40- expect(actionMock).toHaveBeenCalledWith([], cmd);40+ expect(actionMock).toHaveBeenCalledWith([], cmd.opts(), cmd);41 });42 43 test('when extra arguments specified for command then variadic arg is array of values', () => {44 const actionMock = jest.fn();4 unmodified lines49 const extraArguments = ['a', 'b', 'c'];50 51 program.parse(['node', 'test', 'sub', ...extraArguments]);52 53- expect(actionMock).toHaveBeenCalledWith(extraArguments, cmd);53+ expect(actionMock).toHaveBeenCalledWith(extraArguments, cmd.opts(), cmd);54 });55 56 test('when program variadic argument not last then error', () => {57 const program = new commander.Command();14 unmodified linesmodified:tests/command.action.test.js+7 added-19 removed
7 unmodified lines8 const cmd = program9 .command('info')10 .action(actionMock);11 program.parse(['node', 'test', 'info']);12- expect(actionMock).toHaveBeenCalledWith(cmd);12+ expect(actionMock).toHaveBeenCalledWith(cmd.opts(), cmd);13 });14 15 test('when .action called then program.args only contains args', () => {16 // At one time program.args was being modified to contain the same args as the call to .action5 unmodified lines22 program.parse(['node', 'test', 'info', 'my-file']);23 expect(program.args).toEqual(['info', 'my-file']);24 });25 26-test('when .action called with extra arguments then extras also passed to action', () => {27- // This is a new and undocumented behaviour for now.28- // Might make this an error by default in future.29- const actionMock = jest.fn();30- const program = new commander.Command();31- const cmd = program32- .command('info <file>')33- .action(actionMock);34- program.parse(['node', 'test', 'info', 'my-file', 'a']);35- expect(actionMock).toHaveBeenCalledWith('my-file', cmd, ['a']);36-});37-26 test('when .action on program with required argument and argument supplied then action called', () => {27 const actionMock = jest.fn();28 const program = new commander.Command();29 program30 .arguments('<file>')31 .action(actionMock);32 program.parse(['node', 'test', 'my-file']);45- expect(actionMock).toHaveBeenCalledWith('my-file', program);33+ expect(actionMock).toHaveBeenCalledWith('my-file', program.opts(), program);34 });35 36 test('when .action on program with required argument and argument not supplied then action not called', () => {37 const actionMock = jest.fn();15 unmodified lines53 const program = new commander.Command();54 program55 .action(actionMock);56 program.parse(['node', 'test']);69- expect(actionMock).toHaveBeenCalledWith(program);57+ expect(actionMock).toHaveBeenCalledWith(program.opts(), program);58 });59 60 test('when .action on program with optional argument supplied then action called', () => {61 const actionMock = jest.fn();1 unmodified line63 program64 .arguments('[file]')65 .action(actionMock);66 program.parse(['node', 'test', 'my-file']);79- expect(actionMock).toHaveBeenCalledWith('my-file', program);67+ expect(actionMock).toHaveBeenCalledWith('my-file', program.opts(), program);68 });69 70 test('when .action on program without optional argument supplied then action called', () => {71 const actionMock = jest.fn();1 unmodified line73 program74 .arguments('[file]')75 .action(actionMock);76 program.parse(['node', 'test']);89- expect(actionMock).toHaveBeenCalledWith(undefined, program);77+ expect(actionMock).toHaveBeenCalledWith(undefined, program.opts(), program);78 });79 80 test('when .action on program with optional argument and subcommand and program argument then program action called', () => {81 const actionMock = jest.fn();5 unmodified lines87 .command('subcommand');88 89 program.parse(['node', 'test', 'a']);90 103- expect(actionMock).toHaveBeenCalledWith('a', program);91+ expect(actionMock).toHaveBeenCalledWith('a', program.opts(), program);92 });93 94 // Changes made in #1062 to allow this case95 test('when .action on program with optional argument and subcommand and no program argument then program action called', () => {6 unmodified lines102 .command('subcommand');103 104 program.parse(['node', 'test']);105 118- expect(actionMock).toHaveBeenCalledWith(undefined, program);106+ expect(actionMock).toHaveBeenCalledWith(undefined, program.opts(), program);107 });108 109 test('when action is async then can await parseAsync', async() => {110 let asyncFinished = false;13 unmodified linesmodified:tests/command.allowExcessArguments.test.js+4 added-4 removed
16 unmodified lines17 afterAll(() => {18 writeErrorSpy.mockRestore();19 });20 21- test('when specify excess program argument then ignored by default', () => {21+ test('when specify excess program argument then error by default', () => {22 const program = new commander.Command();23 program24 .exitOverride()25 .action(() => {});26 27 expect(() => {28 program.parse(['excess'], { from: 'user' });29- }).not.toThrow();29+ }).toThrow();30 });31 32 test('when specify excess program argument and allowExcessArguments(false) then error', () => {33 const program = new commander.Command();30 unmodified lines64 program.parse(['excess'], { from: 'user' });65 }).not.toThrow();66 });67 68- test('when specify excess command argument then no error (by default)', () => {68+ test('when specify excess command argument then error (by default)', () => {69 const program = new commander.Command();70 program71 .exitOverride()72 .command('sub')73 .action(() => { });74 75 expect(() => {76 program.parse(['sub', 'excess'], { from: 'user' });77- }).not.toThrow();77+ }).toThrow();78 });79 80 test('when specify excess command argument and allowExcessArguments(false) then error', () => {81 const program = new commander.Command();64 unmodified linesmodified:tests/command.allowUnknownOption.test.js+1 added
81 unmodified lines82 const program = new commander.Command();83 program84 .exitOverride()85 .command('sub')86+ .arguments('[args...]') // unknown option will be passed as an argument87 .allowUnknownOption()88 .option('-p, --pepper', 'add pepper')89 .action(() => { });90 5 unmodified linesmodified:tests/command.asterisk.test.js+2 added
31 unmodified lines32 const mockAction = jest.fn();33 const program = new commander.Command();34 program35 .command('*')36+ .arguments('[args...]')37 .action(mockAction);38 program.parse(['node', 'test', 'unrecognised-command']);39 expect(mockAction).toHaveBeenCalled();40 });17 unmodified lines58 program59 .command('install');60 program61 .command('*')62+ .arguments('[args...]')63 .action(mockAction);64 program.parse(['node', 'test', 'unrecognised-command']);65 expect(mockAction).toHaveBeenCalled();66 });45 unmodified linesmodified:tests/command.chain.test.js-6 removed
80 unmodified lines81 const result = program.storeOptionsAsProperties();82 expect(result).toBe(program);83 });84 85- test('when call .passCommandToAction() then returns this', () => {86- const program = new Command();87- const result = program.passCommandToAction();88- expect(result).toBe(program);89- });90-85 test('when call .version() then returns this', () => {86 const program = new Command();87 const result = program.version('1.2.3');88 expect(result).toBe(program);56 unmodified linesmodified:tests/command.default.test.js+2 added
32 unmodified lines33 .command('other');34 program35 .command('default', { isDefault: true })36 .allowUnknownOption()37+ .allowExcessArguments()38 .action(actionMock);39 return { program, actionMock };40 }41 20 unmodified lines62 function makeProgram() {63 const actionMock = jest.fn();64 const defaultCmd = new commander.Command('default')65 .allowUnknownOption()66+ .allowExcessArguments()67 .action(actionMock);68 69 const program = new commander.Command();70 program24 unmodified linesmodified:tests/command.unknownCommand.test.js+2 added-1 removed
22 unmodified lines23 program.parse('node test.js unknown'.split(' '));24 }).not.toThrow();25 });26 27- test('when unknown command but action handler then no error', () => {27+ test('when unknown command but action handler taking arg then no error', () => {28 const program = new commander.Command();29 program30 .exitOverride()31 .command('sub');32 program33+ .arguments('[args...]')34 .action(() => { });35 expect(() => {36 program.parse('node test.js unknown'.split(' '));37 }).not.toThrow();28 unmodified linesmodified:tests/commander.configureCommand.test.js+14 added-23 removed
2 unmodified lines3 // 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', () => {7+test('when default then options not 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');12+ expect(program.foo).toBeUndefined();13+ expect(program.opts().foo).toBe('bar');14 });15 15-test('when default then command passed to action', () => {16+test('when default then options+command passed to action', () => {17 const program = new commander.Command();18 const callback = jest.fn();19 program20 .arguments('<value>')21 .action(callback);22 program.parse(['node', 'test', 'value']);22- expect(callback).toHaveBeenCalledWith('value', program);23+ expect(callback).toHaveBeenCalledWith('value', program.opts(), program);24 });25 26 // storeOptionsAsProperties27 3 unmodified lines31 .storeOptionsAsProperties()32 .option('--foo <value>', 'description');33 program.parse(['node', 'test', '--foo', 'bar']);34 expect(program.foo).toBe('bar');35+ expect(program.opts().foo).toBe('bar');36 });37 38 test('when storeOptionsAsProperties(true) then options stored on command', () => {39 const program = new commander.Command();1 unmodified line41 .storeOptionsAsProperties(true)42 .option('--foo <value>', 'description');43 program.parse(['node', 'test', '--foo', 'bar']);44 expect(program.foo).toBe('bar');45+ expect(program.opts().foo).toBe('bar');46 });47 48 test('when storeOptionsAsProperties(false) then options not stored on command', () => {49 const program = new commander.Command();1 unmodified line51 .storeOptionsAsProperties(false)52 .option('--foo <value>', 'description');53 program.parse(['node', 'test', '--foo', 'bar']);54 expect(program.foo).toBeUndefined();55+ expect(program.opts().foo).toBe('bar');56 });57 54-// passCommandToAction55-56-test('when passCommandToAction() then command passed to action', () => {58+test('when storeOptionsAsProperties() then command+command passed to action', () => {59 const program = new commander.Command();60 const callback = jest.fn();61 program60- .passCommandToAction()62+ .storeOptionsAsProperties()63 .arguments('<value>')64 .action(callback);65 program.parse(['node', 'test', 'value']);64- expect(callback).toHaveBeenCalledWith('value', program);66+ expect(callback).toHaveBeenCalledWith('value', program, program);67 });68 67-test('when passCommandToAction(true) then command passed to action', () => {69+test('when storeOptionsAsProperties(false) then opts+command passed to action', () => {70 const program = new commander.Command();71 const callback = jest.fn();72 program71- .passCommandToAction(true)73+ .storeOptionsAsProperties(false)74 .arguments('<value>')75 .action(callback);76 program.parse(['node', 'test', 'value']);75- expect(callback).toHaveBeenCalledWith('value', program);77+ expect(callback).toHaveBeenCalledWith('value', program.opts(), program);78 });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/deprecated.test.js+3 added-3 removed
8 unmodified lines9 const program = new commander.Command();10 program11 .option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');12 program.parse([], { from: 'user' });13- expect(program.cheese).toEqual('mild');13+ expect(program.opts().cheese).toEqual('mild');14 });15 16 test('when argument matches regexp then value is as specified', () => {17 const program = new commander.Command();18 program19 .option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');20 program.parse(['--cheese', 'tasty'], { from: 'user' });21- expect(program.cheese).toEqual('tasty');21+ expect(program.opts().cheese).toEqual('tasty');22 });23 24 test('when argument does mot matches regexp then value is default', () => {25 const program = new commander.Command();26 program27 .option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');28 program.parse(['--cheese', 'other'], { from: 'user' });29- expect(program.cheese).toEqual('mild');29+ expect(program.opts().cheese).toEqual('mild');30 });31 });modified:tests/options.bool.combo.test.js+14 added-14 removed
14 unmodified lines15 16 test('when boolean combo not specified then value is undefined', () => {17 const program = createPepperProgram();18 program.parse(['node', 'test']);19- expect(program.pepper).toBeUndefined();19+ expect(program.opts().pepper).toBeUndefined();20 });21 22 test('when boolean combo positive then value is true', () => {23 const program = createPepperProgram();24 program.parse(['node', 'test', '--pepper']);25- expect(program.pepper).toBe(true);25+ expect(program.opts().pepper).toBe(true);26 });27 28 test('when boolean combo negative then value is false', () => {29 const program = createPepperProgram();30 program.parse(['node', 'test', '--no-pepper']);31- expect(program.pepper).toBe(false);31+ expect(program.opts().pepper).toBe(false);32 });33 34 test('when boolean combo last is positive then value is true', () => {35 const program = createPepperProgram();36 program.parse(['node', 'test', '--no-pepper', '--pepper']);37- expect(program.pepper).toBe(true);37+ expect(program.opts().pepper).toBe(true);38 });39 40 test('when boolean combo last is negative then value is false', () => {41 const program = createPepperProgram();42 program.parse(['node', 'test', '--pepper', '--no-pepper']);43- expect(program.pepper).toBe(false);43+ expect(program.opts().pepper).toBe(false);44 });45 });46 47 // Flag with default, say from an environment variable.10 unmodified lines58 describe('boolean option combo, default true, long flags', () => {59 test('when boolean combo not specified then value is true', () => {60 const program = createPepperProgramWithDefault(true);61 program.parse(['node', 'test']);62- expect(program.pepper).toBe(true);62+ expect(program.opts().pepper).toBe(true);63 });64 65 test('when boolean combo positive then value is true', () => {66 const program = createPepperProgramWithDefault(true);67 program.parse(['node', 'test', '--pepper']);68- expect(program.pepper).toBe(true);68+ expect(program.opts().pepper).toBe(true);69 });70 71 test('when boolean combo negative then value is false', () => {72 const program = createPepperProgramWithDefault(true);73 program.parse(['node', 'test', '--no-pepper']);74- expect(program.pepper).toBe(false);74+ expect(program.opts().pepper).toBe(false);75 });76 });77 78 // boolean option combo, default false, short flags79 describe('boolean option combo, default false, short flags', () => {80 test('when boolean combo not specified then value is false', () => {81 const program = createPepperProgramWithDefault(false);82 program.parse(['node', 'test']);83- expect(program.pepper).toBe(false);83+ expect(program.opts().pepper).toBe(false);84 });85 86 test('when boolean combo positive then value is true', () => {87 const program = createPepperProgramWithDefault(false);88 program.parse(['node', 'test', '-p']);89- expect(program.pepper).toBe(true);89+ expect(program.opts().pepper).toBe(true);90 });91 92 test('when boolean combo negative then value is false', () => {93 const program = createPepperProgramWithDefault(false);94 program.parse(['node', 'test', '-P']);95- expect(program.pepper).toBe(false);95+ expect(program.opts().pepper).toBe(false);96 });97 });98 99 // This is a somewhat undocumented special behaviour which appears in some examples.4 unmodified lines104 test('when boolean combo not specified then value is undefined', () => {105 const flagValue = 'red';106 const program = createPepperProgramWithDefault(flagValue);107 program.parse(['node', 'test']);108- expect(program.pepper).toBeUndefined();108+ expect(program.opts().pepper).toBeUndefined();109 });110 111 test('when boolean combo positive then value is "default" value', () => {112 const flagValue = 'red';113 const program = createPepperProgramWithDefault(flagValue);114 program.parse(['node', 'test', '--pepper']);115- expect(program.pepper).toBe(flagValue);115+ expect(program.opts().pepper).toBe(flagValue);116 });117 118 test('when boolean combo negative then value is false', () => {119 const flagValue = 'red';120 const program = createPepperProgramWithDefault(flagValue);121 program.parse(['node', 'test', '--no-pepper']);122- expect(program.pepper).toBe(false);122+ expect(program.opts().pepper).toBe(false);123 });124 });modified:tests/options.bool.small.combined.test.js+2 added-2 removed
6 unmodified lines7 .option('-c, --cheese', 'add cheese');8 9 program.parse(['node', 'test', '-pc']);10 11- expect(program.pepper).toBe(true);12- expect(program.cheese).toBe(true);11+ expect(program.opts().pepper).toBe(true);12+ expect(program.opts().cheese).toBe(true);13 });modified:tests/options.bool.test.js+20 added-20 removed
7 unmodified lines8 const program = new commander.Command();9 program10 .option('--pepper', 'add pepper');11 program.parse(['node', 'test']);12- expect(program.pepper).toBeUndefined();12+ expect(program.opts().pepper).toBeUndefined();13 });14 15 test('when boolean flag specified then value is true', () => {16 const program = new commander.Command();17 program18 .option('--pepper', 'add pepper');19 program.parse(['node', 'test', '--pepper']);20- expect(program.pepper).toBe(true);20+ expect(program.opts().pepper).toBe(true);21 });22 23 test('when negatable boolean flag not specified then value is true', () => {24 const program = new commander.Command();25 program26 .option('--no-cheese', 'remove cheese');27 program.parse(['node', 'test']);28- expect(program.cheese).toBe(true);28+ expect(program.opts().cheese).toBe(true);29 });30 31 test('when negatable boolean flag specified then value is false', () => {32 const program = new commander.Command();33 program34 .option('--no-cheese', 'remove cheese');35 program.parse(['node', 'test', '--no-cheese']);36- expect(program.cheese).toBe(false);36+ expect(program.opts().cheese).toBe(false);37 });38 });39 40 // boolean flag on command41 describe('boolean flag on command', () => {42 test('when boolean flag not specified then value is undefined', () => {43- let subCommand;43+ let subCommandOptions;44 const program = new commander.Command();45 program46 .command('sub')47 .option('--pepper', 'add pepper')48- .action((cmd) => { subCommand = cmd; });48+ .action((options) => { subCommandOptions = options; });49 program.parse(['node', 'test', 'sub']);50- expect(subCommand.pepper).toBeUndefined();50+ expect(subCommandOptions.pepper).toBeUndefined();51 });52 53 test('when boolean flag specified then value is true', () => {54- let subCommand;54+ let subCommandOptions;55 const program = new commander.Command();56 program57 .command('sub')58 .option('--pepper', 'add pepper')59- .action((cmd) => { subCommand = cmd; });59+ .action((options) => { subCommandOptions = options; });60 program.parse(['node', 'test', 'sub', '--pepper']);61- expect(subCommand.pepper).toBe(true);61+ expect(subCommandOptions.pepper).toBe(true);62 });63 64 test('when negatable boolean flag not specified then value is true', () => {65- let subCommand;65+ let subCommandOptions;66 const program = new commander.Command();67 program68 .command('sub')69 .option('--no-cheese', 'remove cheese')70- .action((cmd) => { subCommand = cmd; });70+ .action((options) => { subCommandOptions = options; });71 program.parse(['node', 'test', 'sub']);72- expect(subCommand.cheese).toBe(true);72+ expect(subCommandOptions.cheese).toBe(true);73 });74 75 test('when negatable boolean flag specified then value is false', () => {76- let subCommand;76+ let subCommandOptions;77 const program = new commander.Command();78 program79 .command('sub')80 .option('--no-cheese', 'remove cheese')81- .action((cmd) => { subCommand = cmd; });81+ .action((options) => { subCommandOptions = options; });82 program.parse(['node', 'test', 'sub', '--no-cheese']);83- expect(subCommand.cheese).toBe(false);83+ expect(subCommandOptions.cheese).toBe(false);84 });85 });86 87 // This is a somewhat undocumented special behaviour which appears in some examples.6 unmodified lines94 const program = new commander.Command();95 program96 .option('--olives', 'Add olives? Sorry we only have black.', flagValue);97 program.parse(['node', 'test']);98- expect(program.olives).toBeUndefined();98+ expect(program.opts().olives).toBeUndefined();99 });100 101 test('when flag specified then value is "default" value', () => {102 const flagValue = 'black';103 const program = new commander.Command();104 program105 .option('-v, --olives', 'Add olives? Sorry we only have black.', flagValue);106 program.parse(['node', 'test', '--olives']);107- expect(program.olives).toBe(flagValue);107+ expect(program.opts().olives).toBe(flagValue);108 });109 });110 111 // Regression test for #1301 with `-no-` in middle of option2 unmodified lines114 const program = new commander.Command();115 program116 .option('--module-no-parse');117 program.parse(['node', 'test']);118- expect(program.moduleNoParse).toBeUndefined();118+ expect(program.opts().moduleNoParse).toBeUndefined();119 });120 121 test('when flag specified then value is true', () => {122 const program = new commander.Command();123 program124 .option('--module-no-parse');125 program.parse(['node', 'test', '--module-no-parse']);126- expect(program.moduleNoParse).toEqual(true);126+ expect(program.opts().moduleNoParse).toEqual(true);127 });128 });modified:tests/options.camelcase.test.js+6 added-6 removed
5 unmodified lines6 const program = new commander.Command();7 program8 .option('--my-option', 'description');9 program.parse(['node', 'test', '--my-option']);10- expect(program.myOption).toBe(true);10+ expect(program.opts().myOption).toBe(true);11 });12 13 test('when option defined with --word-wORD then option property is wordWORD', () => {14 const program = new commander.Command();15 program16 .option('--my-oPTION', 'description');17 program.parse(['node', 'test', '--my-oPTION']);18- expect(program.myOPTION).toBe(true);18+ expect(program.opts().myOPTION).toBe(true);19 });20 21 test('when option defined with --word-WORD then option property is wordWORD', () => {22 const program = new commander.Command();23 program24 .option('--my-OPTION', 'description');25 program.parse(['node', 'test', '--my-OPTION']);26- expect(program.myOPTION).toBe(true);26+ expect(program.opts().myOPTION).toBe(true);27 });28 29 test('when option defined with --word-word-word then option property is wordWordWord', () => {30 const program = new commander.Command();31 program32 .option('--my-special-option', 'description');33 program.parse(['node', 'test', '--my-special-option']);34- expect(program.mySpecialOption).toBe(true);34+ expect(program.opts().mySpecialOption).toBe(true);35 });36 37 test('when option defined with --word-WORD-word then option property is wordWORDWord', () => {38 const program = new commander.Command();39 program40 .option('--my-SPECIAL-option', 'description');41 program.parse(['node', 'test', '--my-SPECIAL-option']);42- expect(program.mySPECIALOption).toBe(true);42+ expect(program.opts().mySPECIALOption).toBe(true);43 });44 45 test('when option defined with --Word then option property is Word', () => {46 const program = new commander.Command();47 program48 .option('--Myoption', 'description');49 program.parse(['node', 'test', '--Myoption']);50- expect(program.Myoption).toBe(true);50+ expect(program.opts().Myoption).toBe(true);51 });modified:tests/options.custom-processing.test.js+9 added-9 removed
29 unmodified lines30 const program = new commander.Command();31 program32 .option('-i, --integer <n>', 'number', myParseInt);33 program.parse(['node', 'test']);34- expect(program.integer).toBeUndefined();34+ expect(program.opts().integer).toBeUndefined();35 });36 37 test('when starting value is defined and option not specified then callback not called', () => {38 const mockCoercion = jest.fn();10 unmodified lines49 const program = new commander.Command();50 program51 .option('-i, --integer <n>', 'number', myParseInt, startingValue);52 program.parse(['node', 'test']);53- expect(program.integer).toBe(startingValue);53+ expect(program.opts().integer).toBe(startingValue);54 });55 56 test('when option specified then callback called with value', () => {57 const mockCoercion = jest.fn();12 unmodified lines70 .option('-i, --integer <n>', 'number', () => {71 return callbackResult;72 });73 program.parse(['node', 'test', '-i', '0']);74- expect(program.integer).toBe(callbackResult);74+ expect(program.opts().integer).toBe(callbackResult);75 });76 77 test('when starting value is defined and option specified then callback called with value and starting value', () => {78 const mockCoercion = jest.fn();25 unmodified lines104 program105 .exitOverride()106 .addOption(new commander.Option('--colour <shade>').choices(['red', 'blue']));107 program.parse(['--colour', 'red'], { from: 'user' });108- expect(program.colour).toBe('red');108+ expect(program.opts().colour).toBe('red');109 });110 111 // Now some functional tests like the examples in the README!112 1 unmodified line114 const program = new commander.Command();115 program116 .option('-f, --float <number>', 'float argument', parseFloat);117 program.parse(['node', 'test', '-f', '1e2']);118- expect(program.float).toBe(100);118+ expect(program.opts().float).toBe(100);119 });120 121 test('when myParseInt "1" then value is 1', () => {122 const program = new commander.Command();123 program124 .option('-i, --integer <number>', 'integer argument', myParseInt);125 program.parse(['node', 'test', '-i', '1']);126- expect(program.integer).toBe(1);126+ expect(program.opts().integer).toBe(1);127 });128 129 test('when increaseVerbosity -v -v -v then value is 3', () => {130 const program = new commander.Command();131 program132 .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0);133 program.parse(['node', 'test', '-v', '-v', '-v']);134- expect(program.verbose).toBe(3);134+ expect(program.opts().verbose).toBe(3);135 });136 137 test('when collect -c a -c b -c c then value is [a, b, c]', () => {138 const program = new commander.Command();139 program140 .option('-c, --collect <value>', 'repeatable value', collect, []);141 program.parse(['node', 'test', '-c', 'a', '-c', 'b', '-c', 'c']);142- expect(program.collect).toEqual(['a', 'b', 'c']);142+ expect(program.opts().collect).toEqual(['a', 'b', 'c']);143 });144 145 test('when commaSeparatedList x,y,z then value is [x, y, z]', () => {146 const program = new commander.Command();147 program148 .option('-l, --list <items>', 'comma separated list', commaSeparatedList);149 program.parse(['node', 'test', '--list', 'x,y,z']);150- expect(program.list).toEqual(['x', 'y', 'z']);150+ expect(program.opts().list).toEqual(['x', 'y', 'z']);151 });deleted:tests/options.detectClash.test.js-52 removed
1-const commander = require('../');2-3-// Check detection of likely name clashes4-5-test('when option clashes with property then throw', () => {6- const program = new commander.Command();7- expect(() => {8- program.option('-n, --name <name>');9- }).toThrow();10-});11-12-test('when option clashes with property and storeOptionsAsProperties(true) then ok', () => {13- const program = new commander.Command();14- program.storeOptionsAsProperties(true);15- expect(() => {16- program.option('-n, --name <name>');17- }).not.toThrow();18-});19-20-test('when option would clash with property but storeOptionsAsProperties(false) then ok', () => {21- const program = new commander.Command();22- program.storeOptionsAsProperties(false);23- expect(() => {24- program.option('-n, --name <name>');25- }).not.toThrow();26-});27-28-test('when negated option clashes with property then throw', () => {29- const program = new commander.Command();30- expect(() => {31- program.option('-E, --no-emit');32- }).toThrow();33-});34-35-test('when positive and negative option then ok', () => {36- const program = new commander.Command();37- expect(() => {38- program39- .option('-c, --colour', 'red')40- .option('-C, --no-colour');41- }).not.toThrow();42-});43-44-test('when negative and positive option then ok', () => {45- // Not a likely pattern, but possible and not an error.46- const program = new commander.Command();47- expect(() => {48- program49- .option('-C, --no-colour')50- .option('-c, --colour');51- }).not.toThrow();52-});modified:tests/options.flags.test.js+10 added-10 removed
5 unmodified lines6 const program = new commander.Command();7 program8 .option('-p', 'add pepper');9 program.parse(['node', 'test']);10- expect(program.p).toBeUndefined();10+ expect(program.opts().p).toBeUndefined();11 });12 13 test('when only short flag defined and specified then value is true', () => {14 const program = new commander.Command();15 program16 .option('-p', 'add pepper');17 program.parse(['node', 'test', '-p']);18- expect(program.p).toBe(true);18+ expect(program.opts().p).toBe(true);19 });20 21 test('when only long flag defined and not specified then value is undefined', () => {22 const program = new commander.Command();23 program24 .option('--pepper', 'add pepper');25 program.parse(['node', 'test']);26- expect(program.pepper).toBeUndefined();26+ expect(program.opts().pepper).toBeUndefined();27 });28 29 test('when only long flag defined and specified then value is true', () => {30 const program = new commander.Command();31 program32 .option('--pepper', 'add pepper');33 program.parse(['node', 'test', '--pepper']);34- expect(program.pepper).toBe(true);34+ expect(program.opts().pepper).toBe(true);35 });36 37 test('when "short,long" flags defined and short specified then value is true', () => {38 const program = new commander.Command();39 program40 .option('-p,--pepper', 'add pepper');41 program.parse(['node', 'test', '-p']);42- expect(program.pepper).toBe(true);42+ expect(program.opts().pepper).toBe(true);43 });44 45 test('when "short,long" flags defined and long specified then value is true', () => {46 const program = new commander.Command();47 program48 .option('-p,--pepper', 'add pepper');49 program.parse(['node', 'test', '--pepper']);50- expect(program.pepper).toBe(true);50+ expect(program.opts().pepper).toBe(true);51 });52 53 test('when "short|long" flags defined and short specified then value is true', () => {54 const program = new commander.Command();55 program56 .option('-p|--pepper', 'add pepper');57 program.parse(['node', 'test', '-p']);58- expect(program.pepper).toBe(true);58+ expect(program.opts().pepper).toBe(true);59 });60 61 test('when "short|long" flags defined and long specified then value is true', () => {62 const program = new commander.Command();63 program64 .option('-p|--pepper', 'add pepper');65 program.parse(['node', 'test', '--pepper']);66- expect(program.pepper).toBe(true);66+ expect(program.opts().pepper).toBe(true);67 });68 69 test('when "short long" flags defined and short specified then value is true', () => {70 const program = new commander.Command();71 program72 .option('-p --pepper', 'add pepper');73 program.parse(['node', 'test', '-p']);74- expect(program.pepper).toBe(true);74+ expect(program.opts().pepper).toBe(true);75 });76 77 test('when "short long" flags defined and long specified then value is true', () => {78 const program = new commander.Command();79 program80 .option('-p --pepper', 'add pepper');81 program.parse(['node', 'test', '--pepper']);82- expect(program.pepper).toBe(true);82+ expect(program.opts().pepper).toBe(true);83 });modified:tests/options.mandatory.test.js+14 added-14 removed
8 unmodified lines9 program10 .exitOverride()11 .requiredOption('--cheese <type>', 'cheese type');12 program.parse(['node', 'test', '--cheese', 'blue']);13- expect(program.cheese).toBe('blue');13+ expect(program.opts().cheese).toBe('blue');14 });15 16 test('when program has option with name different than property then still recognised', () => {17 const program = new commander.Command();18 program19 .exitOverride()20 .requiredOption('--cheese-type <type>', 'cheese type');21 program.parse(['node', 'test', '--cheese-type', 'blue']);22- expect(program.cheeseType).toBe('blue');22+ expect(program.opts().cheeseType).toBe('blue');23 });24 25 test('when program has required value default then default value', () => {26 const program = new commander.Command();27 program28 .exitOverride()29 .requiredOption('--cheese <type>', 'cheese type', 'default');30 program.parse(['node', 'test']);31- expect(program.cheese).toBe('default');31+ expect(program.opts().cheese).toBe('default');32 });33 34 test('when program has optional value flag specified then true', () => {35 const program = new commander.Command();36 program37 .exitOverride()38 .requiredOption('--cheese [type]', 'cheese type');39 program.parse(['node', 'test', '--cheese']);40- expect(program.cheese).toBe(true);40+ expect(program.opts().cheese).toBe(true);41 });42 43 test('when program has optional value default then default value', () => {44 const program = new commander.Command();45 program46 .exitOverride()47 .requiredOption('--cheese [type]', 'cheese type', 'default');48 program.parse(['node', 'test']);49- expect(program.cheese).toBe('default');49+ expect(program.opts().cheese).toBe('default');50 });51 52 test('when program has value/no flag specified with value then specified value', () => {53 const program = new commander.Command();1 unmodified line55 .exitOverride()56 .requiredOption('--cheese <type>', 'cheese type')57 .requiredOption('--no-cheese', 'no cheese thanks');58 program.parse(['node', 'test', '--cheese', 'blue']);59- expect(program.cheese).toBe('blue');59+ expect(program.opts().cheese).toBe('blue');60 });61 62 test('when program has mandatory-yes/no flag specified with flag then true', () => {63 const program = new commander.Command();1 unmodified line65 .exitOverride()66 .requiredOption('--cheese', 'cheese type')67 .option('--no-cheese', 'no cheese thanks');68 program.parse(['node', 'test', '--cheese']);69- expect(program.cheese).toBe(true);69+ expect(program.opts().cheese).toBe(true);70 });71 72 test('when program has mandatory-yes/mandatory-no flag specified with flag then true', () => {73 const program = new commander.Command();1 unmodified line75 .exitOverride()76 .requiredOption('--cheese', 'cheese type')77 .requiredOption('--no-cheese', 'no cheese thanks');78 program.parse(['node', 'test', '--cheese']);79- expect(program.cheese).toBe(true);79+ expect(program.opts().cheese).toBe(true);80 });81 82 test('when program has yes/no flag specified negated then false', () => {83 const program = new commander.Command();1 unmodified line85 .exitOverride()86 .requiredOption('--cheese <type>', 'cheese type')87 .option('--no-cheese', 'no cheese thanks');88 program.parse(['node', 'test', '--no-cheese']);89- expect(program.cheese).toBe(false);89+ expect(program.opts().cheese).toBe(false);90 });91 92 test('when program has required value specified and subcommand then specified value', () => {93 const program = new commander.Command();2 unmodified lines96 .requiredOption('--cheese <type>', 'cheese type')97 .command('sub')98 .action(() => {});99 program.parse(['node', 'test', '--cheese', 'blue', 'sub']);100- expect(program.cheese).toBe('blue');100+ expect(program.opts().cheese).toBe('blue');101 });102 });103 104 describe('required program option with mandatory value not specified', () => {67 unmodified lines172 program173 .exitOverride()174 .command('sub')175 .requiredOption('--subby <type>', 'description')176- .action((cmd) => {177- cmdOptions = cmd;176+ .action((options) => {177+ cmdOptions = options;178 });179 180 program.parse(['node', 'test', 'sub', '--subby', 'blue']);181 22 unmodified lines204 program205 .exitOverride()206 .command('sub')207 .requiredOption('--subby <type>', 'description')208- .action((cmd) => {});208+ .action(() => {});209 210 expect(() => {211 program.parse(['node', 'test', 'sub']);212 }).toThrow();4 unmodified lines217 program218 .exitOverride()219 .command('sub')220 .requiredOption('--subby <type>', 'description')221- .action((cmd) => {});221+ .action(() => {});222 program223 .command('sub2');224 225 expect(() => {55 unmodified linesmodified:tests/options.optional.test.js+7 added-7 removed
5 unmodified lines6 const program = new commander.Command();7 program8 .option('--cheese [type]', 'cheese type');9 program.parse(['node', 'test']);10- expect(program.cheese).toBeUndefined();10+ expect(program.opts().cheese).toBeUndefined();11 });12 13 test('when option specified then value is as specified', () => {14 const program = new commander.Command();15 program16 .option('--cheese [type]', 'cheese type');17 const cheeseType = 'blue';18 program.parse(['node', 'test', '--cheese', cheeseType]);19- expect(program.cheese).toBe(cheeseType);19+ expect(program.opts().cheese).toBe(cheeseType);20 });21 22 test('when option specified without value then value is true', () => {23 const program = new commander.Command();24 program25 .option('--cheese [type]', 'cheese type');26 program.parse(['node', 'test', '--cheese']);27- expect(program.cheese).toBe(true);27+ expect(program.opts().cheese).toBe(true);28 });29 30 test('when option specified without value and following option then value is true', () => {31 // optional options do not eat values with dashes1 unmodified line33 program34 .option('--cheese [type]', 'cheese type')35 .option('--some-option');36 program.parse(['node', 'test', '--cheese', '--some-option']);37- expect(program.cheese).toBe(true);37+ expect(program.opts().cheese).toBe(true);38 });39 });40 41 // option with optional value, with default3 unmodified lines45 const program = new commander.Command();46 program47 .option('--cheese [type]', 'cheese type', defaultValue);48 program.parse(['node', 'test']);49- expect(program.cheese).toBe(defaultValue);49+ expect(program.opts().cheese).toBe(defaultValue);50 });51 52 test('when option specified then value is as specified', () => {53 const defaultValue = 'default';1 unmodified line55 program56 .option('--cheese [type]', 'cheese type', defaultValue);57 const cheeseType = 'blue';58 program.parse(['node', 'test', '--cheese', cheeseType]);59- expect(program.cheese).toBe(cheeseType);59+ expect(program.opts().cheese).toBe(cheeseType);60 });61 62 test('when option specified without value then value is default', () => {63 const defaultValue = 'default';64 const program = new commander.Command();65 program66 .option('--cheese [type]', 'cheese type', defaultValue);67 program.parse(['node', 'test', '--cheese']);68- expect(program.cheese).toBe(defaultValue);68+ expect(program.opts().cheese).toBe(defaultValue);69 });70 });modified:tests/options.opts.test.js+2 added-1 removed
1 unmodified line2 3 // Test the `.opts()` way of accessing option values.4 // Basic coverage of the main option types (leaving out negatable flags and options with optional values).5 6-test('when .version used then version in opts', () => {6+test('when .version used with storeOptionsAsProperties() then version in opts', () => {7 const program = new commander.Command();8 const version = '0.0.1';9 program10+ .storeOptionsAsProperties()11 .version(version);12 program.parse(['node', 'test']);13 expect(program.opts()).toEqual({ version });14 });60 unmodified linesmodified:tests/options.required.test.js+4 added-4 removed
5 unmodified lines6 const program = new commander.Command();7 program8 .option('--cheese <type>', 'cheese type');9 program.parse(['node', 'test']);10- expect(program.cheese).toBeUndefined();10+ expect(program.opts().cheese).toBeUndefined();11 });12 13 test('when option specified then value is as specified', () => {14 const program = new commander.Command();15 program16 .option('--cheese <type>', 'cheese type');17 const cheeseType = 'blue';18 program.parse(['node', 'test', '--cheese', cheeseType]);19- expect(program.cheese).toBe(cheeseType);19+ expect(program.opts().cheese).toBe(cheeseType);20 });21 22 test('when option value not specified then error', () => {23 // Arrange. Mock error routine to allow interception.22 unmodified lines46 const program = new commander.Command();47 program48 .option('--cheese <type>', 'cheese type', defaultValue);49 program.parse(['node', 'test']);50- expect(program.cheese).toBe(defaultValue);50+ expect(program.opts().cheese).toBe(defaultValue);51 });52 53 test('when option specified then value is as specified', () => {54 const defaultValue = 'default';1 unmodified line56 program57 .option('--cheese <type>', 'cheese type', defaultValue);58 const cheeseType = 'blue';59 program.parse(['node', 'test', '--cheese', cheeseType]);60- expect(program.cheese).toBe(cheeseType);60+ expect(program.opts().cheese).toBe(cheeseType);61 });62 63 test('when option value not specified then error', () => {64 // Arrange. Mock error routine to allow interception.18 unmodified linesmodified:tests/options.values.test.js+9 added-9 removed
16 unmodified lines17 18 test('when short flag followed by value then value is as specified', () => {19 const program = createPortProgram();20 program.parse(['node', 'test', '-p', value]);21- expect(program.port).toBe(value);21+ expect(program.opts().port).toBe(value);22 });23 24 test('when short flag concatenated with value then value is as specified', () => {25 const program = createPortProgram();26 program.parse(['node', 'test', `-p${value}`]);27- expect(program.port).toBe(value);27+ expect(program.opts().port).toBe(value);28 });29 30 test('when long flag followed by value then value is as specified', () => {31 const program = createPortProgram();32 program.parse(['node', 'test', '--port', value]);33- expect(program.port).toBe(value);33+ expect(program.opts().port).toBe(value);34 });35 36 test('when long flag = value then value is as specified', () => {37 const program = createPortProgram();38 program.parse(['node', 'test', `--port=${value}`]);39- expect(program.port).toBe(value);39+ expect(program.opts().port).toBe(value);40 });41 });42 43 // option with optional value7 unmodified lines51 52 test('when short flag followed by value then value is as specified', () => {53 const program = createPortProgram();54 program.parse('node test -p 80'.split(' '));55- expect(program.port).toBe('80');55+ expect(program.opts().port).toBe('80');56 });57 58 test('when short flag concatenated with value then value is as specified', () => {59 const program = createPortProgram();60 program.parse('node test -p80'.split(' '));61- expect(program.port).toBe('80');61+ expect(program.opts().port).toBe('80');62 });63 64 test('when long flag followed by value then value is as specified', () => {65 const program = createPortProgram();66 program.parse('node test --port 80'.split(' '));67- expect(program.port).toBe('80');67+ expect(program.opts().port).toBe('80');68 });69 70 test('when long flag = value then value is as specified', () => {71 const program = createPortProgram();72 program.parse('node test --port=80'.split(' '));73- expect(program.port).toBe('80');73+ expect(program.opts().port).toBe('80');74 });75 76 test('when long flag followed empty string then value is empty string', () => {77 const program = createPortProgram();78 program79 .option('-c, --cheese [type]', 'optionally specify the type of cheese');80 program.parse(['node', 'test', '--cheese', '']);81- expect(program.cheese).toBe('');81+ expect(program.opts().cheese).toBe('');82 });83 });modified:typings/commander-tests.ts+2 added-18 removed
7 unmodified lines8 9 // This conflicts with esline rule saying no space!10 /* eslint-disable @typescript-eslint/space-before-function-paren */11 12-// Defined stricter type, as the options as properties `[key: string]: any`13-// makes the type checking very weak.14-// https://github.com/Microsoft/TypeScript/issues/25987#issuecomment-44122469015-type KnownKeys<T> = {16- [K in keyof T]: string extends K ? never : number extends K ? never : K17-} extends {[_ in keyof T]: infer U} ? ({} extends U ? never : U) : never;18-type CommandWithoutOptionsAsProperties = Pick<commander.Command, KnownKeys<commander.Command>>;19-20-const program: CommandWithoutOptionsAsProperties = commander.program;21-const programWithOptions = commander.program;12+const program: commander.Command = new commander.Command();13 // program.silly; // <-- Error, hurrah!14 15 // Check for exported global Command objects16 const importedDefaultProgram: commander.Command = commander;6 unmodified lines23 const errorInstance = new commander.CommanderError(1, 'code', 'message');24 const invalidOptionErrorInstance = new commander.InvalidOptionArgumentError('message');25 26 // Command properties36-console.log(programWithOptions.someOption);37-// eslint-disable-next-line @typescript-eslint/dot-notation38-console.log(programWithOptions['someOption']);39-const theArgs = program.args;27+const theArgs: string[] = program.args;28 const theCommands: commander.Command[] = program.commands;29 30 // version31 const versionThis1: commander.Command = program.version('1.2.3');102 unmodified lines134 // storeOptionsAsProperties135 const storeOptionsAsPropertiesThis1: commander.Command = program.storeOptionsAsProperties();136 const storeOptionsAsPropertiesThis2: commander.Command = program.storeOptionsAsProperties(false);137 150-// passCommandToAction151-const passCommandToActionThis1: commander.Command = program.passCommandToAction();152-const passCommandToActionThis2: commander.Command = program.passCommandToAction(false);153-138 // combineFlagAndOptionalValue139 const combineFlagAndOptionalValueThis1: commander.Command = program.combineFlagAndOptionalValue();140 const combineFlagAndOptionalValueThis2: commander.Command = program.combineFlagAndOptionalValue(false);141 189 unmodified linesmodified:typings/index.d.ts-10 removed
147 unmodified lines148 149 type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';150 151 interface Command {152- [key: string]: any; // options as properties153-152 args: string[];153 154 commands: Command[];155 218 unmodified lines374 */375 storeOptionsAsProperties(storeAsProperties?: boolean): this;376 377 /**380- * Whether to pass command to action handler,381- * or just the options (specify false).382- *383- * @returns `this` command for chaining384- */385- passCommandToAction(passCommand?: boolean): this;386-387- /**378 * Alter parsing of short flags with optional values.379 *380 * @example381 * // for `.option('-f,--flag [value]'):211 unmodified linesmodified:CHANGELOG.md+95 added
6 unmodified lines7 8 <!-- markdownlint-disable MD024 -->9 <!-- markdownlint-disable MD004 -->10 11+## [Unreleased] (date goes here)12+13+### Migration Tips14+15+The biggest change is the parsed option values. Previously the options were stored by default as properties on the command object, and now the options are stored separately.16+17+If you wish to restore the old behaviour and get running quickly you can call `.storeOptionsAsProperties()`. 18+To allow you to move to the new code patterns incrementally, the action handler will be passed the command _twice_,19+to match the new "options" and "command" parameters (see below).20+21+**program options**22+23+Use the `.opts()` method to access the options. This is available on any command but is used most with the program.24+25+```js26+program.option('-d, --debug');27+program.parse();28+// Old code before Commander 729+if (program.debug) console.log(`Program name is ${program.name()}`);30+```31+32+```js33+// New code34+const options = program.opts();35+if (options.debug) console.log(`Program name is ${program.name()}`);36+```37+38+**action handler**39+40+The action handler gets passed a parameter for each command-argument you declared. Previously by default the next parameter was the command object with the options as properties. Now the next two parameters are instead the options and the command. If you41+only accessed the options there may be no code changes required.42+43+```js44+program45+ .command('compress <filename>')46+ .option('-t, --trace')47+ // Old code before Commander 748+ .action((filename, cmd)) => {49+ if (cmd.trace) console.log(`Command name is ${cmd.name()}`);50+ });51+```52+53+```js54+ // New code55+ .action((filename, options, command)) => {56+ if (options.trace) console.log(`Command name is ${command.name()}`);57+ });58+```59+60+If you already set `.storeOptionsAsProperties(false)` you may still need to adjust your code.61+62+```js63+program64+ .command('compress <filename>')65+ .storeOptionsAsProperties(false)66+ .option('-t, --trace')67+ // Old code before Commander 768+ .action((filename, command)) => {69+ if (command.opts().trace) console.log(`Command name is ${command.name()}`);70+ });71+```72+73+```js74+ // New code75+ .action((filename, options, command)) => {76+ if (command.opts().trace) console.log(`Command name is ${command.name()}`);77+ });78+```79+80+**excess command-arguments**81+82+There is now an error if there are too many command-arguments on the command line (only checked if there is an action handler).83+If the extra arguments are supported by your command then you can either declare the expected arguments, or allow excess arguments.84+85+```js86+// Old code before Commander 787+program88+ .action(() => {});89+program.parse(['a', 'b', 'c'], { from: 'user' }); // now causes an error90+```91+92+```js93+// New code, declare arguments94+program95+ .arguments('[args...]')96+ .action(() => {});97+```98+99+```js100+// New code, allow excess arguments101+program102+ .allowExcessArguments()103+ .action(() => {});104+```105+106 ## [7.0.0-1] (2020-11-21)107 108 ### Added109 287 unmodified linesmodified:index.js+5 added-70 removed
533 unmodified lines534 this.commands = [];535 this.options = [];536 this.parent = null;537 this._allowUnknownOption = false;538- this._allowExcessArguments = true;538+ this._allowExcessArguments = false;539 this._args = [];540 this.rawArgs = null;541 this._scriptPath = null;542 this._name = name || '';543 this._optionValues = {};544- this._storeOptionsAsProperties = true; // backwards compatible by default545- this._storeOptionsAsPropertiesCalled = false;546- this._passCommandToAction = true; // backwards compatible by default544+ this._storeOptionsAsProperties = false;545 this._actionResults = [];546 this._actionHandler = null;547 this._executableHandler = false;548 this._executableFile = null; // custom name for executable82 unmodified lines631 cmd._helpCommandDescription = this._helpCommandDescription;632 cmd._helpConfiguration = this._helpConfiguration;633 cmd._exitCallback = this._exitCallback;634 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;637- cmd._passCommandToAction = this._passCommandToAction;635 cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;636 637 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor638 this.commands.push(cmd);253 unmodified lines892 const listener = (args) => {893 // The .action callback takes an extra parameter which is the command or options.894 const expectedArgsCount = this._args.length;895 const actionArgs = args.slice(0, expectedArgsCount);899- if (this._passCommandToAction) {900- actionArgs[expectedArgsCount] = this;896+ if (this._storeOptionsAsProperties) {897+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"898 } else {899 actionArgs[expectedArgsCount] = this.opts();900 }904- // Add the extra arguments so available too.905- if (args.length > expectedArgsCount) {906- actionArgs.push(args.slice(expectedArgsCount));907- }901+ actionArgs.push(this);902 903 const actionResult = fn.apply(this, actionArgs);904 // Remember result in case it is async. Assume parseAsync getting called on root.905 let rootCommand = this;6 unmodified lines912 return this;913 };914 915 /**922- * Internal routine to check whether there is a clash storing option value with a Command property.923- *924- * @param {Option} option925- * @api private926- */927-928- _checkForOptionNameClash(option) {929- if (!this._storeOptionsAsProperties || this._storeOptionsAsPropertiesCalled) {930- // Storing options safely, or user has been explicit and up to them.931- return;932- }933- // User may override help, and hard to tell if worth warning.934- if (option.name() === 'help') {935- return;936- }937-938- const commandProperty = this._getOptionValue(option.attributeName());939- if (commandProperty === undefined) {940- // no clash941- return;942- }943-944- let foundClash = true;945- if (option.negate) {946- // It is ok if define foo before --no-foo.947- const positiveLongFlag = option.long.replace(/^--no-/, '--');948- foundClash = !this._findOption(positiveLongFlag);949- } else if (option.long) {950- const negativeLongFlag = option.long.replace(/^--/, '--no-');951- foundClash = !this._findOption(negativeLongFlag);952- }953-954- if (foundClash) {955- throw new Error(`option '${option.name()}' clashes with existing property '${option.attributeName()}' on Command956-- call storeOptionsAsProperties(false) to store option values safely,957-- or call storeOptionsAsProperties(true) to suppress this check,958-- or change option name959-960-Read more on https://git.io/JJc0W`);961- }962- };963-964- /**916 * Factory routine to create a new unattached option.917 *918 * See .option() for creating an attached option, which uses this routine to919 * create the option. You can override createOption to return a custom option.16 unmodified lines936 addOption(option) {937 const oname = option.name();938 const name = option.attributeName();939 989- this._checkForOptionNameClash(option);990-940 let defaultValue = option.defaultValue;941 942 // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value943 if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {197 unmodified lines1141 * @return {Command} `this` command for chaining1142 */1143 1144 storeOptionsAsProperties(storeAsProperties = true) {1196- this._storeOptionsAsPropertiesCalled = true;1145 this._storeOptionsAsProperties = !!storeAsProperties;1146 if (this.options.length) {1147 throw new Error('call .storeOptionsAsProperties() before adding options');1148 }1149 return this;1150 };1151 1152 /**1205- * Whether to pass command to action handler,1206- * or just the options (specify false).1207- *1208- * @param {boolean} [passCommand=true]1209- * @return {Command} `this` command for chaining1210- */1211-1212- passCommandToAction(passCommand = true) {1213- this._passCommandToAction = !!passCommand;1214- return this;1215- };1216-1217- /**1153 * Store option value1154 *1155 * @param {string} key1156 * @param {Object} value990 unmodified linesmodified:Readme.md+104 added-105 removed
21 unmodified lines22 - [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)26+ - [Action handler](#action-handler)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)3 unmodified lines34 - [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)38+ - [Legacy options as properties](#legacy-options-as-properties)39 - [TypeScript](#typescript)40 - [createCommand()](#createcommand)41 - [Import into ECMAScript Module](#import-into-ecmascript-module)42 - [Node options such as `--harmony`](#node-options-such-as---harmony)33 unmodified lines76 ## Options77 78 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 or vertical bar ('|').79 80-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. See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes).80+The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler. Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.81 82 Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value).83 For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.84 15 unmodified lines100 .option('-p, --pizza-type <type>', 'flavour of pizza');101 102 program.parse(process.argv);103 104-if (program.debug) console.log(program.opts());104+const options = program.opts();105+if (options.debug) console.log(options);106 console.log('pizza details:');106-if (program.small) console.log('- small pizza size');107-if (program.pizzaType) console.log(`- ${program.pizzaType}`);107+if (options.small) console.log('- small pizza size');108+if (options.pizzaType) console.log(`- ${options.pizzaType}`);109 ```110 111 ```bash112 $ pizza-options -d10 unmodified lines123 pizza details:124 - cheese125 ```126 126-`program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array.127+`program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array. The parameter is optional and defaults to `process.argv`.128 129 ### Default option value130 131 You can specify a default value for an option which takes a value.3 unmodified lines135 ```js136 program137 .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');138 138-program.parse(process.argv);139+program.parse();140 140-console.log(`cheese: ${program.cheese}`);141+console.log(`cheese: ${program.opts().cheese}`);142 ```143 144 ```bash145 $ pizza-options16 unmodified lines162 program163 .option('--no-sauce', 'Remove sauce')164 .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')165 .option('--no-cheese', 'plain with no cheese')165- .parse(process.argv);166+ .parse();167 168+const options = program.opts();167-const sauceStr = program.sauce ? 'sauce' : 'no sauce';168-const cheeseStr = (program.cheese === false) ? 'no cheese' : `${program.cheese} cheese`;169+const sauceStr = options.sauce ? 'sauce' : 'no sauce';170+const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;171 console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);172 ```173 174 ```bash17 unmodified lines192 .option('-c, --cheese [type]', 'Add cheese with optional type');193 194 program.parse(process.argv);195 196+const options = program.opts();194-if (program.cheese === undefined) console.log('no cheese');195-else if (program.cheese === true) console.log('add cheese');196-else console.log(`add cheese type ${program.cheese}`);197+if (options.cheese === undefined) console.log('no cheese');198+else if (options.cheese === true) console.log('add cheese');199+else console.log(`add cheese type ${options.cheese}`);200 ```201 202 ```bash203 $ pizza-options15 unmodified lines219 ```js220 program221 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');222 220-program.parse(process.argv);223+program.parse();224 ```225 226 ```bash227 $ pizza121 unmodified lines349 .option('-c, --collect <value>', 'repeatable value', collect, [])350 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)351 ;352 350-program.parse(process.argv);353+program.parse();354 352-if (program.float !== undefined) console.log(`float: ${program.float}`);353-if (program.integer !== undefined) console.log(`integer: ${program.integer}`);354-if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);355-if (program.collect.length > 0) console.log(program.collect);356-if (program.list !== undefined) console.log(program.list);355+const options = program.opts();356+if (options.float !== undefined) console.log(`float: ${options.float}`);357+if (options.integer !== undefined) console.log(`integer: ${options.integer}`);358+if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);359+if (options.collect.length > 0) console.log(options.collect);360+if (options.list !== undefined) console.log(options.list);361 ```362 363 ```bash364 $ custom -f 1e250 unmodified lines415 included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required command-arguments.416 Square brackets (e.g. `[optional]`) indicate optional command-arguments.417 You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`.418 415-Example file: [env](./examples/env)419+Example file: [arguments.js](./examples/arguments.js)420 421 ```js422 program423 .version('0.1.0')420- .arguments('<cmd> [env]')424+ .arguments('<username> [password]')425 .description('test command', {422- cmd: 'command to run',423- env: 'environment to run test in'426+ username: 'user to login',427+ password: 'password for user, if required'428 })425- .action(function (cmd, env) {426- console.log('command:', cmd);427- console.log('environment:', env || 'no environment given');429+ .action((username, password) => {430+ console.log('username:', username);431+ console.log('environment:', password || 'no password given');432 });429-430-program.parse(process.argv);433 ```434 435 The last argument of a command can be variadic, and only the last argument. To make an argument variadic you436 append `...` to the argument name. For example:437 438 ```js437-const { program } = require('commander');438-439 program440 .version('0.1.0')441- .command('rmdir <dir> [otherDirs...]')442- .action(function (dir, otherDirs) {443- console.log('rmdir %s', dir);444- if (otherDirs) {445- otherDirs.forEach(function (oDir) {446- console.log('rmdir %s', oDir);447- });448- }441+ .command('rmdir <dirs...>')442+ .action(function (dirs) {443+ dirs.forEach((dir) => {444+ console.log('rmdir %s', dir);445+ });446 });450-451-program.parse(process.argv);447 ```448 449 The variadic argument is passed to the action handler as an array.450 456-### Action handler (sub)commands451+### Action handler452 458-You can add options to a command that uses an action handler.459-The action handler gets passed a parameter for each argument you declared, and one additional argument which is the460-command object itself. This command argument has the values for the command-specific options added as properties.453+The action handler gets passed a parameter for each command-argument you declared, and two additional parameters454+which are the parsed options and the command object itself. 455 462-```js463-const { program } = require('commander');456+Example file: [thank.js](./examples/thank.js)457 458+```js459 program466- .command('rm <dir>')467- .option('-r, --recursive', 'Remove recursively')468- .action(function (dir, cmdObj) {469- console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : ''))470- })471-472-program.parse(process.argv)460+ .arguments('<name>')461+ .option('-t, --title <honorific>', 'title to use before name')462+ .option('-d, --debug', 'display some debugging')463+ .action((name, options, command) => {464+ if (options.debug) {465+ console.error('Called %s with options %o', command.name(), options);466+ }467+ const title = options.title ? `${options.title} ` : '';468+ console.log(`Thank-you ${title}${name}`);469+ });470 ```471 472 You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.473 7 unmodified lines481 await program.parseAsync(process.argv);482 }483 ```484 488-A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error.485+A command's options and arguments on the command line are validated when the command is used. Any unknown options or unexpected command-arguments will be reported as an error, or you can suppress these checks with `.allowUnknownOption()` and `.allowExcessArguments()`.486 487 ### Stand-alone executable (sub)commands488 489 When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.27 unmodified lines517 ```bash518 $ node ./examples/pizza --help519 Usage: pizza [options]520 524-An application for pizzas ordering521+An application for pizza ordering522 523 Options:527- -V, --version output the version number524 -p, --peppers Add peppers525 -c, --cheese <type> Add the specified type of cheese (default: "marble")526 -C, --no-cheese You do not want any cheese527 -h, --help display help for command155 unmodified lines683 program.parse(); // Implicit, and auto-detect electron684 program.parse(['-f', 'filename'], { from: 'user' });685 ```686 691-### Avoiding option name clashes687+### Legacy options as properties 688 693-The original and default behaviour is that the option values are stored694-as properties on the program, and the action handler is passed a695-command object with the options values stored as properties.696-This is very convenient to code, but the downside is possible clashes with697-existing properties of Command.689+Before Commander 7, the option values were stored as properties on the command.690+This was convenient to code but the downside was possible clashes with691+existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.692 699-There are two new routines to change the behaviour, and the default behaviour may change in the future:700-701-- `storeOptionsAsProperties`: whether to store option values as properties on command object, or store separately (specify false) and access using `.opts()`702-- `passCommandToAction`: whether to pass command to action handler,703-or just the options (specify false)704-705-Example file: [storeOptionsAsProperties-action.js](./examples/storeOptionsAsProperties-action.js)706-693 ```js694 program709- .storeOptionsAsProperties(false)710- .passCommandToAction(false);711-712-program713- .name('my-program-name')714- .option('-n,--name <name>');715-716-program717- .command('show')718- .option('-a,--action <action>')719- .action((options) => {720- console.log(options.action);695+ .storeOptionsAsProperties()696+ .option('-d, --debug')697+ .action((commandAndOptions) => {698+ if (commandAndOptions.debug) {699+ console.error(`Called ${commandAndOptions.name()}`);700+ }701 });722-723-program.parse(process.argv);724-725-const programOptions = program.opts();726-console.log(programOptions.name);702 ```703 704 ### TypeScript705 93 unmodified lines799 - [options taking varying arguments](./docs/options-taking-varying-arguments.md)800 801 ## Examples802 828-Example file: [deploy](./examples/deploy)803+In a single command program, you might not need an action handler.804 805+Example file: [pizza](./examples/pizza)806+807 ```js808 const { program } = require('commander');809 810 program834- .version('0.1.0')835- .option('-C, --chdir <path>', 'change the working directory')836- .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')837- .option('-T, --no-tests', 'ignore test hook');811+ .description('An application for pizza ordering')812+ .option('-p, --peppers', 'Add peppers')813+ .option('-c, --cheese <type>', 'Add the specified type of cheese', 'marble')814+ .option('-C, --no-cheese', 'You do not want any cheese');815 816+program.parse();817+818+const options = program.opts();819+console.log('you ordered a pizza with:');820+if (options.peppers) console.log(' - peppers');821+const cheese = !options.cheese ? 'no' : options.cheese;822+console.log(' - %s cheese', cheese);823+```824+825+In a multi-command program, you will have action handlers for each command (or stand-alone executables for the commands).826+827+Example file: [deploy](./examples/deploy)828+829+```js830+const { Command } = require('commander');831+const program = new Command();832+833 program834+ .version('0.0.1')835+ .option('-c, --config <path>', 'set config path', './deploy.conf');836+837+program838 .command('setup [env]')839 .description('run setup commands for all envs')842- .option("-s, --setup_mode [mode]", "Which setup mode to use")843- .action(function(env, options){844- const mode = options.setup_mode || "normal";840+ .option('-s, --setup_mode <mode>', 'Which setup mode to use', 'normal')841+ .action((env, options) => {842 env = env || 'all';843+ console.log('read config from %s', program.opts().config);846- console.log('setup for %s env(s) with %s mode', env, mode);844+ console.log('setup for %s env(s) with %s mode', env, options.setup_mode);845 });846 847 program850- .command('exec <cmd>')848+ .command('exec <script>')849 .alias('ex')850 .description('execute the given remote cmd')853- .option("-e, --exec_mode <mode>", "Which exec mode to use")854- .action(function(cmd, options){855- console.log('exec "%s" using %s mode', cmd, options.exec_mode);851+ .option('-e, --exec_mode <mode>', 'Which exec mode to use', 'fast')852+ .action((script, options) => {853+ console.log('read config from %s', program.opts().config);854+ console.log('exec "%s" using %s mode and config %s', script, options.exec_mode, program.opts().config);855 }).addHelpText('after', `856 Examples:857 $ deploy exec sequential858 $ deploy exec async`859 );861-860+ 861 program.parse(process.argv);862 ```863 865-More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.864+More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.865 866 ## Support867 868 The current version of Commander is fully supported on Long Term Support versions of Node, and is likely to work with Node 6 but not tested.9 unmodified lines