Skip to content
Myr

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

authored by John Gee · committed by GitHub · parent 1db83b6 · Browse files · 46 files+475 added−669 removed
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

46 files+475 added−669 removed

added:examples/arguments.js+26 added
modified:examples/custom-command-class.js+4 added-4 removed
modified:examples/custom-command-function.js+4 added-4 removed
modified:examples/custom-help-description+1 added-1 removed
12 unmodified lines
1314program15 .command('child')16 .option('--gender', 'specific gender of child')17 .action((cmd) => {17 .action((options) => {18 console.log('Childsubcommand...');19 });2021program.parse(process.argv);
modified:examples/defaultCommand.js+2 added-2 removed
modified:examples/deploy+10 added-11 removed
4 unmodified lines
5const program = new Command();67program8 .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');1011program12 .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 });2021program24 .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', `30Examples:31 $ deploy exec sequential32 $ deploy exec async`
3 unmodified lines
deleted:examples/env-29 removed
1#!/usr/bin/env node23// This example shows specifying the arguments for the program to pass to the action handler.45// const { Command } = require('commander'); // (normal include)6const { Command } = require('../'); // include commander in git clone of commander repo7const program = new Command();89let cmdValue;10let envValue;1112program13 .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 });2324program.parse(process.argv);2526// Try the following:27// node env --help28// node env add29// node env add browser
modified:examples/options-boolean-or-value.js+9 added-12 removed
modified:examples/options-common.js+10 added-20 removed
1#!/usr/bin/env node23// 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// - cheese56// const commander = require('commander'); // (normal include)7const commander = require('../'); // include commander in git clone of commander repo8const program = new commander.Command();
4 unmodified lines
13 .option('-p, --pizza-type <type>', 'flavour of pizza');1415program.parse(process.argv);1634if (program.debug) console.log(program.opts());17const options = program.opts();18if (options.debug) console.log(options);19console.log('pizza details:');36if (program.small) console.log('- small pizza size');37if (program.pizzaType) console.log(`- ${program.pizzaType}`);20if (options.small) console.log('- small pizza size');21if (options.pizzaType) console.log(`- ${options.pizzaType}`);2223// 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=cheese
modified:examples/options-custom-processing.js+16 added-22 removed
1#!/usr/bin/env node23// 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.67// const commander = require('commander'); // (normal include)8const commander = require('../'); // include commander in git clone of commander repo9const program = new commander.Command();
26 unmodified lines
36 .option('-c, --collect <value>', 'repeatable value', collect, [])37 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)38;3955program.parse(process.argv);56if (program.float !== undefined) console.log(`float: ${program.float}`);57if (program.integer !== undefined) console.log(`integer: ${program.integer}`);58if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);59if (program.collect.length > 0) console.log(program.collect);60if (program.list !== undefined) console.log(program.list);40program.parse();4142const options = program.opts();43if (options.float !== undefined) console.log(`float: ${options.float}`);44if (options.integer !== undefined) console.log(`integer: ${options.integer}`);45if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);46if (options.collect.length > 0) console.log(options.collect);47if (options.list !== undefined) console.log(options.list);4849// 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,z
modified:examples/options-defaults.js+6 added-10 removed
1#!/usr/bin/env node23// 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: stilton56// const commander = require('commander'); // (normal include)7const commander = require('../'); // include commander in git clone of commander repo8const program = new commander.Command();910program11 .option('-c, --cheese <type>', 'Add the specified type of cheese', 'blue');1221program.parse(process.argv);13program.parse();1423console.log(`cheese: ${program.cheese}`);15console.log(`cheese: ${program.opts().cheese}`);1617// Try the following:18// node options-defaults.js19// node options-defaults.js --cheese stilton
modified:examples/options-negatable.js+10 added-14 removed
1 unmodified line
23// 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 cheese67// const commander = require('commander'); // (normal include)8const commander = require('../'); // include commander in git clone of commander repo9const program = new commander.Command();
2 unmodified lines
12 .option('--no-sauce', 'Remove sauce')13 .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')14 .option('--no-cheese', 'plain with no cheese');1527program.parse(process.argv);16program.parse();1718const options = program.opts();29const sauceStr = program.sauce ? 'sauce' : 'no sauce';30const cheeseStr = (program.cheese === false) ? 'no cheese' : `${program.cheese} cheese`;19const sauceStr = options.sauce ? 'sauce' : 'no sauce';20const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;21console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);2223// 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-cheese
modified:examples/options-required.js+1 added-1 removed
15 unmodified lines
1617program18 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');1920program.parse(process.argv);20program.parse();
modified:examples/pizza+5 added-10 removed
3 unmodified lines
4const { Command } = require('../'); // include commander in git clone of commander repo5const program = new Command();67program8 .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');1214program.parse(process.argv);13program.parse();1415const options = program.opts();16console.log('you ordered a pizza with:');17if (program.peppers) console.log(' - peppers');18if (program.pineapple) console.log(' - pineapple');19if (program.bbq) console.log(' - bbq');2021const cheese = !program.cheese ? 'no' : program.cheese;2217if (options.peppers) console.log(' - peppers');18const cheese = !options.cheese ? 'no' : options.cheese;19console.log(' - %s cheese', cheese);24console.log(program.args);
deleted:examples/storeOptionsAsProperties-action.js-41 removed
1#!/usr/bin/env node23// 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// foo1819// const commander = require('commander'); // (normal include)20const commander = require('../'); // include commander in git clone of commander repo21const program = new commander.Command();2223program24 .storeOptionsAsProperties(false) // <--- change behaviour25 .passCommandToAction(false); // <--- change behaviour2627program28 .name('my-program-name')29 .option('-n,--name <name>');3031program32 .command('show')33 .option('-a,--action <action>')34 .action((options) => { // <--- passed options, not Command35 console.log(options.action); // <--- matches old code36 });3738program.parse(process.argv);3940const programOptions = program.opts(); // <--- use opts to access option values41console.log(programOptions.name);
deleted:examples/storeOptionsAsProperties-opts.js-39 removed
1#!/usr/bin/env node23// 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// foo1617// const commander = require('commander'); // (normal include)18const commander = require('../'); // include commander in git clone of commander repo19const program = new commander.Command();2021program22 .storeOptionsAsProperties(false); // <--- change behaviour2324program25 .name('my-program-name')26 .option('-n,--name <name>');2728program29 .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 });3536program.parse(process.argv);3738const programOptions = program.opts(); // <--- use opts to access option values39console.log(programOptions.name);
deleted:examples/storeOptionsAsProperties-problem.js-36 removed
1#!/usr/bin/env node23// 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// foo1819// const commander = require('commander'); // (normal include)20const commander = require('../'); // include commander in git clone of commander repo21const program = new commander.Command();2223program24 .name('my-program-name')25 .option('-n,--name <name>'); // Oops, clash with .name()2627program28 .command('show')29 .option('-a,--action <action>') // Oops, clash with .action()30 .action((cmd) => {31 console.log(cmd.action);32 });3334program.parse(process.argv);3536console.log(program.name);
added:examples/thank.js+26 added
1#!/usr/bin/env node23// This example is used as an example in the README for the action handler.45// const { Command } = require('commander'); // (normal include)6const { Command } = require('../'); // include commander in git clone of commander repo7const program = new Command();89program10 .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 });2021program.parse();2223// Try the following:24// node thank.js John25// node thank.js Doe --title Mr26// node thank.js --debug Doe --title Mr
modified:tests/args.literal.test.js+3 added-2 removed
10 unmodified lines
11 .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});2021test('when arguments include -- then more literals are passed-through as args', () => {
7 unmodified lines
modified:tests/args.variadic.test.js+4 added-4 removed
10 unmodified lines
11 .action(actionMock);1213 program.parse(['node', 'test', 'id']);1415 expect(actionMock).toHaveBeenCalledWith('id', [], program);15 expect(actionMock).toHaveBeenCalledWith('id', [], program.opts(), program);16 });1718 test('when extra arguments specified for program then variadic arg is array of values', () => {19 const actionMock = jest.fn();
4 unmodified lines
24 const extraArguments = ['a', 'b', 'c'];2526 program.parse(['node', 'test', 'id', ...extraArguments]);2728 expect(actionMock).toHaveBeenCalledWith('id', extraArguments, program);28 expect(actionMock).toHaveBeenCalledWith('id', extraArguments, program.opts(), program);29 });3031 test('when no extra arguments specified for command then variadic arg is empty array', () => {32 const actionMock = jest.fn();
3 unmodified lines
36 .action(actionMock);3738 program.parse(['node', 'test', 'sub']);3940 expect(actionMock).toHaveBeenCalledWith([], cmd);40 expect(actionMock).toHaveBeenCalledWith([], cmd.opts(), cmd);41 });4243 test('when extra arguments specified for command then variadic arg is array of values', () => {44 const actionMock = jest.fn();
4 unmodified lines
49 const extraArguments = ['a', 'b', 'c'];5051 program.parse(['node', 'test', 'sub', ...extraArguments]);5253 expect(actionMock).toHaveBeenCalledWith(extraArguments, cmd);53 expect(actionMock).toHaveBeenCalledWith(extraArguments, cmd.opts(), cmd);54 });5556 test('when program variadic argument not last then error', () => {57 const program = new commander.Command();
14 unmodified lines
modified:tests/command.action.test.js+7 added-19 removed
7 unmodified lines
8 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});1415test('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 .action
5 unmodified lines
22 program.parse(['node', 'test', 'info', 'my-file']);23 expect(program.args).toEqual(['info', 'my-file']);24});2526test('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});3726test('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});3536test('when .action on program with required argument and argument not supplied then action not called', () => {37 const actionMock = jest.fn();
15 unmodified lines
53 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});5960test('when .action on program with optional argument supplied then action called', () => {61 const actionMock = jest.fn();
1 unmodified line
63 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});6970test('when .action on program without optional argument supplied then action called', () => {71 const actionMock = jest.fn();
1 unmodified line
73 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});7980test('when .action on program with optional argument and subcommand and program argument then program action called', () => {81 const actionMock = jest.fn();
5 unmodified lines
87 .command('subcommand');8889 program.parse(['node', 'test', 'a']);90103 expect(actionMock).toHaveBeenCalledWith('a', program);91 expect(actionMock).toHaveBeenCalledWith('a', program.opts(), program);92});9394// Changes made in #1062 to allow this case95test('when .action on program with optional argument and subcommand and no program argument then program action called', () => {
6 unmodified lines
102 .command('subcommand');103104 program.parse(['node', 'test']);105118 expect(actionMock).toHaveBeenCalledWith(undefined, program);106 expect(actionMock).toHaveBeenCalledWith(undefined, program.opts(), program);107});108109test('when action is async then can await parseAsync', async() => {110 let asyncFinished = false;
13 unmodified lines
modified:tests/command.allowExcessArguments.test.js+4 added-4 removed
16 unmodified lines
17 afterAll(() => {18 writeErrorSpy.mockRestore();19 });2021 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(() => {});2627 expect(() => {28 program.parse(['excess'], { from: 'user' });29 }).not.toThrow();29 }).toThrow();30 });3132 test('when specify excess program argument and allowExcessArguments(false) then error', () => {33 const program = new commander.Command();
30 unmodified lines
64 program.parse(['excess'], { from: 'user' });65 }).not.toThrow();66 });6768 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(() => { });7475 expect(() => {76 program.parse(['sub', 'excess'], { from: 'user' });77 }).not.toThrow();77 }).toThrow();78 });7980 test('when specify excess command argument and allowExcessArguments(false) then error', () => {81 const program = new commander.Command();
64 unmodified lines
modified:tests/command.allowUnknownOption.test.js+1 added
81 unmodified lines
82 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 lines
modified:tests/command.asterisk.test.js+2 added
31 unmodified lines
32 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 lines
58 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 lines
modified:tests/command.chain.test.js-6 removed
80 unmodified lines
81 const result = program.storeOptionsAsProperties();82 expect(result).toBe(program);83 });8485 test('when call .passCommandToAction() then returns this', () => {86 const program = new Command();87 const result = program.passCommandToAction();88 expect(result).toBe(program);89 });9085 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 lines
modified:tests/command.default.test.js+2 added
32 unmodified lines
33 .command('other');34 program35 .command('default', { isDefault: true })36 .allowUnknownOption()37 .allowExcessArguments()38 .action(actionMock);39 return { program, actionMock };40 }41
20 unmodified lines
62 function makeProgram() {63 const actionMock = jest.fn();64 const defaultCmd = new commander.Command('default')65 .allowUnknownOption()66 .allowExcessArguments()67 .action(actionMock);6869 const program = new commander.Command();70 program
24 unmodified lines
modified:tests/command.unknownCommand.test.js+2 added-1 removed
22 unmodified lines
23 program.parse('node test.js unknown'.split(' '));24 }).not.toThrow();25 });2627 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 lines
modified:tests/commander.configureCommand.test.js+14 added-23 removed
2 unmodified lines
3// Mostly testing direct on program, limited check that (sub)command working same.45// Default behaviours67test('when default then options stored on command', () => {7test('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});1515test('when default then command passed to action', () => {16test('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});2526// storeOptionsAsProperties27
3 unmodified lines
31 .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});3738test('when storeOptionsAsProperties(true) then options stored on command', () => {39 const program = new commander.Command();
1 unmodified line
41 .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});4748test('when storeOptionsAsProperties(false) then options not stored on command', () => {49 const program = new commander.Command();
1 unmodified line
51 .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});5754// passCommandToAction5556test('when passCommandToAction() then command passed to action', () => {58test('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});6867test('when passCommandToAction(true) then command passed to action', () => {69test('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});7778test('when passCommandToAction(false) then options passed to action', () => {79 const program = new commander.Command();80 const callback = jest.fn();81 program82 .passCommandToAction(false)83 .arguments('<value>')84 .action(callback);85 program.parse(['node', 'test', 'value']);86 expect(callback).toHaveBeenCalledWith('value', program.opts());87});
modified:tests/deprecated.test.js+3 added-3 removed
8 unmodified lines
9 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 });1516 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 });2324 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 lines
1516 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 });2122 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 });2728 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 });3334 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 });3940 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});4647// Flag with default, say from an environment variable.
10 unmodified lines
58describe('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 });6465 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 });7071 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});7778// boolean option combo, default false, short flags79describe('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 });8586 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 });9192 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});9899// This is a somewhat undocumented special behaviour which appears in some examples.
4 unmodified lines
104 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 });110111 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 });117118 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 lines
7 .option('-c, --cheese', 'add cheese');89 program.parse(['node', 'test', '-pc']);1011 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 lines
8 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 });1415 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 });2223 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 });3031 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});3940// boolean flag on command41describe('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 });5253 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 });6364 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 });7475 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});8687// This is a somewhat undocumented special behaviour which appears in some examples.
6 unmodified lines
94 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 });100101 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});110111// Regression test for #1301 with `-no-` in middle of option
2 unmodified lines
114 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 });120121 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 lines
6 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});1213test('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});2021test('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});2829test('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});3637test('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});4445test('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 lines
30 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});3637test('when starting value is defined and option not specified then callback not called', () => {38 const mockCoercion = jest.fn();
10 unmodified lines
49 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});5556test('when option specified then callback called with value', () => {57 const mockCoercion = jest.fn();
12 unmodified lines
70 .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});7677test('when starting value is defined and option specified then callback called with value and starting value', () => {78 const mockCoercion = jest.fn();
25 unmodified lines
104 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});110111// Now some functional tests like the examples in the README!112
1 unmodified line
114 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});120121test('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});128129test('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});136137test('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});144145test('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
1const commander = require('../');23// Check detection of likely name clashes45test('when option clashes with property then throw', () => {6 const program = new commander.Command();7 expect(() => {8 program.option('-n, --name <name>');9 }).toThrow();10});1112test('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});1920test('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});2728test('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});3435test('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});4344test('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 lines
6 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});1213test('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});2021test('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});2829test('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});3637test('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});4445test('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});5253test('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});6061test('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});6869test('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});7677test('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 lines
9 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 });1516 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 });2425 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 });3334 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 });4243 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 });5152 test('when program has value/no flag specified with value then specified value', () => {53 const program = new commander.Command();
1 unmodified line
55 .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 });6162 test('when program has mandatory-yes/no flag specified with flag then true', () => {63 const program = new commander.Command();
1 unmodified line
65 .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 });7172 test('when program has mandatory-yes/mandatory-no flag specified with flag then true', () => {73 const program = new commander.Command();
1 unmodified line
75 .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 });8182 test('when program has yes/no flag specified negated then false', () => {83 const program = new commander.Command();
1 unmodified line
85 .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 });9192 test('when program has required value specified and subcommand then specified value', () => {93 const program = new commander.Command();
2 unmodified lines
96 .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});103104describe('required program option with mandatory value not specified', () => {
67 unmodified lines
172 program173 .exitOverride()174 .command('sub')175 .requiredOption('--subby <type>', 'description')176 .action((cmd) => {177 cmdOptions = cmd;176 .action((options) => {177 cmdOptions = options;178 });179180 program.parse(['node', 'test', 'sub', '--subby', 'blue']);181
22 unmodified lines
204 program205 .exitOverride()206 .command('sub')207 .requiredOption('--subby <type>', 'description')208 .action((cmd) => {});208 .action(() => {});209210 expect(() => {211 program.parse(['node', 'test', 'sub']);212 }).toThrow();
4 unmodified lines
217 program218 .exitOverride()219 .command('sub')220 .requiredOption('--subby <type>', 'description')221 .action((cmd) => {});221 .action(() => {});222 program223 .command('sub2');224225 expect(() => {
55 unmodified lines
modified:tests/options.optional.test.js+7 added-7 removed
5 unmodified lines
6 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 });1213 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 });2122 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 });2930 test('when option specified without value and following option then value is true', () => {31 // optional options do not eat values with dashes
1 unmodified line
33 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});4041// option with optional value, with default
3 unmodified lines
45 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 });5152 test('when option specified then value is as specified', () => {53 const defaultValue = 'default';
1 unmodified line
55 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 });6162 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 line
23// 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).56test('when .version used then version in opts', () => {6test('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 lines
modified:tests/options.required.test.js+4 added-4 removed
5 unmodified lines
6 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 });1213 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 });2122 test('when option value not specified then error', () => {23 // Arrange. Mock error routine to allow interception.
22 unmodified lines
46 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 });5253 test('when option specified then value is as specified', () => {54 const defaultValue = 'default';
1 unmodified line
56 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 });6263 test('when option value not specified then error', () => {64 // Arrange. Mock error routine to allow interception.
18 unmodified lines
modified:tests/options.values.test.js+9 added-9 removed
16 unmodified lines
1718 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 });2324 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 });2930 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 });3536 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 });4243// option with optional value
7 unmodified lines
5152 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 });5758 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 });6364 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 });6970 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 });7576 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 lines
89// This conflicts with esline rule saying no space!10/* eslint-disable @typescript-eslint/space-before-function-paren */1112// 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-44122469015type 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;18type CommandWithoutOptionsAsProperties = Pick<commander.Command, KnownKeys<commander.Command>>;1920const program: CommandWithoutOptionsAsProperties = commander.program;21const programWithOptions = commander.program;12const program: commander.Command = new commander.Command();13// program.silly; // <-- Error, hurrah!1415// Check for exported global Command objects16const importedDefaultProgram: commander.Command = commander;
6 unmodified lines
23const errorInstance = new commander.CommanderError(1, 'code', 'message');24const invalidOptionErrorInstance = new commander.InvalidOptionArgumentError('message');2526// Command properties36console.log(programWithOptions.someOption);37// eslint-disable-next-line @typescript-eslint/dot-notation38console.log(programWithOptions['someOption']);39const theArgs = program.args;27const theArgs: string[] = program.args;28const theCommands: commander.Command[] = program.commands;2930// version31const versionThis1: commander.Command = program.version('1.2.3');
102 unmodified lines
134// storeOptionsAsProperties135const storeOptionsAsPropertiesThis1: commander.Command = program.storeOptionsAsProperties();136const storeOptionsAsPropertiesThis2: commander.Command = program.storeOptionsAsProperties(false);137150// passCommandToAction151const passCommandToActionThis1: commander.Command = program.passCommandToAction();152const passCommandToActionThis2: commander.Command = program.passCommandToAction(false);153138// combineFlagAndOptionalValue139const combineFlagAndOptionalValueThis1: commander.Command = program.combineFlagAndOptionalValue();140const combineFlagAndOptionalValueThis2: commander.Command = program.combineFlagAndOptionalValue(false);141
189 unmodified lines
modified:typings/index.d.ts-10 removed
147 unmodified lines
148149 type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';150151 interface Command {152 [key: string]: any; // options as properties153152 args: string[];153154 commands: Command[];155
218 unmodified lines
374 */375 storeOptionsAsProperties(storeAsProperties?: boolean): this;376377 /**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;386387 /**378 * Alter parsing of short flags with optional values.379 *380 * @example381 * // for `.option('-f,--flag [value]'):
211 unmodified lines
modified:CHANGELOG.md+95 added
6 unmodified lines
78<!-- markdownlint-disable MD024 -->9<!-- markdownlint-disable MD004 -->1011## [Unreleased] (date goes here)1213### Migration Tips1415The 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.1617If you wish to restore the old behaviour and get running quickly you can call `.storeOptionsAsProperties()`. 18To allow you to move to the new code patterns incrementally, the action handler will be passed the command _twice_,19to match the new "options" and "command" parameters (see below).2021**program options**2223Use the `.opts()` method to access the options. This is available on any command but is used most with the program.2425```js26program.option('-d, --debug');27program.parse();28// Old code before Commander 729if (program.debug) console.log(`Program name is ${program.name()}`);30```3132```js33// New code34const options = program.opts();35if (options.debug) console.log(`Program name is ${program.name()}`);36```3738**action handler**3940The 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 you41only accessed the options there may be no code changes required.4243```js44program45 .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```5253```js54 // New code55 .action((filename, options, command)) => {56 if (options.trace) console.log(`Command name is ${command.name()}`);57 });58```5960If you already set `.storeOptionsAsProperties(false)` you may still need to adjust your code.6162```js63program64 .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```7273```js74 // New code75 .action((filename, options, command)) => {76 if (command.opts().trace) console.log(`Command name is ${command.name()}`);77 });78```7980**excess command-arguments**8182There is now an error if there are too many command-arguments on the command line (only checked if there is an action handler).83If the extra arguments are supported by your command then you can either declare the expected arguments, or allow excess arguments.8485```js86// Old code before Commander 787program88 .action(() => {});89program.parse(['a', 'b', 'c'], { from: 'user' }); // now causes an error90```9192```js93// New code, declare arguments94program95 .arguments('[args...]')96 .action(() => {});97```9899```js100// New code, allow excess arguments101program102 .allowExcessArguments()103 .action(() => {});104```105106## [7.0.0-1] (2020-11-21)107108### Added109
287 unmodified lines
modified:index.js+5 added-70 removed
533 unmodified lines
534 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 executable
82 unmodified lines
631 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;636637 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor638 this.commands.push(cmd);
253 unmodified lines
892 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);902903 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 lines
912 return this;913 };914915 /**922 * Internal routine to check whether there is a clash storing option value with a Command property.923 *924 * @param {Option} option925 * @api private926 */927928 _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 }937938 const commandProperty = this._getOptionValue(option.attributeName());939 if (commandProperty === undefined) {940 // no clash941 return;942 }943944 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 }953954 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 name959960Read more on https://git.io/JJc0W`);961 }962 };963964 /**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 lines
936 addOption(option) {937 const oname = option.name();938 const name = option.attributeName();939989 this._checkForOptionNameClash(option);990940 let defaultValue = option.defaultValue;941942 // 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 lines
1141 * @return {Command} `this` command for chaining1142 */11431144 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 };11511152 /**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 */12111212 passCommandToAction(passCommand = true) {1213 this._passCommandToAction = !!passCommand;1214 return this;1215 };12161217 /**1153 * Store option value1154 *1155 * @param {string} key1156 * @param {Object} value
990 unmodified lines
modified:Readme.md+104 added-105 removed
21 unmodified lines
22 - [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 lines
34 - [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 lines
76## Options7778Options 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 ('|').7980The 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).80The 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.8182Multiple 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).83For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.84
15 unmodified lines
100 .option('-p, --pizza-type <type>', 'flavour of pizza');101102program.parse(process.argv);103104if (program.debug) console.log(program.opts());104const options = program.opts();105if (options.debug) console.log(options);106console.log('pizza details:');106if (program.small) console.log('- small pizza size');107if (program.pizzaType) console.log(`- ${program.pizzaType}`);107if (options.small) console.log('- small pizza size');108if (options.pizzaType) console.log(`- ${options.pizzaType}`);109```110111```bash112$ pizza-options -d
10 unmodified lines
123pizza details:124- cheese125```126126`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`.128129### Default option value130131You can specify a default value for an option which takes a value.
3 unmodified lines
135```js136program137 .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');138138program.parse(process.argv);139program.parse();140140console.log(`cheese: ${program.cheese}`);141console.log(`cheese: ${program.opts().cheese}`);142```143144```bash145$ pizza-options
16 unmodified lines
162program163 .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();167168const options = program.opts();167const sauceStr = program.sauce ? 'sauce' : 'no sauce';168const cheeseStr = (program.cheese === false) ? 'no cheese' : `${program.cheese} cheese`;169const sauceStr = options.sauce ? 'sauce' : 'no sauce';170const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;171console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);172```173174```bash
17 unmodified lines
192 .option('-c, --cheese [type]', 'Add cheese with optional type');193194program.parse(process.argv);195196const options = program.opts();194if (program.cheese === undefined) console.log('no cheese');195else if (program.cheese === true) console.log('add cheese');196else console.log(`add cheese type ${program.cheese}`);197if (options.cheese === undefined) console.log('no cheese');198else if (options.cheese === true) console.log('add cheese');199else console.log(`add cheese type ${options.cheese}`);200```201202```bash203$ pizza-options
15 unmodified lines
219```js220program221 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');222220program.parse(process.argv);223program.parse();224```225226```bash227$ pizza
121 unmodified lines
349 .option('-c, --collect <value>', 'repeatable value', collect, [])350 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)351;352350program.parse(process.argv);353program.parse();354352if (program.float !== undefined) console.log(`float: ${program.float}`);353if (program.integer !== undefined) console.log(`integer: ${program.integer}`);354if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);355if (program.collect.length > 0) console.log(program.collect);356if (program.list !== undefined) console.log(program.list);355const options = program.opts();356if (options.float !== undefined) console.log(`float: ${options.float}`);357if (options.integer !== undefined) console.log(`integer: ${options.integer}`);358if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);359if (options.collect.length > 0) console.log(options.collect);360if (options.list !== undefined) console.log(options.list);361```362363```bash364$ custom -f 1e2
50 unmodified lines
415included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required command-arguments.416Square brackets (e.g. `[optional]`) indicate optional command-arguments.417You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`.418415Example file: [env](./examples/env)419Example file: [arguments.js](./examples/arguments.js)420421```js422program423 .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 });429430program.parse(process.argv);433```434435 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:437438```js437const { program } = require('commander');438439program440 .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 });450451program.parse(process.argv);447```448449The variadic argument is passed to the action handler as an array.450456### Action handler (sub)commands451### Action handler452458You can add options to a command that uses an action handler.459The action handler gets passed a parameter for each argument you declared, and one additional argument which is the460command object itself. This command argument has the values for the command-specific options added as properties.453The action handler gets passed a parameter for each command-argument you declared, and two additional parameters454which are the parsed options and the command object itself. 455462```js463const { program } = require('commander');456Example file: [thank.js](./examples/thank.js)457458```js459program466 .command('rm <dir>')467 .option('-r, --recursive', 'Remove recursively')468 .action(function (dir, cmdObj) {469 console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : ''))470 })471472program.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```471472You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.473
7 unmodified lines
481 await program.parseAsync(process.argv);482}483```484488A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error.485A 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()`.486487### Stand-alone executable (sub)commands488489When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.
27 unmodified lines
517```bash518$ node ./examples/pizza --help519Usage: pizza [options]520524An application for pizzas ordering521An application for pizza ordering522523Options: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 command
155 unmodified lines
683program.parse(); // Implicit, and auto-detect electron684program.parse(['-f', 'filename'], { from: 'user' });685```686691### Avoiding option name clashes687### Legacy options as properties 688693The original and default behaviour is that the option values are stored694as properties on the program, and the action handler is passed a695command object with the options values stored as properties.696This is very convenient to code, but the downside is possible clashes with697existing properties of Command.689Before Commander 7, the option values were stored as properties on the command.690This was convenient to code but the downside was possible clashes with691existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.692699There are two new routines to change the behaviour, and the default behaviour may change in the future:700701- `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,703or just the options (specify false)704705Example file: [storeOptionsAsProperties-action.js](./examples/storeOptionsAsProperties-action.js)706693```js694program709 .storeOptionsAsProperties(false)710 .passCommandToAction(false);711712program713 .name('my-program-name')714 .option('-n,--name <name>');715716program717 .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 });722723program.parse(process.argv);724725const programOptions = program.opts();726console.log(programOptions.name);702```703704### TypeScript705
93 unmodified lines
799- [options taking varying arguments](./docs/options-taking-varying-arguments.md)800801## Examples802828Example file: [deploy](./examples/deploy)803In a single command program, you might not need an action handler.804805Example file: [pizza](./examples/pizza)806807```js808const { program } = require('commander');809810program834 .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');815816program.parse();817818const options = program.opts();819console.log('you ordered a pizza with:');820if (options.peppers) console.log(' - peppers');821const cheese = !options.cheese ? 'no' : options.cheese;822console.log(' - %s cheese', cheese);823```824825In a multi-command program, you will have action handlers for each command (or stand-alone executables for the commands).826827Example file: [deploy](./examples/deploy)828829```js830const { Command } = require('commander');831const program = new Command();832833program834 .version('0.0.1')835 .option('-c, --config <path>', 'set config path', './deploy.conf');836837program838 .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 });846847program850 .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', `856Examples:857 $ deploy exec sequential858 $ deploy exec async`859 );861860 861program.parse(process.argv);862```863865More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.864More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.865866## Support867868The 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