Skip to content
Myr

Reformat code with Prettier (#2180)

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

authored by John Gee · committed by GitHub · parent 6fc933e · Browse files · 132 files+3022 added−2126 removed
This commit

State

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

Diff stats

132 files+3022 added−2126 removed

  • tests:+1960 added−1647 removed
  • other:+1062 added−479 removed

132 files+3022 added−2126 removed

modified:examples/action-this.js+1 added-1 removed
modified:examples/arguments-extra.js+13 added-2 removed
modified:examples/configure-help.js+9 added-3 removed
modified:examples/configure-output.js+8 added-12 removed
modified:examples/custom-command-class.js+3 added-5 removed
modified:examples/custom-help+6 added-4 removed
4 unmodified lines
56const { Command } = require('commander');7const program = new Command();89program10 .option('-f, --foo', 'enable some foo');9program.option('-f, --foo', 'enable some foo');1012program.addHelpText('after', `11program.addHelpText(12 'after',13 `1415Example call:15 $ custom-help --help`);16 $ custom-help --help`,17);1819program.parse(process.argv);2021// Try the following:
1 unmodified line
modified:examples/custom-help-text.js+5 added-2 removed
modified:examples/deploy+12 added-4 removed
23 unmodified lines
24 .description('execute the given remote cmd')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', `28 console.log(29 'exec "%s" using %s mode and config %s',30 script,31 options.exec_mode,32 program.opts().config,33 );34 })35 .addHelpText(36 'after',37 `38Examples:39 $ deploy exec sequential32 $ deploy exec async`40 $ deploy exec async`,41 );34 4243program.parse(process.argv);
modified:examples/global-options-added.js+4 added-2 removed
21 unmodified lines
22}2324const program = new MyRootCommand();2526program.command('print')26program27 .command('print')28 .option('--a4', 'Use A4 sized paper')29 .action((options) => {30 console.log('print options: %O', options);31 });3232program.command('serve')33program34 .command('serve')35 .option('-p, --port <number>', 'port number for server')36 .action((options) => {37 console.log('serve options: %O', options);38 });
14 unmodified lines
modified:examples/global-options-nested.js+2 added-4 removed
7 unmodified lines
89const { Command } = require('commander');10const program = new Command();1112program13 .configureHelp({ showGlobalOptions: true })14 .option('-g, --global');12program.configureHelp({ showGlobalOptions: true }).option('-g, --global');1314program15 .command('sub')16 .option('-l, --local')17 .action((options, cmd) => {18 console.log({19 opts: cmd.opts(),22 optsWithGlobals: cmd.optsWithGlobals()20 optsWithGlobals: cmd.optsWithGlobals(),21 });22 });2324program.parse();
4 unmodified lines
modified:examples/help-subcommands-usage.js+10 added-5 removed
4 unmodified lines
5//6// See also ./configure-help.js which shows configuring the subcommand list to have no usage at all7// and just the subcommand name.89const program = new commander.Command()10 .configureHelp({ subcommandTerm: (cmd) => cmd.name() + ' ' + cmd.usage() });9const program = new commander.Command().configureHelp({10 subcommandTerm: (cmd) => cmd.name() + ' ' + cmd.usage(),11});1213program12program.command('make <FILENAME>')14 .command('make <FILENAME>')15 .usage('-root ROOTDIR [-abc] <FILENAME>')16 .requiredOption('--root <ROOTDIR>')17 .option('-a')18 .option('-b')19 .option('-c')20 .summary('example command with custom usage')19 .description('this full description is displayed in the full help and not in the list of subcommands');21 .description(22 'this full description is displayed in the full help and not in the list of subcommands',23 );2425program21program.command('serve <SERVICE>')26 .command('serve <SERVICE>')27 .option('--port <PORTNUMBER>')28 .description('example command with default simple usage');2930program.parse();
3 unmodified lines
modified:examples/hook.js+12 added-5 removed
22 unmodified lines
23 .option('--trace', 'display trace statements for commands')24 .hook('preAction', (thisCommand, actionCommand) => {25 if (thisCommand.opts().trace) {26 console.log('>>>>');27 console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);27 console.log(28 `About to call action handler for subcommand: ${actionCommand.name()}`,29 );30 console.log('arguments: %O', actionCommand.args);31 console.log('options: %o', actionCommand.opts());32 console.log('<<<<');33 }
10 unmodified lines
44 console.log(`About to call subcommand: ${subcommand.name()}`);45 }46 });4746program.command('start')48program49 .command('start')50 .argument('[script]', 'script name', 'server.js')51 .option('-d, --delay <seconds>', 'how long to delay before starting')49 .addOption(new Option('-p, --port <number>', 'port number').default(8080).env('PORT'))50 .action(async(script, options) => {52 .addOption(53 new Option('-p, --port <number>', 'port number').default(8080).env('PORT'),54 )55 .action(async (script, options) => {56 if (options.delay) {52 await new Promise(resolve => setTimeout(resolve, parseInt(options.delay) * 1000));57 await new Promise((resolve) =>58 setTimeout(resolve, parseInt(options.delay) * 1000),59 );60 }61 console.log(`Starting ${script} on port ${options.port}`);62 });63
8 unmodified lines
modified:examples/nestedCommands.js+12 added-20 removed
7 unmodified lines
8// .addCommand() adds a prepared command with an action handler.910// Add nested commands using `.command()`.11const brew = program.command('brew');12brew13 .command('tea')14 .action(() => {15 console.log('brew tea');16 });17brew18 .command('coffee')19 .action(() => {20 console.log('brew coffee');21 });12brew.command('tea').action(() => {13 console.log('brew tea');14});15brew.command('coffee').action(() => {16 console.log('brew coffee');17});1819// Add nested commands using `.addCommand().20// The command could be created separately in another module.21function makeHeatCommand() {22 const heat = new commander.Command('heat');27 heat28 .command('jug')29 .action(() => {30 console.log('heat jug');31 });32 heat33 .command('pot')34 .action(() => {35 console.log('heat pot');36 });23 heat.command('jug').action(() => {24 console.log('heat jug');25 });26 heat.command('pot').action(() => {27 console.log('heat pot');28 });29 return heat;30}31program.addCommand(makeHeatCommand());32
5 unmodified lines
modified:examples/options-boolean-or-value.js+1 added-2 removed
5 unmodified lines
67const commander = require('commander');8const program = new commander.Command();910program11 .option('-c, --cheese [type]', 'Add cheese with optional type');10program.option('-c, --cheese [type]', 'Add cheese with optional type');1112program.parse(process.argv);1314const options = program.opts();
8 unmodified lines
modified:examples/options-conflicts.js+31 added-15 removed
7 unmodified lines
8 .addOption(new Option('--cash').conflicts('creditCard'))9 .addOption(new Option('--credit-card'))10 .action((options) => {11 if (options.cash) {12 console.log('Paying by cash')12 console.log('Paying by cash');13 } else if (options.creditCard) {14 console.log('Paying by credit card')14 console.log('Paying by credit card');15 } else {16 console.log('Payment method unknown')16 console.log('Payment method unknown');17 }18 });1920 // The default value for an option does not cause a conflict.21 // A value specified using an environment variable is checked for conflicts.20// The default value for an option does not cause a conflict.21// A value specified using an environment variable is checked for conflicts.22program23 .command('source')24 .addOption(new Option('-p, --port <number>', 'port number for server')25 .default(80)26 .env('PORT')27 ).addOption(new Option('--interactive', 'prompt for user input instead of listening to a port')28 .conflicts('port')29 ).action((options) => {24 .addOption(25 new Option('-p, --port <number>', 'port number for server')26 .default(80)27 .env('PORT'),28 )29 .addOption(30 new Option(31 '--interactive',32 'prompt for user input instead of listening to a port',33 ).conflicts('port'),34 )35 .action((options) => {36 if (options.interactive) {31 console.log('What do you want to do today?')37 console.log('What do you want to do today?');38 } else {39 console.log(`Running server on port: ${options.port}`);40 }41 });
1 unmodified line
43// You can use .conflicts() with an array of option names.44// A negated option is not separate from the positive option for conflicts (they have same option name).45program46 .command('paint')41 .addOption(new Option('--summer', 'use a mixture of summer colors').conflicts(['autumn', 'colour']))42 .addOption(new Option('--autumn', 'use a mixture of autumn colors').conflicts(['summer', 'colour']))47 .addOption(48 new Option('--summer', 'use a mixture of summer colors').conflicts([49 'autumn',50 'colour',51 ]),52 )53 .addOption(54 new Option('--autumn', 'use a mixture of autumn colors').conflicts([55 'summer',56 'colour',57 ]),58 )59 .addOption(new Option('--colour <shade>', 'use a single solid colour'))60 .addOption(new Option('--no-colour', 'leave surface natural'))61 .action((options) => {62 let colour = 'not specified';
6 unmodified lines
69 } else if (options.autumn) {70 colour = 'autumn';71 }72 console.log(`Painting colour is ${colour}`);57 });73 });7475program.parse();7677// Try the following:
9 unmodified lines
modified:examples/options-custom-processing.js+7 added-3 removed
29 unmodified lines
3031program32 .option('-f, --float <number>', 'float argument', parseFloat)33 .option('-i, --integer <number>', 'integer argument', myParseInt)34 .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)34 .option(35 '-v, --verbose',36 'verbosity that can be increased',37 increaseVerbosity,38 0,39 )40 .option('-c, --collect <value>', 'repeatable value', collect, [])36 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)37;41 .option('-l, --list <items>', 'comma separated list', commaSeparatedList);4243program.parse();4445const options = program.opts();
12 unmodified lines
modified:examples/options-defaults.js+5 added-2 removed
4 unmodified lines
56const commander = require('commander');7const program = new commander.Command();89program10 .option('-c, --cheese <type>', 'Add the specified type of cheese', 'blue');9program.option(10 '-c, --cheese <type>',11 'Add the specified type of cheese',12 'blue',13);1415program.parse();1617console.log(`cheese: ${program.opts().cheese}`);
4 unmodified lines
modified:examples/options-env.js+12 added-10 removed
1#!/usr/bin/env node2const { Command, Option } = require('commander');3const program = new Command();45program.addOption(5program.addOption(new Option('-p, --port <number>', 'specify port number')6 .default(80)7 .env('PORT')6 new Option('-p, --port <number>', 'specify port number')7 .default(80)8 .env('PORT'),9);9program.addOption(new Option('-c, --colour', 'turn on colour output')10 .env('COLOUR')10program.addOption(11 new Option('-c, --colour', 'turn on colour output').env('COLOUR'),12);12program.addOption(new Option('-C, --no-colour', 'turn off colour output')13 .env('NO_COLOUR')13program.addOption(14 new Option('-C, --no-colour', 'turn off colour output').env('NO_COLOUR'),15);16program.addOption(15program.addOption(new Option('-s, --size <type>', 'specify size of drink')16 .choices(['small', 'medium', 'large'])17 .env('SIZE')17 new Option('-s, --size <type>', 'specify size of drink')18 .choices(['small', 'medium', 'large'])19 .env('SIZE'),20);2122program.parse();23console.log(program.opts());
16 unmodified lines
modified:examples/options-extra.js+26 added-5 removed
7 unmodified lines
8const program = new Command();910program11 .addOption(new Option('-s, --secret').hideHelp())12 .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))13 .addOption(new Option('-d, --drink <size>', 'drink cup size').choices(['small', 'medium', 'large']))12 .addOption(13 new Option('-t, --timeout <delay>', 'timeout in seconds').default(14 60,15 'one minute',16 ),17 )18 .addOption(19 new Option('-d, --drink <size>', 'drink cup size').choices([20 'small',21 'medium',22 'large',23 ]),24 )25 .addOption(new Option('-p, --port <number>', 'port number').env('PORT'))15 .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat))16 .addOption(new Option('--disable-server', 'disables the server').conflicts('port'))17 .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' }));26 .addOption(27 new Option('--donate [amount]', 'optional donation in dollars')28 .preset('20')29 .argParser(parseFloat),30 )31 .addOption(32 new Option('--disable-server', 'disables the server').conflicts('port'),33 )34 .addOption(35 new Option('--free-drink', 'small drink included free ').implies({36 drink: 'small',37 }),38 );3940program.parse();4142console.log('Options: ', program.opts());
9 unmodified lines
modified:examples/options-implies.js+16 added-3 removed
2 unmodified lines
3const program = new Command();45program6 .addOption(new Option('--quiet').implies({ logLevel: 'off' }))7 .addOption(new Option('--log-level <level>').choices(['info', 'warning', 'error', 'off']).default('info'))8 .addOption(new Option('-c, --cheese <type>', 'Add the specified type of cheese').implies({ dairy: true }))9 .addOption(new Option('--no-cheese', 'You do not want any cheese').implies({ dairy: false }))7 .addOption(8 new Option('--log-level <level>')9 .choices(['info', 'warning', 'error', 'off'])10 .default('info'),11 )12 .addOption(13 new Option(14 '-c, --cheese <type>',15 'Add the specified type of cheese',16 ).implies({ dairy: true }),17 )18 .addOption(19 new Option('--no-cheese', 'You do not want any cheese').implies({20 dairy: false,21 }),22 )23 .addOption(new Option('--dairy', 'May contain dairy'));2425program.parse();26console.log(program.opts());
7 unmodified lines
modified:examples/options-negatable.js+2 added-1 removed
14 unmodified lines
15program.parse();1617const options = program.opts();18const sauceStr = options.sauce ? 'sauce' : 'no sauce';19const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;19const cheeseStr =20 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.js
3 unmodified lines
modified:examples/options-required.js+1 added-2 removed
6 unmodified lines
78const commander = require('commander');9const program = new commander.Command();1011program12 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');11program.requiredOption('-c, --cheese <type>', 'pizza must have cheese');1213program.parse();1415console.log(`Cheese type: ${program.opts().cheese}`);
4 unmodified lines
modified:examples/pizza+2 added-2 removed
16 unmodified lines
17const cheese = !options.cheese ? 'no' : options.cheese;18console.log(' - %s cheese', cheese);1920// Try the following on macOS or Linux:21// ./pizza --help 21// ./pizza --help22//23// Try the following:24// ./pizza --help 24// ./pizza --help25// node pizza --peppers --cheese=blue26// node pizza --no-cheese
modified:examples/pm+7 added-3 removed
12 unmodified lines
13program14 .name('pm')15 .version('0.0.1')16 .description('Fake package manager')17 .command('install [name]', 'install one or more packages').alias('i')18 .command('search [query]', 'search with optional query').alias('s')19 .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })17 .command('install [name]', 'install one or more packages')18 .alias('i')19 .command('search [query]', 'search with optional query')20 .alias('s')21 .command('update', 'update installed packages', {22 executableFile: 'myUpdateSubCommand',23 })24 .command('list', 'list packages installed', { isDefault: true });2526program.parse(process.argv);27
9 unmodified lines
modified:examples/pm-install+2 added-3 removed
1 unmodified line
23const { Command } = require('commander');4const program = new Command();56program7 .option('-f, --force', 'force installation');6program.option('-f, --force', 'force installation');78program.parse(process.argv);910const pkgs = program.args;
4 unmodified lines
15}1617console.log();18if (program.opts().force) console.log(' force: install');20pkgs.forEach(function(pkg) {19pkgs.forEach(function (pkg) {20 console.log(' install : %s', pkg);21});22console.log();
modified:examples/positional-options.js+1 added-3 removed
1 unmodified line
23const { Command } = require('commander');4const program = new Command();56program7 .enablePositionalOptions()8 .option('-p, --progress');6program.enablePositionalOptions().option('-p, --progress');78program9 .command('upload <file>')10 .option('-p, --port <number>', 'port number', 80)
13 unmodified lines
modified:examples/split.js+1 added-3 removed
1const { program } = require('commander');23// This is used as an example in the README for the Quick Start.45program6 .option('--first')7 .option('-s, --separator <char>');5program.option('--first').option('-s, --separator <char>');67program.parse();89const options = program.opts();
7 unmodified lines
modified:examples/string-util.js+4 added-2 removed
6 unmodified lines
7 .name('string-util')8 .description('CLI to some JavaScript string utilities')9 .version('0.8.0');1011program.command('split')11program12 .command('split')13 .description('Split a string into substrings and display as an array.')14 .argument('<string>', 'string to split')15 .option('--first', 'display just the first substring')16 .option('-s, --separator <char>', 'separator character', ',')
1 unmodified line
18 const limit = options.first ? 1 : undefined;19 console.log(str.split(options.separator, limit));20 });2121program.command('join')22program23 .command('join')24 .description('Join the command-arguments into a single string')25 .argument('<strings...>', 'one or more strings')26 .option('-s, --separator <char>', 'separator character', ',')27 .action((strings, options) => {
11 unmodified lines
modified:lib/argument.js+4 added-4 removed
96 unmodified lines
97 choices(values) {98 this.argChoices = values.slice();99 this.parseArg = (arg, previous) => {100 if (!this.argChoices.includes(arg)) {101 throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`);101 throw new InvalidArgumentError(102 `Allowed choices are ${this.argChoices.join(', ')}.`,103 );104 }105 if (this.variadic) {106 return this._concatValue(arg, previous);107 }
29 unmodified lines
137138function humanReadableArgName(arg) {139 const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');140139 return arg.required140 ? '<' + nameOutput + '>'141 : '[' + nameOutput + ']';141 return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';142}143144exports.Argument = Argument;145exports.humanReadableArgName = humanReadableArgName;
modified:lib/command.js+324 added-146 removed
58 unmodified lines
59 // see .configureOutput() for docs60 this._outputConfiguration = {61 writeOut: (str) => process.stdout.write(str),62 writeErr: (str) => process.stderr.write(str),63 getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined,64 getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined,65 outputError: (str, write) => write(str)63 getOutHelpWidth: () =>64 process.stdout.isTTY ? process.stdout.columns : undefined,65 getErrHelpWidth: () =>66 process.stderr.isTTY ? process.stderr.columns : undefined,67 outputError: (str, write) => write(str),68 };6970 this._hidden = false;71 /** @type {(Option | null | undefined)} */
18 unmodified lines
90 this._helpCommand = sourceCommand._helpCommand;91 this._helpConfiguration = sourceCommand._helpConfiguration;92 this._exitCallback = sourceCommand._exitCallback;93 this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;92 this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;94 this._combineFlagAndOptionalValue =95 sourceCommand._combineFlagAndOptionalValue;96 this._allowExcessArguments = sourceCommand._allowExcessArguments;97 this._enablePositionalOptions = sourceCommand._enablePositionalOptions;98 this._showHelpAfterError = sourceCommand._showHelpAfterError;99 this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
237 unmodified lines
337 * @return {Command} `this` command for chaining338 */339340 arguments(names) {341 names342 .trim()343 .split(/ +/)338 names.trim().split(/ +/).forEach((detail) => {339 this.argument(detail);340 });344 .forEach((detail) => {345 this.argument(detail);346 });347 return this;348 }349350 /**
4 unmodified lines
355 */356 addArgument(argument) {357 const previousArgument = this.registeredArguments.slice(-1)[0];358 if (previousArgument && previousArgument.variadic) {353 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);359 throw new Error(360 `only the last argument can be variadic '${previousArgument.name()}'`,361 );362 }355 if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {356 throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);363 if (364 argument.required &&365 argument.defaultValue !== undefined &&366 argument.parseArg === undefined367 ) {368 throw new Error(369 `a default value for a required argument is never used: '${argument.name()}'`,370 );371 }372 this.registeredArguments.push(argument);373 return this;374 }
59 unmodified lines
434 * @return {(Command|null)}435 * @package436 */437 _getHelpCommand() {424 const hasImplicitHelpCommand = this._addImplicitHelpCommand ??425 (this.commands.length && !this._actionHandler && !this._findCommand('help'));438 const hasImplicitHelpCommand =439 this._addImplicitHelpCommand ??440 (this.commands.length &&441 !this._actionHandler &&442 !this._findCommand('help'));443444 if (hasImplicitHelpCommand) {445 if (this._helpCommand === undefined) {446 this.helpCommand(undefined, undefined); // use default name and description
143 unmodified lines
590 * @api private591 */592593 _registerOption(option) {577 const matchingOption = (option.short && this._findOption(option.short)) ||594 const matchingOption =595 (option.short && this._findOption(option.short)) ||596 (option.long && this._findOption(option.long));597 if (matchingOption) {580 const matchingFlag = (option.long && this._findOption(option.long)) ? option.long : option.short;598 const matchingFlag =599 option.long && this._findOption(option.long)600 ? option.long601 : option.short;602 throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'603- already used by option '${matchingOption.flags}'`);604 }605
12 unmodified lines
618 const knownBy = (cmd) => {619 return [cmd.name()].concat(cmd.aliases());620 };621601 const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));622 const alreadyUsed = knownBy(command).find((name) =>623 this._findCommand(name),624 );625 if (alreadyUsed) {626 const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');627 const newCmd = knownBy(command).join('|');605 throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);628 throw new Error(629 `cannot add command '${newCmd}' as already have command '${existingCmd}'`,630 );631 }632633 this.commands.push(command);634 }
14 unmodified lines
649 if (option.negate) {650 // --no-foo is special and defaults foo to true, unless a --foo option is already defined651 const positiveLongFlag = option.long.replace(/^--no-/, '--');652 if (!this._findOption(positiveLongFlag)) {628 this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');653 this.setOptionValueWithSource(654 name,655 option.defaultValue === undefined ? true : option.defaultValue,656 'default',657 );658 }659 } else if (option.defaultValue !== undefined) {660 this.setOptionValueWithSource(name, option.defaultValue, 'default');661 }
48 unmodified lines
710 * @private711 */712 _optionEx(config, flags, description, fn, defaultValue) {713 if (typeof flags === 'object' && flags instanceof Option) {685 throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');714 throw new Error(715 'To add an Option object use addOption() instead of option() or requiredOption()',716 );717 }718 const option = this.createOption(flags, description);719 option.makeOptionMandatory(!!config.mandatory);720 if (typeof fn === 'function') {
39 unmodified lines
760 return this._optionEx({}, flags, description, parseArg, defaultValue);761 }762763 /**733 * Add a required option which must have a value after parsing. This usually means734 * the option must be specified on the command line. (Otherwise the same as .option().)735 *736 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.737 *738 * @param {string} flags739 * @param {string} [description]740 * @param {(Function|*)} [parseArg] - custom option processing function or default value741 * @param {*} [defaultValue]742 * @return {Command} `this` command for chaining743 */764 * Add a required option which must have a value after parsing. This usually means765 * the option must be specified on the command line. (Otherwise the same as .option().)766 *767 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.768 *769 * @param {string} flags770 * @param {string} [description]771 * @param {(Function|*)} [parseArg] - custom option processing function or default value772 * @param {*} [defaultValue]773 * @return {Command} `this` command for chaining774 */775776 requiredOption(flags, description, parseArg, defaultValue) {746 return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);777 return this._optionEx(778 { mandatory: true },779 flags,780 description,781 parseArg,782 defaultValue,783 );784 }785786 /**787 * Alter parsing of short flags with optional values.
63 unmodified lines
851 * @private852 */853854 _checkForBrokenPassThrough() {818 if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {819 throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);855 if (856 this.parent &&857 this._passThroughOptions &&858 !this.parent._enablePositionalOptions859 ) {860 throw new Error(861 `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,862 );863 }864 }865866 /**824 * Whether to store option values as properties on command object,825 * or store separately (specify false). In both cases the option values can be accessed using .opts().826 *827 * @param {boolean} [storeAsProperties=true]828 * @return {Command} `this` command for chaining829 */867 * Whether to store option values as properties on command object,868 * or store separately (specify false). In both cases the option values can be accessed using .opts().869 *870 * @param {boolean} [storeAsProperties=true]871 * @return {Command} `this` command for chaining872 */873874 storeOptionsAsProperties(storeAsProperties = true) {875 if (this.options.length) {876 throw new Error('call .storeOptionsAsProperties() before adding options');877 }878 if (Object.keys(this._optionValues).length) {836 throw new Error('call .storeOptionsAsProperties() before setting option values');879 throw new Error(880 'call .storeOptionsAsProperties() before setting option values',881 );882 }883 this._storeOptionsAsProperties = !!storeAsProperties;884 return this;885 }
24 unmodified lines
910 return this.setOptionValueWithSource(key, value, undefined);911 }912913 /**869 * Store option value and where the value came from.870 *871 * @param {string} key872 * @param {Object} value873 * @param {string} source - expected values are default/config/env/cli/implied874 * @return {Command} `this` command for chaining875 */914 * Store option value and where the value came from.915 *916 * @param {string} key917 * @param {Object} value918 * @param {string} source - expected values are default/config/env/cli/implied919 * @return {Command} `this` command for chaining920 */921922 setOptionValueWithSource(key, value, source) {923 if (this._storeOptionsAsProperties) {924 this[key] = value;
4 unmodified lines
929 return this;930 }931932 /**888 * Get source of option value.889 * Expected values are default | config | env | cli | implied890 *891 * @param {string} key892 * @return {string}893 */933 * Get source of option value.934 * Expected values are default | config | env | cli | implied935 *936 * @param {string} key937 * @return {string}938 */939940 getOptionValueSource(key) {941 return this._optionValueSources[key];942 }943944 /**900 * Get source of option value. See also .optsWithGlobals().901 * Expected values are default | config | env | cli | implied902 *903 * @param {string} key904 * @return {string}905 */945 * Get source of option value. See also .optsWithGlobals().946 * Expected values are default | config | env | cli | implied947 *948 * @param {string} key949 * @return {string}950 */951952 getOptionValueSourceWithGlobals(key) {953 // global overwrites local, like optsWithGlobals954 let source;
47 unmodified lines
1002 case 'user':1003 userArgs = argv.slice(0);1004 break;1005 default:961 throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);1006 throw new Error(1007 `unexpected parse option { from: '${parseOptions.from}' }`,1008 );1009 }10101011 // Find default name for program from arguments.965 if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);1012 if (!this._name && this._scriptPath)1013 this.nameFromFilename(this._scriptPath);1014 this._name = this._name || 'program';10151016 return userArgs;1017 }
67 unmodified lines
1085 // Stop looking if candidate already has an expected extension.1086 if (sourceExt.includes(path.extname(baseName))) return undefined;10871088 // Try all the extensions.1041 const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));1089 const foundExt = sourceExt.find((ext) =>1090 fs.existsSync(`${localBin}${ext}`),1091 );1092 if (foundExt) return `${localBin}${foundExt}`;10931094 return undefined;1095 }
2 unmodified lines
1098 this._checkForMissingMandatoryOptions();1099 this._checkForConflictingOptions();11001101 // executableFile and executableDir might be full path, or just a name1102 let executableFile =1052 let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;1103 subcommand._executableFile || `${this._name}-${subcommand._name}`;1104 let executableDir = this._executableDir || '';1105 if (this._scriptPath) {1106 let resolvedScriptPath; // resolve possible symlink for installed npm binary1107 try {1108 resolvedScriptPath = fs.realpathSync(this._scriptPath);1109 } catch (err) {1110 resolvedScriptPath = this._scriptPath;1111 }1061 executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);1112 executableDir = path.resolve(1113 path.dirname(resolvedScriptPath),1114 executableDir,1115 );1116 }11171118 // Look for a local file in preference to a command in PATH.1119 if (executableDir) {1120 let localFile = findFile(executableDir, executableFile);11211122 // Legacy search using prefix of script name instead of command name1123 if (!localFile && !subcommand._executableFile && this._scriptPath) {1070 const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));1124 const legacyName = path.basename(1125 this._scriptPath,1126 path.extname(this._scriptPath),1127 );1128 if (legacyName !== this._name) {1072 localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);1129 localFile = findFile(1130 executableDir,1131 `${legacyName}-${subcommand._name}`,1132 );1133 }1134 }1135 executableFile = localFile || executableFile;1136 }
17 unmodified lines
1154 args = incrementNodeInspectorPort(process.execArgv).concat(args);1155 proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });1156 }11571158 if (!proc.killed) {1098 if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn1159 // testing mainly to avoid leak warnings during unit tests with mocked spawn1160 const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];1161 signals.forEach((signal) => {1162 process.on(signal, () => {1163 if (proc.killed === false && proc.exitCode === null) {
9 unmodified lines
1173 code = code ?? 1; // code is null if spawned process terminated due to a signal1174 if (!exitCallback) {1175 process.exit(code);1176 } else {1116 exitCallback(new CommanderError(code, 'commander.executeSubCommandAsync', '(close)'));1177 exitCallback(1178 new CommanderError(1179 code,1180 'commander.executeSubCommandAsync',1181 '(close)',1182 ),1183 );1184 }1185 });1186 proc.on('error', (err) => {1120 // @ts-ignore: because err.code is an unknown property 1187 // @ts-ignore: because err.code is an unknown property1188 if (err.code === 'ENOENT') {1189 const executableDirMessage = executableDir1190 ? `searched for local subcommand relative to directory '${executableDir}'`1191 : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
1 unmodified line
1193 - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead1194 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path1195 - ${executableDirMessage}`;1196 throw new Error(executableMissing);1130 // @ts-ignore: because err.code is an unknown property1197 // @ts-ignore: because err.code is an unknown property1198 } else if (err.code === 'EACCES') {1199 throw new Error(`'${executableFile}' not executable`);1200 }1201 if (!exitCallback) {1202 process.exit(1);1203 } else {1137 const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');1204 const wrappedError = new CommanderError(1205 1,1206 'commander.executeSubCommandAsync',1207 '(error)',1208 );1209 wrappedError.nestedError = err;1210 exitCallback(wrappedError);1211 }1212 });
10 unmodified lines
1223 const subCommand = this._findCommand(commandName);1224 if (!subCommand) this.help({ error: true });12251226 let promiseChain;1156 promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');1227 promiseChain = this._chainOrCallSubCommandHook(1228 promiseChain,1229 subCommand,1230 'preSubcommand',1231 );1232 promiseChain = this._chainOrCall(promiseChain, () => {1233 if (subCommand._executableHandler) {1234 this._executeSubCommand(subCommand, operands.concat(unknown));1235 } else {
19 unmodified lines
1255 subCommand.help();1256 }12571258 // Fallback to parsing the help flag to invoke the help.1184 return this._dispatchSubcommand(subcommandName, [], [1185 this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'1186 ]);1259 return this._dispatchSubcommand(1260 subcommandName,1261 [],1262 [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],1263 );1264 }12651266 /**1267 * Check this.args against expected this.registeredArguments.
8 unmodified lines
1276 this.missingArgument(arg.name());1277 }1278 });1279 // too many1203 if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {1280 if (1281 this.registeredArguments.length > 0 &&1282 this.registeredArguments[this.registeredArguments.length - 1].variadic1283 ) {1284 return;1285 }1286 if (this.args.length > this.registeredArguments.length) {1287 this._excessArguments(this.args);
11 unmodified lines
1299 // Extra processing for nice error message on parsing failure.1300 let parsedValue = value;1301 if (value !== null && argument.parseArg) {1302 const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;1223 parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);1303 parsedValue = this._callParseArg(1304 argument,1305 value,1306 previous,1307 invalidValueMessage,1308 );1309 }1310 return parsedValue;1311 };1312
56 unmodified lines
1369 let result = promise;1370 const hooks = [];1371 this._getCommandAndAncestors()1372 .reverse()1288 .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)1289 .forEach(hookedCommand => {1373 .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)1374 .forEach((hookedCommand) => {1375 hookedCommand._lifeCycleHooks[event].forEach((callback) => {1376 hooks.push({ hookedCommand, callback });1377 });1378 });
47 unmodified lines
14261427 if (operands && this._findCommand(operands[0])) {1428 return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);1429 }1345 if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {1430 if (1431 this._getHelpCommand() &&1432 operands[0] === this._getHelpCommand().name()1433 ) {1434 return this._dispatchHelpCommand(operands[1]);1435 }1436 if (this._defaultCommandName) {1437 this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command1350 return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);1438 return this._dispatchSubcommand(1439 this._defaultCommandName,1440 operands,1441 unknown,1442 );1443 }1352 if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {1444 if (1445 this.commands.length &&1446 this.args.length === 0 &&1447 !this._actionHandler &&1448 !this._defaultCommandName1449 ) {1450 // probably missing subcommand and no handler, user needs help (and exit)1451 this.help({ error: true });1452 }1453
14 unmodified lines
1468 this._processArguments();14691470 let promiseChain;1471 promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');1375 promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));1472 promiseChain = this._chainOrCall(promiseChain, () =>1473 this._actionHandler(this.processedArgs),1474 );1475 if (this.parent) {1476 promiseChain = this._chainOrCall(promiseChain, () => {1477 this.parent.emit(commandEvent, operands, unknown); // legacy1478 });
5 unmodified lines
1484 checkForUnknownOptions();1485 this._processArguments();1486 this.parent.emit(commandEvent, operands, unknown); // legacy1487 } else if (operands.length) {1389 if (this._findCommand('*')) { // legacy default command1488 if (this._findCommand('*')) {1489 // legacy default command1490 return this._dispatchSubcommand('*', operands, unknown);1491 }1492 if (this.listenerCount('command:*')) {1493 // skip option check, emit event for possible misspelling suggestion
21 unmodified lines
1515 * @private1516 */1517 _findCommand(name) {1518 if (!name) return undefined;1419 return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));1519 return this.commands.find(1520 (cmd) => cmd._name === name || cmd._aliases.includes(name),1521 );1522 }15231524 /**1525 * Return an option matching `arg` if any.
3 unmodified lines
1529 * @package internal use only1530 */15311532 _findOption(arg) {1431 return this.options.find(option => option.is(arg));1533 return this.options.find((option) => option.is(arg));1534 }15351536 /**1537 * Display an error message if a mandatory option does not have a value.
5 unmodified lines
1543 _checkForMissingMandatoryOptions() {1544 // Walk up hierarchy so can call in subcommand after checking for displaying help.1545 this._getCommandAndAncestors().forEach((cmd) => {1546 cmd.options.forEach((anOption) => {1445 if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {1547 if (1548 anOption.mandatory &&1549 cmd.getOptionValue(anOption.attributeName()) === undefined1550 ) {1551 cmd.missingMandatoryOptionValue(anOption);1552 }1553 });1554 });
4 unmodified lines
1559 *1560 * @private1561 */1562 _checkForConflictingLocalOptions() {1458 const definedNonDefaultOptions = this.options.filter(1459 (option) => {1460 const optionKey = option.attributeName();1461 if (this.getOptionValue(optionKey) === undefined) {1462 return false;1563 const definedNonDefaultOptions = this.options.filter((option) => {1564 const optionKey = option.attributeName();1565 if (this.getOptionValue(optionKey) === undefined) {1566 return false;1463 }1464 return this.getOptionValueSource(optionKey) !== 'default';1567 }1568 return this.getOptionValueSource(optionKey) !== 'default';1466 );1569 });15701571 const optionsWithConflicting = definedNonDefaultOptions.filter(1469 (option) => option.conflictsWith.length > 01572 (option) => option.conflictsWith.length > 0,1573 );15741575 optionsWithConflicting.forEach((option) => {1576 const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>1474 option.conflictsWith.includes(defined.attributeName())1577 option.conflictsWith.includes(defined.attributeName()),1578 );1579 if (conflictingAndDefined) {1580 this._conflictingOption(option, conflictingAndDefined);1581 }
71 unmodified lines
1653 if (args.length > 0 && !maybeOption(args[0])) {1654 value = args.shift();1655 }1656 this.emit(`option:${option.name()}`, value);1554 } else { // boolean flag1657 } else {1658 // boolean flag1659 this.emit(`option:${option.name()}`);1660 }1661 activeVariadicOption = option.variadic ? option : null;1662 continue;
3 unmodified lines
1666 // Look for combo options following single dash, eat first one if known.1667 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {1668 const option = this._findOption(`-${arg[1]}`);1669 if (option) {1566 if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {1670 if (1671 option.required ||1672 (option.optional && this._combineFlagAndOptionalValue)1673 ) {1674 // option with value following in same argument1675 this.emit(`option:${option.name()}`, arg.slice(2));1676 } else {1677 // boolean option, emit and put back remainder of arg for further processing
22 unmodified lines
1700 dest = unknown;1701 }17021703 // If using positionalOptions, stop processing our options at subcommand.1597 if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {1704 if (1705 (this._enablePositionalOptions || this._passThroughOptions) &&1706 operands.length === 0 &&1707 unknown.length === 01708 ) {1709 if (this._findCommand(arg)) {1710 operands.push(arg);1711 if (args.length > 0) unknown.push(...args);1712 break;1602 } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {1713 } else if (1714 this._getHelpCommand() &&1715 arg === this._getHelpCommand().name()1716 ) {1717 operands.push(arg);1718 if (args.length > 0) operands.push(...args);1719 break;1720 } else if (this._defaultCommandName) {
29 unmodified lines
1750 const len = this.options.length;17511752 for (let i = 0; i < len; i++) {1753 const key = this.options[i].attributeName();1754 result[key] =1640 result[key] = key === this._versionOptionName ? this._version : this[key];1755 key === this._versionOptionName ? this._version : this[key];1756 }1757 return result;1758 }1759
8 unmodified lines
1768 optsWithGlobals() {1769 // globals overwrite locals1770 return this._getCommandAndAncestors().reduce(1771 (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),1657 {}1772 {},1773 );1774 }17751776 /**
5 unmodified lines
1782 * @param {number} [errorOptions.exitCode] - used with process.exit1783 */1784 error(message, errorOptions) {1785 // output handling1671 this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);1786 this._outputConfiguration.outputError(1787 `${message}\n`,1788 this._outputConfiguration.writeErr,1789 );1790 if (typeof this._showHelpAfterError === 'string') {1791 this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);1792 } else if (this._showHelpAfterError) {1793 this._outputConfiguration.writeErr('\n');
17 unmodified lines
1811 this.options.forEach((option) => {1812 if (option.envVar && option.envVar in process.env) {1813 const optionKey = option.attributeName();1814 // Priority check. Do not overwrite cli or options from unknown source (client-code).1697 if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {1698 if (option.required || option.optional) { // option can take a value1815 if (1816 this.getOptionValue(optionKey) === undefined ||1817 ['default', 'config', 'env'].includes(1818 this.getOptionValueSource(optionKey),1819 )1820 ) {1821 if (option.required || option.optional) {1822 // option can take a value1823 // keep very simple, optional always takes value1824 this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);1701 } else { // boolean1825 } else {1826 // boolean1827 // keep very simple, only care that envVar defined and not the value1828 this.emit(`optionEnv:${option.name()}`);1829 }1830 }
8 unmodified lines
1839 */1840 _parseOptionsImplied() {1841 const dualHelper = new DualOptions(this.options);1842 const hasCustomOptionValue = (optionKey) => {1718 return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));1843 return (1844 this.getOptionValue(optionKey) !== undefined &&1845 !['default', 'implied'].includes(this.getOptionValueSource(optionKey))1846 );1847 };1848 this.options1721 .filter(option => (option.implied !== undefined) &&1722 hasCustomOptionValue(option.attributeName()) &&1723 dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))1849 .filter(1850 (option) =>1851 option.implied !== undefined &&1852 hasCustomOptionValue(option.attributeName()) &&1853 dualHelper.valueFromOption(1854 this.getOptionValue(option.attributeName()),1855 option,1856 ),1857 )1858 .forEach((option) => {1859 Object.keys(option.implied)1726 .filter(impliedKey => !hasCustomOptionValue(impliedKey))1727 .forEach(impliedKey => {1728 this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');1860 .filter((impliedKey) => !hasCustomOptionValue(impliedKey))1861 .forEach((impliedKey) => {1862 this.setOptionValueWithSource(1863 impliedKey,1864 option.implied[impliedKey],1865 'implied',1866 );1867 });1868 });1869 }1870
45 unmodified lines
1916 // value, so do some work to take an educated guess.1917 const findBestOptionFromValue = (option) => {1918 const optionKey = option.attributeName();1919 const optionValue = this.getOptionValue(optionKey);1782 const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());1783 const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());1784 if (negativeOption && (1785 (negativeOption.presetArg === undefined && optionValue === false) ||1786 (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)1787 )) {1920 const negativeOption = this.options.find(1921 (target) => target.negate && optionKey === target.attributeName(),1922 );1923 const positiveOption = this.options.find(1924 (target) => !target.negate && optionKey === target.attributeName(),1925 );1926 if (1927 negativeOption &&1928 ((negativeOption.presetArg === undefined && optionValue === false) ||1929 (negativeOption.presetArg !== undefined &&1930 optionValue === negativeOption.presetArg))1931 ) {1932 return negativeOption;1933 }1934 return positiveOption || option;1935 };
28 unmodified lines
1964 let candidateFlags = [];1965 // eslint-disable-next-line @typescript-eslint/no-this-alias1966 let command = this;1967 do {1824 const moreFlags = command.createHelp().visibleOptions(command)1825 .filter(option => option.long)1826 .map(option => option.long);1968 const moreFlags = command1969 .createHelp()1970 .visibleOptions(command)1971 .filter((option) => option.long)1972 .map((option) => option.long);1973 candidateFlags = candidateFlags.concat(moreFlags);1974 command = command.parent;1975 } while (command && !command._enablePositionalOptions);1976 suggestion = suggestSimilar(flag, candidateFlags);
13 unmodified lines
1990 _excessArguments(receivedArgs) {1991 if (this._allowExcessArguments) return;19921993 const expected = this.registeredArguments.length;1848 const s = (expected === 1) ? '' : 's';1994 const s = expected === 1 ? '' : 's';1995 const forSubcommand = this.parent ? ` for '${this.name()}'` : '';1996 const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;1997 this.error(message, { code: 'commander.excessArguments' });1998 }
9 unmodified lines
2008 let suggestion = '';20092010 if (this._showSuggestionAfterError) {2011 const candidateNames = [];2012 this.createHelp()2013 .visibleCommands(this)1866 this.createHelp().visibleCommands(this).forEach((command) => {1867 candidateNames.push(command.name());1868 // just visible alias1869 if (command.alias()) candidateNames.push(command.alias());1870 });2014 .forEach((command) => {2015 candidateNames.push(command.name());2016 // just visible alias2017 if (command.alias()) candidateNames.push(command.alias());2018 });2019 suggestion = suggestSimilar(unknownName, candidateNames);2020 }20212022 const message = `error: unknown command '${unknownName}'${suggestion}`;
36 unmodified lines
2059 * @param {Object} [argsDescription]2060 * @return {(string|Command)}2061 */2062 description(str, argsDescription) {1915 if (str === undefined && argsDescription === undefined) return this._description;2063 if (str === undefined && argsDescription === undefined)2064 return this._description;2065 this._description = str;2066 if (argsDescription) {2067 this._argsDescription = argsDescription;2068 }
26 unmodified lines
20952096 /** @type {Command} */2097 // eslint-disable-next-line @typescript-eslint/no-this-alias2098 let command = this;1950 if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {2099 if (2100 this.commands.length !== 0 &&2101 this.commands[this.commands.length - 1]._executableHandler2102 ) {2103 // assume adding alias for last added executable subcommand, rather than this2104 command = this.commands[this.commands.length - 1];2105 }21061955 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');2107 if (alias === command._name)2108 throw new Error("Command alias can't be the same as its name");2109 const matchingCommand = this.parent?._findCommand(alias);2110 if (matchingCommand) {2111 // c.f. _registerCommand1959 const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join('|');1960 throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);2112 const existingCmd = [matchingCommand.name()]2113 .concat(matchingCommand.aliases())2114 .join('|');2115 throw new Error(2116 `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,2117 );2118 }21192120 command._aliases.push(alias);2121 return this;
29 unmodified lines
21512152 const args = this.registeredArguments.map((arg) => {2153 return humanReadableArgName(arg);2154 });1998 return [].concat(1999 (this.options.length || (this._helpOption !== null) ? '[options]' : []),2000 (this.commands.length ? '[command]' : []),2001 (this.registeredArguments.length ? args : [])2002 ).join(' ');2155 return []2156 .concat(2157 this.options.length || this._helpOption !== null ? '[options]' : [],2158 this.commands.length ? '[command]' : [],2159 this.registeredArguments.length ? args : [],2160 )2161 .join(' ');2162 }21632164 this._usage = str;2165 return this;
58 unmodified lines
22242225 helpInformation(contextOptions) {2226 const helper = this.createHelp();2227 if (helper.helpWidth === undefined) {2069 helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();2228 helper.helpWidth =2229 contextOptions && contextOptions.error2230 ? this._outputConfiguration.getErrHelpWidth()2231 : this._outputConfiguration.getOutHelpWidth();2232 }2233 return helper.formatHelp(this, helper);2234 }2235
30 unmodified lines
2266 contextOptions = undefined;2267 }2268 const context = this._getHelpContext(contextOptions);22692108 this._getCommandAndAncestors().reverse().forEach(command => command.emit('beforeAllHelp', context));2270 this._getCommandAndAncestors()2271 .reverse()2272 .forEach((command) => command.emit('beforeAllHelp', context));2273 this.emit('beforeHelp', context);22742275 let helpInformation = this.helpInformation(context);2276 if (deprecatedCallback) {2277 helpInformation = deprecatedCallback(helpInformation);2114 if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {2278 if (2279 typeof helpInformation !== 'string' &&2280 !Buffer.isBuffer(helpInformation)2281 ) {2282 throw new Error('outputHelp callback must return a string or a Buffer');2283 }2284 }2285 context.write(helpInformation);
1 unmodified line
2287 if (this._getHelpOption()?.long) {2288 this.emit(this._getHelpOption().long); // deprecated2289 }2290 this.emit('afterHelp', context);2124 this._getCommandAndAncestors().forEach(command => command.emit('afterAllHelp', context));2291 this._getCommandAndAncestors().forEach((command) =>2292 command.emit('afterAllHelp', context),2293 );2294 }22952296 /**2297 * You can pass in flags and a description to customise the built-in help option.
64 unmodified lines
23622363 help(contextOptions) {2364 this.outputHelp(contextOptions);2365 let exitCode = process.exitCode || 0;2197 if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {2366 if (2367 exitCode === 0 &&2368 contextOptions &&2369 typeof contextOptions !== 'function' &&2370 contextOptions.error2371 ) {2372 exitCode = 1;2373 }2374 // message: do not have all displayed text available so only passing placeholder.2375 this._exit(exitCode, 'commander.help', '(outputHelp)');
39 unmodified lines
2415 */24162417 _outputHelpIfRequested(args) {2418 const helpOption = this._getHelpOption();2245 const helpRequested = helpOption && args.find(arg => helpOption.is(arg));2419 const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));2420 if (helpRequested) {2421 this.outputHelp();2422 // (Do not have all displayed text available so only passing placeholder.)2423 this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
24 unmodified lines
2448 let match;2449 if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {2450 // e.g. --inspect2451 debugOption = match[1];2278 } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {2452 } else if (2453 (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null2454 ) {2455 debugOption = match[1];2456 if (/^\d+$/.test(match[3])) {2457 // e.g. --inspect=12342458 debugPort = match[3];2459 } else {2460 // e.g. --inspect=localhost2461 debugHost = match[3];2462 }2287 } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {2463 } else if (2464 (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null2465 ) {2466 // e.g. --inspect=localhost:12342467 debugOption = match[1];2468 debugHost = match[3];2469 debugPort = match[4];
10 unmodified lines
modified:lib/help.js+97 added-34 removed
23 unmodified lines
24 * @returns {Command[]}25 */2627 visibleCommands(cmd) {28 const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);28 const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);29 const helpCommand = cmd._getHelpCommand();30 if (helpCommand && !helpCommand._hidden) {31 visibleCommands.push(helpCommand);32 }
15 unmodified lines
48 */49 compareOptions(a, b) {50 const getSortKey = (option) => {51 // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.52 return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '');52 return option.short53 ? option.short.replace(/^-/, '')54 : option.long.replace(/^--/, '');55 };56 return getSortKey(a).localeCompare(getSortKey(b));57 }58
14 unmodified lines
73 const removeLong = helpOption.long && cmd._findOption(helpOption.long);74 if (!removeShort && !removeLong) {75 visibleOptions.push(helpOption); // no changes needed76 } else if (helpOption.long && !removeLong) {75 visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));77 visibleOptions.push(78 cmd.createOption(helpOption.long, helpOption.description),79 );80 } else if (helpOption.short && !removeShort) {77 visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));81 visibleOptions.push(82 cmd.createOption(helpOption.short, helpOption.description),83 );84 }85 }86 if (this.sortOptions) {87 visibleOptions.sort(this.compareOptions);
11 unmodified lines
99 visibleGlobalOptions(cmd) {100 if (!this.showGlobalOptions) return [];101102 const globalOptions = [];97 for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {98 const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);103 for (104 let ancestorCmd = cmd.parent;105 ancestorCmd;106 ancestorCmd = ancestorCmd.parent107 ) {108 const visibleOptions = ancestorCmd.options.filter(109 (option) => !option.hidden,110 );111 globalOptions.push(...visibleOptions);112 }113 if (this.sortOptions) {114 globalOptions.sort(this.compareOptions);
10 unmodified lines
125126 visibleArguments(cmd) {127 // Side effect! Apply the legacy descriptions before the arguments are displayed.128 if (cmd._argsDescription) {117 cmd.registeredArguments.forEach(argument => {118 argument.description = argument.description || cmd._argsDescription[argument.name()] || '';129 cmd.registeredArguments.forEach((argument) => {130 argument.description =131 argument.description || cmd._argsDescription[argument.name()] || '';132 });133 }134135 // If there are any arguments with a description then return all the arguments.123 if (cmd.registeredArguments.find(argument => argument.description)) {136 if (cmd.registeredArguments.find((argument) => argument.description)) {137 return cmd.registeredArguments;138 }139 return [];140 }
6 unmodified lines
147 */148149 subcommandTerm(cmd) {150 // Legacy. Ignores custom usage string, and nested commands.138 const args = cmd.registeredArguments.map(arg => humanReadableArgName(arg)).join(' ');139 return cmd._name +151 const args = cmd.registeredArguments152 .map((arg) => humanReadableArgName(arg))153 .join(' ');154 return (155 cmd._name +156 (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +157 (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option142 (args ? ' ' + args : '');158 (args ? ' ' + args : '')159 );160 }161162 /**163 * Get the option term to show in the list of options.
86 unmodified lines
250 if (cmd._aliases[0]) {251 cmdName = cmdName + '|' + cmd._aliases[0];252 }253 let ancestorCmdNames = '';237 for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {254 for (255 let ancestorCmd = cmd.parent;256 ancestorCmd;257 ancestorCmd = ancestorCmd.parent258 ) {259 ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;260 }261 return ancestorCmdNames + cmdName + ' ' + cmd.usage();262 }
35 unmodified lines
298299 if (option.argChoices) {300 extraInfo.push(301 // use stringify to match the display of the default value281 `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);302 `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,303 );304 }305 if (option.defaultValue !== undefined) {306 // default for boolean and negated more for programmer than end user,307 // but show true/false for boolean option as may be for hand-rolled env or config processing.286 const showDefault = option.required || option.optional ||308 const showDefault =309 option.required ||310 option.optional ||311 (option.isBoolean() && typeof option.defaultValue === 'boolean');312 if (showDefault) {289 extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);313 extraInfo.push(314 `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,315 );316 }317 }318 // preset for boolean and negated are more for programmer than end user319 if (option.presetArg !== undefined && option.optional) {
20 unmodified lines
340 const extraInfo = [];341 if (argument.argChoices) {342 extraInfo.push(343 // use stringify to match the display of the default value318 `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);344 `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,345 );346 }347 if (argument.defaultValue !== undefined) {321 extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);348 extraInfo.push(349 `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,350 );351 }352 if (extraInfo.length > 0) {353 const extraDescripton = `(${extraInfo.join(', ')})`;354 if (argument.description) {
19 unmodified lines
374 const itemSeparatorWidth = 2; // between term and description375 function formatItem(term, description) {376 if (description) {377 const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;349 return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);378 return helper.wrap(379 fullText,380 helpWidth - itemIndentWidth,381 termWidth + itemSeparatorWidth,382 );383 }384 return term;385 }386 function formatList(textArray) {
5 unmodified lines
392393 // Description394 const commandDescription = helper.commandDescription(cmd);395 if (commandDescription.length > 0) {363 output = output.concat([helper.wrap(commandDescription, helpWidth, 0), '']);396 output = output.concat([397 helper.wrap(commandDescription, helpWidth, 0),398 '',399 ]);400 }401402 // Arguments403 const argumentList = helper.visibleArguments(cmd).map((argument) => {368 return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));404 return formatItem(405 helper.argumentTerm(argument),406 helper.argumentDescription(argument),407 );408 });409 if (argumentList.length > 0) {410 output = output.concat(['Arguments:', formatList(argumentList), '']);411 }412413 // Options414 const optionList = helper.visibleOptions(cmd).map((option) => {376 return formatItem(helper.optionTerm(option), helper.optionDescription(option));415 return formatItem(416 helper.optionTerm(option),417 helper.optionDescription(option),418 );419 });420 if (optionList.length > 0) {421 output = output.concat(['Options:', formatList(optionList), '']);422 }423424 if (this.showGlobalOptions) {383 const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {384 return formatItem(helper.optionTerm(option), helper.optionDescription(option));385 });425 const globalOptionList = helper426 .visibleGlobalOptions(cmd)427 .map((option) => {428 return formatItem(429 helper.optionTerm(option),430 helper.optionDescription(option),431 );432 });433 if (globalOptionList.length > 0) {387 output = output.concat(['Global Options:', formatList(globalOptionList), '']);434 output = output.concat([435 'Global Options:',436 formatList(globalOptionList),437 '',438 ]);439 }440 }441442 // Commands443 const commandList = helper.visibleCommands(cmd).map((cmd) => {393 return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));444 return formatItem(445 helper.subcommandTerm(cmd),446 helper.subcommandDescription(cmd),447 );448 });449 if (commandList.length > 0) {450 output = output.concat(['Commands:', formatList(commandList), '']);451 }
13 unmodified lines
465 return Math.max(466 helper.longestOptionTermLength(cmd, helper),467 helper.longestGlobalOptionTermLength(cmd, helper),468 helper.longestSubcommandTermLength(cmd, helper),415 helper.longestArgumentTermLength(cmd, helper)469 helper.longestArgumentTermLength(cmd, helper),470 );471 }472473 /**
9 unmodified lines
483 */484485 wrap(str, width, indent, minColumnWidth = 40) {486 // Full \s characters, minus the linefeeds.487 const indents =433 const indents = ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff';488 ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff';489 // Detect manually wrapped and indented strings by searching for line break followed by spaces.490 const manualIndent = new RegExp(`[\\n][${indents}]+`);491 if (str.match(manualIndent)) return str;492 // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).
6 unmodified lines
499 const zeroWidthSpace = '\u200B';500 const breaks = `\\s${zeroWidthSpace}`;501 // Match line end (so empty lines don't collapse),502 // or as much text as will fit in column, or excess text up to first break.448 const regex = new RegExp(`\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, 'g');503 const regex = new RegExp(504 `\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,505 'g',506 );507 const lines = columnText.match(regex) || [];508 return (509 leadingStr +510 lines450 return leadingStr + lines.map((line, i) => {451 if (line === '\n') return ''; // preserve empty lines452 return ((i > 0) ? indentString : '') + line.trimEnd();453 }).join('\n');511 .map((line, i) => {512 if (line === '\n') return ''; // preserve empty lines513 return (i > 0 ? indentString : '') + line.trimEnd();514 })515 .join('\n')516 );517 }518}519520exports.Help = Help;
modified:lib/option.js+7 added-4 removed
178 unmodified lines
179 choices(values) {180 this.argChoices = values.slice();181 this.parseArg = (arg, previous) => {182 if (!this.argChoices.includes(arg)) {183 throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`);183 throw new InvalidArgumentError(184 `Allowed choices are ${this.argChoices.join(', ')}.`,185 );186 }187 if (this.variadic) {188 return this._concatValue(arg, previous);189 }
66 unmodified lines
256 constructor(options) {257 this.positiveOptions = new Map();258 this.negativeOptions = new Map();259 this.dualOptions = new Set();258 options.forEach(option => {260 options.forEach((option) => {261 if (option.negate) {262 this.negativeOptions.set(option.attributeName(), option);263 } else {264 this.positiveOptions.set(option.attributeName(), option);
18 unmodified lines
283 if (!this.dualOptions.has(optionKey)) return true;284285 // Use the value to deduce if (probably) came from the option.286 const preset = this.negativeOptions.get(optionKey).presetArg;285 const negativeValue = (preset !== undefined) ? preset : false;287 const negativeValue = preset !== undefined ? preset : false;288 return option.negate === (negativeValue === value);289 }290}291
22 unmodified lines
314 let longFlag;315 // Use original very loose parsing to maintain backwards compatibility for now,316 // which allowed for example unintended `-sw, --short-word` [sic].317 const flagParts = flags.split(/[ |,]+/);316 if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();318 if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))319 shortFlag = flagParts.shift();320 longFlag = flagParts.shift();321 // Add support for lone short flag without significantly changing parsing!322 if (!shortFlag && /^-[^-]$/.test(longFlag)) {323 shortFlag = longFlag;
7 unmodified lines
modified:lib/suggestSimilar.js+5 added-4 removed
4 unmodified lines
5 // Calculating optimal string alignment distance, no substring is edited more than once.6 // (Simple implementation.)78 // Quick early exit, return worst case.9 if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);9 if (Math.abs(a.length - b.length) > maxDistance)10 return Math.max(a.length, b.length);1112 // distance between prefix substrings of a and b13 const d = [];14
17 unmodified lines
32 }33 d[i][j] = Math.min(34 d[i - 1][j] + 1, // deletion35 d[i][j - 1] + 1, // insertion35 d[i - 1][j - 1] + cost // substitution36 d[i - 1][j - 1] + cost, // substitution37 );38 // transposition39 if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {40 d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
19 unmodified lines
6061 const searchingOptions = word.startsWith('--');62 if (searchingOptions) {63 word = word.slice(2);63 candidates = candidates.map(candidate => candidate.slice(2));64 candidates = candidates.map((candidate) => candidate.slice(2));65 }6667 let similar = [];68 let bestDistance = maxDistance;
16 unmodified lines
85 });8687 similar.sort((a, b) => a.localeCompare(b));88 if (searchingOptions) {88 similar = similar.map(candidate => `--${candidate}`);89 similar = similar.map((candidate) => `--${candidate}`);90 }9192 if (similar.length > 1) {93 return `\n(Did you mean one of ${similar.join(', ')}?)`;
8 unmodified lines
modified:tests/fixtures/inspect.js+1 added-3 removed
2 unmodified lines
3const { program } = require('../../');45process.env.FORCE_COLOR = 0; // work-around bug in Jest: https://github.com/jestjs/jest/issues/1439167program8 .command('sub', 'install one or more packages')9 .parse(process.argv);7program.command('sub', 'install one or more packages').parse(process.argv);
modified:tests/fixtures/pm+28 added-13 removed
5 unmodified lines
6process.env.FORCE_COLOR = 0; // work-around bug in Jest: https://github.com/jestjs/jest/issues/1439178program9 .version('0.0.1')10 .command('install [name]', 'install one or more packages').alias('i')11 .command('search [query]', 'search with optional query').alias('s')12 .command('cache', 'actions dealing with the cache').alias('c')10 .command('install [name]', 'install one or more packages')11 .alias('i')12 .command('search [query]', 'search with optional query')13 .alias('s')14 .command('cache', 'actions dealing with the cache')15 .alias('c')16 .command('echo', 'echo arguments')14 .command('list', 'list packages installed').alias('lst')15 .command('listen', 'listen for supported signal events').alias('l')16 .command('publish', 'publish or update package').alias('p')17 .command('list', 'list packages installed')18 .alias('lst')19 .command('listen', 'listen for supported signal events')20 .alias('l')21 .command('publish', 'publish or update package')22 .alias('p')23 .command('default', 'default command', { hidden: true, isDefault: true })18 .command('specifyInstall', 'specify install subcommand', { executableFile: 'pm-install' })19 .command('specifyPublish', 'specify publish subcommand', { executableFile: 'pm-publish' })24 .command('specifyInstall', 'specify install subcommand', {25 executableFile: 'pm-install',26 })27 .command('specifyPublish', 'specify publish subcommand', {28 executableFile: 'pm-publish',29 })30 .command('silent', 'silently succeed')31 .command('fail', 'exit with non-zero status code')32 .command('terminate', 'terminate due to signal');3334program35 .command('exit-override')26 .exitOverride((err) => { process.exit(err.exitCode); })27 .command('fail', 'exit with non-zero status code', { executableFile: path.join(__dirname, 'pm-fail.js') })28 .command('terminate', 'terminate due to signal', { executableFile: path.join(__dirname, 'pm-terminate.js') });36 .exitOverride((err) => {37 process.exit(err.exitCode);38 })39 .command('fail', 'exit with non-zero status code', {40 executableFile: path.join(__dirname, 'pm-fail.js'),41 })42 .command('terminate', 'terminate due to signal', {43 executableFile: path.join(__dirname, 'pm-terminate.js'),44 });4530program31 .parse(process.argv);46program.parse(process.argv);
modified:tests/fixtures/pm-listen+6 added-6 removed
1#!/usr/bin/env node23process.on('SIGUSR1', function() {3process.on('SIGUSR1', function () {4 process.stdout.write('SIGUSR1');5 process.exit();6});78process.on('SIGUSR2', function() {8process.on('SIGUSR2', function () {9 process.stdout.write('SIGUSR2');10 process.exit();11});1213process.on('SIGTERM', function() {13process.on('SIGTERM', function () {14 process.stdout.write('SIGTERM');15 process.exit();16});1718process.on('SIGINT', function() {18process.on('SIGINT', function () {19 process.stdout.write('SIGINT');20 process.exit();21});2223process.on('SIGHUP', function() {23process.on('SIGHUP', function () {24 process.stdout.write('SIGHUP');25 process.exit();26});2728process.stdout.write('Listening for signal...');29setInterval(function() {}, 1000); // Stay running29setInterval(function () {}, 1000); // Stay running
modified:tests/args.variadic.test.js+11 added-16 removed
4 unmodified lines
5describe('variadic argument', () => {6 test('when no extra arguments specified for program then variadic arg is empty array', () => {7 const actionMock = jest.fn();8 const program = new commander.Command();9 program10 .arguments('<id> [variadicArg...]')11 .action(actionMock);9 program.arguments('<id> [variadicArg...]').action(actionMock);1011 program.parse(['node', 'test', 'id']);1213 expect(actionMock).toHaveBeenCalledWith('id', [], program.opts(), program);
1 unmodified line
1516 test('when extra arguments specified for program then variadic arg is array of values', () => {17 const actionMock = jest.fn();18 const program = new commander.Command();21 program22 .arguments('<id> [variadicArg...]')23 .action(actionMock);19 program.arguments('<id> [variadicArg...]').action(actionMock);20 const extraArguments = ['a', 'b', 'c'];2122 program.parse(['node', 'test', 'id', ...extraArguments]);2328 expect(actionMock).toHaveBeenCalledWith('id', extraArguments, program.opts(), program);24 expect(actionMock).toHaveBeenCalledWith(25 'id',26 extraArguments,27 program.opts(),28 program,29 );30 });3132 test('when no extra arguments specified for command then variadic arg is empty array', () => {33 const actionMock = jest.fn();34 const program = new commander.Command();34 const cmd = program35 .command('sub [variadicArg...]')36 .action(actionMock);35 const cmd = program.command('sub [variadicArg...]').action(actionMock);3637 program.parse(['node', 'test', 'sub']);3839 expect(actionMock).toHaveBeenCalledWith([], cmd.opts(), cmd);
1 unmodified line
4142 test('when extra arguments specified for command then variadic arg is array of values', () => {43 const actionMock = jest.fn();44 const program = new commander.Command();46 const cmd = program47 .command('sub [variadicArg...]')48 .action(actionMock);45 const cmd = program.command('sub [variadicArg...]').action(actionMock);46 const extraArguments = ['a', 'b', 'c'];4748 program.parse(['node', 'test', 'sub', ...extraArguments]);49
17 unmodified lines
67 });6869 test('when variadic argument then usage shows variadic', () => {70 const program = new commander.Command();74 program75 .name('foo')76 .arguments('[args...]');71 program.name('foo').arguments('[args...]');7273 expect(program.usage()).toBe('[options] [args...]');74 });75});
modified:tests/argument.chain.test.js+1 added-1 removed
7 unmodified lines
8 });910 test('when call .argParser() then returns this', () => {11 const argument = new Argument('<value>');12 const result = argument.argParser(() => { });12 const result = argument.argParser(() => {});13 expect(result).toBe(argument);14 });1516 test('when call .choices() then returns this', () => {
17 unmodified lines
modified:tests/argument.choices.test.js+5 added-3 removed
4 unmodified lines
5 let shade;6 program7 .exitOverride()8 .addArgument(new commander.Argument('<shade>').choices(['red', 'blue']))9 .action((shadeParam) => { shade = shadeParam; });9 .action((shadeParam) => {10 shade = shadeParam;11 });12 program.parse(['red'], { from: 'user' });13 expect(shade).toBe('red');14});15
2 unmodified lines
18 const program = new commander.Command();19 program20 .exitOverride()21 .configureOutput({20 writeErr: () => {}22 writeErr: () => {},23 })24 .addArgument(new commander.Argument('<shade>').choices(['red', 'blue']));25 expect(() => {26 program.parse(['orange'], { from: 'user' });
22 unmodified lines
49 const param = ['red', 'blue'];50 program51 .exitOverride()52 .configureOutput({51 writeErr: () => {}53 writeErr: () => {},54 })55 .addArgument(new commander.Argument('<shade>').choices(param));56 param.push('orange');57 expect(() => {
4 unmodified lines
modified:tests/argument.custom-processing.test.js+22 added-42 removed
4 unmodified lines
56test('when argument not specified then callback not called', () => {7 const mockCoercion = jest.fn();8 const program = new commander.Command();9 program10 .argument('[n]', 'number', mockCoercion)11 .action(() => {});9 program.argument('[n]', 'number', mockCoercion).action(() => {});10 program.parse([], { from: 'user' });11 expect(mockCoercion).not.toHaveBeenCalled();12});1314test('when argument not specified then action argument undefined', () => {15 let actionValue = 'foo';16 const program = new commander.Command();19 program20 .argument('[n]', 'number', parseFloat)21 .action((arg) => {22 actionValue = arg;23 });17 program.argument('[n]', 'number', parseFloat).action((arg) => {18 actionValue = arg;19 });20 program.parse([], { from: 'user' });21 expect(actionValue).toBeUndefined();22});2324test('when custom with starting value and argument not specified then callback not called', () => {25 const mockCoercion = jest.fn();26 const program = new commander.Command();31 program32 .argument('[n]', 'number', parseFloat, 1)33 .action(() => {});27 program.argument('[n]', 'number', parseFloat, 1).action(() => {});28 program.parse([], { from: 'user' });29 expect(mockCoercion).not.toHaveBeenCalled();30});3132test('when custom with starting value and argument not specified with action handler then action argument is starting value', () => {33 const startingValue = 1;34 let actionValue;35 const program = new commander.Command();42 program43 .argument('[n]', 'number', parseFloat, startingValue)44 .action((arg) => {45 actionValue = arg;46 });36 program.argument('[n]', 'number', parseFloat, startingValue).action((arg) => {37 actionValue = arg;38 });39 program.parse([], { from: 'user' });40 expect(actionValue).toEqual(startingValue);41 expect(program.processedArgs).toEqual([startingValue]);42});4344test('when custom with starting value and argument not specified without action handler then .processedArgs has starting value', () => {45 const startingValue = 1;46 const program = new commander.Command();55 program56 .argument('[n]', 'number', parseFloat, startingValue);47 program.argument('[n]', 'number', parseFloat, startingValue);48 program.parse([], { from: 'user' });49 expect(program.processedArgs).toEqual([startingValue]);50});5152test('when default value is defined (without custom processing) and argument not specified with action handler then action argument is default value', () => {53 const defaultValue = 1;54 let actionValue;55 const program = new commander.Command();65 program66 .argument('[n]', 'number', defaultValue)67 .action((arg) => {68 actionValue = arg;69 });56 program.argument('[n]', 'number', defaultValue).action((arg) => {57 actionValue = arg;58 });59 program.parse([], { from: 'user' });60 expect(actionValue).toEqual(defaultValue);61 expect(program.processedArgs).toEqual([defaultValue]);62});6364test('when default value is defined (without custom processing) and argument not specified without action handler then .processedArgs is default value', () => {65 const defaultValue = 1;66 const program = new commander.Command();78 program79 .argument('[n]', 'number', defaultValue);67 program.argument('[n]', 'number', defaultValue);68 program.parse([], { from: 'user' });69 expect(program.processedArgs).toEqual([defaultValue]);70});7172test('when argument specified then callback called with value', () => {73 const mockCoercion = jest.fn();74 const value = '1';75 const program = new commander.Command();88 program89 .argument('[n]', 'number', mockCoercion)90 .action(() => {});76 program.argument('[n]', 'number', mockCoercion).action(() => {});77 program.parse([value], { from: 'user' });78 expect(mockCoercion).toHaveBeenCalledWith(value, undefined);79});80
15 unmodified lines
9697test('when argument specified without action handler then .processedArgs is as returned from callback', () => {98 const callbackResult = 2;99 const program = new commander.Command();114 program115 .argument('[n]', 'number', () => {116 return callbackResult;117 });100 program.argument('[n]', 'number', () => {101 return callbackResult;102 });103 program.parse(['node', 'test', 'alpha']);104 expect(program.processedArgs).toEqual([callbackResult]);105});106
25 unmodified lines
132 const mockCoercion = jest.fn().mockImplementation(() => {133 return 'callback';134 });135 const program = new commander.Command();151 program152 .argument('<n...>', 'number', mockCoercion)153 .action(() => {});136 program.argument('<n...>', 'number', mockCoercion).action(() => {});137 program.parse(['1', '2'], { from: 'user' });138 expect(mockCoercion).toHaveBeenCalledTimes(2);139 expect(mockCoercion).toHaveBeenNthCalledWith(1, '1', undefined);140 expect(mockCoercion).toHaveBeenNthCalledWith(2, '2', 'callback');141});142143test('when variadic argument without action handler then .processedArg has array', () => {144 const program = new commander.Command();162 program163 .argument('<n...>', 'number');145 program.argument('<n...>', 'number');146 program.parse(['1', '2'], { from: 'user' });147 expect(program.processedArgs).toEqual([['1', '2']]);148});149150test('when parseFloat "1e2" then action argument is 100', () => {151 let actionValue;152 const program = new commander.Command();171 program172 .argument('<number>', 'float argument', parseFloat)173 .action((arg) => {174 actionValue = arg;175 });153 program.argument('<number>', 'float argument', parseFloat).action((arg) => {154 actionValue = arg;155 });156 program.parse(['1e2'], { from: 'user' });157 expect(actionValue).toEqual(100);158 expect(program.processedArgs).toEqual([actionValue]);159});
28 unmodified lines
modified:tests/argument.variadic.test.js+17 added-19 removed
4 unmodified lines
5describe('variadic argument', () => {6 test('when no extra arguments specified for program then variadic arg is empty array', () => {7 const actionMock = jest.fn();8 const program = new commander.Command();9 program10 .argument('<id>')11 .argument('[variadicArg...]')12 .action(actionMock);9 program.argument('<id>').argument('[variadicArg...]').action(actionMock);1011 program.parse(['node', 'test', 'id']);1213 expect(actionMock).toHaveBeenCalledWith('id', [], program.opts(), program);
9 unmodified lines
23 const extraArguments = ['a', 'b', 'c'];2425 program.parse(['node', 'test', 'id', ...extraArguments]);2630 expect(actionMock).toHaveBeenCalledWith('id', extraArguments, program.opts(), program);27 expect(actionMock).toHaveBeenCalledWith(28 'id',29 extraArguments,30 program.opts(),31 program,32 );33 });3435 test('when no extra arguments specified for command then variadic arg is empty array', () => {36 const actionMock = jest.fn();37 const program = new commander.Command();36 const cmd = program37 .command('sub [variadicArg...]')38 .action(actionMock);38 const cmd = program.command('sub [variadicArg...]').action(actionMock);3940 program.parse(['node', 'test', 'sub']);4142 expect(actionMock).toHaveBeenCalledWith([], cmd.opts(), cmd);
1 unmodified line
4445 test('when extra arguments specified for command then variadic arg is array of values', () => {46 const actionMock = jest.fn();47 const program = new commander.Command();48 const cmd = program49 .command('sub [variadicArg...]')50 .action(actionMock);48 const cmd = program.command('sub [variadicArg...]').action(actionMock);49 const extraArguments = ['a', 'b', 'c'];5051 program.parse(['node', 'test', 'sub', ...extraArguments]);52
3 unmodified lines
56 test('when program variadic argument not last then error', () => {57 const program = new commander.Command();5859 expect(() => {62 program63 .argument('<variadicArg...>')64 .argument('[optionalArg]');60 program.argument('<variadicArg...>').argument('[optionalArg]');61 }).toThrow("only the last argument can be variadic 'variadicArg'");62 });6364 test('when command variadic argument not last then error', () => {
5 unmodified lines
70 });7172 test('when variadic argument then usage shows variadic', () => {73 const program = new commander.Command();78 program79 .name('foo')80 .argument('[args...]');74 program.name('foo').argument('[args...]');7576 expect(program.usage()).toBe('[options] [args...]');77 });78
1 unmodified line
80 const program = new commander.Command();81 let passedArg;82 program83 .addArgument(new commander.Argument('<value...>').choices(['one', 'two']))90 .action((value) => { passedArg = value; });84 .action((value) => {85 passedArg = value;86 });8788 program.parse(['one'], { from: 'user' });89 expect(passedArg).toEqual(['one']);90 });
2 unmodified lines
93 const program = new commander.Command();94 let passedArg;95 program96 .addArgument(new commander.Argument('<value...>').choices(['one', 'two']))101 .action((value) => { passedArg = value; });97 .action((value) => {98 passedArg = value;99 });100101 program.parse(['one', 'two'], { from: 'user' });102 expect(passedArg).toEqual(['one', 'two']);103 });
1 unmodified line
modified:tests/command.action.test.js+78 added-61 removed
3 unmodified lines
45test('when .action called then command passed to action', () => {6 const actionMock = jest.fn();7 const program = new commander.Command();8 const cmd = program9 .command('info')10 .action(actionMock);8 const cmd = program.command('info').action(actionMock);9 program.parse(['node', 'test', 'info']);10 expect(actionMock).toHaveBeenCalledWith(cmd.opts(), cmd);11});1213test('when .action called then this is set to command', () => {14 const program = new commander.Command();15 let actionThis;18 const cmd = program19 .command('info')20 .action(function() { actionThis = this; });16 const cmd = program.command('info').action(function () {17 actionThis = this;18 });19 program.parse(['node', 'test', 'info']);20 expect(actionThis).toBe(cmd);21});2223test('when .action called then program.args only contains args', () => {24 // At one time program.args was being modified to contain the same args as the call to .action25 // and so included the command as an extra and unexpected complex item in array.26 const program = new commander.Command();29 program30 .command('info <file>')31 .action(() => {});27 program.command('info <file>').action(() => {});28 program.parse(['node', 'test', 'info', 'my-file']);29 expect(program.args).toEqual(['info', 'my-file']);30});3132test.each(getTestCases('<file>'))(33 'when .action on program with required argument via %s and argument supplied then action called',36test.each(getTestCases('<file>'))('when .action on program with required argument via %s and argument supplied then action called', (methodName, program) => {37 const actionMock = jest.fn();38 program.action(actionMock);39 program.parse(['node', 'test', 'my-file']);40 expect(actionMock).toHaveBeenCalledWith('my-file', program.opts(), program);41});34 (methodName, program) => {35 const actionMock = jest.fn();36 program.action(actionMock);37 program.parse(['node', 'test', 'my-file']);38 expect(actionMock).toHaveBeenCalledWith('my-file', program.opts(), program);39 },40);4142test.each(getTestCases('<file>'))(43 'when .action on program with required argument via %s and argument not supplied then action not called',43test.each(getTestCases('<file>'))('when .action on program with required argument via %s and argument not supplied then action not called', (methodName, program) => {44 const actionMock = jest.fn();45 program46 .exitOverride()47 .configureOutput({ writeErr: () => {} })48 .action(actionMock);49 expect(() => {50 program.parse(['node', 'test']);51 }).toThrow();52 expect(actionMock).not.toHaveBeenCalled();53});44 (methodName, program) => {45 const actionMock = jest.fn();46 program47 .exitOverride()48 .configureOutput({ writeErr: () => {} })49 .action(actionMock);50 expect(() => {51 program.parse(['node', 'test']);52 }).toThrow();53 expect(actionMock).not.toHaveBeenCalled();54 },55);5657// Changes made in #729 to call program action handler58test('when .action on program and no arguments then action called', () => {59 const actionMock = jest.fn();60 const program = new commander.Command();59 program60 .action(actionMock);61 program.action(actionMock);62 program.parse(['node', 'test']);63 expect(actionMock).toHaveBeenCalledWith(program.opts(), program);64});6566test.each(getTestCases('[file]'))(67 'when .action on program with optional argument via %s supplied then action called',65test.each(getTestCases('[file]'))('when .action on program with optional argument via %s supplied then action called', (methodName, program) => {66 const actionMock = jest.fn();67 program.action(actionMock);68 program.parse(['node', 'test', 'my-file']);69 expect(actionMock).toHaveBeenCalledWith('my-file', program.opts(), program);70});68 (methodName, program) => {69 const actionMock = jest.fn();70 program.action(actionMock);71 program.parse(['node', 'test', 'my-file']);72 expect(actionMock).toHaveBeenCalledWith('my-file', program.opts(), program);73 },74);7576test.each(getTestCases('[file]'))(77 'when .action on program without optional argument supplied then action called',72test.each(getTestCases('[file]'))('when .action on program without optional argument supplied then action called', (methodName, program) => {73 const actionMock = jest.fn();74 program.action(actionMock);75 program.parse(['node', 'test']);76 expect(actionMock).toHaveBeenCalledWith(undefined, program.opts(), program);77});78 (methodName, program) => {79 const actionMock = jest.fn();80 program.action(actionMock);81 program.parse(['node', 'test']);82 expect(actionMock).toHaveBeenCalledWith(undefined, program.opts(), program);83 },84);8579test.each(getTestCases('[file]'))('when .action on program with optional argument via %s and subcommand and program argument then program action called', (methodName, program) => {80 const actionMock = jest.fn();81 program.action(actionMock);82 program83 .command('subcommand');86test.each(getTestCases('[file]'))(87 'when .action on program with optional argument via %s and subcommand and program argument then program action called',88 (methodName, program) => {89 const actionMock = jest.fn();90 program.action(actionMock);91 program.command('subcommand');9285 program.parse(['node', 'test', 'a']);93 program.parse(['node', 'test', 'a']);9487 expect(actionMock).toHaveBeenCalledWith('a', program.opts(), program);88});95 expect(actionMock).toHaveBeenCalledWith('a', program.opts(), program);96 },97);9899// Changes made in #1062 to allow this case100test.each(getTestCases('[file]'))(101 'when .action on program with optional argument via %s and subcommand and no program argument then program action called',91test.each(getTestCases('[file]'))('when .action on program with optional argument via %s and subcommand and no program argument then program action called', (methodName, program) => {92 const actionMock = jest.fn();93 program.action(actionMock);94 program.command('subcommand');102 (methodName, program) => {103 const actionMock = jest.fn();104 program.action(actionMock);105 program.command('subcommand');10696 program.parse(['node', 'test']);107 program.parse(['node', 'test']);10898 expect(actionMock).toHaveBeenCalledWith(undefined, program.opts(), program);99});109 expect(actionMock).toHaveBeenCalledWith(undefined, program.opts(), program);110 },111);112101test('when action is async then can await parseAsync', async() => {113test('when action is async then can await parseAsync', async () => {114 let asyncFinished = false;115 async function delay() {104 await new Promise(resolve => setTimeout(resolve, 100));116 await new Promise((resolve) => setTimeout(resolve, 100));117 asyncFinished = true;118 }119 const program = new commander.Command();108 program109 .action(delay);120 program.action(delay);121122 const later = program.parseAsync(['node', 'test']);123 expect(asyncFinished).toBe(false);124 await later;
2 unmodified lines
127128function getTestCases(arg) {129 const withArguments = new commander.Command().arguments(arg);130 const withArgument = new commander.Command().argument(arg);120 const withAddArgument = new commander.Command().addArgument(new commander.Argument(arg));121 return [['.arguments', withArguments], ['.argument', withArgument], ['.addArgument', withAddArgument]];131 const withAddArgument = new commander.Command().addArgument(132 new commander.Argument(arg),133 );134 return [135 ['.arguments', withArguments],136 ['.argument', withArgument],137 ['.addArgument', withAddArgument],138 ];139}
modified:tests/command.addCommand.test.js+2 added-5 removed
3 unmodified lines
4test('when addCommand and specify subcommand then called', () => {5 const program = new commander.Command();6 const leafAction = jest.fn();7 const sub = new commander.Command();8 sub9 .name('sub')10 .action(leafAction);11 program12 .addCommand(sub);8 sub.name('sub').action(leafAction);9 program.addCommand(sub);1011 program.parse('node test.js sub'.split(' '));12 expect(leafAction).toHaveBeenCalled();13});
45 unmodified lines
modified:tests/command.addHelpOption.test.js+9 added-10 removed
6 unmodified lines
7 let writeErrorSpy;89 beforeAll(() => {10 // Optional. Suppress expected output to keep test output clean.11 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });12 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });11 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => {});12 writeErrorSpy = jest13 .spyOn(process.stderr, 'write')14 .mockImplementation(() => {});15 });1617 afterEach(() => {18 writeSpy.mockClear();
6 unmodified lines
25 });2627 test('when addHelpOption has custom flags then custom short flag invokes help', () => {28 const program = new Command();27 program28 .exitOverride()29 .addHelpOption(new Option('-c,--custom-help'));29 program.exitOverride().addHelpOption(new Option('-c,--custom-help'));3031 expect(() => {32 program.parse(['-c'], { from: 'user' });33 }).toThrow('(outputHelp)');34 });3536 test('when addHelpOption has custom flags then custom long flag invokes help', () => {37 const program = new Command();38 program39 .exitOverride()40 .addHelpOption(new Option('-c,--custom-help'));38 program.exitOverride().addHelpOption(new Option('-c,--custom-help'));3940 expect(() => {41 program.parse(['--custom-help'], { from: 'user' });42 }).toThrow('(outputHelp)');43 });4445 test('when addHelpOption with hidden help option then help does not include help option', () => {46 const program = new Command();49 program50 .addHelpOption(new Option('-c,--custom-help', 'help help help').hideHelp());47 program.addHelpOption(48 new Option('-c,--custom-help', 'help help help').hideHelp(),49 );50 const helpInfo = program.helpInformation();51 expect(helpInfo).not.toMatch(/help/);52 });53});
modified:tests/command.addHelpText.test.js+27 added-26 removed
4 unmodified lines
5describe('program calls to addHelpText', () => {6 let writeSpy;78 beforeAll(() => {9 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });9 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => {});10 });1112 afterEach(() => {13 writeSpy.mockClear();
20 unmodified lines
34 });3536 test('when "before" function returns nothing then no effect', () => {37 const program = new commander.Command();38 program.addHelpText('before', () => { });38 program.addHelpText('before', () => {});39 program.outputHelp();40 expect(writeSpy).toHaveBeenNthCalledWith(1, program.helpInformation());41 });42
46 unmodified lines
89describe('program and subcommand calls to addHelpText', () => {90 let writeSpy;9192 beforeAll(() => {93 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });93 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => {});94 });9596 afterEach(() => {97 writeSpy.mockClear();
44 unmodified lines
142 let stdoutSpy;143 let stderrSpy;144145 beforeAll(() => {146 stdoutSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });147 stderrSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });146 stdoutSpy = jest147 .spyOn(process.stdout, 'write')148 .mockImplementation(() => {});149 stderrSpy = jest150 .spyOn(process.stderr, 'write')151 .mockImplementation(() => {});152 });153154 afterEach(() => {155 stdoutSpy.mockClear();
6 unmodified lines
162 });163164 test('when help requested then text is on stdout', () => {165 const program = new commander.Command();162 program163 .exitOverride()164 .addHelpText('before', 'text');166 program.exitOverride().addHelpText('before', 'text');167 expect(() => {168 program.parse(['--help'], { from: 'user' });169 }).toThrow();170 expect(stdoutSpy).toHaveBeenCalledWith('text\n');171 });172173 test('when help for error then text is on stderr', () => {174 const program = new commander.Command();173 program174 .exitOverride()175 .addHelpText('before', 'text')176 .command('sub');175 program.exitOverride().addHelpText('before', 'text').command('sub');176 expect(() => {177 program.parse([], { from: 'user' });178 }).toThrow();179 expect(stderrSpy).toHaveBeenCalledWith('text\n');
1 unmodified line
181182 test('when help requested then context.error is false', () => {183 let context;184 const program = new commander.Command();186 program187 .exitOverride()188 .addHelpText('before', (contextParam) => { context = contextParam; });185 program.exitOverride().addHelpText('before', (contextParam) => {186 context = contextParam;187 });188 expect(() => {189 program.parse(['--help'], { from: 'user' });190 }).toThrow();191 expect(context.error).toBe(false);
3 unmodified lines
195 let context;196 const program = new commander.Command();197 program198 .exitOverride()200 .addHelpText('before', (contextParam) => { context = contextParam; })199 .addHelpText('before', (contextParam) => {200 context = contextParam;201 })202 .command('sub');203 expect(() => {204 program.parse([], { from: 'user' });205 }).toThrow();
2 unmodified lines
208209 test('when help on program then context.command is program', () => {210 let context;211 const program = new commander.Command();211 program212 .exitOverride()213 .addHelpText('before', (contextParam) => { context = contextParam; });212 program.exitOverride().addHelpText('before', (contextParam) => {213 context = contextParam;214 });215 expect(() => {216 program.parse(['--help'], { from: 'user' });217 }).toThrow();218 expect(context.command).toBe(program);
1 unmodified line
220221 test('when help on subcommand and "before" subcommand then context.command is subcommand', () => {222 let context;223 const program = new commander.Command();223 program224 .exitOverride();225 const sub = program.command('sub')226 .addHelpText('before', (contextParam) => { context = contextParam; });224 program.exitOverride();225 const sub = program.command('sub').addHelpText('before', (contextParam) => {226 context = contextParam;227 });228 expect(() => {229 program.parse(['sub', '--help'], { from: 'user' });230 }).toThrow();231 expect(context.command).toBe(sub);
1 unmodified line
233234 test('when help on subcommand and "beforeAll" on program then context.command is subcommand', () => {235 let context;236 const program = new commander.Command();236 program237 .exitOverride()238 .addHelpText('beforeAll', (contextParam) => { context = contextParam; });237 program.exitOverride().addHelpText('beforeAll', (contextParam) => {238 context = contextParam;239 });240 const sub = program.command('sub');241 expect(() => {242 program.parse(['sub', '--help'], { from: 'user' });243 }).toThrow();
3 unmodified lines
modified:tests/command.alias.test.js+8 added-29 removed
3 unmodified lines
4// Test various other behaviours for .alias56test('when command has alias then appears in help', () => {7 const program = new commander.Command();8 program9 .command('info [thing]')10 .alias('i');8 program.command('info [thing]').alias('i');9 const helpInformation = program.helpInformation();10 expect(helpInformation).toMatch('info|i');11});1213test('when command has aliases added separately then only first appears in help', () => {14 const program = new commander.Command();17 program18 .command('list [thing]')19 .alias('ls')20 .alias('dir');15 program.command('list [thing]').alias('ls').alias('dir');16 const helpInformation = program.helpInformation();17 expect(helpInformation).toMatch('list|ls ');18});1920test('when command has aliases then only first appears in help', () => {21 const program = new commander.Command();27 program28 .command('list [thing]')29 .aliases(['ls', 'dir']);22 program.command('list [thing]').aliases(['ls', 'dir']);23 const helpInformation = program.helpInformation();24 expect(helpInformation).toMatch('list|ls ');25});2627test('when command name = alias then error', () => {28 const program = new commander.Command();29 expect(() => {37 program38 .command('fail')39 .alias('fail');30 program.command('fail').alias('fail');31 }).toThrow("Command alias can't be the same as its name");32});3334test('when use alias then action handler called', () => {35 const program = new commander.Command();36 const actionMock = jest.fn();46 program47 .command('list')48 .alias('ls')49 .action(actionMock);37 program.command('list').alias('ls').action(actionMock);38 program.parse(['ls'], { from: 'user' });39 expect(actionMock).toHaveBeenCalled();40});4142test('when use second alias added separately then action handler called', () => {43 const program = new commander.Command();44 const actionMock = jest.fn();57 program58 .command('list')59 .alias('ls')60 .alias('dir')61 .action(actionMock);45 program.command('list').alias('ls').alias('dir').action(actionMock);46 program.parse(['dir'], { from: 'user' });47 expect(actionMock).toHaveBeenCalled();48});4950test('when use second of aliases then action handler called', () => {51 const program = new commander.Command();52 const actionMock = jest.fn();69 program70 .command('list')71 .aliases(['ls', 'dir'])72 .action(actionMock);53 program.command('list').aliases(['ls', 'dir']).action(actionMock);54 program.parse(['dir'], { from: 'user' });55 expect(actionMock).toHaveBeenCalled();56});57
13 unmodified lines
7172test('when set alias on executable then can get alias', () => {73 const program = new commander.Command();74 const alias = 'abcde';94 program95 .command('external', 'external command')96 .alias(alias);75 program.command('external', 'external command').alias(alias);76 expect(program.commands[0].alias()).toEqual(alias);77});7879describe('aliases parameter is treated as readonly, per TypeScript declaration', () => {
24 unmodified lines
modified:tests/command.allowExcessArguments.test.js+90 added-103 removed
1const commander = require('../');23// Not testing output, just testing whether an error is detected.45describe.each([true, false])('allowExcessArguments when action handler: %s', (hasActionHandler) => {6 function configureCommand(cmd) {7 cmd8 .exitOverride()9 .configureOutput({10 writeErr: () => {}5describe.each([true, false])(6 'allowExcessArguments when action handler: %s',7 (hasActionHandler) => {8 function configureCommand(cmd) {9 cmd.exitOverride().configureOutput({10 writeErr: () => {},11 });12 if (hasActionHandler) {13 cmd.action(() => {});12 if (hasActionHandler) {13 cmd.action(() => {});14 }15 }15 }1617 test('when specify excess program argument then no error by default', () => {18 const program = new commander.Command();19 configureCommand(program);17 test('when specify excess program argument then no error by default', () => {18 const program = new commander.Command();19 configureCommand(program);2021 expect(() => {22 program.parse(['excess'], { from: 'user' });23 }).not.toThrow();24 });21 expect(() => {22 program.parse(['excess'], { from: 'user' });23 }).not.toThrow();24 });2526 test('when specify excess program argument and allowExcessArguments(false) then error', () => {27 const program = new commander.Command();28 configureCommand(program);29 program30 .allowExcessArguments(false);26 test('when specify excess program argument and allowExcessArguments(false) then error', () => {27 const program = new commander.Command();28 configureCommand(program);29 program.allowExcessArguments(false);3032 expect(() => {33 program.parse(['excess'], { from: 'user' });34 }).toThrow();35 });31 expect(() => {32 program.parse(['excess'], { from: 'user' });33 }).toThrow();34 });3537 test('when specify excess program argument and allowExcessArguments() then no error', () => {38 const program = new commander.Command();39 configureCommand(program);40 program41 .allowExcessArguments();36 test('when specify excess program argument and allowExcessArguments() then no error', () => {37 const program = new commander.Command();38 configureCommand(program);39 program.allowExcessArguments();4043 expect(() => {44 program.parse(['excess'], { from: 'user' });45 }).not.toThrow();46 });41 expect(() => {42 program.parse(['excess'], { from: 'user' });43 }).not.toThrow();44 });4548 test('when specify excess program argument and allowExcessArguments(true) then no error', () => {49 const program = new commander.Command();50 configureCommand(program);51 program52 .allowExcessArguments(true);46 test('when specify excess program argument and allowExcessArguments(true) then no error', () => {47 const program = new commander.Command();48 configureCommand(program);49 program.allowExcessArguments(true);5054 expect(() => {55 program.parse(['excess'], { from: 'user' });56 }).not.toThrow();57 });51 expect(() => {52 program.parse(['excess'], { from: 'user' });53 }).not.toThrow();54 });5559 test('when specify excess command argument then no error (by default)', () => {60 const program = new commander.Command();61 const sub = program62 .command('sub');63 configureCommand(sub);56 test('when specify excess command argument then no error (by default)', () => {57 const program = new commander.Command();58 const sub = program.command('sub');59 configureCommand(sub);6065 expect(() => {66 program.parse(['sub', 'excess'], { from: 'user' });67 }).not.toThrow();68 });61 expect(() => {62 program.parse(['sub', 'excess'], { from: 'user' });63 }).not.toThrow();64 });6570 test('when specify excess command argument and allowExcessArguments(false) then error', () => {71 const program = new commander.Command();72 const sub = program73 .command('sub')74 .allowExcessArguments(false);75 configureCommand(sub);66 test('when specify excess command argument and allowExcessArguments(false) then error', () => {67 const program = new commander.Command();68 const sub = program.command('sub').allowExcessArguments(false);69 configureCommand(sub);7077 expect(() => {78 program.parse(['sub', 'excess'], { from: 'user' });79 }).toThrow();80 });71 expect(() => {72 program.parse(['sub', 'excess'], { from: 'user' });73 }).toThrow();74 });7582 test('when specify expected arg and allowExcessArguments(false) then no error', () => {83 const program = new commander.Command();84 configureCommand(program);85 program86 .argument('<file>')87 .allowExcessArguments(false);76 test('when specify expected arg and allowExcessArguments(false) then no error', () => {77 const program = new commander.Command();78 configureCommand(program);79 program.argument('<file>').allowExcessArguments(false);8089 expect(() => {90 program.parse(['file'], { from: 'user' });91 }).not.toThrow();92 });81 expect(() => {82 program.parse(['file'], { from: 'user' });83 }).not.toThrow();84 });8594 test('when specify excess after <arg> and allowExcessArguments(false) then error', () => {95 const program = new commander.Command();96 configureCommand(program);97 program98 .argument('<file>')99 .allowExcessArguments(false);86 test('when specify excess after <arg> and allowExcessArguments(false) then error', () => {87 const program = new commander.Command();88 configureCommand(program);89 program.argument('<file>').allowExcessArguments(false);90101 expect(() => {102 program.parse(['file', 'excess'], { from: 'user' });103 }).toThrow();104 });91 expect(() => {92 program.parse(['file', 'excess'], { from: 'user' });93 }).toThrow();94 });95106 test('when specify excess after [arg] and allowExcessArguments(false) then error', () => {107 const program = new commander.Command();108 configureCommand(program);109 program110 .argument('[file]')111 .allowExcessArguments(false);96 test('when specify excess after [arg] and allowExcessArguments(false) then error', () => {97 const program = new commander.Command();98 configureCommand(program);99 program.argument('[file]').allowExcessArguments(false);100113 expect(() => {114 program.parse(['file', 'excess'], { from: 'user' });115 }).toThrow();116 });101 expect(() => {102 program.parse(['file', 'excess'], { from: 'user' });103 }).toThrow();104 });105118 test('when specify args for [args...] and allowExcessArguments(false) then no error', () => {119 const program = new commander.Command();120 configureCommand(program);121 program122 .argument('[files...]')123 .allowExcessArguments(false);106 test('when specify args for [args...] and allowExcessArguments(false) then no error', () => {107 const program = new commander.Command();108 configureCommand(program);109 program.argument('[files...]').allowExcessArguments(false);110125 expect(() => {126 program.parse(['file1', 'file2', 'file3'], { from: 'user' });127 }).not.toThrow();128 });129});111 expect(() => {112 program.parse(['file1', 'file2', 'file3'], { from: 'user' });113 }).not.toThrow();114 });115 },116);
modified:tests/command.allowUnknownOption.test.js+6 added-6 removed
5 unmodified lines
6 // Optional. Use internal knowledge to suppress output to keep test output clean.7 let writeErrorSpy;89 beforeAll(() => {10 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });10 writeErrorSpy = jest11 .spyOn(process.stderr, 'write')12 .mockImplementation(() => {});13 });1415 afterEach(() => {16 writeErrorSpy.mockClear();
4 unmodified lines
21 });2223 test('when specify unknown program option then error', () => {24 const program = new commander.Command();23 program24 .exitOverride()25 .option('-p, --pepper', 'add pepper');25 program.exitOverride().option('-p, --pepper', 'add pepper');2627 expect(() => {28 program.parse(['node', 'test', '-m']);29 }).toThrow();
40 unmodified lines
70 program71 .exitOverride()72 .command('sub')73 .option('-p, --pepper', 'add pepper')74 .action(() => { });74 .action(() => {});7576 expect(() => {77 program.parse(['node', 'test', 'sub', '-m']);78 }).toThrow();
6 unmodified lines
85 .command('sub')86 .argument('[args...]') // unknown option will be passed as an argument87 .allowUnknownOption()88 .option('-p, --pepper', 'add pepper')89 .action(() => { });89 .action(() => {});9091 expect(() => {92 program.parse(['node', 'test', 'sub', '-m']);93 }).not.toThrow();
2 unmodified lines
modified:tests/command.argumentVariations.test.js+100 added-69 removed
1 unmodified line
23// Do some low-level checks that the multiple ways of specifying command arguments produce same internal result,4// and not exhaustively testing all methods elsewhere.56test.each(getSingleArgCases('<explicit-required>'))(7 'when add "<arg>" using %s then argument required',6test.each(getSingleArgCases('<explicit-required>'))('when add "<arg>" using %s then argument required', (methodName, cmd) => {7 const argument = cmd.registeredArguments[0];8 const expectedShape = {9 _name: 'explicit-required',10 required: true,11 variadic: false,12 description: ''13 };14 expect(argument).toEqual(expectedShape);15});8 (methodName, cmd) => {9 const argument = cmd.registeredArguments[0];10 const expectedShape = {11 _name: 'explicit-required',12 required: true,13 variadic: false,14 description: '',15 };16 expect(argument).toEqual(expectedShape);17 },18);1920test.each(getSingleArgCases('implicit-required'))(21 'when add "arg" using %s then argument required',17test.each(getSingleArgCases('implicit-required'))('when add "arg" using %s then argument required', (methodName, cmd) => {18 const argument = cmd.registeredArguments[0];19 const expectedShape = {20 _name: 'implicit-required',21 required: true,22 variadic: false,23 description: ''24 };25 expect(argument).toEqual(expectedShape);26});22 (methodName, cmd) => {23 const argument = cmd.registeredArguments[0];24 const expectedShape = {25 _name: 'implicit-required',26 required: true,27 variadic: false,28 description: '',29 };30 expect(argument).toEqual(expectedShape);31 },32);3334test.each(getSingleArgCases('[optional]'))(35 'when add "[arg]" using %s then argument optional',28test.each(getSingleArgCases('[optional]'))('when add "[arg]" using %s then argument optional', (methodName, cmd) => {29 const argument = cmd.registeredArguments[0];30 const expectedShape = {31 _name: 'optional',32 required: false,33 variadic: false,34 description: ''35 };36 expect(argument).toEqual(expectedShape);37});36 (methodName, cmd) => {37 const argument = cmd.registeredArguments[0];38 const expectedShape = {39 _name: 'optional',40 required: false,41 variadic: false,42 description: '',43 };44 expect(argument).toEqual(expectedShape);45 },46);4748test.each(getSingleArgCases('<explicit-required...>'))(49 'when add "<arg...>" using %s then argument required and variadic',39test.each(getSingleArgCases('<explicit-required...>'))('when add "<arg...>" using %s then argument required and variadic', (methodName, cmd) => {40 const argument = cmd.registeredArguments[0];41 const expectedShape = {42 _name: 'explicit-required',43 required: true,44 variadic: true,45 description: ''46 };47 expect(argument).toEqual(expectedShape);48});50 (methodName, cmd) => {51 const argument = cmd.registeredArguments[0];52 const expectedShape = {53 _name: 'explicit-required',54 required: true,55 variadic: true,56 description: '',57 };58 expect(argument).toEqual(expectedShape);59 },60);6162test.each(getSingleArgCases('implicit-required...'))(63 'when add "arg..." using %s then argument required and variadic',50test.each(getSingleArgCases('implicit-required...'))('when add "arg..." using %s then argument required and variadic', (methodName, cmd) => {51 const argument = cmd.registeredArguments[0];52 const expectedShape = {53 _name: 'implicit-required',54 required: true,55 variadic: true,56 description: ''57 };58 expect(argument).toEqual(expectedShape);59});64 (methodName, cmd) => {65 const argument = cmd.registeredArguments[0];66 const expectedShape = {67 _name: 'implicit-required',68 required: true,69 variadic: true,70 description: '',71 };72 expect(argument).toEqual(expectedShape);73 },74);7576test.each(getSingleArgCases('[optional...]'))(77 'when add "[arg...]" using %s then argument optional and variadic',61test.each(getSingleArgCases('[optional...]'))('when add "[arg...]" using %s then argument optional and variadic', (methodName, cmd) => {62 const argument = cmd.registeredArguments[0];63 const expectedShape = {64 _name: 'optional',65 required: false,66 variadic: true,67 description: ''68 };69 expect(argument).toEqual(expectedShape);70});78 (methodName, cmd) => {79 const argument = cmd.registeredArguments[0];80 const expectedShape = {81 _name: 'optional',82 required: false,83 variadic: true,84 description: '',85 };86 expect(argument).toEqual(expectedShape);87 },88);8990function getSingleArgCases(arg) {91 return [92 ['.arguments', new commander.Command().arguments(arg)],93 ['.argument', new commander.Command().argument(arg)],76 ['.addArgument', new commander.Command('add-argument').addArgument(new commander.Argument(arg))],77 ['.command', new commander.Command().command(`command ${arg}`)]94 [95 '.addArgument',96 new commander.Command('add-argument').addArgument(97 new commander.Argument(arg),98 ),99 ],100 ['.command', new commander.Command().command(`command ${arg}`)],101 ];102}103104test.each(getMultipleArgCases('<first>', '[second]'))(105 'when add two arguments using %s then two arguments',81test.each(getMultipleArgCases('<first>', '[second]'))('when add two arguments using %s then two arguments', (methodName, cmd) => {82 expect(cmd.registeredArguments[0].name()).toEqual('first');83 expect(cmd.registeredArguments[1].name()).toEqual('second');84});106 (methodName, cmd) => {107 expect(cmd.registeredArguments[0].name()).toEqual('first');108 expect(cmd.registeredArguments[1].name()).toEqual('second');109 },110);111112function getMultipleArgCases(arg1, arg2) {113 return [114 ['.arguments', new commander.Command().arguments(`${arg1} ${arg2}`)],115 ['.argument', new commander.Command().argument(arg1).argument(arg2)],90 ['.addArgument', new commander.Command('add-argument').addArgument(new commander.Argument(arg1)).addArgument(new commander.Argument(arg2))],91 ['.command', new commander.Command().command(`command ${arg1} ${arg2}`)]116 [117 '.addArgument',118 new commander.Command('add-argument')119 .addArgument(new commander.Argument(arg1))120 .addArgument(new commander.Argument(arg2)),121 ],122 ['.command', new commander.Command().command(`command ${arg1} ${arg2}`)],123 ];124}125126test('when add arguments using multiple methods then all added', () => {
2 unmodified lines
129 const cmd = program.command('sub <arg1> <arg2>');130 cmd.arguments('<arg3> <arg4>');131 cmd.argument('<arg5>');132 cmd.addArgument(new commander.Argument('arg6'));102 const argNames = cmd.registeredArguments.map(arg => arg.name());133 const argNames = cmd.registeredArguments.map((arg) => arg.name());134 expect(argNames).toEqual(['arg1', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6']);135});
modified:tests/command.asterisk.test.js+22 added-42 removed
10 unmodified lines
11// Historical: the event 'command:*' used to also be shared by the action handler on the program.1213describe(".command('*')", () => {14 test('when no arguments then asterisk action not called', () => {15 const writeMock = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });15 const writeMock = jest16 .spyOn(process.stderr, 'write')17 .mockImplementation(() => {});18 const mockAction = jest.fn();19 const program = new commander.Command();20 program21 .exitOverride() // to catch help22 .command('*')23 .action(mockAction);24 try {25 program.parse(['node', 'test']);24 } catch (err) { /* empty */ }26 } catch (err) {27 /* empty */28 }29 expect(mockAction).not.toHaveBeenCalled();30 writeMock.mockRestore();31 });3233 test('when unrecognised argument then asterisk action called', () => {34 const mockAction = jest.fn();35 const program = new commander.Command();32 program33 .command('*')34 .argument('[args...]')35 .action(mockAction);36 program.command('*').argument('[args...]').action(mockAction);37 program.parse(['node', 'test', 'unrecognised-command']);38 expect(mockAction).toHaveBeenCalled();39 });4041 test('when recognised command then asterisk action not called', () => {42 const mockAction = jest.fn();43 const program = new commander.Command();43 program44 .command('install')45 .action(() => { });46 program47 .command('*')48 .action(mockAction);44 program.command('install').action(() => {});45 program.command('*').action(mockAction);46 program.parse(['node', 'test', 'install']);47 expect(mockAction).not.toHaveBeenCalled();48 });4950 test('when unrecognised command/argument then asterisk action called', () => {51 const mockAction = jest.fn();52 const program = new commander.Command();56 program57 .command('install');58 program59 .command('*')60 .argument('[args...]')61 .action(mockAction);53 program.command('install');54 program.command('*').argument('[args...]').action(mockAction);55 program.parse(['node', 'test', 'unrecognised-command']);56 expect(mockAction).toHaveBeenCalled();57 });5859 test('when unrecognised argument and known option then asterisk action called', () => {60 // This tests for a regression between v4 and v5. Known default option should not be rejected by program.61 const mockAction = jest.fn();62 const program = new commander.Command();70 program71 .command('install');63 program.command('install');64 const star = program65 .command('*')66 .argument('[args...]')67 .option('-d, --debug')
9 unmodified lines
77 const program = new commander.Command();78 program79 .exitOverride()80 .configureOutput({89 writeErr: () => {}81 writeErr: () => {},82 })83 .command('install');92 program93 .command('*')94 .argument('[args...]')95 .action(mockAction);84 program.command('*').argument('[args...]').action(mockAction);85 let caughtErr;86 try {87 program.parse(['node', 'test', 'some-argument', '--unknown']);88 } catch (err) {
7 unmodified lines
96describe(".on('command:*')", () => {97 test('when no arguments then listener not called', () => {98 const mockAction = jest.fn();99 const program = new commander.Command();111 program112 .on('command:*', mockAction);100 program.on('command:*', mockAction);101 program.parse(['node', 'test']);102 expect(mockAction).not.toHaveBeenCalled();103 });104105 test('when unrecognised argument then listener called', () => {106 const mockAction = jest.fn();107 const program = new commander.Command();120 program121 .on('command:*', mockAction);108 program.on('command:*', mockAction);109 program.parse(['node', 'test', 'unrecognised-command']);110 expect(mockAction).toHaveBeenCalled();111 });112113 test('when recognised command then listener not called', () => {114 const mockAction = jest.fn();115 const program = new commander.Command();129 program130 .command('install')131 .action(() => { });132 program133 .on('command:*', mockAction);116 program.command('install').action(() => {});117 program.on('command:*', mockAction);118 program.parse(['node', 'test', 'install']);119 expect(mockAction).not.toHaveBeenCalled();120 });121122 test('when unrecognised command/argument then listener called', () => {123 const mockAction = jest.fn();124 const program = new commander.Command();141 program142 .command('install');143 program144 .on('command:*', mockAction);125 program.command('install');126 program.on('command:*', mockAction);127 program.parse(['node', 'test', 'unrecognised-command']);128 expect(mockAction).toHaveBeenCalled();129 });130
2 unmodified lines
133 // could only be unknown because the command is not correct.134 // Regression identified in https://github.com/tj/commander.js/issues/1460#issuecomment-772313494135 const mockAction = jest.fn();136 const program = new commander.Command();155 program156 .command('install');157 program158 .on('command:*', mockAction);137 program.command('install');138 program.on('command:*', mockAction);139 program.parse(['node', 'test', 'intsall', '--unknown']);140 expect(mockAction).toHaveBeenCalled();141 });142});
modified:tests/command.chain.test.js+4 added-4 removed
82 unmodified lines
83 });8485 test('when call .exitOverride() then returns this', () => {86 const program = new Command();87 const result = program.exitOverride(() => { });87 const result = program.exitOverride(() => {});88 expect(result).toBe(program);89 });9091 test('when call .action() then returns this', () => {92 const program = new Command();93 const result = program.action(() => { });93 const result = program.action(() => {});94 expect(result).toBe(program);95 });9697 test('when call .addOption() then returns this', () => {
94 unmodified lines
192 });193194 test('when call .configureHelp() then returns this', () => {195 const program = new Command();196 const result = program.configureHelp({ });196 const result = program.configureHelp({});197 expect(result).toBe(program);198 });199200 test('when call .configureOutput() then returns this', () => {201 const program = new Command();202 const result = program.configureOutput({ });202 const result = program.configureOutput({});203 expect(result).toBe(program);204 });205206 test('when call .passThroughOptions() then returns this', () => {
54 unmodified lines
modified:tests/command.commandHelp.test.js+2 added-4 removed
2 unmodified lines
3// This is a ported legacy test.45test('when program has command then appears in help', () => {6 const program = new commander.Command();7 program8 .command('bare');7 program.command('bare');8 const commandHelp = program.helpInformation();9 expect(commandHelp).toMatch(/Commands:\n +bare\n/);10});1112test('when program has command with optional arg then appears in help', () => {13 const program = new commander.Command();15 program16 .command('bare [bare-arg]');14 program.command('bare [bare-arg]');15 const commandHelp = program.helpInformation();16 expect(commandHelp).toMatch(/Commands:\n +bare \[bare-arg\]\n/);17});
modified:tests/command.configureHelp.test.js+11 added-3 removed
1const commander = require('../');23test('when configure program then affects program helpInformation', () => {4 const program = new commander.Command();5 program.configureHelp({ formatHelp: () => { return 'custom'; } });5 program.configureHelp({6 formatHelp: () => {7 return 'custom';8 },9 });10 expect(program.helpInformation()).toEqual('custom');11});1213test('when configure program then affects subcommand helpInformation', () => {14 const program = new commander.Command();11 program.configureHelp({ formatHelp: () => { return 'custom'; } });15 program.configureHelp({16 formatHelp: () => {17 return 'custom';18 },19 });20 const sub = program.command('sub');21 expect(sub.helpInformation()).toEqual('custom');22});23
8 unmodified lines
32 program.configureHelp({33 mySecretValue: 'secret',34 formatHelp: (cmd, helper) => {35 return helper.mySecretValue;28 }36 },37 });38 expect(program.helpInformation()).toEqual('secret');39});
modified:tests/command.configureOutput.test.js+73 added-53 removed
1const commander = require('../');23test('when default writeErr() then error on stderr', () => {4 const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });4 const writeSpy = jest5 .spyOn(process.stderr, 'write')6 .mockImplementation(() => {});7 const program = new commander.Command();8 program.exitOverride();910 try {11 program.parse(['--unknown'], { from: 'user' });10 } catch (err) { /* empty */ }12 } catch (err) {13 /* empty */14 }1516 expect(writeSpy).toHaveBeenCalledTimes(1);17 writeSpy.mockRestore();18});1920test('when custom writeErr() then error on custom output', () => {17 const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });21 const writeSpy = jest22 .spyOn(process.stderr, 'write')23 .mockImplementation(() => {});24 const customWrite = jest.fn();25 const program = new commander.Command();20 program21 .exitOverride()22 .configureOutput({ writeErr: customWrite });26 program.exitOverride().configureOutput({ writeErr: customWrite });2728 try {29 program.parse(['--unknown'], { from: 'user' });26 } catch (err) { /* empty */ }30 } catch (err) {31 /* empty */32 }3334 expect(writeSpy).toHaveBeenCalledTimes(0);35 expect(customWrite).toHaveBeenCalledTimes(1);36 writeSpy.mockRestore();37});3839test('when default write() then version on stdout', () => {34 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });40 const writeSpy = jest41 .spyOn(process.stdout, 'write')42 .mockImplementation(() => {});43 const program = new commander.Command();36 program37 .exitOverride()38 .version('1.2.3');44 program.exitOverride().version('1.2.3');4546 expect(() => {47 program.parse(['--version'], { from: 'user' });48 }).toThrow();
2 unmodified lines
51 writeSpy.mockRestore();52});5354test('when custom write() then version on custom output', () => {49 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });55 const writeSpy = jest56 .spyOn(process.stdout, 'write')57 .mockImplementation(() => {});58 const customWrite = jest.fn();59 const program = new commander.Command();60 program61 .exitOverride()
9 unmodified lines
71 writeSpy.mockRestore();72});7374test('when default write() then help on stdout', () => {67 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });75 const writeSpy = jest76 .spyOn(process.stdout, 'write')77 .mockImplementation(() => {});78 const program = new commander.Command();79 program.outputHelp();8081 expect(writeSpy).toHaveBeenCalledTimes(1);82 writeSpy.mockRestore();83});8485test('when custom write() then help error on custom output', () => {76 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });86 const writeSpy = jest87 .spyOn(process.stdout, 'write')88 .mockImplementation(() => {});89 const customWrite = jest.fn();90 const program = new commander.Command();91 program.configureOutput({ writeOut: customWrite });92 program.outputHelp();
3 unmodified lines
96 writeSpy.mockRestore();97});9899test('when default writeErr then help error on stderr', () => {88 const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });100 const writeSpy = jest101 .spyOn(process.stderr, 'write')102 .mockImplementation(() => {});103 const program = new commander.Command();104 program.outputHelp({ error: true });105106 expect(writeSpy).toHaveBeenCalledTimes(1);107 writeSpy.mockRestore();108});109110test('when custom writeErr then help error on custom output', () => {97 const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });111 const writeSpy = jest112 .spyOn(process.stderr, 'write')113 .mockImplementation(() => {});114 const customWrite = jest.fn();115 const program = new commander.Command();116 program.configureOutput({ writeErr: customWrite });117 program.outputHelp({ error: true });
12 unmodified lines
130 process.stderr.isTTY = true;131 process.stdout.columns = expectedColumns;132 process.stdout.isTTY = true;133 const program = new commander.Command();118 program119 .configureHelp({120 formatHelp: (cmd, helper) => {121 helpWidth = helper.helpWidth;122 return '';123 }124 });134 program.configureHelp({135 formatHelp: (cmd, helper) => {136 helpWidth = helper.helpWidth;137 return '';138 },139 });140 program.outputHelp();141142 expect(helpWidth).toBe(expectedColumns);143 process.stdout.columns = holdColumns;
9 unmodified lines
153 .configureHelp({154 formatHelp: (cmd, helper) => {155 helpWidth = helper.helpWidth;156 return '';157 },142 }143 }).configureOutput({144 getOutHelpWidth: () => expectedColumns158 })159 .configureOutput({160 getOutHelpWidth: () => expectedColumns,161 });162 program.outputHelp();163164 expect(helpWidth).toBe(expectedColumns);
7 unmodified lines
172173 process.stderr.isTTY = true;174 process.stderr.columns = expectedColumns;175 const program = new commander.Command();160 program161 .configureHelp({162 formatHelp: (cmd, helper) => {163 helpWidth = helper.helpWidth;164 return '';165 }166 });176 program.configureHelp({177 formatHelp: (cmd, helper) => {178 helpWidth = helper.helpWidth;179 return '';180 },181 });182 program.outputHelp({ error: true });183184 expect(helpWidth).toBe(expectedColumns);185 process.stderr.isTTY = holdIsTTY;
9 unmodified lines
195 .configureHelp({196 formatHelp: (cmd, helper) => {197 helpWidth = helper.helpWidth;198 return '';199 },184 }185 }).configureOutput({186 getErrHelpWidth: () => expectedColumns200 })201 .configureOutput({202 getErrHelpWidth: () => expectedColumns,203 });204 program.outputHelp({ error: true });205206 expect(helpWidth).toBe(expectedColumns);
9 unmodified lines
216 formatHelp: (cmd, helper) => {217 helpWidth = helper.helpWidth;218 return '';219 },204 helpWidth: expectedColumns205 }).configureOutput({206 getOutHelpWidth: () => 999220 helpWidth: expectedColumns,221 })222 .configureOutput({223 getOutHelpWidth: () => 999,224 });225 program.outputHelp();226227 expect(helpWidth).toBe(expectedColumns);
9 unmodified lines
237 formatHelp: (cmd, helper) => {238 helpWidth = helper.helpWidth;239 return '';240 },224 helpWidth: expectedColumns225 }).configureOutput({226 getErrHelpWidth: () => 999241 helpWidth: expectedColumns,242 })243 .configureOutput({244 getErrHelpWidth: () => 999,245 });246 program.outputHelp({ error: true });247248 expect(helpWidth).toBe(expectedColumns);
4 unmodified lines
253 writeOut: jest.fn(),254 writeErr: jest.fn(),255 getOutHelpWidth: jest.fn(),256 getErrHelpWidth: jest.fn(),239 outputError: jest.fn()257 outputError: jest.fn(),258 };259 const program = new commander.Command();260 program.configureOutput(outputOptions);261 expect(program.configureOutput()).toEqual(outputOptions);
1 unmodified line
263264test('when custom outputErr and error then outputErr called', () => {265 const outputError = jest.fn();266 const program = new commander.Command();249 program250 .exitOverride()251 .configureOutput({252 outputError253 });267 program.exitOverride().configureOutput({268 outputError,269 });270271 expect(() => {272 program.parse(['--unknownOption'], { from: 'user' });273 }).toThrow();258 expect(outputError).toHaveBeenCalledWith("error: unknown option '--unknownOption'\n", program._outputConfiguration.writeErr);274 expect(outputError).toHaveBeenCalledWith(275 "error: unknown option '--unknownOption'\n",276 program._outputConfiguration.writeErr,277 );278});279280test('when custom outputErr and writeErr and error then outputErr passed writeErr', () => {281 const writeErr = () => jest.fn();282 const outputError = jest.fn();283 const program = new commander.Command();265 program266 .exitOverride()267 .configureOutput({ writeErr, outputError });284 program.exitOverride().configureOutput({ writeErr, outputError });285286 expect(() => {287 program.parse(['--unknownOption'], { from: 'user' });288 }).toThrow();272 expect(outputError).toHaveBeenCalledWith("error: unknown option '--unknownOption'\n", writeErr);289 expect(outputError).toHaveBeenCalledWith(290 "error: unknown option '--unknownOption'\n",291 writeErr,292 );293});
modified:tests/command.default.test.js+6 added-9 removed
7 unmodified lines
8describe('default executable command', () => {9 // Calling node explicitly so pm works without file suffix cross-platform.10 const pm = path.join(__dirname, './fixtures/pm');1112 test('when default subcommand and no command then call default', async() => {12 test('when default subcommand and no command then call default', async () => {13 const { stdout } = await execFileAsync('node', [pm]);14 expect(stdout).toBe('default\n');15 });1617 test('when default subcommand and unrecognised argument then call default with argument', async() => {17 test('when default subcommand and unrecognised argument then call default with argument', async () => {18 const { stdout } = await execFileAsync('node', [pm, 'an-argument']);19 expect(stdout).toBe("default\n[ 'an-argument' ]\n");20 });2122 test('when default subcommand and unrecognised option then call default with option', async() => {22 test('when default subcommand and unrecognised option then call default with option', async () => {23 const { stdout } = await execFileAsync('node', [pm, '--an-option']);24 expect(stdout).toBe("default\n[ '--an-option' ]\n");25 });26});
1 unmodified line
28describe('default action command', () => {29 function makeProgram() {30 const program = new commander.Command();31 const actionMock = jest.fn();32 program.command('other');33 program33 .command('other');34 program34 .command('default', { isDefault: true })35 .allowUnknownOption()36 .allowExcessArguments()37 .action(actionMock);
27 unmodified lines
65 .allowExcessArguments()66 .action(actionMock);6768 const program = new commander.Command();70 program71 .command('other');72 program73 .addCommand(defaultCmd, { isDefault: true });69 program.command('other');70 program.addCommand(defaultCmd, { isDefault: true });71 return { program, actionMock };72 }7374 test('when default subcommand and no command then call default', () => {
17 unmodified lines
modified:tests/command.error.test.js+13 added-8 removed
1const commander = require('../');23test('when error called with message then message displayed on stderr', () => {4 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => { });5 const stderrSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });4 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {});5 const stderrSpy = jest6 .spyOn(process.stderr, 'write')7 .mockImplementation(() => {});89 const program = new commander.Command();10 const message = 'Goodbye';11 program.error(message);
3 unmodified lines
15 exitSpy.mockRestore();16});1718test('when error called with no exitCode then process.exit(1)', () => {17 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => { });19 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {});2021 const program = new commander.Command();22 program.configureOutput({21 writeErr: () => {}23 writeErr: () => {},24 });2526 program.error('Goodbye');27
1 unmodified line
29 exitSpy.mockRestore();30});3132test('when error called with exitCode 2 then process.exit(2)', () => {31 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => { });33 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {});3435 const program = new commander.Command();36 program.configureOutput({35 writeErr: () => {}37 writeErr: () => {},38 });39 program.error('Goodbye', { exitCode: 2 });4041 expect(exitSpy).toHaveBeenCalledWith(2);
3 unmodified lines
45test('when error called with code and exitOverride then throws with code', () => {46 const program = new commander.Command();47 let errorThrown;48 program47 .exitOverride((err) => { errorThrown = err; throw err; })49 .exitOverride((err) => {50 errorThrown = err;51 throw err;52 })53 .configureOutput({49 writeErr: () => {}54 writeErr: () => {},55 });5657 const code = 'commander.test';58 expect(() => {
4 unmodified lines
modified:tests/command.executableSubcommand.inspect.test.js+43 added-15 removed
7 unmodified lines
8// If we reuse port we can get conflicts because port not released fast enough.910const inspectCommand = path.join(__dirname, './fixtures', 'inspect.js');1112test('when execArgv empty then spawn execArgs empty', async() => {12test('when execArgv empty then spawn execArgs empty', async () => {13 const { stdout } = await execFileAsync('node', [inspectCommand, 'sub']);14 expect(stdout).toBe('[]\n');15});1617test('when execArgv --harmony then spawn execArgs --harmony', async() => {18 const { stdout } = await execFileAsync('node', ['--harmony', inspectCommand, 'sub']);17test('when execArgv --harmony then spawn execArgs --harmony', async () => {18 const { stdout } = await execFileAsync('node', [19 '--harmony',20 inspectCommand,21 'sub',22 ]);23 expect(stdout).toBe("[ '--harmony' ]\n");24});2526// --inspect defaults to 127.0.0.1:9229, port should be incremented23test('when execArgv --inspect then spawn execArgs using port 9230', async() => {24 const { stdout } = await execFileAsync('node', ['--inspect', inspectCommand, 'sub']);27test('when execArgv --inspect then spawn execArgs using port 9230', async () => {28 const { stdout } = await execFileAsync('node', [29 '--inspect',30 inspectCommand,31 'sub',32 ]);33 expect(stdout).toBe("[ '--inspect=127.0.0.1:9230' ]\n");34});3536// custom port29test('when execArgv --inspect=9240 then spawn execArgs using port 9241', async() => {30 const { stdout } = await execFileAsync('node', ['--inspect=9240', inspectCommand, 'sub']);37test('when execArgv --inspect=9240 then spawn execArgs using port 9241', async () => {38 const { stdout } = await execFileAsync('node', [39 '--inspect=9240',40 inspectCommand,41 'sub',42 ]);43 expect(stdout).toBe("[ '--inspect=127.0.0.1:9241' ]\n");44});4546// zero is special, random port35test('when execArgv --inspect=0 then spawn execArgs --inspect=0', async() => {36 const { stdout } = await execFileAsync('node', ['--inspect=0', inspectCommand, 'sub']);47test('when execArgv --inspect=0 then spawn execArgs --inspect=0', async () => {48 const { stdout } = await execFileAsync('node', [49 '--inspect=0',50 inspectCommand,51 'sub',52 ]);53 expect(stdout).toBe("[ '--inspect=0' ]\n");54});5556// ip address41test('when execArgv --inspect=127.0.0.1:9250 then spawn execArgs --inspect=127.0.0.1:9251', async() => {42 const { stdout } = await execFileAsync('node', ['--inspect=127.0.0.1:9250', inspectCommand, 'sub']);57test('when execArgv --inspect=127.0.0.1:9250 then spawn execArgs --inspect=127.0.0.1:9251', async () => {58 const { stdout } = await execFileAsync('node', [59 '--inspect=127.0.0.1:9250',60 inspectCommand,61 'sub',62 ]);63 expect(stdout).toBe("[ '--inspect=127.0.0.1:9251' ]\n");64});6566// localhost47test('when execArgv --inspect=localhost:9260 then spawn execArgs --inspect=localhost:9261', async() => {48 const { stdout } = await execFileAsync('node', ['--inspect=localhost:9260', inspectCommand, 'sub']);67test('when execArgv --inspect=localhost:9260 then spawn execArgs --inspect=localhost:9261', async () => {68 const { stdout } = await execFileAsync('node', [69 '--inspect=localhost:9260',70 inspectCommand,71 'sub',72 ]);73 expect(stdout).toBe("[ '--inspect=localhost:9261' ]\n");74});7576// --inspect-port, just test most likely format53test('when execArgv --inspect-port=9270 then spawn execArgs --inspect-port=127.0.0.1:9271', async() => {54 const { stdout } = await execFileAsync('node', ['--inspect-port=9270', inspectCommand, 'sub']);77test('when execArgv --inspect-port=9270 then spawn execArgs --inspect-port=127.0.0.1:9271', async () => {78 const { stdout } = await execFileAsync('node', [79 '--inspect-port=9270',80 inspectCommand,81 'sub',82 ]);83 expect(stdout).toBe("[ '--inspect-port=127.0.0.1:9271' ]\n");84});
modified:tests/command.executableSubcommand.lookup.test.js+27 added-21 removed
8 unmodified lines
910// Suppress false positive warnings due to use of testOrSkipOnWindows11/* eslint-disable jest/no-standalone-expect */1213const testOrSkipOnWindows = (process.platform === 'win32') ? test.skip : test;13const testOrSkipOnWindows = process.platform === 'win32' ? test.skip : test;14const pm = path.join(__dirname, './fixtures/pm');1516test('when subcommand file missing then error', () => {17 expect.assertions(1);
22 unmodified lines
40 }41 });42});4344test('when subcommand file has no suffix then lookup succeeds', async() => {44test('when subcommand file has no suffix then lookup succeeds', async () => {45 const { stdout } = await execFileAsync('node', [pm, 'install']);46 expect(stdout).toBe('install\n');47});4849test('when alias subcommand file has no suffix then lookup succeeds', async() => {49test('when alias subcommand file has no suffix then lookup succeeds', async () => {50 const { stdout } = await execFileAsync('node', [pm, 'i']);51 expect(stdout).toBe('install\n');52});5354test('when subcommand target executablefile has no suffix then lookup succeeds', async() => {54test('when subcommand target executablefile has no suffix then lookup succeeds', async () => {55 const { stdout } = await execFileAsync('node', [pm, 'specifyInstall']);56 expect(stdout).toBe('install\n');57});5859test('when subcommand file suffix .js then lookup succeeds', async() => {59test('when subcommand file suffix .js then lookup succeeds', async () => {60 const { stdout } = await execFileAsync('node', [pm, 'publish']);61 expect(stdout).toBe('publish\n');62});6364test('when alias subcommand file suffix .js then lookup succeeds', async() => {64test('when alias subcommand file suffix .js then lookup succeeds', async () => {65 const { stdout } = await execFileAsync('node', [pm, 'p']);66 expect(stdout).toBe('publish\n');67});6869test('when subcommand target executablefile has suffix .js then lookup succeeds', async() => {69test('when subcommand target executablefile has suffix .js then lookup succeeds', async () => {70 const { stdout } = await execFileAsync('node', [pm, 'specifyPublish']);71 expect(stdout).toBe('publish\n');72});7374testOrSkipOnWindows(75 'when subcommand file is symlink then lookup succeeds',74testOrSkipOnWindows('when subcommand file is symlink then lookup succeeds', async() => {75 const pmlink = path.join(__dirname, 'fixtures', 'pmlink');76 const { stdout } = await execFileAsync('node', [pmlink, 'install']);77 expect(stdout).toBe('install\n');78});76 async () => {77 const pmlink = path.join(__dirname, 'fixtures', 'pmlink');78 const { stdout } = await execFileAsync('node', [pmlink, 'install']);79 expect(stdout).toBe('install\n');80 },81);8283testOrSkipOnWindows(84 'when subcommand file is double symlink then lookup succeeds',80testOrSkipOnWindows('when subcommand file is double symlink then lookup succeeds', async() => {81 const pmlink = path.join(__dirname, 'fixtures', 'another-dir', 'pm');82 const { stdout } = await execFileAsync('node', [pmlink, 'install']);83 expect(stdout).toBe('install\n');84});85 async () => {86 const pmlink = path.join(__dirname, 'fixtures', 'another-dir', 'pm');87 const { stdout } = await execFileAsync('node', [pmlink, 'install']);88 expect(stdout).toBe('install\n');89 },90);9186test('when subcommand suffix is .ts then lookup succeeds', async() => {92test('when subcommand suffix is .ts then lookup succeeds', async () => {93 // We support looking for ts files for ts-node in particular, but don't need to test ts-node itself.94 // The subcommand is both plain JavaScript code for this test.95 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');96 // childProcess.execFile('node', ['-r', 'ts-node/register', binLinkTs, 'install'], function(_error, stdout, stderr) {97 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-ts']);98 expect(stdout).toBe('found .ts\n');99});10095test('when subcommand suffix is .cjs then lookup succeeds', async() => {101test('when subcommand suffix is .cjs then lookup succeeds', async () => {102 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');103 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-cjs']);104 expect(stdout).toBe('found .cjs\n');105});106101test('when subcommand suffix is .mjs then lookup succeeds', async() => {107test('when subcommand suffix is .mjs then lookup succeeds', async () => {108 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');109 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-mjs']);110 expect(stdout).toBe('found .mjs\n');111});112107test('when subsubcommand then lookup sub-sub-command', async() => {113test('when subsubcommand then lookup sub-sub-command', async () => {114 const { stdout } = await execFileAsync('node', [pm, 'cache', 'clear']);115 expect(stdout).toBe('cache-clear\n');116});
modified:tests/command.executableSubcommand.mock.test.js+13 added-5 removed
14 unmodified lines
15test('when subcommand executable missing (ENOENT) then throw custom message', () => {16 // If the command is not found, we show a custom error with an explanation and offer17 // some advice for possible fixes.18 const mockProcess = new EventEmitter();19 const spawnSpy = jest.spyOn(childProcess, 'spawn').mockImplementation(() => { return mockProcess; });19 const spawnSpy = jest.spyOn(childProcess, 'spawn').mockImplementation(() => {20 return mockProcess;21 });22 const program = new commander.Command();23 program.exitOverride();24 program.command('executable', 'executable description');25 program.parse(['executable'], { from: 'user' });
5 unmodified lines
3132test('when subcommand executable not executable (EACCES) then throw custom message', () => {33 // Side note: this error does not actually happen on Windows! But we can still simulate the behaviour on other platforms.34 const mockProcess = new EventEmitter();33 const spawnSpy = jest.spyOn(childProcess, 'spawn').mockImplementation(() => { return mockProcess; });35 const spawnSpy = jest.spyOn(childProcess, 'spawn').mockImplementation(() => {36 return mockProcess;37 });38 const program = new commander.Command();39 program.exitOverride();40 program.command('executable', 'executable description');41 program.parse(['executable'], { from: 'user' });
6 unmodified lines
48test('when subcommand executable fails with other error and exitOverride then return in custom wrapper', () => {49 // The existing behaviour is to just silently fail for unexpected errors, as it is happening50 // asynchronously in spawned process and client can not catch errors.51 const mockProcess = new EventEmitter();48 const spawnSpy = jest.spyOn(childProcess, 'spawn').mockImplementation(() => { return mockProcess; });52 const spawnSpy = jest.spyOn(childProcess, 'spawn').mockImplementation(() => {53 return mockProcess;54 });55 const program = new commander.Command();56 program.exitOverride((err) => {57 throw err;58 });
13 unmodified lines
72test('when subcommand executable fails with other error then exit', () => {73 // The existing behaviour is to just silently fail for unexpected errors, as it is happening74 // asynchronously in spawned process and client can not catch errors.75 const mockProcess = new EventEmitter();70 const spawnSpy = jest.spyOn(childProcess, 'spawn').mockImplementation(() => { return mockProcess; });71 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => { });76 const spawnSpy = jest.spyOn(childProcess, 'spawn').mockImplementation(() => {77 return mockProcess;78 });79 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {});80 const program = new commander.Command();81 program.command('executable', 'executable description');82 program.parse(['executable'], { from: 'user' });83 mockProcess.emit('error', makeSystemError('OTHER'));
4 unmodified lines
modified:tests/command.executableSubcommand.search.test.js+93 added-47 removed
19 unmodified lines
20 // child_process.spawn(command[, args][, options])21 return mock.mock.calls[0][0];22}2324const describeOrSkipOnWindows = (process.platform === 'win32') ? describe.skip : describe;24const describeOrSkipOnWindows =25 process.platform === 'win32' ? describe.skip : describe;2627describe('search for subcommand', () => {28 let spawnSpy;29 let existsSpy;
1 unmodified line
31 beforeAll(() => {32 spawnSpy = jest.spyOn(childProcess, 'spawn').mockImplementation(() => {33 return {34 on: () => {},34 killed: true35 killed: true,36 };37 });38 });39
44 unmodified lines
84 });85 });8687 // We always use node on Windows, and don't spawn executable as the command (which may be a feature or a shortcoming!?).88 describeOrSkipOnWindows(89 'subcommand command name with no matching local file (non-Windows)',87 describeOrSkipOnWindows('subcommand command name with no matching local file (non-Windows)', () => {88 beforeEach(() => {89 existsSpy.mockImplementation(() => false);90 });90 () => {91 beforeEach(() => {92 existsSpy.mockImplementation(() => false);93 });9492 test('when named pm and no script arg or executableDir then spawn pm-sub as command', () => {93 const program = new commander.Command();94 program.name('pm');95 program.command('sub', 'executable description');96 program.parse(['sub'], { from: 'user' });95 test('when named pm and no script arg or executableDir then spawn pm-sub as command', () => {96 const program = new commander.Command();97 program.name('pm');98 program.command('sub', 'executable description');99 program.parse(['sub'], { from: 'user' });10098 expect(extractMockSpawnCommand(spawnSpy)).toEqual('pm-sub');99 });101 expect(extractMockSpawnCommand(spawnSpy)).toEqual('pm-sub');102 });103101 test('when named pm and script arg then still spawn pm-sub as command', () => {102 const program = new commander.Command();103 program.name('pm');104 program.command('sub', 'executable description');105 program.parse(['node', 'script-name', 'sub']);104 test('when named pm and script arg then still spawn pm-sub as command', () => {105 const program = new commander.Command();106 program.name('pm');107 program.command('sub', 'executable description');108 program.parse(['node', 'script-name', 'sub']);109107 expect(extractMockSpawnCommand(spawnSpy)).toEqual('pm-sub');108 });110 expect(extractMockSpawnCommand(spawnSpy)).toEqual('pm-sub');111 });112110 test('when no name and script arg then spawn script-sub as command', () => {111 const program = new commander.Command();112 program.command('sub', 'executable description');113 program.parse(['node', 'script.js', 'sub']);113 test('when no name and script arg then spawn script-sub as command', () => {114 const program = new commander.Command();115 program.command('sub', 'executable description');116 program.parse(['node', 'script.js', 'sub']);117115 expect(extractMockSpawnCommand(spawnSpy)).toEqual('script-sub');116 });118 expect(extractMockSpawnCommand(spawnSpy)).toEqual('script-sub');119 });120118 test('when named pm and script arg and executableFile then spawn executableFile as command', () => {119 const program = new commander.Command();120 program.command('sub', 'executable description', { executableFile: 'myExecutable' });121 program.parse(['node', 'script.js', 'sub']);121 test('when named pm and script arg and executableFile then spawn executableFile as command', () => {122 const program = new commander.Command();123 program.command('sub', 'executable description', {124 executableFile: 'myExecutable',125 });126 program.parse(['node', 'script.js', 'sub']);127123 expect(extractMockSpawnCommand(spawnSpy)).toEqual('myExecutable');124 });125 });128 expect(extractMockSpawnCommand(spawnSpy)).toEqual('myExecutable');129 });130 },131 );132133 describe('subcommand command name with matching local file', () => {134 test('when construct with name pm and script arg then spawn local pm-sub.js', () => {135 const program = new commander.Command('pm');136 program.command('sub', 'executable description');137138 const localPath = path.resolve(gLocalDirectory, 'pm-sub.js');139 existsSpy.mockImplementation((path) => path === localPath);134 program.parse(['node', path.resolve(gLocalDirectory, 'script.js'), 'sub']);140 program.parse([141 'node',142 path.resolve(gLocalDirectory, 'script.js'),143 'sub',144 ]);145146 expect(extractMockSpawnArgs(spawnSpy)).toEqual([localPath]);147 });148
3 unmodified lines
152 program.command('sub', 'executable description');153154 const localPath = path.resolve(gLocalDirectory, 'pm-sub.js');155 existsSpy.mockImplementation((path) => path === localPath);146 program.parse(['node', path.resolve(gLocalDirectory, 'script.js'), 'sub']);156 program.parse([157 'node',158 path.resolve(gLocalDirectory, 'script.js'),159 'sub',160 ]);161162 expect(extractMockSpawnArgs(spawnSpy)).toEqual([localPath]);163 });164
2 unmodified lines
167 program.command('sub', 'executable description');168169 const localPath = path.resolve(gLocalDirectory, 'script-sub.js');170 existsSpy.mockImplementation((path) => path === localPath);157 program.parse(['node', path.resolve(gLocalDirectory, 'script.js'), 'sub']);171 program.parse([172 'node',173 path.resolve(gLocalDirectory, 'script.js'),174 'sub',175 ]);176177 expect(extractMockSpawnArgs(spawnSpy)).toEqual([localPath]);178 });179
4 unmodified lines
184185 // Fallback for compatibility with Commander <= v8186 const localPath = path.resolve(gLocalDirectory, 'script-sub.js');187 existsSpy.mockImplementation((path) => path === localPath);170 program.parse(['node', path.resolve(gLocalDirectory, 'script.js'), 'sub']);188 program.parse([189 'node',190 path.resolve(gLocalDirectory, 'script.js'),191 'sub',192 ]);193194 expect(extractMockSpawnArgs(spawnSpy)).toEqual([localPath]);195 });196
31 unmodified lines
228 const execDir = path.resolve(gLocalDirectory, 'exec-dir');229 program.executableDir(execDir);230 const localPath = path.resolve(execDir, 'script-sub.js');231 existsSpy.mockImplementation((path) => path === localPath);210 program.parse(['node', path.resolve(gLocalDirectory, 'script-Dir', 'script'), 'sub']);232 program.parse([233 'node',234 path.resolve(gLocalDirectory, 'script-Dir', 'script'),235 'sub',236 ]);237238 expect(extractMockSpawnArgs(spawnSpy)).toEqual([localPath]);239 });240
2 unmodified lines
243 program.command('sub', 'executable description');244245 const linkPath = path.resolve(gLocalDirectory, 'link', 'link');246 const scriptPath = path.resolve(gLocalDirectory, 'script', 'script.js');221 const scriptSubPath = path.resolve(gLocalDirectory, 'script', 'link-sub.js');222 const realPathSyncSpy = jest.spyOn(fs, 'realpathSync').mockImplementation((path) => {223 return path === linkPath ? scriptPath : linkPath;224 });247 const scriptSubPath = path.resolve(248 gLocalDirectory,249 'script',250 'link-sub.js',251 );252 const realPathSyncSpy = jest253 .spyOn(fs, 'realpathSync')254 .mockImplementation((path) => {255 return path === linkPath ? scriptPath : linkPath;256 });257 existsSpy.mockImplementation((path) => path === scriptSubPath);258 program.parse(['node', linkPath, 'sub']);259 realPathSyncSpy.mockRestore();260
3 unmodified lines
264 test('when name pm and script arg and relative executableFile then spawn local exec.js', () => {265 const program = new commander.Command('pm');266 const localPath = path.join('relative', 'exec.js');267 const absolutePath = path.resolve(gLocalDirectory, localPath);236 program.command('sub', 'executable description', { executableFile: localPath });268 program.command('sub', 'executable description', {269 executableFile: localPath,270 });271272 existsSpy.mockImplementation((path) => path === absolutePath);239 program.parse(['node', path.resolve(gLocalDirectory, 'script.js'), 'sub']);273 program.parse([274 'node',275 path.resolve(gLocalDirectory, 'script.js'),276 'sub',277 ]);278279 expect(extractMockSpawnArgs(spawnSpy)).toEqual([absolutePath]);280 });281282 test('when name pm and script arg and absolute executableFile then spawn local exec.js', () => {283 const program = new commander.Command('pm');284 const localPath = path.resolve(gLocalDirectory, 'absolute', 'exec.js');247 program.command('sub', 'executable description', { executableFile: localPath });285 program.command('sub', 'executable description', {286 executableFile: localPath,287 });288289 existsSpy.mockImplementation((path) => path === localPath);250 program.parse(['node', path.resolve(gLocalDirectory, 'script.js'), 'sub']);290 program.parse([291 'node',292 path.resolve(gLocalDirectory, 'script.js'),293 'sub',294 ]);295296 expect(extractMockSpawnArgs(spawnSpy)).toEqual([localPath]);297 });298 });
6 unmodified lines
305 const scriptPath = path.resolve(gLocalDirectory, 'script');306 program.parse(['node', scriptPath, 'sub']);307 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];308 sourceExt.forEach((ext) => {265 expect(existsSpy).toHaveBeenCalledWith(path.resolve(gLocalDirectory, `script-sub${ext}`));309 expect(existsSpy).toHaveBeenCalledWith(310 path.resolve(gLocalDirectory, `script-sub${ext}`),311 );312 });313 });314 });315});
modified:tests/command.executableSubcommand.signals.test.js+32 added-20 removed
4 unmodified lines
56// Disabling some tests on Windows as:7// "Windows does not support sending signals"8// https://nodejs.org/api/process.html#process_signal_events9const describeOrSkipOnWindows = (process.platform === 'win32') ? describe.skip : describe;9const describeOrSkipOnWindows =10 process.platform === 'win32' ? describe.skip : describe;1112describeOrSkipOnWindows('signals', () => {13 test.each(['SIGINT', 'SIGHUP', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'])(14 'when program sent %s then executableSubcommand sent signal too',12 test.each(['SIGINT', 'SIGHUP', 'SIGTERM', 'SIGUSR1', 'SIGUSR2'])('when program sent %s then executableSubcommand sent signal too', (signal, done) => {13 // Spawn program. The listen subcommand waits for a signal and writes the name of the signal to stdout.14 const proc = childProcess.spawn(pmPath, ['listen'], {});15 (signal, done) => {16 // Spawn program. The listen subcommand waits for a signal and writes the name of the signal to stdout.17 const proc = childProcess.spawn(pmPath, ['listen'], {});1816 let processOutput = '';17 proc.stdout.on('data', (data) => {18 if (processOutput.length === 0) {19 // Send signal to program.20 proc.kill(`${signal}`);21 }22 processOutput += data.toString();23 });24 proc.on('close', (code) => {25 // Check the child subcommand received the signal too.26 expect(processOutput).toBe(`Listening for signal...${signal}`);27 done();28 });29 });19 let processOutput = '';20 proc.stdout.on('data', (data) => {21 if (processOutput.length === 0) {22 // Send signal to program.23 proc.kill(`${signal}`);24 }25 processOutput += data.toString();26 });27 proc.on('close', (code) => {28 // Check the child subcommand received the signal too.29 expect(processOutput).toBe(`Listening for signal...${signal}`);30 done();31 });32 },33 );3435 test('when executable subcommand sent signal then program exit code is non-zero', () => {36 const { status } = childProcess.spawnSync(pmPath, ['terminate'], {});37 expect(status).toBeGreaterThan(0);38 });3940 test('when command has exitOverride and executable subcommand sent signal then exit code is non-zero', () => {37 const { status } = childProcess.spawnSync(pmPath, ['exit-override', 'terminate'], {});41 const { status } = childProcess.spawnSync(42 pmPath,43 ['exit-override', 'terminate'],44 {},45 );46 expect(status).toBeGreaterThan(0);47 });4849 // Not a signal test, but closely related code so adding here.50 test('when command has exitOverride and executable subcommand fails then program exit code is subcommand exit code', () => {43 const { status } = childProcess.spawnSync(pmPath, ['exit-override', 'fail'], {});51 const { status } = childProcess.spawnSync(52 pmPath,53 ['exit-override', 'fail'],54 {},55 );56 expect(status).toEqual(42);57 });58});
modified:tests/command.executableSubcommand.test.js+6 added-2 removed
3 unmodified lines
45// This is the default behaviour when no default command and no action handlers6test('when no command specified and executable then display help', () => {7 // Optional. Suppress normal output to keep test output clean.8 const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });8 const writeSpy = jest9 .spyOn(process.stderr, 'write')10 .mockImplementation(() => {});11 const program = new commander.Command();12 program11 .exitOverride((err) => { throw err; })13 .exitOverride((err) => {14 throw err;15 })16 .command('install', 'install description');17 expect(() => {18 program.parse(['node', 'test']);19 }).toThrow('(outputHelp)');
2 unmodified lines
modified:tests/command.exitOverride.test.js+128 added-57 removed
18 unmodified lines
19 // Use internal knowledge to suppress output to keep test output clean.20 let stderrSpy;2122 beforeAll(() => {23 stderrSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });23 stderrSpy = jest24 .spyOn(process.stderr, 'write')25 .mockImplementation(() => {});26 });2728 afterEach(() => {29 stderrSpy.mockClear();
4 unmodified lines
34 });3536 test('when specify unknown program option then throw CommanderError', () => {37 const program = new commander.Command();36 program37 .exitOverride();38 program.exitOverride();3940 let caughtErr;41 try {42 program.parse(['node', 'test', '-m']);
1 unmodified line
44 caughtErr = err;45 }4647 expect(stderrSpy).toHaveBeenCalled();47 expectCommanderError(caughtErr, 1, 'commander.unknownOption', "error: unknown option '-m'");48 expectCommanderError(49 caughtErr,50 1,51 'commander.unknownOption',52 "error: unknown option '-m'",53 );54 });5556 test('when specify unknown command then throw CommanderError', () => {57 const program = new commander.Command();52 program53 .name('prog')54 .exitOverride()55 .command('sub');58 program.name('prog').exitOverride().command('sub');5960 let caughtErr;61 try {62 program.parse(['node', 'test', 'oops']);
1 unmodified line
64 caughtErr = err;65 }6667 expect(stderrSpy).toHaveBeenCalled();65 expectCommanderError(caughtErr, 1, 'commander.unknownCommand', "error: unknown command 'oops'");68 expectCommanderError(69 caughtErr,70 1,71 'commander.unknownCommand',72 "error: unknown command 'oops'",73 );74 });7576 // Same error as above, but with custom handler.77 test('when supply custom handler then throw custom error', () => {70 const customError = new commander.CommanderError(123, 'custom-code', 'custom-message');78 const customError = new commander.CommanderError(79 123,80 'custom-code',81 'custom-message',82 );83 const program = new commander.Command();72 program73 .exitOverride((_err) => {74 throw customError;75 });84 program.exitOverride((_err) => {85 throw customError;86 });8788 let caughtErr;89 try {90 program.parse(['node', 'test', '-m']);91 } catch (err) {92 caughtErr = err;93 }9484 expectCommanderError(caughtErr, customError.exitCode, customError.code, customError.message);95 expectCommanderError(96 caughtErr,97 customError.exitCode,98 customError.code,99 customError.message,100 );101 });102103 test('when specify option without required value then throw CommanderError', () => {104 const optionFlags = '-p, --pepper <type>';105 const program = new commander.Command();90 program91 .exitOverride()92 .option(optionFlags, 'add pepper');106 program.exitOverride().option(optionFlags, 'add pepper');107108 let caughtErr;109 try {110 program.parse(['node', 'test', '--pepper']);
1 unmodified line
112 caughtErr = err;113 }114115 expect(stderrSpy).toHaveBeenCalled();102 expectCommanderError(caughtErr, 1, 'commander.optionMissingArgument', `error: option '${optionFlags}' argument missing`);116 expectCommanderError(117 caughtErr,118 1,119 'commander.optionMissingArgument',120 `error: option '${optionFlags}' argument missing`,121 );122 });123124 test('when specify command without required argument then throw CommanderError', () => {125 const program = new commander.Command();126 program127 .exitOverride()128 .command('compress <arg-name>')110 .action(() => { });129 .action(() => {});130131 let caughtErr;132 try {133 program.parse(['node', 'test', 'compress']);
1 unmodified line
135 caughtErr = err;136 }137138 expect(stderrSpy).toHaveBeenCalled();120 expectCommanderError(caughtErr, 1, 'commander.missingArgument', "error: missing required argument 'arg-name'");139 expectCommanderError(140 caughtErr,141 1,142 'commander.missingArgument',143 "error: missing required argument 'arg-name'",144 );145 });146147 test('when specify program without required argument and no action handler then throw CommanderError', () => {148 const program = new commander.Command();125 program126 .exitOverride()127 .argument('<arg-name>');149 program.exitOverride().argument('<arg-name>');150151 let caughtErr;152 try {153 program.parse(['node', 'test']);
1 unmodified line
155 caughtErr = err;156 }157158 expect(stderrSpy).toHaveBeenCalled();137 expectCommanderError(caughtErr, 1, 'commander.missingArgument', "error: missing required argument 'arg-name'");159 expectCommanderError(160 caughtErr,161 1,162 'commander.missingArgument',163 "error: missing required argument 'arg-name'",164 );165 });166167 test('when specify excess argument then throw CommanderError', () => {168 const program = new commander.Command();169 program170 .exitOverride()171 .allowExcessArguments(false)145 .action(() => { });172 .action(() => {});173174 let caughtErr;175 try {176 program.parse(['node', 'test', 'excess']);
1 unmodified line
178 caughtErr = err;179 }180181 expect(stderrSpy).toHaveBeenCalled();155 expectCommanderError(caughtErr, 1, 'commander.excessArguments', 'error: too many arguments. Expected 0 arguments but got 1.');182 expectCommanderError(183 caughtErr,184 1,185 'commander.excessArguments',186 'error: too many arguments. Expected 0 arguments but got 1.',187 );188 });189190 test('when specify command with excess argument then throw CommanderError', () => {191 const program = new commander.Command();192 program193 .exitOverride()194 .command('speak')195 .allowExcessArguments(false)164 .action(() => { });196 .action(() => {});197198 let caughtErr;199 try {200 program.parse(['node', 'test', 'speak', 'excess']);
1 unmodified line
202 caughtErr = err;203 }204205 expect(stderrSpy).toHaveBeenCalled();174 expectCommanderError(caughtErr, 1, 'commander.excessArguments', "error: too many arguments for 'speak'. Expected 0 arguments but got 1.");206 expectCommanderError(207 caughtErr,208 1,209 'commander.excessArguments',210 "error: too many arguments for 'speak'. Expected 0 arguments but got 1.",211 );212 });213214 test('when specify --help then throw CommanderError', () => {178 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });215 const writeSpy = jest216 .spyOn(process.stdout, 'write')217 .mockImplementation(() => {});218 const program = new commander.Command();180 program181 .exitOverride();219 program.exitOverride();220221 let caughtErr;222 try {223 program.parse(['node', 'test', '--help']);224 } catch (err) {225 caughtErr = err;226 }227190 expectCommanderError(caughtErr, 0, 'commander.helpDisplayed', '(outputHelp)');228 expectCommanderError(229 caughtErr,230 0,231 'commander.helpDisplayed',232 '(outputHelp)',233 );234 writeSpy.mockRestore();235 });236237 test('when executable subcommand and no command specified then throw CommanderError', () => {238 const program = new commander.Command();196 program197 .exitOverride()198 .command('compress', 'compress description');239 program.exitOverride().command('compress', 'compress description');240241 let caughtErr;242 try {243 program.parse(['node', 'test']);
4 unmodified lines
248 expectCommanderError(caughtErr, 1, 'commander.help', '(outputHelp)');249 });250251 test('when specify --version then throw CommanderError', () => {211 const stdoutSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });252 const stdoutSpy = jest253 .spyOn(process.stdout, 'write')254 .mockImplementation(() => {});255 const myVersion = '1.2.3';256 const program = new commander.Command();214 program215 .exitOverride()216 .version(myVersion);257 program.exitOverride().version(myVersion);258259 let caughtErr;260 try {261 program.parse(['node', 'test', '--version']);
4 unmodified lines
266 expectCommanderError(caughtErr, 0, 'commander.version', myVersion);267 stdoutSpy.mockRestore();268 });269229 test('when executableSubcommand succeeds then call exitOverride', async() => {270 test('when executableSubcommand succeeds then call exitOverride', async () => {271 expect.hasAssertions();272 const pm = path.join(__dirname, 'fixtures/pm');273 const program = new commander.Command();274 await new Promise((resolve) => {275 program276 .exitOverride((err) => {236 expectCommanderError(err, 0, 'commander.executeSubCommandAsync', '(close)');277 expectCommanderError(278 err,279 0,280 'commander.executeSubCommandAsync',281 '(close)',282 );283 resolve();284 })285 .command('silent', 'description');286 program.parse(['node', pm, 'silent']);
2 unmodified lines
289290 test('when mandatory program option missing then throw CommanderError', () => {291 const optionFlags = '-p, --pepper <type>';292 const program = new commander.Command();247 program248 .exitOverride()249 .requiredOption(optionFlags, 'add pepper');293 program.exitOverride().requiredOption(optionFlags, 'add pepper');294295 let caughtErr;296 try {297 program.parse(['node', 'test']);298 } catch (err) {299 caughtErr = err;300 }301258 expectCommanderError(caughtErr, 1, 'commander.missingMandatoryOptionValue', `error: required option '${optionFlags}' not specified`);302 expectCommanderError(303 caughtErr,304 1,305 'commander.missingMandatoryOptionValue',306 `error: required option '${optionFlags}' not specified`,307 );308 });309310 test('when option argument not in choices then throw CommanderError', () => {311 const optionFlags = '--colour <shade>';
8 unmodified lines
320 } catch (err) {321 caughtErr = err;322 }323275 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: option '--colour <shade>' argument 'green' is invalid. Allowed choices are red, blue.");324 expectCommanderError(325 caughtErr,326 1,327 'commander.invalidArgument',328 "error: option '--colour <shade>' argument 'green' is invalid. Allowed choices are red, blue.",329 );330 });331332 test('when command argument not in choices then throw CommanderError', () => {333 const program = new commander.Command();
8 unmodified lines
342 } catch (err) {343 caughtErr = err;344 }345292 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: command-argument value 'green' is invalid for argument 'shade'. Allowed choices are red, blue.");346 expectCommanderError(347 caughtErr,348 1,349 'commander.invalidArgument',350 "error: command-argument value 'green' is invalid for argument 'shade'. Allowed choices are red, blue.",351 );352 });353354 test('when custom processing for option throws InvalidArgumentError then catch CommanderError', () => {355 function justSayNo(value) {356 throw new commander.InvalidArgumentError('NO');357 }358 const optionFlags = '--colour <shade>';359 const program = new commander.Command();301 program302 .exitOverride()303 .option(optionFlags, 'specify shade', justSayNo);360 program.exitOverride().option(optionFlags, 'specify shade', justSayNo);361362 let caughtErr;363 try {364 program.parse(['--colour', 'green'], { from: 'user' });365 } catch (err) {366 caughtErr = err;367 }368312 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: option '--colour <shade>' argument 'green' is invalid. NO");369 expectCommanderError(370 caughtErr,371 1,372 'commander.invalidArgument',373 "error: option '--colour <shade>' argument 'green' is invalid. NO",374 );375 });376377 test('when custom processing for argument throws InvalidArgumentError then catch CommanderError', () => {378 function justSayNo(value) {
11 unmodified lines
390 } catch (err) {391 caughtErr = err;392 }393332 expectCommanderError(caughtErr, 1, 'commander.invalidArgument', "error: command-argument value 'green' is invalid for argument 'n'. NO");394 expectCommanderError(395 caughtErr,396 1,397 'commander.invalidArgument',398 "error: command-argument value 'green' is invalid for argument 'n'. NO",399 );400 });401402 test('when has conflicting option then throw CommanderError', () => {403 const program = new commander.Command();
8 unmodified lines
412 } catch (err) {413 caughtErr = err;414 }415349 expectCommanderError(caughtErr, 1, 'commander.conflictingOption', "error: option '--debug' cannot be used with option '--silent'");416 expectCommanderError(417 caughtErr,418 1,419 'commander.conflictingOption',420 "error: option '--debug' cannot be used with option '--silent'",421 );422 });423424 test('when call error() then throw CommanderError', () => {425 const program = new commander.Command();354 program355 .exitOverride();426 program.exitOverride();427428 let caughtErr;429 try {430 program.error('message');
5 unmodified lines
436 });437});438439test('when no override and error then exit(1)', () => {369 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => { });440 const exitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {});441 const program = new commander.Command();442 program.configureOutput({ outputError: () => {} });443 program.parse(['--unknownOption'], { from: 'user' });444 expect(exitSpy).toHaveBeenCalledWith(1);
16 unmodified lines
modified:tests/command.help.test.js+74 added-65 removed
6 unmodified lines
78// Avoid doing many full format tests as will be broken by any layout changes!9test('when call helpInformation for program then help format is as expected (usage, options, commands)', () => {10 const program = new commander.Command();11 program12 .command('my-command <file>');13 const expectedHelpInformation =11 program.command('my-command <file>');12 const expectedHelpInformation = `Usage: test [options] [command]14`Usage: test [options] [command]1314Options:15 -h, --help display help for command16
8 unmodified lines
25});2627test('when use .description for command then help includes description', () => {28 const program = new commander.Command();31 program32 .command('simple-command')33 .description('custom-description');29 program.command('simple-command').description('custom-description');30 program._help = 'test';31 const helpInformation = program.helpInformation();32 expect(helpInformation).toMatch(/simple-command +custom-description/);33});3435test('when call .help then exit', () => {36 // Optional. Suppress normal output to keep test output clean.41 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });37 const writeSpy = jest38 .spyOn(process.stdout, 'write')39 .mockImplementation(() => {});40 const program = new commander.Command();43 program44 .exitOverride();41 program.exitOverride();42 expect(() => {43 program.help();44 }).toThrow('(outputHelp)');45 writeSpy.mockClear();46});4748test('when specify --help then exit', () => {49 // Optional. Suppress normal output to keep test output clean.53 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });50 const writeSpy = jest51 .spyOn(process.stdout, 'write')52 .mockImplementation(() => {});53 const program = new commander.Command();55 program56 .exitOverride();54 program.exitOverride();55 expect(() => {56 program.parse(['node', 'test', '--help']);57 }).toThrow('(outputHelp)');58 writeSpy.mockClear();59});6061test('when call help(cb) then display cb output and exit', () => {62 // Using spy to detect custom output65 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });63 const writeSpy = jest64 .spyOn(process.stdout, 'write')65 .mockImplementation(() => {});66 const helpReplacement = 'reformatted help';67 const program = new commander.Command();68 program69 .exitOverride();68 program.exitOverride();69 expect(() => {70 program.help((helpInformation) => {71 return helpReplacement;72 });
3 unmodified lines
76});7778test('when call outputHelp(cb) then display cb output', () => {79 // Using spy to detect custom output81 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });80 const writeSpy = jest81 .spyOn(process.stdout, 'write')82 .mockImplementation(() => {});83 const helpReplacement = 'reformatted help';84 const program = new commander.Command();85 program.outputHelp((helpInformation) => {86 return helpReplacement;
10 unmodified lines
97});9899test('when command sets deprecated noHelp then not displayed in helpInformation', () => {100 const program = new commander.Command();100 program101 .command('secret', 'secret description', { noHelp: true });101 program.command('secret', 'secret description', { noHelp: true });102 const helpInformation = program.helpInformation();103 expect(helpInformation).not.toMatch('secret');104});105106test('when command sets hidden then not displayed in helpInformation', () => {107 const program = new commander.Command();108 program109 .command('secret', 'secret description', { hidden: true });108 program.command('secret', 'secret description', { hidden: true });109 const helpInformation = program.helpInformation();110 expect(helpInformation).not.toMatch('secret');111});112113test('when addCommand with hidden:true then not displayed in helpInformation', () => {114 const secretCmd = new commander.Command('secret');115116 const program = new commander.Command();118 program119 .addCommand(secretCmd, { hidden: true });117 program.addCommand(secretCmd, { hidden: true });118 const helpInformation = program.helpInformation();119 expect(helpInformation).not.toMatch('secret');120});121122test('when help short flag masked then not displayed in helpInformation', () => {123 const program = new commander.Command();126 program127 .option('-h, --host', 'select host');124 program.option('-h, --host', 'select host');125 const helpInformation = program.helpInformation();126 expect(helpInformation).not.toMatch(/\W-h\W.*display help/);127});128129test('when both help flags masked then not displayed in helpInformation', () => {130 const program = new commander.Command();134 program135 .option('-h, --help', 'custom');131 program.option('-h, --help', 'custom');132 const helpInformation = program.helpInformation();133 expect(helpInformation).not.toMatch('display help');134});135136test('when call .help then output on stdout', () => {141 const writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });137 const writeSpy = jest138 .spyOn(process.stdout, 'write')139 .mockImplementation(() => {});140 const program = new commander.Command();143 program144 .exitOverride();141 program.exitOverride();142 expect(() => {143 program.help();144 }).toThrow('(outputHelp)');145 expect(writeSpy).toHaveBeenCalledWith(program.helpInformation());146 writeSpy.mockClear();147});148149test('when call .help with { error: true } then output on stderr', () => {153 const writeSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });150 const writeSpy = jest151 .spyOn(process.stderr, 'write')152 .mockImplementation(() => {});153 const program = new commander.Command();155 program156 .exitOverride();154 program.exitOverride();155 expect(() => {156 program.help({ error: true });157 }).toThrow('(outputHelp)');158 expect(writeSpy).toHaveBeenCalledWith(program.helpInformation());
2 unmodified lines
161162test('when no options then Options not included in helpInformation', () => {163 const program = new commander.Command();164 // No custom options, no version option, no help option167 program168 .helpOption(false);165 program.helpOption(false);166 const helpInformation = program.helpInformation();167 expect(helpInformation).not.toMatch('Options');168});169170test('when negated option then option included in helpInformation', () => {171 const program = new commander.Command();175 program176 .option('-C, --no-colour', 'colourless');172 program.option('-C, --no-colour', 'colourless');173 const helpInformation = program.helpInformation();174 expect(helpInformation).toMatch('--no-colour');175 expect(helpInformation).toMatch('colourless');176});177178test('when option.hideHelp() then option not included in helpInformation', () => {179 const program = new commander.Command();184 program185 .addOption(new commander.Option('-s,--secret', 'secret option').hideHelp());180 program.addOption(181 new commander.Option('-s,--secret', 'secret option').hideHelp(),182 );183 const helpInformation = program.helpInformation();184 expect(helpInformation).not.toMatch('secret');185});186187test('when option.hideHelp(true) then option not included in helpInformation', () => {188 const program = new commander.Command();192 program193 .addOption(new commander.Option('-s,--secret', 'secret option').hideHelp(true));189 program.addOption(190 new commander.Option('-s,--secret', 'secret option').hideHelp(true),191 );192 const helpInformation = program.helpInformation();193 expect(helpInformation).not.toMatch('secret');194});195196test('when option.hideHelp(false) then option included in helpInformation', () => {197 const program = new commander.Command();200 program201 .addOption(new commander.Option('-s,--secret', 'secret option').hideHelp(false));198 program.addOption(199 new commander.Option('-s,--secret', 'secret option').hideHelp(false),200 );201 const helpInformation = program.helpInformation();202 expect(helpInformation).toMatch('secret');203});204205test('when option has default value then default included in helpInformation', () => {206 const program = new commander.Command();208 program209 .option('-p, --port <portNumber>', 'port number', 80);207 program.option('-p, --port <portNumber>', 'port number', 80);208 const helpInformation = program.helpInformation();209 expect(helpInformation).toMatch('(default: 80)');210});211212test('when option has default value description then default description included in helpInformation', () => {213 const program = new commander.Command();216 program217 .addOption(new commander.Option('-a, --address <dotted>', 'ip address').default('127.0.0.1', 'home'));214 program.addOption(215 new commander.Option('-a, --address <dotted>', 'ip address').default(216 '127.0.0.1',217 'home',218 ),219 );220 const helpInformation = program.helpInformation();221 expect(helpInformation).toMatch('(default: home)');222});223224test('when option has choices then choices included in helpInformation', () => {225 const program = new commander.Command();224 program225 .addOption(new commander.Option('-c, --colour <colour>').choices(['red', 'blue']));226 program.addOption(227 new commander.Option('-c, --colour <colour>').choices(['red', 'blue']),228 );229 const helpInformation = program.helpInformation();230 expect(helpInformation).toMatch('(choices: "red", "blue")');231});232233test('when option has choices and default then both included in helpInformation', () => {234 const program = new commander.Command();232 program233 .addOption(new commander.Option('-c, --colour <colour>').choices(['red', 'blue']).default('red'));235 program.addOption(236 new commander.Option('-c, --colour <colour>')237 .choices(['red', 'blue'])238 .default('red'),239 );240 const helpInformation = program.helpInformation();241 expect(helpInformation).toMatch('(choices: "red", "blue", default: "red")');242});243244test('when argument then included in helpInformation', () => {245 const program = new commander.Command();240 program241 .name('foo')242 .argument('<file>');246 program.name('foo').argument('<file>');247 const helpInformation = program.helpInformation();248 expect(helpInformation).toMatch('Usage: foo [options] <file>');249});250251test('when argument described then included in helpInformation', () => {252 const program = new commander.Command();249 program250 .argument('<file>', 'input source')251 .helpOption(false);253 program.argument('<file>', 'input source').helpOption(false);254 const helpInformation = program.helpInformation();255 expect(helpInformation).toMatch(/Arguments:\n +file +input source/);256});257258test('when argument described with default then included in helpInformation', () => {259 const program = new commander.Command();258 program259 .argument('[file]', 'input source', 'test.txt')260 .helpOption(false);260 program.argument('[file]', 'input source', 'test.txt').helpOption(false);261 const helpInformation = program.helpInformation();262 expect(helpInformation).toMatch(/Arguments:\n +file +input source \(default: "test.txt"\)/);262 expect(helpInformation).toMatch(263 /Arguments:\n +file +input source \(default: "test.txt"\)/,264 );265});266267test('when arguments described in deprecated way then included in helpInformation', () => {268 const program = new commander.Command();
16 unmodified lines
285});286287test('when argument has choices then choices included in helpInformation', () => {288 const program = new commander.Command();287 program288 .addArgument(new commander.Argument('<colour>', 'preferred colour').choices(['red', 'blue']));289 program.addArgument(290 new commander.Argument('<colour>', 'preferred colour').choices([291 'red',292 'blue',293 ]),294 );295 const helpInformation = program.helpInformation();296 expect(helpInformation).toMatch('(choices: "red", "blue")');297});298299test('when argument has choices and default then both included in helpInformation', () => {300 const program = new commander.Command();295 program296 .addArgument(new commander.Argument('<colour>', 'preferred colour').choices(['red', 'blue']).default('red'));301 program.addArgument(302 new commander.Argument('<colour>', 'preferred colour')303 .choices(['red', 'blue'])304 .default('red'),305 );306 const helpInformation = program.helpInformation();307 expect(helpInformation).toMatch('(choices: "red", "blue", default: "red")');308});
modified:tests/command.helpCommand.test.js+29 added-12 removed
57 unmodified lines
58 let writeErrorSpy;59 let writeSpy;6061 beforeAll(() => {62 writeErrorSpy = jest63 .spyOn(process.stderr, 'write')62 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });63 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });64 .mockImplementation(() => {});65 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => {});66 });6768 afterEach(() => {69 writeErrorSpy.mockClear();
8 unmodified lines
78 test('when "program help" then program', () => {79 const program = new commander.Command();80 program.exitOverride();81 program.command('sub1');80 program.exitOverride(() => { throw new Error('program'); });82 program.exitOverride(() => {83 throw new Error('program');84 });85 expect(() => {86 program.parse('node test.js help'.split(' '));87 }).toThrow('program');88 });
1 unmodified line
90 test('when "program help unknown" then program', () => {91 const program = new commander.Command();92 program.exitOverride();93 program.command('sub1');90 program.exitOverride(() => { throw new Error('program'); });94 program.exitOverride(() => {95 throw new Error('program');96 });97 expect(() => {98 program.parse('node test.js help unknown'.split(' '));99 }).toThrow('program');100 });
1 unmodified line
102 test('when "program help sub1" then sub1', () => {103 const program = new commander.Command();104 program.exitOverride();105 const sub1 = program.command('sub1');100 sub1.exitOverride(() => { throw new Error('sub1'); });106 sub1.exitOverride(() => {107 throw new Error('sub1');108 });109 expect(() => {110 program.parse('node test.js help sub1'.split(' '));111 }).toThrow('sub1');112 });
2 unmodified lines
115 const program = new commander.Command();116 program.exitOverride();117 const sub1 = program.command('sub1');118 const sub2 = sub1.command('sub2');111 sub2.exitOverride(() => { throw new Error('sub2'); });119 sub2.exitOverride(() => {120 throw new Error('sub2');121 });122 expect(() => {123 program.parse('node test.js sub1 help sub2'.split(' '));124 }).toThrow('sub2');125 });
1 unmodified line
127 test('when default command and "program help" then program', () => {128 const program = new commander.Command();129 program.exitOverride();130 program.command('sub1', { isDefault: true });121 program.exitOverride(() => { throw new Error('program'); });131 program.exitOverride(() => {132 throw new Error('program');133 });134 expect(() => {135 program.parse('node test.js help'.split(' '));136 }).toThrow('program');137 });
3 unmodified lines
141 program.exitOverride();142 program.helpOption('-H');143 const sub = program.command('sub');144 // Patch help for easy way to check called.133 sub.help = () => { throw new Error('sub help'); };145 sub.help = () => {146 throw new Error('sub help');147 };148 expect(() => {149 program.parse(['help', 'sub'], { from: 'user' });150 }).toThrow('sub help');151 });152153 test('when no help options in sub then "help sub" works', () => {154 const program = new commander.Command();155 program.exitOverride();142 const sub = program.command('sub')143 .helpOption(false);156 const sub = program.command('sub').helpOption(false);157 // Patch help for easy way to check called.145 sub.help = () => { throw new Error('sub help'); };158 sub.help = () => {159 throw new Error('sub help');160 };161 expect(() => {162 program.parse(['help', 'sub'], { from: 'user' });163 }).toThrow('sub help');164 });
4 unmodified lines
169 const sub = program.command('sub');170 program.helpOption('-h, --help');171 sub.helpOption('-a, --assist');172 // Patch help for easy way to check called.158 sub.help = () => { throw new Error('sub help'); };173 sub.help = () => {174 throw new Error('sub help');175 };176 expect(() => {177 program.parse(['help', 'sub'], { from: 'user' });178 }).toThrow('sub help');179 });
1 unmodified line
modified:tests/command.helpOption.test.js+18 added-33 removed
4 unmodified lines
5 let writeErrorSpy;67 beforeAll(() => {8 // Optional. Suppress expected output to keep test output clean.9 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });10 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });9 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => {});10 writeErrorSpy = jest11 .spyOn(process.stderr, 'write')12 .mockImplementation(() => {});13 });1415 afterEach(() => {16 writeSpy.mockClear();
6 unmodified lines
23 });2425 test('when helpOption has custom flags then custom short flag invokes help', () => {26 const program = new commander.Command();25 program26 .exitOverride()27 .helpOption('-c,--custom-help', 'custom help output');27 program.exitOverride().helpOption('-c,--custom-help', 'custom help output');28 expect(() => {29 program.parse(['-c'], { from: 'user' });30 }).toThrow('(outputHelp)');31 });3233 test('when helpOption has custom flags then custom long flag invokes help', () => {34 const program = new commander.Command();35 program36 .exitOverride()37 .helpOption('-c,--custom-help', 'custom help output');35 program.exitOverride().helpOption('-c,--custom-help', 'custom help output');36 expect(() => {37 program.parse(['--custom-help'], { from: 'user' });38 }).toThrow('(outputHelp)');39 });4041 test('when helpOption has just custom short flag then custom short flag invokes help', () => {42 const program = new commander.Command();45 program46 .exitOverride()47 .helpOption('-c', 'custom help output');43 program.exitOverride().helpOption('-c', 'custom help output');44 expect(() => {45 program.parse(['-c'], { from: 'user' });46 }).toThrow('(outputHelp)');47 });4849 test('when helpOption has just custom long flag then custom long flag invokes help', () => {50 const program = new commander.Command();55 program56 .exitOverride()57 .helpOption('--custom-help', 'custom help output');51 program.exitOverride().helpOption('--custom-help', 'custom help output');52 expect(() => {53 program.parse(['--custom-help'], { from: 'user' });54 }).toThrow('(outputHelp)');55 });5657 test('when helpOption has custom description then helpInformation include custom description', () => {58 const program = new commander.Command();65 program66 .helpOption('-C,--custom-help', 'custom help output');59 program.helpOption('-C,--custom-help', 'custom help output');60 const helpInformation = program.helpInformation();61 expect(helpInformation).toMatch(/-C,--custom-help +custom help output/);62 });6364 test('when helpOption has just flags then helpInformation includes default description', () => {65 const program = new commander.Command();73 program74 .helpOption('-C,--custom-help');66 program.helpOption('-C,--custom-help');67 const helpInformation = program.helpInformation();76 expect(helpInformation).toMatch(/-C,--custom-help +display help for command/);68 expect(helpInformation).toMatch(69 /-C,--custom-help +display help for command/,70 );71 });7273 test('when helpOption has just description then helpInformation includes default flags', () => {74 const program = new commander.Command();81 program82 .helpOption(undefined, 'custom help output');75 program.helpOption(undefined, 'custom help output');76 const helpInformation = program.helpInformation();77 expect(helpInformation).toMatch(/-h, --help +custom help output/);78 });7980 test('when helpOption(false) then helpInformation does not include --help', () => {81 const program = new commander.Command();89 program90 .helpOption(false);82 program.helpOption(false);83 const helpInformation = program.helpInformation();84 expect(helpInformation).not.toMatch('--help');85 });8687 test('when helpOption(false) then --help is an unknown option', () => {88 const program = new commander.Command();97 program98 .exitOverride()99 .helpOption(false);89 program.exitOverride().helpOption(false);90 let caughtErr;91 try {92 program.parse(['--help'], { from: 'user' });93 } catch (err) {
3 unmodified lines
97 });9899 test('when helpOption(false) then -h is an unknown option', () => {100 const program = new commander.Command();111 program112 .exitOverride()113 .helpOption(false);101 program.exitOverride().helpOption(false);102 let caughtErr;103 try {104 program.parse(['-h'], { from: 'user' });105 } catch (err) {
3 unmodified lines
109 });110111 test('when helpOption(false) then unknown command error does not suggest --help', () => {112 const program = new commander.Command();125 program126 .exitOverride()127 .helpOption(false)128 .command('foo');113 program.exitOverride().helpOption(false).command('foo');114 expect(() => {115 program.parse(['UNKNOWN'], { from: 'user' });116 }).toThrow("error: unknown command 'UNKNOWN'");117 });
1 unmodified line
modified:tests/command.hook.test.js+107 added-77 removed
8 unmodified lines
910test('when no action then action hooks not called', () => {11 const hook = jest.fn();12 const program = new commander.Command();13 program14 .hook('preAction', hook)15 .hook('postAction', hook);13 program.hook('preAction', hook).hook('postAction', hook);14 program.parse([], { from: 'user' });15 expect(hook).not.toHaveBeenCalled();16});17
42 unmodified lines
6061 test('when hook preAction at program and sub then hooks called program then sub', () => {62 const calls = [];63 const program = new commander.Command();64 program.hook('preAction', () => calls.push('program'));65 program67 .hook('preAction', () => calls.push('program'));68 program.command('sub')66 .command('sub')67 .hook('preAction', () => calls.push('sub'))68 .action(() => calls.push('action'));69 program.parse(['sub'], { from: 'user' });70 expect(calls).toEqual(['program', 'sub', 'action']);
1 unmodified line
7273 test('when hook postAction at program and sub then hooks called sub then program', () => {74 const calls = [];75 const program = new commander.Command();76 program.hook('postAction', () => calls.push('program'));77 program79 .hook('postAction', () => calls.push('program'));80 program.command('sub')78 .command('sub')79 .hook('postAction', () => calls.push('sub'))80 .action(() => calls.push('action'));81 program.parse(['sub'], { from: 'user' });82 expect(calls).toEqual(['action', 'sub', 'program']);
7 unmodified lines
90 .hook('postAction', () => calls.push('pa1'));91 program92 .hook('preAction', () => calls.push('pb2'))93 .hook('postAction', () => calls.push('pa2'));96 program.command('sub')94 program95 .command('sub')96 .hook('preAction', () => calls.push('sb'))97 .hook('postAction', () => calls.push('sa'))98 .action(() => calls.push('action'));99 program.parse(['sub'], { from: 'user' });
4 unmodified lines
104describe('action hooks context', () => {105 test('when hook on program then passed program/program', () => {106 const hook = jest.fn();107 const program = new commander.Command();109 program110 .hook('preAction', hook)111 .action(() => {});108 program.hook('preAction', hook).action(() => {});109 program.parse([], { from: 'user' });110 expect(hook).toHaveBeenCalledWith(program, program);111 });112113 test('when hook on program and call sub then passed program/sub', () => {114 const hook = jest.fn();115 const program = new commander.Command();119 program120 .hook('preAction', hook);121 const sub = program.command('sub')116 program.hook('preAction', hook);117 const sub = program.command('sub').action(() => {});122 .action(() => {});118 program.parse(['sub'], { from: 'user' });119 expect(hook).toHaveBeenCalledWith(program, sub);120 });121122 test('when hook on sub and call sub then passed sub/sub', () => {123 const hook = jest.fn();124 const program = new commander.Command();130 const sub = program.command('sub')125 const sub = program126 .command('sub')127 .hook('preAction', hook)128 .action(() => {});129 program.parse(['sub'], { from: 'user' });130 expect(hook).toHaveBeenCalledWith(sub, sub);
13 unmodified lines
144145 test('when hook program on preAction and call sub then thisCommand has program options set', () => {146 expect.assertions(1);147 const program = new commander.Command();152 program153 .option('--debug')154 .hook('preAction', (thisCommand) => {155 expect(thisCommand.opts().debug).toEqual(true);156 });157 program.command('sub')148 program.option('--debug').hook('preAction', (thisCommand) => {149 expect(thisCommand.opts().debug).toEqual(true);150 });151 program.command('sub').action(() => {});158 .action(() => {});152 program.parse(['sub', '--debug'], { from: 'user' });153 });154155 test('when hook program on preAction and call sub then actionCommand has sub options set', () => {156 expect.assertions(1);157 const program = new commander.Command();158 program.hook('preAction', (thisCommand, actionCommand) => {159 expect(actionCommand.opts().debug).toEqual(true);160 });161 program166 .hook('preAction', (thisCommand, actionCommand) => {167 expect(actionCommand.opts().debug).toEqual(true);168 });169 program.command('sub')162 .command('sub')163 .option('--debug')164 .action(() => {});165 program.parse(['sub', '--debug'], { from: 'user' });166 });
25 unmodified lines
192193 test('when hook program on preAction and call sub then thisCommand has program args set', () => {194 expect.assertions(1);195 const program = new commander.Command();203 program204 .argument('[arg]')205 .hook('preAction', (thisCommand) => {206 expect(thisCommand.args).toEqual(['sub', 'value']);207 });208 program.command('sub')196 program.argument('[arg]').hook('preAction', (thisCommand) => {197 expect(thisCommand.args).toEqual(['sub', 'value']);198 });199 program.command('sub').action(() => {});209 .action(() => {});200 program.parse(['sub', 'value'], { from: 'user' });201 });202203 test('when hook program on preAction and call sub then actionCommand has sub args set', () => {204 expect.assertions(1);205 const program = new commander.Command();216 program217 .hook('preAction', (thisCommand, actionCommand) => {218 expect(actionCommand.args).toEqual(['value']);219 });220 program.command('sub')206 program.hook('preAction', (thisCommand, actionCommand) => {207 expect(actionCommand.args).toEqual(['value']);208 });209 program.command('sub').action(() => {});221 .action(() => {});210 program.parse(['sub', 'value'], { from: 'user' });211 });212});213214describe('action hooks async', () => {227 test('when async preAction then async from preAction', async() => {215 test('when async preAction then async from preAction', async () => {216 const calls = [];217 const program = new commander.Command();218 program231 .hook('preAction', async() => {219 .hook('preAction', async () => {220 await 0;221 calls.push('before');222 })223 .action(() => calls.push('action'));
2 unmodified lines
226 await result;227 expect(calls).toEqual(['before', 'action']);228 });229242 test('when async postAction then async from postAction', async() => {230 test('when async postAction then async from postAction', async () => {231 const calls = [];232 const program = new commander.Command();233 program246 .hook('postAction', async() => {234 .hook('postAction', async () => {235 await 0;236 calls.push('after');237 })238 .action(() => calls.push('action'));
2 unmodified lines
241 await result;242 expect(calls).toEqual(['action', 'after']);243 });244257 test('when async action then async from action', async() => {245 test('when async action then async from action', async () => {246 const calls = [];247 const program = new commander.Command();248 program249 .hook('preAction', () => calls.push('before'))250 .hook('postAction', () => calls.push('after'))263 .action(async() => {251 .action(async () => {252 await 0;253 calls.push('action');254 });255 const result = program.parseAsync([], { from: 'user' });
1 unmodified line
257 await result;258 expect(calls).toEqual(['before', 'action', 'after']);259 });260273 test('when async first preAction then async from first preAction', async() => {261 test('when async first preAction then async from first preAction', async () => {262 const calls = [];263 const program = new commander.Command();264 program277 .hook('preAction', async() => {265 .hook('preAction', async () => {266 await 0;267 calls.push('1');268 })269 .hook('preAction', () => calls.push('2'))
3 unmodified lines
273 await result;274 expect(calls).toEqual(['1', '2', 'action']);275 });276289 test('when async second preAction then async from second preAction', async() => {277 test('when async second preAction then async from second preAction', async () => {278 const calls = [];279 const program = new commander.Command();280 program281 .hook('preAction', () => calls.push('1'))294 .hook('preAction', async() => {282 .hook('preAction', async () => {283 await 0;284 calls.push('2');285 })286 .action(() => calls.push('action'));
2 unmodified lines
289 await result;290 expect(calls).toEqual(['1', '2', 'action']);291 });292305 test('when async hook everything then hooks called nested', async() => {293 test('when async hook everything then hooks called nested', async () => {294 const calls = [];295 const program = new commander.Command();296 program309 .hook('preAction', async() => { await 0; calls.push('pb1'); })310 .hook('postAction', async() => { await 0; calls.push('pa1'); });297 .hook('preAction', async () => {298 await 0;299 calls.push('pb1');300 })301 .hook('postAction', async () => {302 await 0;303 calls.push('pa1');304 });305 program312 .hook('preAction', async() => { await 0; calls.push('pb2'); })313 .hook('postAction', async() => { await 0; calls.push('pa2'); });314 program.command('sub')315 .hook('preAction', async() => { await 0; calls.push('sb'); })316 .hook('postAction', async() => { await 0; calls.push('sa'); })317 .action(async() => { await 0; calls.push('action'); });306 .hook('preAction', async () => {307 await 0;308 calls.push('pb2');309 })310 .hook('postAction', async () => {311 await 0;312 calls.push('pa2');313 });314 program315 .command('sub')316 .hook('preAction', async () => {317 await 0;318 calls.push('sb');319 })320 .hook('postAction', async () => {321 await 0;322 calls.push('sa');323 })324 .action(async () => {325 await 0;326 calls.push('action');327 });328 const result = program.parseAsync(['sub'], { from: 'user' });329 expect(calls).toEqual([]);330 await result;331 expect(calls).toEqual(['pb1', 'pb2', 'sb', 'action', 'sa', 'pa2', 'pa1']);332 });333324 test('preSubcommand hook should work', async() => {334 test('preSubcommand hook should work', async () => {335 const calls = [];336 const program = new commander.Command();327 program328 .hook('preSubcommand', async() => { await 0; calls.push(0); });329 program.command('sub')330 .action(async() => { await 1; calls.push(1); });331 program.action(async() => { await 2; calls.push(2); });337 program.hook('preSubcommand', async () => {338 await 0;339 calls.push(0);340 });341 program.command('sub').action(async () => {342 await 1;343 calls.push(1);344 });345 program.action(async () => {346 await 2;347 calls.push(2);348 });349 const result = program.parseAsync(['sub'], { from: 'user' });350 expect(calls).toEqual([]);351 await result;352 expect(calls).toEqual([0, 1]);353 });337 test('preSubcommand hook should effective for direct subcommands', async() => {354 test('preSubcommand hook should effective for direct subcommands', async () => {355 const calls = [];356 const program = new commander.Command();357 program.hook('preSubcommand', async (thisCommand, subCommand) => {358 await 'preSubcommand';359 calls.push('preSubcommand');360 calls.push(subCommand.name());361 });362 program341 .hook('preSubcommand', async(thisCommand, subCommand) => {342 await 'preSubcommand';343 calls.push('preSubcommand');344 calls.push(subCommand.name());345 });346 program363 .command('first')348 .action(async() => { await 'first'; calls.push('first'); })364 .action(async () => {365 await 'first';366 calls.push('first');367 })368 .command('second')350 .action(async() => { await 'second'; calls.push('second'); })369 .action(async () => {370 await 'second';371 calls.push('second');372 })373 .command('third')352 .action(async() => { await 'third'; calls.push('third'); });353 program.action(async() => { await 2; calls.push(2); });354 const result = program.parseAsync(['first', 'second', 'third'], { from: 'user' });374 .action(async () => {375 await 'third';376 calls.push('third');377 });378 program.action(async () => {379 await 2;380 calls.push(2);381 });382 const result = program.parseAsync(['first', 'second', 'third'], {383 from: 'user',384 });385 expect(calls).toEqual([]);386 await result;387 expect(calls).toEqual(['preSubcommand', 'first', 'third']);388 });
1 unmodified line
modified:tests/command.name.test.js+4 added-3 removed
13 unmodified lines
14});1516test('when program name not set and parse with script argument then plain name is found from script name', () => {17 const program = new commander.Command();18 program.parse(['node', path.resolve(process.cwd(), 'script.js')], { from: 'node' });18 program.parse(['node', path.resolve(process.cwd(), 'script.js')], {19 from: 'node',20 });21 expect(program.name()).toBe('script');22});2324test('when command name not set and no script argument in parse then name is program', () => {
3 unmodified lines
28});2930test('when add command then command is named', () => {31 const program = new commander.Command();30 const subcommand = program31 .command('mycommand <file>');32 const subcommand = program.command('mycommand <file>');33 expect(subcommand.name()).toBe('mycommand');34});3536test('when set program name then name appears in help', () => {
17 unmodified lines
modified:tests/command.nested.test.js+1 added-4 removed
1 unmodified line
23test('when call nested subcommand then runs', () => {4 const program = new commander.Command();5 const leafAction = jest.fn();6 program7 .command('sub1')8 .command('sub2')9 .action(leafAction);6 program.command('sub1').command('sub2').action(leafAction);7 program.parse('node test.js sub1 sub2'.split(' '));8 expect(leafAction).toHaveBeenCalled();9});
modified:tests/command.onCommand.test.js+3 added-8 removed
5 unmodified lines
6describe(".command('*')", () => {7 test('when action handler for subcommand then emit command:subcommand', () => {8 const mockListener = jest.fn();9 const program = new commander.Command();10 program11 .command('sub')12 .action(() => {});10 program.command('sub').action(() => {});11 program.on('command:sub', mockListener);12 program.parse(['sub'], { from: 'user' });13 expect(mockListener).toHaveBeenCalled();14 });1516 test('when no action handler for subcommand then still emit command:subcommand', () => {17 const mockListener = jest.fn();18 const program = new commander.Command();21 program22 .command('sub');19 program.command('sub');20 program.on('command:sub', mockListener);21 program.parse(['sub'], { from: 'user' });22 expect(mockListener).toHaveBeenCalled();23 });2425 test('when subcommand has argument then emit command:subcommand with argument', () => {26 const mockListener = jest.fn();27 const program = new commander.Command();31 program32 .command('sub <file>')33 .action(() => {});28 program.command('sub <file>').action(() => {});29 program.on('command:sub', mockListener);30 program.parse(['sub', 'file'], { from: 'user' });31 expect(mockListener).toHaveBeenCalledWith(['file'], []);32 });
1 unmodified line
modified:tests/command.option-misuse.test.js+2 added-1 removed
1 unmodified line
23// It is a reasonable and easy mistake to pass Option to .option(). Detect this4// and offer advice.56const expectedMessage =6const expectedMessage = 'To add an Option object use addOption() instead of option() or requiredOption()';7 'To add an Option object use addOption() instead of option() or requiredOption()';89test('when pass Option to .option() then throw', () => {10 const program = new Command();11
12 unmodified lines
modified:tests/command.parse.test.js+6 added-8 removed
70 unmodified lines
7172describe('return type', () => {73 test('when call .parse then returns program', () => {74 const program = new commander.Command();75 program76 .action(() => { });75 program.action(() => {});7677 const result = program.parse(['node', 'test']);78 expect(result).toBe(program);79 });8082 test('when await .parseAsync then returns program', async() => {81 test('when await .parseAsync then returns program', async () => {82 const program = new commander.Command();84 program85 .action(() => { });83 program.action(() => {});8485 const result = await program.parseAsync(['node', 'test']);86 expect(result).toBe(program);87 });
41 unmodified lines
129 });130});131132describe('parseAsync parameter is treated as readonly, per TypeScript declaration', () => {135 test('when parse called then parameter does not change', async() => {133 test('when parse called then parameter does not change', async () => {134 const program = new commander.Command();135 program.option('--debug');136 const original = ['node', '--debug', 'arg'];137 const param = original.slice();138 await program.parseAsync(param);139 expect(param).toEqual(original);140 });141144 test('when parseAsync called and parsed args later changed then parameter does not change', async() => {142 test('when parseAsync called and parsed args later changed then parameter does not change', async () => {143 const program = new commander.Command();144 program.option('--debug');145 const original = ['node', '--debug', 'arg'];146 const param = original.slice();
2 unmodified lines
149 program.rawArgs.length = 0;150 expect(param).toEqual(original);151 });152155 test('when parseAsync called and param later changed then parsed args do not change', async() => {153 test('when parseAsync called and param later changed then parsed args do not change', async () => {154 const program = new commander.Command();155 program.option('--debug');156 const param = ['node', '--debug', 'arg'];157 await program.parseAsync(param);
7 unmodified lines
modified:tests/command.parseOptions.test.js+32 added-15 removed
14 unmodified lines
15 const program = new commander.Command();16 program17 .command('doit [id]')18 .option('--better', 'do it better')19 .action((id, cmd) => {20 });19 .action((id, cmd) => {});20 return program;21 }2223 // https://github.com/tj/commander.js/issues/1032
10 unmodified lines
34 expect(program.args.length).toBeGreaterThan(0);35 });3637 // https://github.com/tj/commander.js/issues/50839 test('when arguments to executable include option flags then argument order preserved', async() => {38 test('when arguments to executable include option flags then argument order preserved', async () => {39 const pm = path.join(__dirname, 'fixtures/pm');41 const { stdout } = await execFileAsync('node', [pm, 'echo', '1', '2', '--dry-run', '3', '4', '5', '6']);40 const { stdout } = await execFileAsync('node', [41 pm,42 'echo',43 '1',44 '2',45 '--dry-run',46 '3',47 '4',48 '5',49 '6',50 ]);51 expect(stdout).toBe("[ '1', '2', '--dry-run', '3', '4', '5', '6' ]\n");52 });53});54
4 unmodified lines
59 .option('--global-flag')60 .option('--global-value <value>')61 .command('sub [args...]')62 .option('--sub-flag');54 program55 .action(() => { });63 program.action(() => {});64 return program;65 }6667 // Subcommands are just another potential operand as far as parseOptions is concerned, so limited testing of subcommand as such.
90 unmodified lines
158159 test('when program has literal after unknown option then literal preserved too', () => {160 const program = createProgram();161 const result = program.parseOptions('--unknown1 -- --unknown2'.split(' '));154 expect(result).toEqual({ operands: [], unknown: ['--unknown1', '--', '--unknown2'] });162 expect(result).toEqual({163 operands: [],164 unknown: ['--unknown1', '--', '--unknown2'],165 });166 });167});168169// parse now sets program.args to the result of parseOptions (operands + unknown). Some limited testing.170describe('parse and program.args', () => {171 test('when program has known flag and operand then option removed and operand returned', () => {172 const program = new commander.Command();162 program163 .option('--global-flag');173 program.option('--global-flag');174 program.parse('node test.js --global-flag arg'.split(' '));175 expect(program.args).toEqual(['arg']);176 });177
2 unmodified lines
180 program181 .allowUnknownOption()182 .option('--global-flag')183 .option('--global-value <value>');174 program.parse('node test.js aaa --global-flag bbb --unknown ccc --global-value value'.split(' '));184 program.parse(185 'node test.js aaa --global-flag bbb --unknown ccc --global-value value'.split(186 ' ',187 ),188 );189 expect(program.args).toEqual(['aaa', 'bbb', '--unknown', 'ccc']);190 });191192 test('when subcommand has mixed arguments then program flags removed and rest returned in same order', () => {
2 unmodified lines
195 .option('--global-flag')196 .option('--global-value <value>')197 .command('sub [args...]')198 .option('--sub-flag');185 program.parse('node test.js --global-flag sub --sub-flag arg --global-value value'.split(' '));199 program.parse(200 'node test.js --global-flag sub --sub-flag arg --global-value value'.split(201 ' ',202 ),203 );204 expect(program.args).toEqual(['sub', '--sub-flag', 'arg']);205 });206});207
37 unmodified lines
245 .option('-a,--aaa')246 .option('-b,--bbb')247 .option('-c,--ccc <value>')248 .option('-d,--ddd [value]');231 program232 .action(() => { });249 program.action(() => {});250 return program;251 }252253 test('when program has combo known boolean short flags then arg removed', () => {
6 unmodified lines
260 test('when program has combo unknown short flags then arg preserved', () => {261 const program = createProgram();262 const result = program.parseOptions(['-pq']);263 expect(result).toEqual({ operands: [], unknown: ['-pq'] });247 expect(program.opts()).toEqual({ });264 expect(program.opts()).toEqual({});265 });266267 test('when program has combo known short option and required value then arg removed', () => {268 const program = createProgram();
33 unmodified lines
302 test('when program has unknown long flag=value then arg preserved', () => {303 const program = createProgram();304 const result = program.parseOptions(['--rrr=value']);305 expect(result).toEqual({ operands: [], unknown: ['--rrr=value'] });289 expect(program.opts()).toEqual({ });306 expect(program.opts()).toEqual({});307 });308309 test('when program has combo optional and combineFlagAndOptionalValue() then treat as value', () => {310 const program = createProgram();
19 unmodified lines
modified:tests/command.positionalOptions.test.js+60 added-64 removed
5 unmodified lines
6describe('program with passThrough', () => {7 function makeProgram() {8 const program = new commander.Command();9 program.passThroughOptions();10 program11 .option('-d, --debug')12 .argument('<args...>');10 program.option('-d, --debug').argument('<args...>');11 return program;12 }1314 test('when option before command-argument then option parsed', () => {
20 unmodified lines
35 const program = makeProgram();36 const mockAction = jest.fn();37 program.action(mockAction);38 program.parse(['arg', '--pass'], { from: 'user' });41 expect(mockAction).toHaveBeenCalledWith(['arg', '--pass'], program.opts(), program);39 expect(mockAction).toHaveBeenCalledWith(40 ['arg', '--pass'],41 program.opts(),42 program,43 );44 });4546 test('when help option (without command-argument) then help called', () => {47 const program = makeProgram();48 const mockHelp = jest.fn(() => '');4948 program49 .exitOverride()50 .configureHelp({ formatHelp: mockHelp });50 program.exitOverride().configureHelp({ formatHelp: mockHelp });51 try {52 program.parse(['--help'], { from: 'user' });53 } catch (err) { /* empty */ }53 } catch (err) {54 /* empty */55 }56 expect(mockHelp).toHaveBeenCalled();57 });5859 test('when help option after command-argument then option passed through', () => {
49 unmodified lines
109 });110111 test('when shared option before and after subcommand then both parsed', () => {112 const { program, sub } = makeProgram();111 program.parse(['--shared', 'program', 'sub', '--shared', 'local'], { from: 'user' });113 program.parse(['--shared', 'program', 'sub', '--shared', 'local'], {114 from: 'user',115 });116 expect(program.opts().shared).toEqual('program');117 expect(sub.opts().shared).toEqual('local');118 });119
3 unmodified lines
123 [['--help'], 1, 0],124 [['sub', '--help'], 0, 1],125 [['sub', 'foo', '--help'], 0, 1],126 [['help'], 1, 0],123 [['help', 'sub'], 0, 1]124 ])('help: when user args %p then program/sub help called %p/%p', (userArgs, expectProgramHelpCount, expectSubHelpCount) => {125 const { program, sub } = makeProgram();126 const mockProgramHelp = jest.fn();127 program128 .exitOverride()129 .configureHelp({ formatHelp: mockProgramHelp });130 const mockSubHelp = jest.fn();131 sub132 .exitOverride()133 .configureHelp({ formatHelp: mockSubHelp });127 [['help', 'sub'], 0, 1],128 ])(129 'help: when user args %p then program/sub help called %p/%p',130 (userArgs, expectProgramHelpCount, expectSubHelpCount) => {131 const { program, sub } = makeProgram();132 const mockProgramHelp = jest.fn();133 program.exitOverride().configureHelp({ formatHelp: mockProgramHelp });134 const mockSubHelp = jest.fn();135 sub.exitOverride().configureHelp({ formatHelp: mockSubHelp });136135 try {136 program.parse(userArgs, { from: 'user' });137 } catch (err) { /* empty */ }138 expect(mockProgramHelp).toHaveBeenCalledTimes(expectProgramHelpCount);139 expect(mockSubHelp).toHaveBeenCalledTimes(expectSubHelpCount);140 });137 try {138 program.parse(userArgs, { from: 'user' });139 } catch (err) {140 /* empty */141 }142 expect(mockProgramHelp).toHaveBeenCalledTimes(expectProgramHelpCount);143 expect(mockSubHelp).toHaveBeenCalledTimes(expectSubHelpCount);144 },145 );146});147148// ---------------------------------------------------------------149
41 unmodified lines
191192 test.each([193 [[], 0, 0],194 [['--help'], 1, 0],190 [['help'], 1, 0]191 ])('help: when user args %p then program/sub help called %p/%p', (userArgs, expectProgramHelpCount, expectSubHelpCount) => {192 const { program, sub } = makeProgram();193 const mockProgramHelp = jest.fn();194 program195 .exitOverride()196 .configureHelp({ formatHelp: mockProgramHelp });197 const mockSubHelp = jest.fn();198 sub199 .exitOverride()200 .configureHelp({ formatHelp: mockSubHelp });195 [['help'], 1, 0],196 ])(197 'help: when user args %p then program/sub help called %p/%p',198 (userArgs, expectProgramHelpCount, expectSubHelpCount) => {199 const { program, sub } = makeProgram();200 const mockProgramHelp = jest.fn();201 program.exitOverride().configureHelp({ formatHelp: mockProgramHelp });202 const mockSubHelp = jest.fn();203 sub.exitOverride().configureHelp({ formatHelp: mockSubHelp });204202 try {203 program.parse(userArgs, { from: 'user' });204 } catch (err) { /* empty */ }205 expect(mockProgramHelp).toHaveBeenCalledTimes(expectProgramHelpCount);206 expect(mockSubHelp).toHaveBeenCalledTimes(expectSubHelpCount);207 });205 try {206 program.parse(userArgs, { from: 'user' });207 } catch (err) {208 /* empty */209 }210 expect(mockProgramHelp).toHaveBeenCalledTimes(expectProgramHelpCount);211 expect(mockSubHelp).toHaveBeenCalledTimes(expectSubHelpCount);212 },213 );214});215216// ------------------------------------------------------------------------------217
56 unmodified lines
274 });275276 test('when shared option before sub and after sub and after sub parameter then all three parsed', () => {277 const { program, sub } = makeProgram();272 program.parse(['--shared=global', 'sub', '--shared=local', 'arg', '--shared'], { from: 'user' });278 program.parse(279 ['--shared=global', 'sub', '--shared=local', 'arg', '--shared'],280 { from: 'user' },281 );282 expect(program.opts().shared).toEqual('global');283 expect(sub.opts().shared).toEqual('local');284 expect(sub.args).toEqual(['arg', '--shared']);285 });
3 unmodified lines
289290describe('default command with passThrough', () => {291 function makeProgram() {292 const program = new commander.Command();284 program285 .enablePositionalOptions();293 program.enablePositionalOptions();294 const sub = program295 .command('sub', { isDefault: true })296 .passThroughOptions()297 .argument('[args...]')
80 unmodified lines
378 });379380 test('when program not positional and add subcommand with passThroughOptions then error', () => {381 const program = new commander.Command();374 const sub = new commander.Command('sub')375 .passThroughOptions();382 const sub = new commander.Command('sub').passThroughOptions();383384 expect(() => {385 program.addCommand(sub);386 }).toThrow();
50 unmodified lines
437438describe('program with allowUnknownOption', () => {439 test('when passThroughOptions and unknown option then arguments from unknown passed through', () => {440 const program = new commander.Command();434 program435 .passThroughOptions()436 .allowUnknownOption()437 .option('--debug');441 program.passThroughOptions().allowUnknownOption().option('--debug');442443 program.parse(['--unknown', '--debug'], { from: 'user' });444 expect(program.args).toEqual(['--unknown', '--debug']);445 });446447 test('when positionalOptions and unknown option then known options then known option parsed', () => {448 const program = new commander.Command();445 program446 .enablePositionalOptions()447 .allowUnknownOption()448 .option('--debug');449 program.enablePositionalOptions().allowUnknownOption().option('--debug');450451 program.parse(['--unknown', '--debug'], { from: 'user' });452 expect(program.opts().debug).toBe(true);453 expect(program.args).toEqual(['--unknown']);
4 unmodified lines
458459describe('passThroughOptions(xxx) and option after command-argument', () => {460 function makeProgram() {461 const program = new commander.Command();461 program462 .option('-d, --debug')463 .argument('<args...>');462 program.option('-d, --debug').argument('<args...>');463 return program;464 }465466 test('when passThroughOptions() then option passed through', () => {
23 unmodified lines
490491describe('enablePositionalOptions(xxx) and shared option after subcommand', () => {492 function makeProgram() {493 const program = new commander.Command();495 program496 .option('-d, --debug');497 const sub = program498 .command('sub')499 .option('-d, --debug');494 program.option('-d, --debug');495 const sub = program.command('sub').option('-d, --debug');496 return { program, sub };497 }498499 test('when enablePositionalOptions() then option parsed by subcommand', () => {
21 unmodified lines
modified:tests/command.showHelpAfterError.test.js+4 added-3 removed
65 unmodified lines
66 });6768 test('when too many command-arguments then shows help', () => {69 const { program, writeMock } = makeProgram();70 program71 .allowExcessArguments(false);70 program.allowExcessArguments(false);71 let caughtErr;72 try {73 program.parse(['surprise'], { from: 'user' });74 } catch (err) {
39 unmodified lines
114 .configureOutput({ writeErr: writeMock });115116 try {117 program.parse(['--unknown-option'], { from: 'user' });119 } catch (err) { /* empty */ }118 } catch (err) {119 /* empty */120 }121 expect(writeMock).toHaveBeenLastCalledWith(program.helpInformation());122});
modified:tests/command.showSuggestionAfterError.test.js+8 added-6 removed
1const { Command } = require('../');23function getSuggestion(program, arg) {4 let message = '';5 program6 .exitOverride()7 .configureOutput({8 writeErr: (str) => { message = str; }9 });5 program.exitOverride().configureOutput({6 writeErr: (str) => {7 message = str;8 },9 });1011 try {12 program.parse([arg], { from: 'user' });13 } catch (err) { /* empty */ }13 } catch (err) {14 /* empty */15 }1617 const match = message.match(/Did you mean (one of )?(.*)\?/);18 return match ? match[2] : null;19}
32 unmodified lines
modified:tests/command.unknownCommand.test.js+9 added-18 removed
3 unmodified lines
4 // Optional. Use internal knowledge to suppress output to keep test output clean.5 let writeErrorSpy;67 beforeAll(() => {8 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });8 writeErrorSpy = jest9 .spyOn(process.stderr, 'write')10 .mockImplementation(() => {});11 });1213 afterEach(() => {14 writeErrorSpy.mockClear();
12 unmodified lines
27 });2829 test('when unknown command but action handler taking arg then no error', () => {30 const program = new commander.Command();29 program30 .exitOverride()31 .command('sub');32 program33 .argument('[args...]')34 .action(() => { });31 program.exitOverride().command('sub');32 program.argument('[args...]').action(() => {});33 expect(() => {34 program.parse('node test.js unknown'.split(' '));35 }).not.toThrow();36 });3738 test('when unknown command but listener then no error', () => {39 const program = new commander.Command();42 program43 .exitOverride()44 .command('sub');45 program46 .on('command:*', () => { });40 program.exitOverride().command('sub');41 program.on('command:*', () => {});42 expect(() => {43 program.parse('node test.js unknown'.split(' '));44 }).not.toThrow();45 });4647 test('when unknown command then error', () => {48 const program = new commander.Command();54 program55 .exitOverride()56 .command('sub');49 program.exitOverride().command('sub');50 let caughtErr;51 try {52 program.parse('node test.js unknown'.split(' '));53 } catch (err) {
5 unmodified lines
59 test('when unknown command and unknown option then error is for unknown command', () => {60 // The unknown command is more useful since the option is for an unknown command (and might be61 // ok if the command had been correctly spelled, say).62 const program = new commander.Command();70 program71 .exitOverride()72 .command('sub');63 program.exitOverride().command('sub');64 let caughtErr;65 try {66 program.parse('node test.js sbu --silly'.split(' '));67 } catch (err) {
5 unmodified lines
modified:tests/command.unknownOption.test.js+5 added-5 removed
5 unmodified lines
6 // Optional. Use internal knowledge to suppress output to keep test output clean.7 let writeErrorSpy;89 beforeAll(() => {10 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });10 writeErrorSpy = jest11 .spyOn(process.stderr, 'write')12 .mockImplementation(() => {});13 });1415 afterEach(() => {16 writeErrorSpy.mockClear();
69 unmodified lines
86 });8788 test('when specify unknown option with simple program then error', () => {89 const program = new commander.Command();88 program89 .exitOverride();90 program.exitOverride();91 let caughtErr;92 try {93 program.parse(['node', 'test', '--NONSENSE']);94 } catch (err) {
3 unmodified lines
98 });99100 test('when specify unknown global option before subcommand then error', () => {101 const program = new commander.Command();101 program102 .exitOverride();102 program.exitOverride();103 program.command('sub');104105 let caughtErr;106 try {
7 unmodified lines
modified:tests/command.usage.test.js+8 added-19 removed
10 unmodified lines
1112test('when custom usage and check program help then starts with custom usage', () => {13 const myUsage = 'custom';14 const program = new commander.Command();15 program16 .usage(myUsage);15 program.usage(myUsage);1617 program.name('test');18 const helpInformation = program.helpInformation();19
1 unmodified line
21});2223test('when default usage and check subcommand help then starts with default usage including program name', () => {24 const program = new commander.Command();26 const subCommand = program27 .command('info');25 const subCommand = program.command('info');2627 program.name('test');28 const helpInformation = subCommand.helpInformation();29
2 unmodified lines
3233test('when custom usage and check subcommand help then starts with custom usage including program name', () => {34 const myUsage = 'custom';35 const program = new commander.Command();38 const subCommand = program39 .command('info')40 .usage(myUsage);36 const subCommand = program.command('info').usage(myUsage);3738 program.name('test');39 const helpInformation = subCommand.helpInformation();40
2 unmodified lines
4344test('when has option then [options] included in usage', () => {45 const program = new commander.Command();4651 program52 .option('--foo');47 program.option('--foo');4849 expect(program.usage()).toMatch('[options]');50});5152test('when no options then [options] not included in usage', () => {53 const program = new commander.Command();5460 program61 .helpOption(false);55 program.helpOption(false);5657 expect(program.usage()).not.toMatch('[options]');58});5960test('when has command then [command] included in usage', () => {61 const program = new commander.Command();6269 program70 .command('foo');63 program.command('foo');6465 expect(program.usage()).toMatch('[command]');66});67
5 unmodified lines
7374test('when argument then argument included in usage', () => {75 const program = new commander.Command();7684 program85 .argument('<file>');77 program.argument('<file>');7879 expect(program.usage()).toMatch('<file>');80});8182test('when options and command and argument then all three included in usage', () => {83 const program = new commander.Command();8493 program94 .argument('<file>')95 .option('--alpha')96 .command('beta');85 program.argument('<file>').option('--alpha').command('beta');8687 expect(program.usage()).toEqual('[options] [command] <file>');88});
modified:tests/commander.configureCommand.test.js+6 added-19 removed
4 unmodified lines
5// Default behaviours67test('when default then options not stored on command', () => {8 const program = new commander.Command();9 program10 .option('--foo <value>', 'description');9 program.option('--foo <value>', 'description');10 program.parse(['node', 'test', '--foo', 'bar']);11 expect(program.foo).toBeUndefined();12 expect(program.opts().foo).toBe('bar');13});1415test('when default then options+command passed to action', () => {16 const program = new commander.Command();17 const callback = jest.fn();19 program20 .argument('<value>')21 .action(callback);18 program.argument('<value>').action(callback);19 program.parse(['node', 'test', 'value']);20 expect(callback).toHaveBeenCalledWith('value', program.opts(), program);21});2223// storeOptionsAsProperties2425test('when storeOptionsAsProperties() then options stored on command', () => {26 const program = new commander.Command();30 program31 .storeOptionsAsProperties()32 .option('--foo <value>', 'description');27 program.storeOptionsAsProperties().option('--foo <value>', 'description');28 program.parse(['node', 'test', '--foo', 'bar']);29 expect(program.foo).toBe('bar');30 expect(program.opts().foo).toBe('bar');31});3233test('when storeOptionsAsProperties(true) then options stored on command', () => {34 const program = new commander.Command();40 program41 .storeOptionsAsProperties(true)42 .option('--foo <value>', 'description');35 program.storeOptionsAsProperties(true).option('--foo <value>', 'description');36 program.parse(['node', 'test', '--foo', 'bar']);37 expect(program.foo).toBe('bar');38 expect(program.opts().foo).toBe('bar');39});
10 unmodified lines
5051test('when storeOptionsAsProperties() then command+command passed to action', () => {52 const program = new commander.Command();53 const callback = jest.fn();61 program62 .storeOptionsAsProperties()63 .argument('<value>')64 .action(callback);54 program.storeOptionsAsProperties().argument('<value>').action(callback);55 program.parse(['node', 'test', 'value']);56 expect(callback).toHaveBeenCalledWith('value', program, program);57});5859test('when storeOptionsAsProperties(false) then opts+command passed to action', () => {60 const program = new commander.Command();61 const callback = jest.fn();72 program73 .storeOptionsAsProperties(false)74 .argument('<value>')75 .action(callback);62 program.storeOptionsAsProperties(false).argument('<value>').action(callback);63 program.parse(['node', 'test', 'value']);64 expect(callback).toHaveBeenCalledWith('value', program.opts(), program);65});66
15 unmodified lines
modified:tests/deprecated.test.js+3 added-6 removed
5 unmodified lines
67describe('option with regular expression instead of custom processing function', () => {8 test('when option not given then value is default', () => {9 const program = new commander.Command();10 program11 .option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');10 program.option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');11 program.parse([], { from: 'user' });12 expect(program.opts().cheese).toEqual('mild');13 });1415 test('when argument matches regexp then value is as specified', () => {16 const program = new commander.Command();18 program19 .option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');17 program.option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');18 program.parse(['--cheese', 'tasty'], { from: 'user' });19 expect(program.opts().cheese).toEqual('tasty');20 });2122 test('when argument does not match regexp then value is default', () => {23 const program = new commander.Command();26 program27 .option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');24 program.option('--cheese <type>', 'cheese type', /mild|tasty/, 'mild');25 program.parse(['--cheese', 'other'], { from: 'user' });26 expect(program.opts().cheese).toEqual('mild');27 });28});
modified:tests/esm-imports-test.mjs+13 added-1 removed
1import { program, Command, Option, Argument, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Help, createCommand, createArgument, createOption } from '../esm.mjs';1import {2 program,3 Command,4 Option,5 Argument,6 CommanderError,7 InvalidArgumentError,8 InvalidOptionArgumentError,9 Help,10 createCommand,11 createArgument,12 createOption,13} from '../esm.mjs';1415// Do some simple checks that expected imports are available at runtime.16// Run using `npm run test-esm`.17// Similar tests to test-imports.test.ts
34 unmodified lines
modified:tests/help.argumentDescription.test.js+16 added-5 removed
15 unmodified lines
16 expect(helper.argumentDescription(argument)).toEqual(description);17 });1819 test('when argument has default value then return description and default value', () => {20 const argument = new commander.Argument('[n]', 'description').default('default');20 const argument = new commander.Argument('[n]', 'description').default(21 'default',22 );23 const helper = new commander.Help();22 expect(helper.argumentDescription(argument)).toEqual('description (default: "default")');24 expect(helper.argumentDescription(argument)).toEqual(25 'description (default: "default")',26 );27 });2829 test('when argument has default value description then return description and custom default description', () => {26 const argument = new commander.Argument('[n]', 'description').default('default value', 'custom');30 const argument = new commander.Argument('[n]', 'description').default(31 'default value',32 'custom',33 );34 const helper = new commander.Help();28 expect(helper.argumentDescription(argument)).toEqual('description (default: custom)');35 expect(helper.argumentDescription(argument)).toEqual(36 'description (default: custom)',37 );38 });3940 test('when an argument has default value and no description then still return default value', () => {41 const argument = new commander.Argument('[n]').default('default');42 const helper = new commander.Help();34 expect(helper.argumentDescription(argument)).toEqual('(default: "default")');43 expect(helper.argumentDescription(argument)).toEqual(44 '(default: "default")',45 );46 });47});
modified:tests/help.commandTerm.test.js+6 added-7 removed
10 unmodified lines
11 expect(helper.subcommandTerm(command)).toEqual('program');12 });1314 test('when command has alias then returns name|alias', () => {15 const command = new commander.Command('program')16 .alias('alias');15 const command = new commander.Command('program').alias('alias');16 const helper = new commander.Help();17 expect(helper.subcommandTerm(command)).toEqual('program|alias');18 });1920 test('when command has options then returns name [options]', () => {22 const command = new commander.Command('program')23 .option('-a,--all');21 const command = new commander.Command('program').option('-a,--all');22 const helper = new commander.Help();23 expect(helper.subcommandTerm(command)).toEqual('program [options]');24 });2526 test('when command has <argument> then returns name <argument>', () => {29 const command = new commander.Command('program')30 .argument('<argument>');27 const command = new commander.Command('program').argument('<argument>');28 const helper = new commander.Help();29 expect(helper.subcommandTerm(command)).toEqual('program <argument>');30 });31
2 unmodified lines
34 .alias('alias')35 .option('-a,--all')36 .argument('<argument>');37 const helper = new commander.Help();41 expect(helper.subcommandTerm(command)).toEqual('program|alias [options] <argument>');38 expect(helper.subcommandTerm(command)).toEqual(39 'program|alias [options] <argument>',40 );41 });42});
modified:tests/help.commandUsage.test.js+4 added-10 removed
19 unmodified lines
20 });2122 test('when program has alias then usage includes alias', () => {23 const program = new commander.Command();24 program25 .name('program')26 .alias('alias');24 program.name('program').alias('alias');25 const helper = new commander.Help();26 expect(helper.commandUsage(program)).toEqual('program|alias [options]');27 });2829 test('when help for subcommand then usage includes hierarchy', () => {30 const program = new commander.Command();33 program34 .name('program');35 const sub = program.command('sub')31 program.name('program');32 const sub = program.command('sub').name('sub');36 .name('sub');33 const helper = new commander.Help();34 expect(helper.commandUsage(sub)).toEqual('program sub [options]');35 });3637 test('when program has argument then usage includes argument', () => {38 const program = new commander.Command();43 program44 .name('program')45 .argument('<file>');39 program.name('program').argument('<file>');40 const helper = new commander.Help();41 expect(helper.commandUsage(program)).toEqual('program [options] <file>');42 });43});
modified:tests/help.longestArgumentTermLength.test.js+6 added-2 removed
12 unmodified lines
13 test('when has argument description then returns argument length', () => {14 const program = new commander.Command();15 program.argument('<wonder>', 'wonder description');16 const helper = new commander.Help();17 expect(helper.longestArgumentTermLength(program, helper)).toEqual('wonder'.length);17 expect(helper.longestArgumentTermLength(program, helper)).toEqual(18 'wonder'.length,19 );20 });2122 test('when has multiple argument descriptions then returns longest', () => {23 const program = new commander.Command();24 program.argument('<alpha>', 'x');25 program.argument('<longest>', 'x');26 program.argument('<beta>', 'x');27 const helper = new commander.Help();26 expect(helper.longestArgumentTermLength(program, helper)).toEqual('longest'.length);28 expect(helper.longestArgumentTermLength(program, helper)).toEqual(29 'longest'.length,30 );31 });32});
modified:tests/help.longestCommandTermLength.test.js+15 added-12 removed
11 unmodified lines
1213 test('when command and no help then returns length of term', () => {14 const sub = new commander.Command('sub');15 const program = new commander.Command();16 program17 .addHelpCommand(false)18 .addCommand(sub);16 program.addHelpCommand(false).addCommand(sub);17 const helper = new commander.Help();20 expect(helper.longestSubcommandTermLength(program, helper)).toEqual(helper.subcommandTerm(sub).length);18 expect(helper.longestSubcommandTermLength(program, helper)).toEqual(19 helper.subcommandTerm(sub).length,20 );21 });2223 test('when command with arg and no help then returns length of term', () => {24 const sub = new commander.Command('sub <file)');25 const program = new commander.Command();26 program27 .addHelpCommand(false)28 .addCommand(sub);26 program.addHelpCommand(false).addCommand(sub);27 const helper = new commander.Help();30 expect(helper.longestSubcommandTermLength(program, helper)).toEqual(helper.subcommandTerm(sub).length);28 expect(helper.longestSubcommandTermLength(program, helper)).toEqual(29 helper.subcommandTerm(sub).length,30 );31 });3233 test('when multiple commands then returns longest length', () => {34 const longestCommandName = 'alphabet-soup <longer_than_help>';
3 unmodified lines
38 .command('before', 'desc')39 .command(longestCommandName, 'desc')40 .command('after', 'desc');41 const helper = new commander.Help();42 expect(helper.longestSubcommandTermLength(program, helper)).toEqual(longestCommandName.length);42 expect(helper.longestSubcommandTermLength(program, helper)).toEqual(43 longestCommandName.length,44 );45 });4647 test('when just help command then returns length of help term', () => {48 const program = new commander.Command();47 program48 .addHelpCommand(true);49 program.addHelpCommand(true);50 const helper = new commander.Help();50 expect(helper.longestSubcommandTermLength(program, helper)).toEqual('help [command]'.length);51 expect(helper.longestSubcommandTermLength(program, helper)).toEqual(52 'help [command]'.length,53 );54 });55});
modified:tests/help.longestOptionTermLength.test.js+6 added-2 removed
12 unmodified lines
1314 test('when just implicit help option returns length of help flags', () => {15 const program = new commander.Command();16 const helper = new commander.Help();17 expect(helper.longestOptionTermLength(program, helper)).toEqual('-h, --help'.length);17 expect(helper.longestOptionTermLength(program, helper)).toEqual(18 '-h, --help'.length,19 );20 });2122 test('when multiple option then returns longest length', () => {23 const longestOptionFlags = '-l, --longest <value>';
2 unmodified lines
26 .option('--before', 'optional description of flags')27 .option(longestOptionFlags)28 .option('--after');29 const helper = new commander.Help();28 expect(helper.longestOptionTermLength(program, helper)).toEqual(longestOptionFlags.length);30 expect(helper.longestOptionTermLength(program, helper)).toEqual(31 longestOptionFlags.length,32 );33 });34});
modified:tests/help.optionDescription.test.js+22 added-7 removed
19 unmodified lines
20 test('when boolean option has default value true then return description and default value', () => {21 const description = 'description';22 const option = new commander.Option('-a', description).default(true);23 const helper = new commander.Help();24 expect(helper.optionDescription(option)).toEqual('description (default: true)');24 expect(helper.optionDescription(option)).toEqual(25 'description (default: true)',26 );27 });2829 test('when boolean option has default value string then return description without default', () => {30 const description = 'description';
3 unmodified lines
34 });3536 test('when optional option has preset value then return description and default value', () => {37 const description = 'description';36 const option = new commander.Option('--aa [value]', description).preset('abc');38 const option = new commander.Option('--aa [value]', description).preset(39 'abc',40 );41 const helper = new commander.Help();38 expect(helper.optionDescription(option)).toEqual('description (preset: "abc")');42 expect(helper.optionDescription(option)).toEqual(43 'description (preset: "abc")',44 );45 });4647 test('when boolean option has preset value then return description without default', () => {48 const description = 'description';
10 unmodified lines
5960 test('when option has default value description then return description and custom default description', () => {61 const description = 'description';62 const defaultValueDescription = 'custom';57 const option = new commander.Option('-a <value>', description).default('default value', defaultValueDescription);63 const option = new commander.Option('-a <value>', description).default(64 'default value',65 defaultValueDescription,66 );67 const helper = new commander.Help();59 expect(helper.optionDescription(option)).toEqual(`description (default: ${defaultValueDescription})`);68 expect(helper.optionDescription(option)).toEqual(69 `description (default: ${defaultValueDescription})`,70 );71 });7273 test('when option has choices then return description and choices', () => {74 const description = 'description';75 const choices = ['one', 'two'];65 const option = new commander.Option('-a <value>', description).choices(choices);76 const option = new commander.Option('-a <value>', description).choices(77 choices,78 );79 const helper = new commander.Help();67 expect(helper.optionDescription(option)).toEqual('description (choices: "one", "two")');80 expect(helper.optionDescription(option)).toEqual(81 'description (choices: "one", "two")',82 );83 });84});
modified:tests/help.padWidth.test.js+7 added-17 removed
5 unmodified lines
6describe('padWidth', () => {7 test('when argument term longest return argument length', () => {8 const longestThing = 'veryLongThingBiggerThanOthers';9 const program = new commander.Command();10 program11 .argument(`<${longestThing}>`, 'description')12 .option('-o');13 program14 .command('sub');10 program.argument(`<${longestThing}>`, 'description').option('-o');11 program.command('sub');12 const helper = new commander.Help();13 expect(helper.padWidth(program, helper)).toEqual(longestThing.length);14 });1516 test('when option term longest return option length', () => {17 const longestThing = '--very-long-thing-bigger-than-others';18 const program = new commander.Command();22 program23 .argument('<file>', 'desc')24 .option(longestThing);25 program26 .command('sub');19 program.argument('<file>', 'desc').option(longestThing);20 program.command('sub');21 const helper = new commander.Help();22 expect(helper.padWidth(program, helper)).toEqual(longestThing.length);23 });24
3 unmodified lines
28 program29 .argument('<file>', 'desc')30 .option(longestThing)31 .configureHelp({ showGlobalOptions: true });38 const sub = program39 .command('sub');32 const sub = program.command('sub');33 const helper = sub.createHelp();34 expect(helper.padWidth(sub, helper)).toEqual(longestThing.length);35 });3637 test('when command term longest return command length', () => {38 const longestThing = 'very-long-thing-bigger-than-others';39 const program = new commander.Command();47 program48 .argument('<file>', 'desc')49 .option('-o');50 program51 .command(longestThing);40 program.argument('<file>', 'desc').option('-o');41 program.command(longestThing);42 const helper = new commander.Help();43 expect(helper.padWidth(program, helper)).toEqual(longestThing.length);44 });45});
modified:tests/help.showGlobalOptions.test.js+6 added-16 removed
1const commander = require('../');23test('when default configuration then global options hidden', () => {4 const program = new commander.Command();5 program6 .option('--global');5 program.option('--global');6 const sub = program.command('sub');7 expect(sub.helpInformation()).not.toContain('global');8});910test('when showGlobalOptions:true then program options shown', () => {11 const program = new commander.Command();13 program14 .option('--global')15 .configureHelp({ showGlobalOptions: true });12 program.option('--global').configureHelp({ showGlobalOptions: true });13 const sub = program.command('sub');14 expect(sub.helpInformation()).toContain('global');15});1617test('when showGlobalOptions:true and no global options then global options header not shown', () => {18 const program = new commander.Command();22 program23 .configureHelp({ showGlobalOptions: true });19 program.configureHelp({ showGlobalOptions: true });20 const sub = program.command('sub');21 expect(sub.helpInformation()).not.toContain('Global');22});2324test('when showGlobalOptions:true and nested commands then combined nested options shown program last', () => {25 const program = new commander.Command();30 program31 .option('--global')32 .configureHelp({ showGlobalOptions: true });33 const sub1 = program.command('sub1')26 program.option('--global').configureHelp({ showGlobalOptions: true });27 const sub1 = program.command('sub1').option('--sub1');34 .option('--sub1');28 const sub2 = sub1.command('sub2');29 expect(sub2.helpInformation()).toContain(`Global Options:30 --sub131 --global
6 unmodified lines
38 .option('-3')39 .option('-4')40 .option('-2')41 .configureHelp({ showGlobalOptions: true, sortOptions: true });49 const sub1 = program.command('sub1')50 .option('-6')51 .option('-1')52 .option('-5');42 const sub1 = program.command('sub1').option('-6').option('-1').option('-5');43 const sub2 = sub1.command('sub2');44 expect(sub2.helpInformation()).toContain(`Global Options:45 -146 -2
6 unmodified lines
modified:tests/help.sortCommands.test.js+6 added-2 removed
9 unmodified lines
10 .command('ccc', 'desc')11 .command('aaa', 'desc')12 .command('bbb', 'desc');13 const helper = program.createHelp();14 const visibleCommandNames = helper.visibleCommands(program).map(cmd => cmd.name());14 const visibleCommandNames = helper15 .visibleCommands(program)16 .map((cmd) => cmd.name());17 expect(visibleCommandNames).toEqual(['ccc', 'aaa', 'bbb', 'help']);18 });1920 test('when sortSubcommands:true then commands sorted', () => {
3 unmodified lines
24 .command('ccc', 'desc')25 .command('aaa', 'desc')26 .command('bbb', 'desc');27 const helper = program.createHelp();26 const visibleCommandNames = helper.visibleCommands(program).map(cmd => cmd.name());28 const visibleCommandNames = helper29 .visibleCommands(program)30 .map((cmd) => cmd.name());31 expect(visibleCommandNames).toEqual(['aaa', 'bbb', 'ccc', 'help']);32 });33});
modified:tests/help.sortOptions.test.js+18 added-6 removed
9 unmodified lines
10 .option('--zzz', 'desc')11 .option('--aaa', 'desc')12 .option('--bbb', 'desc');13 const helper = program.createHelp();14 const visibleOptionNames = helper.visibleOptions(program).map(option => option.name());14 const visibleOptionNames = helper15 .visibleOptions(program)16 .map((option) => option.name());17 expect(visibleOptionNames).toEqual(['zzz', 'aaa', 'bbb', 'help']);18 });1920 test('when sortOptions:true then options sorted alphabetically', () => {
3 unmodified lines
24 .option('--zzz', 'desc')25 .option('--aaa', 'desc')26 .option('--bbb', 'desc');27 const helper = program.createHelp();26 const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name());28 const visibleOptionNames = helper29 .visibleOptions(program)30 .map((cmd) => cmd.name());31 expect(visibleOptionNames).toEqual(['aaa', 'bbb', 'help', 'zzz']);32 });3334 test('when both short and long flags then sort on short flag', () => {
3 unmodified lines
38 .option('-m,--zzz', 'desc')39 .option('-n,--aaa', 'desc')40 .option('-o,--bbb', 'desc');41 const helper = program.createHelp();38 const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name());42 const visibleOptionNames = helper43 .visibleOptions(program)44 .map((cmd) => cmd.name());45 expect(visibleOptionNames).toEqual(['help', 'zzz', 'aaa', 'bbb']);46 });4748 test('when lone short and long flags then sort on lone flag', () => {
3 unmodified lines
52 .option('--zzz', 'desc')53 .option('--aaa', 'desc')54 .option('-b', 'desc');55 const helper = program.createHelp();50 const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name());56 const visibleOptionNames = helper57 .visibleOptions(program)58 .map((cmd) => cmd.name());59 expect(visibleOptionNames).toEqual(['aaa', 'b', 'help', 'zzz']);60 });6162 test('when mixed case flags then sort is case insensitive', () => {
3 unmodified lines
66 .option('-B', 'desc')67 .option('-a', 'desc')68 .option('-c', 'desc');69 const helper = program.createHelp();62 const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name());70 const visibleOptionNames = helper71 .visibleOptions(program)72 .map((cmd) => cmd.name());73 expect(visibleOptionNames).toEqual(['a', 'B', 'c', 'help']);74 });7576 test('when negated option then sort negated option separately', () => {
4 unmodified lines
81 .option('--ccc', 'desc')82 .option('--no-bbb', 'desc')83 .option('--aaa', 'desc');84 const helper = program.createHelp();75 const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name());85 const visibleOptionNames = helper86 .visibleOptions(program)87 .map((cmd) => cmd.name());88 expect(visibleOptionNames).toEqual(['aaa', 'bbb', 'ccc', 'help', 'no-bbb']);89 });90});
modified:tests/help.suggestion.test.js+65 added-34 removed
7 unmodified lines
8 program9 .showSuggestionAfterError() // make sure on10 .exitOverride()11 .configureOutput({12 writeErr: (str) => { message = str; }12 writeErr: (str) => {13 message = str;14 },15 });16 // Do the same setup for subcommand.17 const sub = program._findCommand('sub');18 if (sub) sub.copyInheritedSettings(program);
1 unmodified line
20 try {21 // Passing in an array for a few of the tests.22 const args = Array.isArray(arg) ? arg : [arg];23 program.parse(args, { from: 'user' });22 } catch (err) { /* empty */ }24 } catch (err) {25 /* empty */26 }2728 const match = message.match(/Did you mean (one of )?(.*)\?/);29 return match ? match[2] : null;30}
8 unmodified lines
39 ['bat', ['cat'], 'cat', '1 substitution'],40 ['act', ['cat'], 'cat', '1 transposition'],41 ['cxx', ['cat'], null, '2 edits away and short string'],42 ['caxx', ['cart'], 'cart', '2 edits away and longer string'],39 ['1234567', ['1234567890'], '1234567890', '3 edits away is similar for long string'],43 [44 '1234567',45 ['1234567890'],46 '1234567890',47 '3 edits away is similar for long string',48 ],49 ['123456', ['1234567890'], null, '4 edits is too far'],50 ['xat', ['rat', 'cat', 'bat'], 'bat, cat, rat', 'sorted possibles'],42 ['cart', ['camb', 'cant', 'bard'], 'cant', 'only closest of different edit distances']43])('when cli of %s and commands %j then suggest %s because %s', (arg, commandNames, expected) => {44 const program = new Command();45 commandNames.forEach(name => { program.command(name); });46 const suggestion = getSuggestion(program, arg);47 expect(suggestion).toBe(expected);48});51 [52 'cart',53 ['camb', 'cant', 'bard'],54 'cant',55 'only closest of different edit distances',56 ],57])(58 'when cli of %s and commands %j then suggest %s because %s',59 (arg, commandNames, expected) => {60 const program = new Command();61 commandNames.forEach((name) => {62 program.command(name);63 });64 const suggestion = getSuggestion(program, arg);65 expect(suggestion).toBe(expected);66 },67);6869test('when similar alias then suggest alias', () => {70 const program = new Command();52 program.command('xyz')53 .alias('car');71 program.command('xyz').alias('car');72 const suggestion = getSuggestion(program, 'bar');73 expect(suggestion).toBe('car');74});7576test('when similar hidden alias then not suggested', () => {77 const program = new Command();60 program.command('xyz')61 .alias('visible')62 .alias('silent');78 program.command('xyz').alias('visible').alias('silent');79 const suggestion = getSuggestion(program, 'slent');80 expect(suggestion).toBe(null);81});8283test('when similar command and alias then suggest both', () => {84 const program = new Command();69 program.command('aaaaa')70 .alias('cat');85 program.command('aaaaa').alias('cat');86 program.command('bat');87 program.command('ccccc');88 const suggestion = getSuggestion(program, 'mat');89 expect(suggestion).toBe('bat, cat');
56 unmodified lines
146 ['--bat', ['--cat'], '--cat', '1 substitution'],147 ['--act', ['--cat'], '--cat', '1 transposition'],148 ['--cxx', ['--cat'], null, '2 edits away and short string'],149 ['--caxx', ['--cart'], '--cart', '2 edits away and longer string'],135 ['--1234567', ['--1234567890'], '--1234567890', '3 edits away is similar for long string'],150 [151 '--1234567',152 ['--1234567890'],153 '--1234567890',154 '3 edits away is similar for long string',155 ],156 ['--123456', ['--1234567890'], null, '4 edits is too far'],137 ['--xat', ['--rat', '--cat', '--bat'], '--bat, --cat, --rat', 'sorted possibles'],138 ['--cart', ['--camb', '--cant', '--bard'], '--cant', 'only closest of different edit distances']139])('when cli of %s and options %j then suggest %s because %s', (arg, commandNames, expected) => {140 const program = new Command();141 commandNames.forEach(name => { program.option(name); });142 const suggestion = getSuggestion(program, arg);143 expect(suggestion).toBe(expected);144});157 [158 '--xat',159 ['--rat', '--cat', '--bat'],160 '--bat, --cat, --rat',161 'sorted possibles',162 ],163 [164 '--cart',165 ['--camb', '--cant', '--bard'],166 '--cant',167 'only closest of different edit distances',168 ],169])(170 'when cli of %s and options %j then suggest %s because %s',171 (arg, commandNames, expected) => {172 const program = new Command();173 commandNames.forEach((name) => {174 program.option(name);175 });176 const suggestion = getSuggestion(program, arg);177 expect(suggestion).toBe(expected);178 },179);180181test('when no options then no suggestion', () => {182 // Checking nothing blows up as much as no suggestion!183 const program = new Command();149 program150 .helpOption(false);184 program.helpOption(false);185 const suggestion = getSuggestion(program, '--option');186 expect(suggestion).toBe(null);187});188189test('when subcommand option then candidate for subcommand option suggestion', () => {190 const program = new Command();157 program.command('sub')158 .option('-l,--local');191 program.command('sub').option('-l,--local');192 const suggestion = getSuggestion(program, ['sub', '--loca']);193 expect(suggestion).toBe('--local');194});195
6 unmodified lines
202});203204test('when global option but positionalOptions then not candidate for subcommand suggestion', () => {205 const program = new Command();173 program174 .enablePositionalOptions();206 program.enablePositionalOptions();207 program.option('-g, --global');208 program.command('sub');209 const suggestion = getSuggestion(program, ['sub', '--globla']);210 expect(suggestion).toBe(null);
1 unmodified line
212213test('when global and local options then both candidates', () => {214 const program = new Command();215 program.option('--cat');184 program.command('sub')185 .option('--rat');216 program.command('sub').option('--rat');217 const suggestion = getSuggestion(program, ['sub', '--bat']);218 expect(suggestion).toBe('--cat, --rat');219});220
20 unmodified lines
modified:tests/help.visibleArguments.test.js+14 added-6 removed
21 unmodified lines
22 program.argument('<file>', 'file description');23 const helper = new commander.Help();24 const visibleArguments = helper.visibleArguments(program);25 expect(visibleArguments.length).toEqual(1);26 expect(visibleArguments[0]).toEqual(new commander.Argument('<file>', 'file description'));26 expect(visibleArguments[0]).toEqual(27 new commander.Argument('<file>', 'file description'),28 );29 });3031 test('when argument and legacy argument description then returned', () => {32 const program = new commander.Command();33 program.argument('<file>');34 program.description('', {33 file: 'file description'35 file: 'file description',36 });37 const helper = new commander.Help();38 const visibleArguments = helper.visibleArguments(program);39 expect(visibleArguments.length).toEqual(1);38 expect(visibleArguments[0]).toEqual(new commander.Argument('<file>', 'file description'));40 expect(visibleArguments[0]).toEqual(41 new commander.Argument('<file>', 'file description'),42 );43 });4445 test('when arguments and some described then all returned', () => {46 const program = new commander.Command();
1 unmodified line
48 program.argument('<file2>');49 const helper = new commander.Help();50 const visibleArguments = helper.visibleArguments(program);51 expect(visibleArguments.length).toEqual(2);48 expect(visibleArguments[0]).toEqual(new commander.Argument('<file1>', 'file1 description'));52 expect(visibleArguments[0]).toEqual(53 new commander.Argument('<file1>', 'file1 description'),54 );55 expect(visibleArguments[1]).toEqual(new commander.Argument('<file2>'));56 });5758 test('when arguments and some legacy described then all returned', () => {59 const program = new commander.Command();60 program.argument('<file1>');61 program.argument('<file2>');62 program.description('', {57 file1: 'file1 description'63 file1: 'file1 description',64 });65 const helper = new commander.Help();66 const visibleArguments = helper.visibleArguments(program);67 expect(visibleArguments.length).toEqual(2);62 expect(visibleArguments[0]).toEqual(new commander.Argument('<file1>', 'file1 description'));68 expect(visibleArguments[0]).toEqual(69 new commander.Argument('<file1>', 'file1 description'),70 );71 expect(visibleArguments[1]).toEqual(new commander.Argument('<file2>'));72 });73});
modified:tests/help.visibleCommands.test.js+8 added-6 removed
10 unmodified lines
11 });1213 test('when add command then visible (with help)', () => {14 const program = new commander.Command();15 program16 .command('sub');15 program.command('sub');16 const helper = new commander.Help();18 const visibleCommandNames = helper.visibleCommands(program).map(cmd => cmd.name());17 const visibleCommandNames = helper18 .visibleCommands(program)19 .map((cmd) => cmd.name());20 expect(visibleCommandNames).toEqual(['sub', 'help']);21 });2223 test('when commands hidden then not visible', () => {24 const program = new commander.Command();25 program26 .command('visible', 'desc')27 .command('invisible-executable', 'desc', { hidden: true });27 program28 .command('invisible-action', { hidden: true });28 program.command('invisible-action', { hidden: true });29 const helper = new commander.Help();30 const visibleCommandNames = helper.visibleCommands(program).map(cmd => cmd.name());30 const visibleCommandNames = helper31 .visibleCommands(program)32 .map((cmd) => cmd.name());33 expect(visibleCommandNames).toEqual(['visible', 'help']);34 });35});
modified:tests/help.visibleGlobalOptions.test.js+14 added-16 removed
1const commander = require('../');23test('when default configuration then return empty array', () => {4 const program = new commander.Command();5 program6 .option('--global');5 program.option('--global');6 const sub = program.command('sub');7 const helper = sub.createHelp();8 expect(helper.visibleGlobalOptions(program)).toEqual([]);9});1011test('when showGlobalOptions:true then return program options', () => {12 const program = new commander.Command();14 program15 .option('--global')16 .configureHelp({ showGlobalOptions: true });13 program.option('--global').configureHelp({ showGlobalOptions: true });14 const sub = program.command('sub');15 const helper = sub.createHelp();19 const visibleOptionNames = helper.visibleGlobalOptions(sub).map(option => option.name());16 const visibleOptionNames = helper17 .visibleGlobalOptions(sub)18 .map((option) => option.name());19 expect(visibleOptionNames).toEqual(['global']);20});2122test('when showGlobalOptions:true and program has version then return version', () => {23 const program = new commander.Command();25 program26 .configureHelp({ showGlobalOptions: true })27 .version('1.2.3');24 program.configureHelp({ showGlobalOptions: true }).version('1.2.3');25 const sub = program.command('sub');26 const helper = sub.createHelp();30 const visibleOptionNames = helper.visibleGlobalOptions(sub).map(option => option.name());27 const visibleOptionNames = helper28 .visibleGlobalOptions(sub)29 .map((option) => option.name());30 expect(visibleOptionNames).toEqual(['version']);31});3233test('when showGlobalOptions:true and nested commands then return combined global options', () => {34 const program = new commander.Command();36 program37 .configureHelp({ showGlobalOptions: true })38 .option('--global');39 const sub1 = program.command('sub1')40 .option('--sub1');35 program.configureHelp({ showGlobalOptions: true }).option('--global');36 const sub1 = program.command('sub1').option('--sub1');37 const sub2 = sub1.command('sub2');38 const helper = sub2.createHelp();43 const visibleOptionNames = helper.visibleGlobalOptions(sub2).map(option => option.name());39 const visibleOptionNames = helper40 .visibleGlobalOptions(sub2)41 .map((option) => option.name());42 expect(visibleOptionNames).toEqual(['sub1', 'global']);43});
modified:tests/help.visibleOptions.test.js+9 added-3 removed
5 unmodified lines
6describe('visibleOptions', () => {7 test('when no options then just help visible', () => {8 const program = new commander.Command();9 const helper = new commander.Help();10 const visibleOptionNames = helper.visibleOptions(program).map(option => option.name());10 const visibleOptionNames = helper11 .visibleOptions(program)12 .map((option) => option.name());13 expect(visibleOptionNames).toEqual(['help']);14 });1516 test('when no options and no help option then empty array', () => {
6 unmodified lines
23 test('when add option then visible (with help)', () => {24 const program = new commander.Command();25 program.option('-v,--visible');26 const helper = new commander.Help();25 const visibleOptionNames = helper.visibleOptions(program).map(option => option.name());27 const visibleOptionNames = helper28 .visibleOptions(program)29 .map((option) => option.name());30 expect(visibleOptionNames).toEqual(['visible', 'help']);31 });3233 test('when option hidden then not visible', () => {
1 unmodified line
35 program36 .option('-v,--visible')37 .addOption(new commander.Option('--invisible').hideHelp());38 const helper = new commander.Help();35 const visibleOptionNames = helper.visibleOptions(program).map(option => option.name());39 const visibleOptionNames = helper40 .visibleOptions(program)41 .map((option) => option.name());42 expect(visibleOptionNames).toEqual(['visible', 'help']);43 });44});45
31 unmodified lines
modified:tests/help.wrap.test.js+26 added-20 removed
83 unmodified lines
84 test('when long option description then wrap and indent', () => {85 const program = new commander.Command();86 program87 .configureHelp({ helpWidth: 80 })88 .option('-x --extra-long-option-switch', 'kjsahdkajshkahd kajhsd akhds kashd kajhs dkha dkh aksd ka dkha kdh kasd ka kahs dkh sdkh askdh aksd kashdk ahsd kahs dkha skdh');88 .option(89 '-x --extra-long-option-switch',90 'kjsahdkajshkahd kajhsd akhds kashd kajhs dkha dkh aksd ka dkha kdh kasd ka kahs dkh sdkh askdh aksd kashdk ahsd kahs dkha skdh',91 );9290 const expectedOutput =91`Usage: [options]93 const expectedOutput = `Usage: [options]9495Options:96 -x --extra-long-option-switch kjsahdkajshkahd kajhsd akhds kashd kajhs dkha97 dkh aksd ka dkha kdh kasd ka kahs dkh sdkh
7 unmodified lines
105 test('when long option description and default then wrap and indent', () => {106 const program = new commander.Command();107 program108 .configureHelp({ helpWidth: 80 })107 .option('-x --extra-long-option <value>', 'kjsahdkajshkahd kajhsd akhds', 'aaa bbb ccc ddd eee fff ggg');109 .option(110 '-x --extra-long-option <value>',111 'kjsahdkajshkahd kajhsd akhds',112 'aaa bbb ccc ddd eee fff ggg',113 );114109 const expectedOutput =110`Usage: [options]115 const expectedOutput = `Usage: [options]116117Options:118 -x --extra-long-option <value> kjsahdkajshkahd kajhsd akhds (default: "aaa119 bbb ccc ddd eee fff ggg")
7 unmodified lines
127 const program = new commander.Command();128 program129 .configureHelp({ helpWidth: 80 })130 .option('-x --extra-long-option-switch', 'x')126 .command('alpha', 'Lorem mollit quis dolor ex do eu quis ad insa a commodo esse.');131 .command(132 'alpha',133 'Lorem mollit quis dolor ex do eu quis ad insa a commodo esse.',134 );135128 const expectedOutput =129`Usage: [options] [command]136 const expectedOutput = `Usage: [options] [command]137138Options:139 -x --extra-long-option-switch x140 -h, --help display help for command
9 unmodified lines
150151 test('when not enough room then help not wrapped', () => {152 // Not wrapping if less than 40 columns available for wrapping.153 const program = new commander.Command();154 const commandDescription =147 const commandDescription = 'description text of very long command which should not be automatically be wrapped. Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu.';155 'description text of very long command which should not be automatically be wrapped. Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu.';156 program157 .configureHelp({ helpWidth: 60 })158 .command('1234567801234567890x', commandDescription);159152 const expectedOutput =153`Usage: [options] [command]160 const expectedOutput = `Usage: [options] [command]161162Options:163 -h, --help display help for command164
8 unmodified lines
173 test('when option description pre-formatted then only add small indent', () => {174 // #396: leave custom format alone, apart from space-space indent175 const optionSpec = '-t, --time <HH:MM>';176 const program = new commander.Command();170 program171 .configureHelp({ helpWidth: 80 })172 .option(optionSpec, `select time177 program.configureHelp({ helpWidth: 80 }).option(178 optionSpec,179 `select time180181Time can also be specified using special values:182 "dawn" - From night to sunrise.176`);183`,184 );185178 const expectedOutput =179`Usage: [options]186 const expectedOutput = `Usage: [options]187188Options:189 ${optionSpec} select time190
7 unmodified lines
198 });199200 test('when command description long then wrapped', () => {201 const program = new commander.Command();195 program196 .configureHelp({ helpWidth: 80 })202 program.configureHelp({ helpWidth: 80 })203 .description(`Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu204After line break Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu Do fugiat eiusmod ipsum laboris excepteur pariatur sint ullamco tempor labore eu`);205 const expectedOutput = `Usage: [options]206
13 unmodified lines
modified:tests/incrementNodeInspectorPort.test.js+4 added-2 removed
8 unmodified lines
910 beforeAll(() => {11 spawnSpy = jest.spyOn(childProcess, 'spawn').mockImplementation(() => {12 return {13 on: () => {}13 on: () => {},14 };15 });16 signalSpy = jest.spyOn(process, 'on').mockImplementation(() => {});17 });
10 unmodified lines
2829 function makeProgram() {30 const program = new commander.Command();31 const fileWhichExists = path.join(__dirname, './fixtures/pm-cache.js');32 program.command('cache', 'stand-alone command', { executableFile: fileWhichExists });32 program.command('cache', 'stand-alone command', {33 executableFile: fileWhichExists,34 });35 return program;36 }3738 function extractMockExecArgs(mock) {
99 unmodified lines
modified:tests/option.chain.test.js+1 added-1 removed
7 unmodified lines
8 });910 test('when call .argParser() then returns this', () => {11 const option = new Option('-e,--example <value>');12 const result = option.argParser(() => { });12 const result = option.argParser(() => {});13 expect(result).toBe(option);14 });1516 test('when call .makeOptionMandatory() then returns this', () => {
29 unmodified lines
modified:tests/options.bool.combo.test.js+5 added-1 removed
120 unmodified lines
121describe('boolean option combo with non-boolean default and preset', () => {122 function createPepperProgramWithDefaultAndPreset() {123 const program = new commander.Command();124 program125 .addOption(new commander.Option('-p, --pepper').default('default').preset('preset'))125 .addOption(126 new commander.Option('-p, --pepper')127 .default('default')128 .preset('preset'),129 )130 .option('-P, --no-pepper', 'remove pepper');131 return program;132 }133
18 unmodified lines
modified:tests/options.bool.test.js+20 added-20 removed
4 unmodified lines
5// boolean flag on program6describe('boolean flag on program', () => {7 test('when boolean flag not specified then value is undefined', () => {8 const program = new commander.Command();9 program10 .option('--pepper', 'add pepper');9 program.option('--pepper', 'add pepper');10 program.parse(['node', 'test']);11 expect(program.opts().pepper).toBeUndefined();12 });1314 test('when boolean flag specified then value is true', () => {15 const program = new commander.Command();17 program18 .option('--pepper', 'add pepper');16 program.option('--pepper', 'add pepper');17 program.parse(['node', 'test', '--pepper']);18 expect(program.opts().pepper).toBe(true);19 });2021 test('when negatable boolean flag not specified then value is true', () => {22 const program = new commander.Command();25 program26 .option('--no-cheese', 'remove cheese');23 program.option('--no-cheese', 'remove cheese');24 program.parse(['node', 'test']);25 expect(program.opts().cheese).toBe(true);26 });2728 test('when negatable boolean flag specified then value is false', () => {29 const program = new commander.Command();33 program34 .option('--no-cheese', 'remove cheese');30 program.option('--no-cheese', 'remove cheese');31 program.parse(['node', 'test', '--no-cheese']);32 expect(program.opts().cheese).toBe(false);33 });34});
5 unmodified lines
40 const program = new commander.Command();41 program42 .command('sub')43 .option('--pepper', 'add pepper')48 .action((options) => { subCommandOptions = options; });44 .action((options) => {45 subCommandOptions = options;46 });47 program.parse(['node', 'test', 'sub']);48 expect(subCommandOptions.pepper).toBeUndefined();49 });50
2 unmodified lines
53 const program = new commander.Command();54 program55 .command('sub')56 .option('--pepper', 'add pepper')59 .action((options) => { subCommandOptions = options; });57 .action((options) => {58 subCommandOptions = options;59 });60 program.parse(['node', 'test', 'sub', '--pepper']);61 expect(subCommandOptions.pepper).toBe(true);62 });63
2 unmodified lines
66 const program = new commander.Command();67 program68 .command('sub')69 .option('--no-cheese', 'remove cheese')70 .action((options) => { subCommandOptions = options; });70 .action((options) => {71 subCommandOptions = options;72 });73 program.parse(['node', 'test', 'sub']);74 expect(subCommandOptions.cheese).toBe(true);75 });76
2 unmodified lines
79 const program = new commander.Command();80 program81 .command('sub')82 .option('--no-cheese', 'remove cheese')81 .action((options) => { subCommandOptions = options; });83 .action((options) => {84 subCommandOptions = options;85 });86 program.parse(['node', 'test', 'sub', '--no-cheese']);87 expect(subCommandOptions.cheese).toBe(false);88 });89});
4 unmodified lines
94describe('boolean flag with non-boolean default', () => {95 test('when flag not specified then value is "default"', () => {96 const flagValue = 'black';97 const program = new commander.Command();94 program95 .option('--olives', 'Add green olives?', flagValue);98 program.option('--olives', 'Add green olives?', flagValue);99 program.parse(['node', 'test']);100 expect(program.opts().olives).toBe(flagValue);101 });102103 test('when flag specified then value is true', () => {104 const flagValue = 'black';105 const program = new commander.Command();103 program104 .option('-v, --olives', 'Add green olives?', flagValue);106 program.option('-v, --olives', 'Add green olives?', flagValue);107 program.parse(['node', 'test', '--olives']);108 expect(program.opts().olives).toBe(true);109 });110
11 unmodified lines
122// Regression test for #1301 with `-no-` in middle of option123describe('regression test for -no- in middle of option flag', () => {124 test('when flag not specified then value is undefined', () => {125 const program = new commander.Command();124 program125 .option('--module-no-parse');126 program.option('--module-no-parse');127 program.parse(['node', 'test']);128 expect(program.opts().moduleNoParse).toBeUndefined();129 });130131 test('when flag specified then value is true', () => {132 const program = new commander.Command();132 program133 .option('--module-no-parse');133 program.option('--module-no-parse');134 program.parse(['node', 'test', '--module-no-parse']);135 expect(program.opts().moduleNoParse).toEqual(true);136 });137});
modified:tests/options.camelcase.test.js+6 added-12 removed
2 unmodified lines
3// Capitalise the letters of words after dashes, but otherwise preserve case45test('when option defined with --word-word then option property is wordWord', () => {6 const program = new commander.Command();7 program8 .option('--my-option', 'description');7 program.option('--my-option', 'description');8 program.parse(['node', 'test', '--my-option']);9 expect(program.opts().myOption).toBe(true);10});1112test('when option defined with --word-wORD then option property is wordWORD', () => {13 const program = new commander.Command();15 program16 .option('--my-oPTION', 'description');14 program.option('--my-oPTION', 'description');15 program.parse(['node', 'test', '--my-oPTION']);16 expect(program.opts().myOPTION).toBe(true);17});1819test('when option defined with --word-WORD then option property is wordWORD', () => {20 const program = new commander.Command();23 program24 .option('--my-OPTION', 'description');21 program.option('--my-OPTION', 'description');22 program.parse(['node', 'test', '--my-OPTION']);23 expect(program.opts().myOPTION).toBe(true);24});2526test('when option defined with --word-word-word then option property is wordWordWord', () => {27 const program = new commander.Command();31 program32 .option('--my-special-option', 'description');28 program.option('--my-special-option', 'description');29 program.parse(['node', 'test', '--my-special-option']);30 expect(program.opts().mySpecialOption).toBe(true);31});3233test('when option defined with --word-WORD-word then option property is wordWORDWord', () => {34 const program = new commander.Command();39 program40 .option('--my-SPECIAL-option', 'description');35 program.option('--my-SPECIAL-option', 'description');36 program.parse(['node', 'test', '--my-SPECIAL-option']);37 expect(program.opts().mySPECIALOption).toBe(true);38});3940test('when option defined with --Word then option property is Word', () => {41 const program = new commander.Command();47 program48 .option('--Myoption', 'description');42 program.option('--Myoption', 'description');43 program.parse(['node', 'test', '--Myoption']);44 expect(program.opts().Myoption).toBe(true);45});
modified:tests/options.choices.test.js+8 added-4 removed
2 unmodified lines
3test('when option argument in choices then option set', () => {4 const program = new commander.Command();5 program6 .exitOverride()7 .addOption(new commander.Option('--colour <shade>').choices(['red', 'blue']));7 .addOption(8 new commander.Option('--colour <shade>').choices(['red', 'blue']),9 );10 program.parse(['--colour', 'red'], { from: 'user' });11 expect(program.opts().colour).toBe('red');12});13
2 unmodified lines
16 const program = new commander.Command();17 program18 .exitOverride()19 .configureOutput({18 writeErr: () => {}20 writeErr: () => {},21 })20 .addOption(new commander.Option('--colour <shade>').choices(['red', 'blue']));22 .addOption(23 new commander.Option('--colour <shade>').choices(['red', 'blue']),24 );25 expect(() => {26 program.parse(['--colour', 'orange'], { from: 'user' });27 }).toThrow();28});
20 unmodified lines
49 const param = ['red', 'blue'];50 program51 .exitOverride()52 .configureOutput({49 writeErr: () => {}53 writeErr: () => {},54 })55 .addOption(new commander.Option('--colour <shade>').choices(param));56 param.push('orange');57 expect(() => {
4 unmodified lines
modified:tests/options.conflicts.test.js+53 added-19 removed
7 unmodified lines
8 program9 .exitOverride()10 .configureOutput({11 writeErr: () => {},12 writeOut: () => {}12 writeOut: () => {},13 })14 .command('foo')15 .addOption(new commander.Option('-s, --silent', "Don't print anything").env('SILENT'))15 .addOption(17 new commander.Option('-j, --json', 'Format output as json').env('JSON').conflicts([18 'silent'19 ])16 new commander.Option('-s, --silent', "Don't print anything").env(17 'SILENT',18 ),19 )20 .addOption(21 new commander.Option('-j, --json', 'Format output as json')22 .env('JSON')23 .conflicts(['silent']),24 )25 .action(actionMock);2627 return { program, actionMock };28 }
17 unmodified lines
46 program.parse('node test.js foo --silent'.split(' '));47 expect(actionMock).toHaveBeenCalledTimes(1);48 expect(actionMock).toHaveBeenCalledWith(49 { silent: true },46 expect.any(Object)50 expect.any(Object),51 );52 });5354 test('should exit with error if conflicting options were set', () => {55 const { program } = makeProgram();5657 expect(() => {58 program.parse('node test.js foo --silent --json'.split(' '));55 }).toThrow("error: option '-j, --json' cannot be used with option '-s, --silent'");59 }).toThrow(60 "error: option '-j, --json' cannot be used with option '-s, --silent'",61 );62 });6364 test('should report the env variable as the conflicting option source, when conflicting option is set', () => {65 const { program } = makeProgram();
1 unmodified line
67 process.env.SILENT = true;6869 expect(() => {70 program.parse('node test.js foo --json'.split(' '));65 }).toThrow("error: option '-j, --json' cannot be used with environment variable 'SILENT'");71 }).toThrow(72 "error: option '-j, --json' cannot be used with environment variable 'SILENT'",73 );74 });7576 test('should report the env variable as the configured option source, when configured option is set', () => {77 const { program } = makeProgram();
1 unmodified line
79 process.env.JSON = true;8081 expect(() => {82 program.parse('node test.js foo --silent'.split(' '));75 }).toThrow("error: environment variable 'JSON' cannot be used with option '-s, --silent'");83 }).toThrow(84 "error: environment variable 'JSON' cannot be used with option '-s, --silent'",85 );86 });8788 test('should report both env variables as sources, when configured option and conflicting option are set', () => {89 const { program } = makeProgram();
2 unmodified lines
92 process.env.JSON = true;9394 expect(() => {95 program.parse('node test.js foo'.split(' '));86 }).toThrow("error: environment variable 'JSON' cannot be used with environment variable 'SILENT'");96 }).toThrow(97 "error: environment variable 'JSON' cannot be used with environment variable 'SILENT'",98 );99 });100101 test('should allow default value with a conflicting option', () => {102 const { program, actionMock } = makeProgram();10392 program.commands[0].addOption(new commander.Option('-d, --debug', 'print debug logs').default(true).conflicts(['silent']));104 program.commands[0].addOption(105 new commander.Option('-d, --debug', 'print debug logs')106 .default(true)107 .conflicts(['silent']),108 );109110 program.parse('node test.js foo --silent'.split(' '));111112 expect(actionMock).toHaveBeenCalledTimes(1);97 expect(actionMock).toHaveBeenCalledWith({ debug: true, silent: true }, expect.any(Object));113 expect(actionMock).toHaveBeenCalledWith(114 { debug: true, silent: true },115 expect.any(Object),116 );117 });118119 test('should report conflict on negated option flag', () => {120 const { program } = makeProgram();
5 unmodified lines
126 .addOption(new commander.Option('-N, --no-color'));127128 expect(() => {129 program.parse('node test.js bar --red -N'.split(' '));111 }).toThrow("error: option '--red' cannot be used with option '-N, --no-color'");130 }).toThrow(131 "error: option '--red' cannot be used with option '-N, --no-color'",132 );133 });134135 test('should report conflict on negated option env variable', () => {136 const { program } = makeProgram();
7 unmodified lines
144 .addOption(new commander.Option('-N, --no-color').env('NO_COLOR'));145146 expect(() => {147 program.parse('node test.js bar --red'.split(' '));127 }).toThrow("error: option '--red' cannot be used with environment variable 'NO_COLOR'");148 }).toThrow(149 "error: option '--red' cannot be used with environment variable 'NO_COLOR'",150 );151 });152153 test('should report correct error for shorthand negated option', () => {154 const { program } = makeProgram();
4 unmodified lines
159 .addOption(new commander.Option('-N, --no-color').conflicts(['red']));160161 expect(() => {162 program.parse('node test.js bar --red -N'.split(' '));140 }).toThrow("error: option '-N, --no-color' cannot be used with option '--red'");163 }).toThrow(164 "error: option '-N, --no-color' cannot be used with option '--red'",165 );166 });167168 test('should report correct error for positive option when negated is configured', () => {169 const { program } = makeProgram();
34 unmodified lines
204205 process.env.DUAL = 'true';206 expect(() => {207 program.parse('node test.js bar --red'.split(' '));183 }).toThrow("error: environment variable 'DUAL' cannot be used with option '--red'");208 }).toThrow(209 "error: environment variable 'DUAL' cannot be used with option '--red'",210 );211 });212213 test('should report correct error for negated env variable when positive is configured', () => {214 const { program } = makeProgram();
6 unmodified lines
221222 process.env.NO_DUAL = 'true';223 expect(() => {224 program.parse('node test.js bar --red'.split(' '));198 }).toThrow("error: environment variable 'NO_DUAL' cannot be used with option '--red'");225 }).toThrow(226 "error: environment variable 'NO_DUAL' cannot be used with option '--red'",227 );228 });229230 test('should report correct error for positive option with string value when negated is configured', () => {231 const { program } = makeProgram();
5 unmodified lines
237 .addOption(new commander.Option('--no-dual2').preset('BAD'));238239 expect(() => {240 program.parse('node test.js bar --red --dual2 foo'.split(' '));212 }).toThrow("error: option '--dual2 <str>' cannot be used with option '--red'");241 }).toThrow(242 "error: option '--dual2 <str>' cannot be used with option '--red'",243 );244 });245246 test('should report correct error for negated option with preset when negated is configured', () => {247 const { program } = makeProgram();
22 unmodified lines
270271 program.parse('node test.js bar --a --b'.split(' '));272273 expect(actionMock).toHaveBeenCalledTimes(1);243 expect(actionMock).toHaveBeenCalledWith({ a: true, b: true }, expect.any(Object));274 expect(actionMock).toHaveBeenCalledWith(275 { a: true, b: true },276 expect.any(Object),277 );278 });279280 test('should throw error when conflicts is invoked with a single string that equals another option', () => {281 const { program } = makeProgram();
64 unmodified lines
modified:tests/options.custom-processing.test.js+24 added-28 removed
18 unmodified lines
1920test('when option not specified then callback not called', () => {21 const mockCoercion = jest.fn();22 const program = new commander.Command();23 program24 .option('-i, --integer <n>', 'number', mockCoercion);23 program.option('-i, --integer <n>', 'number', mockCoercion);24 program.parse(['node', 'test']);25 expect(mockCoercion).not.toHaveBeenCalled();26});2728test('when option not specified then value is undefined', () => {29 const program = new commander.Command();31 program32 .option('-i, --integer <n>', 'number', myParseInt);30 program.option('-i, --integer <n>', 'number', myParseInt);31 program.parse(['node', 'test']);32 expect(program.opts().integer).toBeUndefined();33});3435test('when starting value is defined and option not specified then callback not called', () => {36 const mockCoercion = jest.fn();37 const program = new commander.Command();40 program41 .option('-i, --integer <n>', 'number', mockCoercion, 1);38 program.option('-i, --integer <n>', 'number', mockCoercion, 1);39 program.parse(['node', 'test']);40 expect(mockCoercion).not.toHaveBeenCalled();41});4243test('when starting value is defined and option not specified then value is starting value', () => {44 // NB: Can not specify a starting value for a boolean flag! Discovered when writing this test...45 const startingValue = 1;46 const program = new commander.Command();50 program51 .option('-i, --integer <n>', 'number', myParseInt, startingValue);47 program.option('-i, --integer <n>', 'number', myParseInt, startingValue);48 program.parse(['node', 'test']);49 expect(program.opts().integer).toBe(startingValue);50});5152test('when option specified then callback called with value', () => {53 const mockCoercion = jest.fn();54 const value = '1';55 const program = new commander.Command();60 program61 .option('-i, --integer <n>', 'number', mockCoercion);56 program.option('-i, --integer <n>', 'number', mockCoercion);57 program.parse(['node', 'test', '-i', value]);58 expect(mockCoercion).toHaveBeenCalledWith(value, undefined);59});6061test('when option specified then value is as returned from callback', () => {62 const callbackResult = 2;63 const program = new commander.Command();69 program70 .option('-i, --integer <n>', 'number', () => {71 return callbackResult;72 });64 program.option('-i, --integer <n>', 'number', () => {65 return callbackResult;66 });67 program.parse(['node', 'test', '-i', '0']);68 expect(program.opts().integer).toBe(callbackResult);69});70
1 unmodified line
72 const mockCoercion = jest.fn();73 const startingValue = 1;74 const value = '2';75 const program = new commander.Command();82 program83 .option('-i, --integer <n>', 'number', mockCoercion, startingValue);76 program.option('-i, --integer <n>', 'number', mockCoercion, startingValue);77 program.parse(['node', 'test', '-i', value]);78 expect(mockCoercion).toHaveBeenCalledWith(value, startingValue);79});80
1 unmodified line
82 const mockCoercion = jest.fn().mockImplementation(() => {83 return 'callback';84 });85 const program = new commander.Command();93 program94 .option('-i, --integer <n>', 'number', mockCoercion);86 program.option('-i, --integer <n>', 'number', mockCoercion);87 program.parse(['node', 'test', '-i', '1', '-i', '2']);88 expect(mockCoercion).toHaveBeenCalledTimes(2);89 expect(mockCoercion).toHaveBeenNthCalledWith(1, '1', undefined);90 expect(mockCoercion).toHaveBeenNthCalledWith(2, '2', 'callback');
2 unmodified lines
93// Now some functional tests like the examples in the README!9495test('when parseFloat "1e2" then value is 100', () => {96 const program = new commander.Command();105 program106 .option('-f, --float <number>', 'float argument', parseFloat);97 program.option('-f, --float <number>', 'float argument', parseFloat);98 program.parse(['node', 'test', '-f', '1e2']);99 expect(program.opts().float).toBe(100);100});101102test('when myParseInt "1" then value is 1', () => {103 const program = new commander.Command();113 program114 .option('-i, --integer <number>', 'integer argument', myParseInt);104 program.option('-i, --integer <number>', 'integer argument', myParseInt);105 program.parse(['node', 'test', '-i', '1']);106 expect(program.opts().integer).toBe(1);107});108109test('when increaseVerbosity -v -v -v then value is 3', () => {110 const program = new commander.Command();121 program122 .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0);111 program.option(112 '-v, --verbose',113 'verbosity that can be increased',114 increaseVerbosity,115 0,116 );117 program.parse(['node', 'test', '-v', '-v', '-v']);118 expect(program.opts().verbose).toBe(3);119});120121test('when collect -c a -c b -c c then value is [a, b, c]', () => {122 const program = new commander.Command();129 program130 .option('-c, --collect <value>', 'repeatable value', collect, []);123 program.option('-c, --collect <value>', 'repeatable value', collect, []);124 program.parse(['node', 'test', '-c', 'a', '-c', 'b', '-c', 'c']);125 expect(program.opts().collect).toEqual(['a', 'b', 'c']);126});127128test('when commaSeparatedList x,y,z then value is [x, y, z]', () => {129 const program = new commander.Command();137 program138 .option('-l, --list <items>', 'comma separated list', commaSeparatedList);130 program.option(131 '-l, --list <items>',132 'comma separated list',133 commaSeparatedList,134 );135 program.parse(['node', 'test', '--list', 'x,y,z']);136 expect(program.opts().list).toEqual(['x', 'y', 'z']);137});
modified:tests/options.dual-options.test.js+3 added-9 removed
21 unmodified lines
22});2324test('when unrelated positive and negative options then no dual options', () => {25 const program = new Command();26 program27 .option('--one')28 .option('--no-two');26 program.option('--one').option('--no-two');27 const helper = new DualOptions(program.options);28 expect(helper.dualOptions.size).toEqual(0);29});3031test('when related positive and negative options then stored as dual option', () => {32 const program = new Command();35 program36 .option('--one')37 .option('--no-one');33 program.option('--one').option('--no-one');34 const helper = new DualOptions(program.options);35 expect(helper.dualOptions.size).toEqual(1);36});3738test('when related negative and positive options then stored as dual option', () => {39 const program = new Command();44 program45 .option('--no-one')46 .option('--one');40 program.option('--no-one').option('--one');41 const helper = new DualOptions(program.options);42 expect(helper.dualOptions.size).toEqual(1);43});44
51 unmodified lines
modified:tests/options.env.test.js+100 added-73 removed
1const commander = require('../');23// treating optional same as required, treat as option taking value rather than as boolean4describe.each(['-f, --foo <required-arg>', '-f, --foo [optional-arg]'])(5 'option declared as: %s',4describe.each(['-f, --foo <required-arg>', '-f, --foo [optional-arg]'])('option declared as: %s', (fooFlags) => {5 test('when env undefined and no cli then option undefined', () => {6 const program = new commander.Command();7 program.addOption(new commander.Option(fooFlags).env('BAR'));8 program.parse([], { from: 'user' });9 expect(program.opts().foo).toBeUndefined();10 });6 (fooFlags) => {7 test('when env undefined and no cli then option undefined', () => {8 const program = new commander.Command();9 program.addOption(new commander.Option(fooFlags).env('BAR'));10 program.parse([], { from: 'user' });11 expect(program.opts().foo).toBeUndefined();12 });1312 test('when env defined and no cli then option from env', () => {13 const program = new commander.Command();14 process.env.BAR = 'env';15 program.addOption(new commander.Option(fooFlags).env('BAR'));16 program.parse([], { from: 'user' });17 expect(program.opts().foo).toBe('env');18 delete process.env.BAR;19 });14 test('when env defined and no cli then option from env', () => {15 const program = new commander.Command();16 process.env.BAR = 'env';17 program.addOption(new commander.Option(fooFlags).env('BAR'));18 program.parse([], { from: 'user' });19 expect(program.opts().foo).toBe('env');20 delete process.env.BAR;21 });2221 test('when env defined and cli then option from cli', () => {22 const program = new commander.Command();23 process.env.BAR = 'env';24 program.addOption(new commander.Option(fooFlags).env('BAR'));25 program.parse(['--foo', 'cli'], { from: 'user' });26 expect(program.opts().foo).toBe('cli');27 delete process.env.BAR;28 });23 test('when env defined and cli then option from cli', () => {24 const program = new commander.Command();25 process.env.BAR = 'env';26 program.addOption(new commander.Option(fooFlags).env('BAR'));27 program.parse(['--foo', 'cli'], { from: 'user' });28 expect(program.opts().foo).toBe('cli');29 delete process.env.BAR;30 });3130 test('when env defined and value source is config then option from env', () => {31 const program = new commander.Command();32 process.env.BAR = 'env';33 program.addOption(new commander.Option(fooFlags).env('BAR'));34 program.setOptionValueWithSource('foo', 'config', 'config');35 program.parse([], { from: 'user' });36 expect(program.opts().foo).toBe('env');37 delete process.env.BAR;38 });32 test('when env defined and value source is config then option from env', () => {33 const program = new commander.Command();34 process.env.BAR = 'env';35 program.addOption(new commander.Option(fooFlags).env('BAR'));36 program.setOptionValueWithSource('foo', 'config', 'config');37 program.parse([], { from: 'user' });38 expect(program.opts().foo).toBe('env');39 delete process.env.BAR;40 });4140 test('when env defined and value source is unspecified then option unchanged', () => {41 const program = new commander.Command();42 process.env.BAR = 'env';43 program.addOption(new commander.Option(fooFlags).env('BAR'));44 program.setOptionValue('foo', 'client');45 program.parse([], { from: 'user' });46 expect(program.opts().foo).toBe('client');47 delete process.env.BAR;48 });42 test('when env defined and value source is unspecified then option unchanged', () => {43 const program = new commander.Command();44 process.env.BAR = 'env';45 program.addOption(new commander.Option(fooFlags).env('BAR'));46 program.setOptionValue('foo', 'client');47 program.parse([], { from: 'user' });48 expect(program.opts().foo).toBe('client');49 delete process.env.BAR;50 });5150 test('when default and env undefined and no cli then option from default', () => {51 const program = new commander.Command();52 program.addOption(new commander.Option(fooFlags).env('BAR').default('default'));53 program.parse([], { from: 'user' });54 expect(program.opts().foo).toBe('default');55 });52 test('when default and env undefined and no cli then option from default', () => {53 const program = new commander.Command();54 program.addOption(55 new commander.Option(fooFlags).env('BAR').default('default'),56 );57 program.parse([], { from: 'user' });58 expect(program.opts().foo).toBe('default');59 });6057 test('when default and env defined and no cli then option from env', () => {58 const program = new commander.Command();59 process.env.BAR = 'env';60 program.addOption(new commander.Option(fooFlags).env('BAR').default('default'));61 program.parse([], { from: 'user' });62 expect(program.opts().foo).toBe('env');63 delete process.env.BAR;64 });61 test('when default and env defined and no cli then option from env', () => {62 const program = new commander.Command();63 process.env.BAR = 'env';64 program.addOption(65 new commander.Option(fooFlags).env('BAR').default('default'),66 );67 program.parse([], { from: 'user' });68 expect(program.opts().foo).toBe('env');69 delete process.env.BAR;70 });7166 test('when default and env defined and cli then option from cli', () => {67 const program = new commander.Command();68 process.env.BAR = 'env';69 program.addOption(new commander.Option(fooFlags).env('BAR').default('default'));70 program.parse(['--foo', 'cli'], { from: 'user' });71 expect(program.opts().foo).toBe('cli');72 delete process.env.BAR;73 });74});72 test('when default and env defined and cli then option from cli', () => {73 const program = new commander.Command();74 process.env.BAR = 'env';75 program.addOption(76 new commander.Option(fooFlags).env('BAR').default('default'),77 );78 program.parse(['--foo', 'cli'], { from: 'user' });79 expect(program.opts().foo).toBe('cli');80 delete process.env.BAR;81 });82 },83);8485describe('boolean flag', () => {86 test('when env undefined and no cli then option undefined', () => {87 const program = new commander.Command();
118 unmodified lines
206describe('custom argParser', () => {207 test('when env defined and no cli then custom parse from env', () => {208 const program = new commander.Command();209 process.env.BAR = 'env';201 program.addOption(new commander.Option('-f, --foo <required>').env('BAR').argParser(str => str.toUpperCase()));210 program.addOption(211 new commander.Option('-f, --foo <required>')212 .env('BAR')213 .argParser((str) => str.toUpperCase()),214 );215 program.parse([], { from: 'user' });216 expect(program.opts().foo).toBe('ENV');217 delete process.env.BAR;218 });
2 unmodified lines
221describe('variadic', () => {222 test('when env defined and no cli then array from env', () => {223 const program = new commander.Command();224 process.env.BAR = 'env';212 program.addOption(new commander.Option('-f, --foo <required...>').env('BAR'));225 program.addOption(226 new commander.Option('-f, --foo <required...>').env('BAR'),227 );228 program.parse([], { from: 'user' });229 expect(program.opts().foo).toEqual(['env']);230 delete process.env.BAR;231 });232233 test('when env defined and cli then array from cli', () => {234 const program = new commander.Command();235 process.env.BAR = 'env';221 program.addOption(new commander.Option('-f, --foo <required...>').env('BAR'));236 program.addOption(237 new commander.Option('-f, --foo <required...>').env('BAR'),238 );239 program.parse(['--foo', 'cli'], { from: 'user' });240 expect(program.opts().foo).toEqual(['cli']);241 delete process.env.BAR;242 });
3 unmodified lines
246 test('when env defined on another subcommand then env not applied', () => {247 // Doing selective processing. Not processing env at addOption time.248 const program = new commander.Command();249 process.env.BAR = 'env';233 program.command('one')250 program.command('one').action(() => {});251 const two = program252 .command('two')253 .addOption(254 new commander.Option('-f, --foo <required...>')255 .env('BAR')256 .default('default'),257 )258 .action(() => {});235 const two = program.command('two')236 .addOption(new commander.Option('-f, --foo <required...>').env('BAR').default('default'))237 .action(() => {});259 program.parse(['one'], { from: 'user' });260 expect(two.opts().foo).toBe('default');261 delete process.env.BAR;262 });
4 unmodified lines
267 const optionEnvEventMock = jest.fn();268 program.on('option:foo', optionEventMock);269 program.on('optionEnv:foo', optionEnvEventMock);270 process.env.BAR = 'env';250 program.addOption(new commander.Option('-f, --foo <required...>').env('BAR'));271 program.addOption(272 new commander.Option('-f, --foo <required...>').env('BAR'),273 );274 program.parse(['--foo', 'cli'], { from: 'user' });275 expect(optionEventMock).toHaveBeenCalledWith('cli');276 expect(optionEventMock).toHaveBeenCalledTimes(1);277 expect(optionEnvEventMock).toHaveBeenCalledTimes(0);
3 unmodified lines
281 test('when env and cli defined then only parse value for cli', () => {282 const program = new commander.Command();283 const parseMock = jest.fn();284 process.env.BAR = 'env';262 program.addOption(new commander.Option('-f, --foo <required...>').env('BAR').argParser(parseMock));285 program.addOption(286 new commander.Option('-f, --foo <required...>')287 .env('BAR')288 .argParser(parseMock),289 );290 program.parse(['--foo', 'cli'], { from: 'user' });291 expect(parseMock).toHaveBeenCalledWith('cli', undefined);292 expect(parseMock).toHaveBeenCalledTimes(1);293 delete process.env.BAR;
62 unmodified lines
modified:tests/options.flags.test.js+10 added-20 removed
2 unmodified lines
3// Test the various ways flags can be specified in the first parameter to `.option`45test('when only short flag defined and not specified then value is undefined', () => {6 const program = new commander.Command();7 program8 .option('-p', 'add pepper');7 program.option('-p', 'add pepper');8 program.parse(['node', 'test']);9 expect(program.opts().p).toBeUndefined();10});1112test('when only short flag defined and specified then value is true', () => {13 const program = new commander.Command();15 program16 .option('-p', 'add pepper');14 program.option('-p', 'add pepper');15 program.parse(['node', 'test', '-p']);16 expect(program.opts().p).toBe(true);17});1819test('when only long flag defined and not specified then value is undefined', () => {20 const program = new commander.Command();23 program24 .option('--pepper', 'add pepper');21 program.option('--pepper', 'add pepper');22 program.parse(['node', 'test']);23 expect(program.opts().pepper).toBeUndefined();24});2526test('when only long flag defined and specified then value is true', () => {27 const program = new commander.Command();31 program32 .option('--pepper', 'add pepper');28 program.option('--pepper', 'add pepper');29 program.parse(['node', 'test', '--pepper']);30 expect(program.opts().pepper).toBe(true);31});3233test('when "short,long" flags defined and short specified then value is true', () => {34 const program = new commander.Command();39 program40 .option('-p,--pepper', 'add pepper');35 program.option('-p,--pepper', 'add pepper');36 program.parse(['node', 'test', '-p']);37 expect(program.opts().pepper).toBe(true);38});3940test('when "short,long" flags defined and long specified then value is true', () => {41 const program = new commander.Command();47 program48 .option('-p,--pepper', 'add pepper');42 program.option('-p,--pepper', 'add pepper');43 program.parse(['node', 'test', '--pepper']);44 expect(program.opts().pepper).toBe(true);45});4647test('when "short|long" flags defined and short specified then value is true', () => {48 const program = new commander.Command();55 program56 .option('-p|--pepper', 'add pepper');49 program.option('-p|--pepper', 'add pepper');50 program.parse(['node', 'test', '-p']);51 expect(program.opts().pepper).toBe(true);52});5354test('when "short|long" flags defined and long specified then value is true', () => {55 const program = new commander.Command();63 program64 .option('-p|--pepper', 'add pepper');56 program.option('-p|--pepper', 'add pepper');57 program.parse(['node', 'test', '--pepper']);58 expect(program.opts().pepper).toBe(true);59});6061test('when "short long" flags defined and short specified then value is true', () => {62 const program = new commander.Command();71 program72 .option('-p --pepper', 'add pepper');63 program.option('-p --pepper', 'add pepper');64 program.parse(['node', 'test', '-p']);65 expect(program.opts().pepper).toBe(true);66});6768test('when "short long" flags defined and long specified then value is true', () => {69 const program = new commander.Command();79 program80 .option('-p --pepper', 'add pepper');70 program.option('-p --pepper', 'add pepper');71 program.parse(['node', 'test', '--pepper']);72 expect(program.opts().pepper).toBe(true);73});
modified:tests/options.getset.test.js+27 added-27 removed
1const commander = require('../');23describe.each([true, false])(4 'storeOptionsAsProperties is %s',3describe.each([true, false])('storeOptionsAsProperties is %s', (storeOptionsAsProperties) => {4 test('when option specified on CLI then value returned by getOptionValue', () => {5 const program = new commander.Command();6 program7 .storeOptionsAsProperties(storeOptionsAsProperties)8 .option('--cheese [type]', 'cheese type');9 const cheeseType = 'blue';10 program.parse(['node', 'test', '--cheese', cheeseType]);11 expect(program.getOptionValue('cheese')).toBe(cheeseType);12 });5 (storeOptionsAsProperties) => {6 test('when option specified on CLI then value returned by getOptionValue', () => {7 const program = new commander.Command();8 program9 .storeOptionsAsProperties(storeOptionsAsProperties)10 .option('--cheese [type]', 'cheese type');11 const cheeseType = 'blue';12 program.parse(['node', 'test', '--cheese', cheeseType]);13 expect(program.getOptionValue('cheese')).toBe(cheeseType);14 });1514 test('when setOptionValue then value returned by opts', () => {15 const program = new commander.Command();16 const cheeseType = 'blue';17 // Note: opts() only returns declared options when options stored as properties18 program19 .storeOptionsAsProperties(storeOptionsAsProperties)20 .option('--cheese [type]', 'cheese type')21 .setOptionValue('cheese', cheeseType);22 expect(program.opts().cheese).toBe(cheeseType);23 });24});16 test('when setOptionValue then value returned by opts', () => {17 const program = new commander.Command();18 const cheeseType = 'blue';19 // Note: opts() only returns declared options when options stored as properties20 program21 .storeOptionsAsProperties(storeOptionsAsProperties)22 .option('--cheese [type]', 'cheese type')23 .setOptionValue('cheese', cheeseType);24 expect(program.opts().cheese).toBe(cheeseType);25 });26 },27);2829test('when setOptionValueWithSource then value returned by opts', () => {30 const program = new commander.Command();31 const cheeseValue = 'blue';
13 unmodified lines
4546test('when option value parsed from env then option source is env', () => {47 const program = new commander.Command();48 process.env.BAR = 'env';46 program47 .addOption(new commander.Option('-f, --foo').env('BAR'));49 program.addOption(new commander.Option('-f, --foo').env('BAR'));50 program.parse([], { from: 'user' });51 expect(program.getOptionValueSource('foo')).toBe('env');52 delete process.env.BAR;53});5455test('when option value parsed from cli then option source is cli', () => {56 const program = new commander.Command();55 program56 .addOption(new commander.Option('-f, --foo').env('BAR'));57 program.addOption(new commander.Option('-f, --foo').env('BAR'));58 program.parse(['--foo'], { from: 'user' });59 expect(program.getOptionValueSource('foo')).toBe('cli');60});6162test('when setOptionValue then clears previous source', () => {63 const program = new commander.Command();63 program64 .option('--foo', 'description', 'default value');64 program.option('--foo', 'description', 'default value');65 expect(program.getOptionValueSource('foo')).toBe('default');66 program.setOptionValue('foo', 'bar');67 expect(program.getOptionValueSource('foo')).toBeUndefined();68});
modified:tests/options.implies.test.js+20 added-15 removed
11 unmodified lines
1213 test('when source default and implied undefined then implied is undefined', () => {14 const program = new Command();15 program16 .addOption(new Option('--foo').implies({ bar: 'implied' }).default('default'))16 .addOption(17 new Option('--foo').implies({ bar: 'implied' }).default('default'),18 )19 .option('--bar');20 program.parse([], { from: 'user' });21 expect(program.opts()).toEqual({ foo: 'default' });22 });
42 unmodified lines
65});6667test('when imply non-option then ok and stored', () => {68 const program = new Command();67 program68 .addOption(new Option('--foo').implies({ bar: 'implied' }));69 program.addOption(new Option('--foo').implies({ bar: 'implied' }));70 program.parse(['--foo'], { from: 'user' });71 expect(program.opts()).toEqual({ foo: true, bar: 'implied' });72});73
9 unmodified lines
8384test('when imply multiple times then store multiple values', () => {85 const program = new Command();86 program86 .addOption(new Option('--foo').implies({ one: 'ONE' }).implies({ two: 'TWO' }))87 .addOption(88 new Option('--foo').implies({ one: 'ONE' }).implies({ two: 'TWO' }),89 )90 .option('--one')91 .option('--two');92 program.parse(['--foo'], { from: 'user' });93 expect(program.opts()).toEqual({ foo: true, one: 'ONE', two: 'TWO' });
18 unmodified lines
112});113114test('when imply from lone negative option then negative implied', () => {115 const program = new Command();113 program114 .addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }));116 program.addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }));117 program.parse(['--no-foo'], { from: 'user' });118 expect(program.opts()).toEqual({ foo: false, implied: 'NEGATIVE' });119});120121test('when imply from negative option with preset then negative implied', () => {122 const program = new Command();123 program124 .addOption(new Option('--foo').implies({ implied: 'POSITIVE' }))123 .addOption(new Option('--no-foo').implies({ implied: 'NEGATIVE' }).preset('FALSE'));125 .addOption(126 new Option('--no-foo').implies({ implied: 'NEGATIVE' }).preset('FALSE'),127 );128 program.parse(['--no-foo'], { from: 'user' });129 expect(program.opts()).toEqual({ foo: 'FALSE', implied: 'NEGATIVE' });130});131
20 unmodified lines
152 const program = new Command();153 program154 .exitOverride()155 .configureOutput({152 writeErr: () => {}156 writeErr: () => {},157 })158 .addOption(new Option('--unary'))159 .addOption(new Option('--binary').conflicts('unary'))160 .addOption(new Option('--one').implies({ unary: true }));
6 unmodified lines
167test('when requiredOption with implied value then not throw', () => {168 const program = new Command();169 program170 .requiredOption('--target <target-file>')167 .addOption(new Option('--default-target').implies({ target: 'default-file' }));171 .addOption(172 new Option('--default-target').implies({ target: 'default-file' }),173 );174175 expect(() => {176 program.parse(['--default-target'], { from: 'user' });177 }).not.toThrow();178});179180test('when implies on program and use subcommand then program updated', () => {181 const program = new Command();176 program177 .addOption(new Option('--foo').implies({ bar: 'implied' }));178 program179 .command('sub')180 .action(() => {});182 program.addOption(new Option('--foo').implies({ bar: 'implied' }));183 program.command('sub').action(() => {});184 program.parse(['--foo', 'sub'], { from: 'user' });185 expect(program.opts().bar).toEqual('implied');186});187
10 unmodified lines
198 let called = false;199 const program = new Command();200 program201 .addOption(new Option('--foo').implies({ bar: true }))199 .option('-b, --bar', 'description', () => { called = true; });202 .option('-b, --bar', 'description', () => {203 called = true;204 });205 program.parse(['--foo'], { from: 'user' });206 expect(program.opts().bar).toEqual(true);207 expect(called).toEqual(false);208});
11 unmodified lines
modified:tests/options.mandatory.test.js+18 added-21 removed
4 unmodified lines
56describe('required program option with mandatory value specified', () => {7 test('when program has required value specified then value as specified', () => {8 const program = new commander.Command();9 program10 .exitOverride()11 .requiredOption('--cheese <type>', 'cheese type');9 program.exitOverride().requiredOption('--cheese <type>', 'cheese type');10 program.parse(['node', 'test', '--cheese', 'blue']);11 expect(program.opts().cheese).toBe('blue');12 });13
16 unmodified lines
30 });3132 test('when program has optional value flag specified then true', () => {33 const program = new commander.Command();36 program37 .exitOverride()38 .requiredOption('--cheese [type]', 'cheese type');34 program.exitOverride().requiredOption('--cheese [type]', 'cheese type');35 program.parse(['node', 'test', '--cheese']);36 expect(program.opts().cheese).toBe(true);37 });38
62 unmodified lines
101 // Optional. Use internal knowledge to suppress output to keep test output clean.102 let writeErrorSpy;103104 beforeAll(() => {109 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });105 writeErrorSpy = jest106 .spyOn(process.stderr, 'write')107 .mockImplementation(() => {});108 });109110 afterEach(() => {111 writeErrorSpy.mockClear();
4 unmodified lines
116 });117118 test('when program has required option not specified then error', () => {119 const program = new commander.Command();122 program123 .exitOverride()124 .requiredOption('--cheese <type>', 'cheese type');120 program.exitOverride().requiredOption('--cheese <type>', 'cheese type');121122 expect(() => {123 program.parse(['node', 'test']);124 }).toThrow();125 });126127 test('when program has optional option not specified then error', () => {128 const program = new commander.Command();133 program134 .exitOverride()135 .requiredOption('--cheese [type]', 'cheese type');129 program.exitOverride().requiredOption('--cheese [type]', 'cheese type');130131 expect(() => {132 program.parse(['node', 'test']);133 }).toThrow();
45 unmodified lines
179 test('when command has required value specified using env then no error and option has specified value', () => {180 const program = new commander.Command();181 program182 .exitOverride()189 .addOption(new commander.Option('-p, --port <number>', 'port number').makeOptionMandatory().env('FOO'));183 .addOption(184 new commander.Option('-p, --port <number>', 'port number')185 .makeOptionMandatory()186 .env('FOO'),187 );188189 process.env.FOO = 'bar';190 program.parse([], { from: 'user' });191 delete process.env.FOO;
6 unmodified lines
198 // Optional. Use internal knowledge to suppress output to keep test output clean.199 let writeErrorSpy;200201 beforeAll(() => {204 writeErrorSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => { });202 writeErrorSpy = jest203 .spyOn(process.stderr, 'write')204 .mockImplementation(() => {});205 });206207 afterEach(() => {208 writeErrorSpy.mockClear();
22 unmodified lines
231 .exitOverride()232 .command('sub')233 .requiredOption('--subby <type>', 'description')234 .action(() => {});235 program236 .command('sub2');235 program.command('sub2');236237 expect(() => {238 program.parse(['node', 'test', 'sub2']);239 }).not.toThrow();
4 unmodified lines
244 // Optional. Use internal knowledge to suppress output to keep test output clean.245 let writeSpy;246247 beforeAll(() => {249 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });248 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => {});249 });250251 afterEach(() => {252 writeSpy.mockClear();
4 unmodified lines
257 });258259 test('when program has required option not specified and --help then help', () => {260 const program = new commander.Command();262 program263 .exitOverride()264 .requiredOption('--cheese <type>', 'cheese type');261 program.exitOverride().requiredOption('--cheese <type>', 'cheese type');262263 let caughtErr;264 try {265 program.parse(['node', 'test', '--help']);
25 unmodified lines
modified:tests/options.optional.test.js+8 added-17 removed
2 unmodified lines
3// option with optional value, no default4describe('option with optional value, no default', () => {5 test('when option not specified then value is undefined', () => {6 const program = new commander.Command();7 program8 .option('--cheese [type]', 'cheese type');7 program.option('--cheese [type]', 'cheese type');8 program.parse(['node', 'test']);9 expect(program.opts().cheese).toBeUndefined();10 });1112 test('when option specified then value is as specified', () => {13 const program = new commander.Command();15 program16 .option('--cheese [type]', 'cheese type');14 program.option('--cheese [type]', 'cheese type');15 const cheeseType = 'blue';16 program.parse(['node', 'test', '--cheese', cheeseType]);17 expect(program.opts().cheese).toBe(cheeseType);18 });1920 test('when option specified without value then value is true', () => {21 const program = new commander.Command();24 program25 .option('--cheese [type]', 'cheese type');22 program.option('--cheese [type]', 'cheese type');23 program.parse(['node', 'test', '--cheese']);24 expect(program.opts().cheese).toBe(true);25 });2627 test('when option specified without value and following option then value is true', () => {28 // optional options do not eat values with dashes29 const program = new commander.Command();33 program34 .option('--cheese [type]', 'cheese type')35 .option('--some-option');30 program.option('--cheese [type]', 'cheese type').option('--some-option');31 program.parse(['node', 'test', '--cheese', '--some-option']);32 expect(program.opts().cheese).toBe(true);33 });34});
2 unmodified lines
37describe('option with optional value, with default', () => {38 test('when option not specified then value is default', () => {39 const defaultValue = 'default';40 const program = new commander.Command();46 program47 .option('--cheese [type]', 'cheese type', defaultValue);41 program.option('--cheese [type]', 'cheese type', defaultValue);42 program.parse(['node', 'test']);43 expect(program.opts().cheese).toBe(defaultValue);44 });4546 test('when option specified then value is as specified', () => {47 const defaultValue = 'default';48 const program = new commander.Command();55 program56 .option('--cheese [type]', 'cheese type', defaultValue);49 program.option('--cheese [type]', 'cheese type', defaultValue);50 const cheeseType = 'blue';51 program.parse(['node', 'test', '--cheese', cheeseType]);52 expect(program.opts().cheese).toBe(cheeseType);53 });5455 test('when option specified without value then value is true', () => {56 const defaultValue = 'default';57 const program = new commander.Command();65 program66 .option('--cheese [type]', 'cheese type', defaultValue);58 program.option('--cheese [type]', 'cheese type', defaultValue);59 program.parse(['node', 'test', '--cheese']);60 expect(program.opts().cheese).toBe(true);61 });6263 test('when option specified without value and preset then value is preset', () => {64 const program = new commander.Command();73 program74 .addOption(new commander.Option('--cheese [type]').preset('preset'));65 program.addOption(new commander.Option('--cheese [type]').preset('preset'));66 program.parse(['node', 'test', '--cheese']);67 expect(program.opts().cheese).toBe('preset');68 });69});
modified:tests/options.opts.test.js+45 added-51 removed
4 unmodified lines
56test('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);9 program.storeOptionsAsProperties().version(version);10 program.parse(['node', 'test']);11 expect(program.opts()).toEqual({ version });12});1314test('when .version used with storeOptionsAsProperties(false) then version not in opts', () => {15 // New behaviour, stop storing version as an option value.16 const program = new commander.Command();17 const version = '0.0.1';20 program21 .storeOptionsAsProperties(false)22 .version(version);18 program.storeOptionsAsProperties(false).version(version);19 program.parse(['node', 'test']);24 expect(program.opts()).toEqual({ });20 expect(program.opts()).toEqual({});21});2227describe.each([true, false])('storeOptionsAsProperties is %s', (storeOptionsAsProperties) => {28 test('when boolean flag not specified then not in opts', () => {29 const program = new commander.Command();30 program.storeOptionsAsProperties(storeOptionsAsProperties);31 program32 .option('--pepper', 'add pepper');33 program.parse(['node', 'test']);34 expect(program.opts()).toEqual({ });35 });23describe.each([true, false])(24 'storeOptionsAsProperties is %s',25 (storeOptionsAsProperties) => {26 test('when boolean flag not specified then not in opts', () => {27 const program = new commander.Command();28 program.storeOptionsAsProperties(storeOptionsAsProperties);29 program.option('--pepper', 'add pepper');30 program.parse(['node', 'test']);31 expect(program.opts()).toEqual({});32 });3337 test('when boolean flag specified then value true', () => {38 const program = new commander.Command();39 program.storeOptionsAsProperties(storeOptionsAsProperties);40 program41 .option('--pepper', 'add pepper');42 program.parse(['node', 'test', '--pepper']);43 expect(program.opts()).toEqual({ pepper: true });44 });34 test('when boolean flag specified then value true', () => {35 const program = new commander.Command();36 program.storeOptionsAsProperties(storeOptionsAsProperties);37 program.option('--pepper', 'add pepper');38 program.parse(['node', 'test', '--pepper']);39 expect(program.opts()).toEqual({ pepper: true });40 });4146 test('when option with required value not specified then not in opts', () => {47 const program = new commander.Command();48 program.storeOptionsAsProperties(storeOptionsAsProperties);49 program50 .option('--pepper <flavour>', 'add pepper');51 program.parse(['node', 'test']);52 expect(program.opts()).toEqual({ });53 });42 test('when option with required value not specified then not in opts', () => {43 const program = new commander.Command();44 program.storeOptionsAsProperties(storeOptionsAsProperties);45 program.option('--pepper <flavour>', 'add pepper');46 program.parse(['node', 'test']);47 expect(program.opts()).toEqual({});48 });4955 test('when option with required value specified then value as specified', () => {56 const pepperValue = 'red';57 const program = new commander.Command();58 program.storeOptionsAsProperties(storeOptionsAsProperties);59 program60 .option('--pepper <flavour>', 'add pepper');61 program.parse(['node', 'test', '--pepper', pepperValue]);62 expect(program.opts()).toEqual({ pepper: pepperValue });63 });50 test('when option with required value specified then value as specified', () => {51 const pepperValue = 'red';52 const program = new commander.Command();53 program.storeOptionsAsProperties(storeOptionsAsProperties);54 program.option('--pepper <flavour>', 'add pepper');55 program.parse(['node', 'test', '--pepper', pepperValue]);56 expect(program.opts()).toEqual({ pepper: pepperValue });57 });5865 test('when option with default value not specified then default value in opts', () => {66 const pepperDefault = 'red';67 const program = new commander.Command();68 program.storeOptionsAsProperties(storeOptionsAsProperties);69 program70 .option('--pepper <flavour>', 'add pepper', pepperDefault);71 program.parse(['node', 'test']);72 expect(program.opts()).toEqual({ pepper: pepperDefault });73 });74});59 test('when option with default value not specified then default value in opts', () => {60 const pepperDefault = 'red';61 const program = new commander.Command();62 program.storeOptionsAsProperties(storeOptionsAsProperties);63 program.option('--pepper <flavour>', 'add pepper', pepperDefault);64 program.parse(['node', 'test']);65 expect(program.opts()).toEqual({ pepper: pepperDefault });66 });67 },68);
modified:tests/options.optsWithGlobals.test.js+14 added-15 removed
17 unmodified lines
1819 test('when options in sub and program then optsWithGlobals includes both', () => {20 const program = new commander.Command();21 let mergedOptions;22 program.option('-g, --global <value>');23 program23 .option('-g, --global <value>');24 program24 .command('sub')25 .option('-l, --local <value)')26 .action((options, cmd) => {27 mergedOptions = cmd.optsWithGlobals();
14 unmodified lines
42 .action((options, cmd) => {43 mergedOptions = cmd.optsWithGlobals();44 });4547 program.parse(['sub', '-g', 'GGG', 'subsub', '-l', 'LLL'], { from: 'user' });46 program.parse(['sub', '-g', 'GGG', 'subsub', '-l', 'LLL'], {47 from: 'user',48 });49 expect(mergedOptions).toEqual({ global: 'GGG', local: 'LLL' });50 });5152 test('when same named option in sub and program then optsWithGlobals includes global', () => {53 const program = new commander.Command();54 let mergedOptions;55 program.option('-c, --common <value>').enablePositionalOptions();56 program55 .option('-c, --common <value>')56 .enablePositionalOptions();57 program57 .command('sub')58 .option('-c, --common <value)')59 .action((options, cmd) => {60 mergedOptions = cmd.optsWithGlobals();
6 unmodified lines
6768describe('getOptionValueSourceWithGlobals', () => {69 test('when option used with simple command then source is defined', () => {70 const program = new commander.Command();72 program73 .option('-g, --global');71 program.option('-g, --global');7273 program.parse(['-g'], { from: 'user' });74 expect(program.getOptionValueSourceWithGlobals('global')).toEqual('cli');75 });7677 test('when option used with program then source is defined', () => {78 const program = new commander.Command();81 program82 .option('-g, --global');83 const sub = program.command('sub')79 program.option('-g, --global');80 const sub = program81 .command('sub')82 .option('-l, --local')83 .action(() => {});8485 program.parse(['sub', '-g'], { from: 'user' });
1 unmodified line
87 });8889 test('when option used with subcommand then source is defined', () => {90 const program = new commander.Command();93 program94 .option('-g, --global');95 const sub = program.command('sub')91 program.option('-g, --global');92 const sub = program93 .command('sub')94 .option('-l, --local')95 .action(() => {});9697 program.parse(['sub', '-l'], { from: 'user' });
4 unmodified lines
102 const program = new commander.Command();103 program104 .enablePositionalOptions()105 .option('-c, --common <value>', 'description', 'default value');108 const sub = program.command('sub')106 const sub = program107 .command('sub')108 .option('-c, --common <value>')109 .action(() => {});110111 program.parse(['sub', '--common', 'value'], { from: 'user' });
3 unmodified lines
modified:tests/options.preset.test.js+3 added-1 removed
35 unmodified lines
36});3738test('when optional with preset and coerce used then preset is coerced', () => {39 const program = new Command();40 program.addOption(new Option('-p, --port [port]').preset('4').argParser(parseFloat));40 program.addOption(41 new Option('-p, --port [port]').preset('4').argParser(parseFloat),42 );43 program.parse(['-p'], { from: 'user' });44 expect(program.opts().port).toBe(4);45});46
13 unmodified lines
modified:tests/options.registerClash.test.js+3 added-6 removed
20 unmodified lines
2122 test('when use help options separately then does not throw', () => {23 expect(() => {24 const program = new Command();25 program26 .option('-h, --help', 'display help');25 program.option('-h, --help', 'display help');26 }).not.toThrow();27 });2829 test('when reuse flags in subcommand then does not throw', () => {30 expect(() => {31 const program = new Command();33 program34 .option('e, --example');35 program.command('sub')36 .option('e, --example');32 program.option('e, --example');33 program.command('sub').option('e, --example');34 }).not.toThrow();35 });36});37
19 unmodified lines
modified:tests/options.required.test.js+6 added-12 removed
2 unmodified lines
3// option with required value, no default4describe('option with required value, no default', () => {5 test('when option not specified then value is undefined', () => {6 const program = new commander.Command();7 program8 .option('--cheese <type>', 'cheese type');7 program.option('--cheese <type>', 'cheese type');8 program.parse(['node', 'test']);9 expect(program.opts().cheese).toBeUndefined();10 });1112 test('when option specified then value is as specified', () => {13 const program = new commander.Command();15 program16 .option('--cheese <type>', 'cheese type');14 program.option('--cheese <type>', 'cheese type');15 const cheeseType = 'blue';16 program.parse(['node', 'test', '--cheese', cheeseType]);17 expect(program.opts().cheese).toBe(cheeseType);18 });
4 unmodified lines
23 throw new Error('optionMissingArgument');24 });25 const program = new commander.Command();26 program.optionMissingArgument = mockOptionMissingArgument;29 program30 .option('--cheese <type>', 'cheese type');27 program.option('--cheese <type>', 'cheese type');2829 // Act. The throw is due to the above mock, and not default behaviour.30 expect(() => {31 program.parse(['node', 'test', '--cheese']);
8 unmodified lines
40describe('option with required value, with default', () => {41 test('when option not specified then value is default', () => {42 const defaultValue = 'default';43 const program = new commander.Command();47 program48 .option('--cheese <type>', 'cheese type', defaultValue);44 program.option('--cheese <type>', 'cheese type', defaultValue);45 program.parse(['node', 'test']);46 expect(program.opts().cheese).toBe(defaultValue);47 });4849 test('when option specified then value is as specified', () => {50 const defaultValue = 'default';51 const program = new commander.Command();56 program57 .option('--cheese <type>', 'cheese type', defaultValue);52 program.option('--cheese <type>', 'cheese type', defaultValue);53 const cheeseType = 'blue';54 program.parse(['node', 'test', '--cheese', cheeseType]);55 expect(program.opts().cheese).toBe(cheeseType);56 });
5 unmodified lines
62 });63 const defaultValue = 'default';64 const program = new commander.Command();65 program.optionMissingArgument = mockOptionMissingArgument;71 program72 .option('--cheese <type>', 'cheese type', defaultValue);66 program.option('--cheese <type>', 'cheese type', defaultValue);6768 // Act. The throw is due to the above mock, and not default behaviour.69 expect(() => {70 program.parse(['node', 'test', '--cheese']);
6 unmodified lines
modified:tests/options.values.test.js+10 added-8 removed
5 unmodified lines
6// options with required values can eat values starting with a dash, including just dash sometimes used as alias for stdin7//8// option with required value, using describe.each to test all matrix of values and tests9describe.each([['str'], ['80'], ['-'], ['-5'], ['--flag']])(10 'option with required value specified as %s', (value) => {10 'option with required value specified as %s',11 (value) => {12 function createPortProgram() {13 const program = new commander.Command();13 program14 .option('-p,--port <number>', 'specify port');14 program.option('-p,--port <number>', 'specify port');15 return program;16 }1718 test('when short flag followed by value then value is as specified', () => {
18 unmodified lines
37 const program = createPortProgram();38 program.parse(['node', 'test', `--port=${value}`]);39 expect(program.opts().port).toBe(value);40 });41 });41 },42);4344// option with optional value45describe('option with optional value', () => {46 function createPortProgram() {47 const program = new commander.Command();47 program48 .option('-p,--port [number]', 'specify port');48 program.option('-p,--port [number]', 'specify port');49 return program;50 }5152 test('when short flag followed by value then value is as specified', () => {
21 unmodified lines
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');78 program.option(79 '-c, --cheese [type]',80 'optionally specify the type of cheese',81 );82 program.parse(['node', 'test', '--cheese', '']);83 expect(program.opts().cheese).toBe('');84 });85});
modified:tests/options.variadic.test.js+27 added-32 removed
13 unmodified lines
14 });1516 test('when variadic with one value then set in array', () => {17 const program = new commander.Command();18 program19 .option('-r,--required <value...>');18 program.option('-r,--required <value...>');1920 program.parse(['--required', 'one'], { from: 'user' });21 expect(program.opts().required).toEqual(['one']);22 });2324 test('when variadic with two values then set in array', () => {25 const program = new commander.Command();27 program28 .option('-r,--required <value...>');26 program.option('-r,--required <value...>');2728 program.parse(['--required', 'one', 'two'], { from: 'user' });29 expect(program.opts().required).toEqual(['one', 'two']);30 });3132 test('when variadic with repeated values then set in array', () => {33 const program = new commander.Command();36 program37 .option('-r,--required <value...>');34 program.option('-r,--required <value...>');3536 program.parse(['--required', 'one', '--required', 'two'], { from: 'user' });37 expect(program.opts().required).toEqual(['one', 'two']);38 });3940 test('when variadic used with choices and one value then set in array', () => {41 const program = new commander.Command();45 program46 .addOption(new commander.Option('-r,--required <value...>').choices(['one', 'two']));42 program.addOption(43 new commander.Option('-r,--required <value...>').choices(['one', 'two']),44 );4546 program.parse(['--required', 'one'], { from: 'user' });47 expect(program.opts().required).toEqual(['one']);48 });4950 test('when variadic used with choices and two values then set in array', () => {51 const program = new commander.Command();54 program55 .addOption(new commander.Option('-r,--required <value...>').choices(['one', 'two']));52 program.addOption(53 new commander.Option('-r,--required <value...>').choices(['one', 'two']),54 );5556 program.parse(['--required', 'one', 'two'], { from: 'user' });57 expect(program.opts().required).toEqual(['one', 'two']);58 });5960 test('when variadic with short combined argument then not variadic', () => {61 const program = new commander.Command();63 program64 .option('-r,--required <value...>')65 .argument('[arg]');62 program.option('-r,--required <value...>').argument('[arg]');6364 program.parse(['-rone', 'operand'], { from: 'user' });65 expect(program.opts().required).toEqual(['one']);66 });6768 test('when variadic with long combined argument then not variadic', () => {69 const program = new commander.Command();73 program74 .option('-r,--required <value...>')75 .argument('[arg]');70 program.option('-r,--required <value...>').argument('[arg]');7172 program.parse(['--required=one', 'operand'], { from: 'user' });73 expect(program.opts().required).toEqual(['one']);74 });
12 unmodified lines
87 });8889 test('when variadic with no value and default then set to default', () => {90 const program = new commander.Command();96 program97 .option('-r,--required <value...>', 'variadic description', 'default');91 program.option(92 '-r,--required <value...>',93 'variadic description',94 'default',95 );9697 program.parse([], { from: 'user' });98 expect(program.opts().required).toEqual('default');99 });100101 test('when variadic with coercion then coercion sets value', () => {102 const program = new commander.Command();105 program106 .option('-r,--required <value...>', 'variadic description', parseFloat);103 program.option(104 '-r,--required <value...>',105 'variadic description',106 parseFloat,107 );108109 // variadic processing reads the multiple values, but up to custom coercion what it does.110 program.parse(['--required', '1e2', '1e3'], { from: 'user' });111 expect(program.opts().required).toEqual(1000);
3 unmodified lines
115// Not retesting everything, but do some tests on variadic with optional116describe('variadic option with optional value', () => {117 test('when variadic not specified then value undefined', () => {118 const program = new commander.Command();118 program119 .option('-o,--optional [value...]');119 program.option('-o,--optional [value...]');120121 program.parse([], { from: 'user' });122 expect(program.opts().optional).toBeUndefined();123 });124125 test('when variadic used as boolean flag then value true', () => {126 const program = new commander.Command();127 program128 .option('-o,--optional [value...]');127 program.option('-o,--optional [value...]');128129 program.parse(['--optional'], { from: 'user' });130 expect(program.opts().optional).toBe(true);131 });132133 test('when variadic with one value then set in array', () => {134 const program = new commander.Command();136 program137 .option('-o,--optional [value...]');135 program.option('-o,--optional [value...]');136137 program.parse(['--optional', 'one'], { from: 'user' });138 expect(program.opts().optional).toEqual(['one']);139 });140141 test('when variadic with two values then set in array', () => {142 const program = new commander.Command();145 program146 .option('-o,--optional [value...]');143 program.option('-o,--optional [value...]');144145 program.parse(['--optional', 'one', 'two'], { from: 'user' });146 expect(program.opts().optional).toEqual(['one', 'two']);147 });
1 unmodified line
149150describe('variadic special cases', () => {151 test('when option flags has word character before dots then is variadic', () => {152 const program = new commander.Command();156 program157 .option('-c,--comma [value...]');153 program.option('-c,--comma [value...]');154155 expect(program.options[0].variadic).toBeTruthy();156 });157158 test('when option flags has special characters before dots then not variadic', () => {159 // This might be used to describe coercion for comma separated values, and is not variadic.160 const program = new commander.Command();165 program166 .option('-c,--comma [value,...]');161 program.option('-c,--comma [value,...]');162163 expect(program.options[0].variadic).toBeFalsy();164 });165});
modified:tests/options.version.test.js+6 added-9 removed
5 unmodified lines
6 test('when no .version and specify --version then unknown option error', () => {7 const errorMessage = 'unknownOption';8 const program = new commander.Command();9 // Override unknownOption as convenient way to check fails as expected.10 jest.spyOn(program, 'unknownOption').mockImplementation(() => { throw new Error(errorMessage); });10 jest.spyOn(program, 'unknownOption').mockImplementation(() => {11 throw new Error(errorMessage);12 });1314 expect(() => {15 program.parse(['node', 'test', '--version']);16 }).toThrow(errorMessage);
40 unmodified lines
5758 test('when default .version then helpInformation includes default version help', () => {59 const myVersion = '1.2.3';60 const program = new commander.Command();59 program60 .version(myVersion);61 program.version(myVersion);6263 const helpInformation = program.helpInformation();6465 expect(helpInformation.includes('-V, --version')).toBe(true);
64 unmodified lines
130 const myVersion = '1.2.3';131 const myVersionFlags = '-r, --revision';132 const myVersionDescription = 'custom description';133 const program = new commander.Command();133 program134 .version(myVersion, myVersionFlags, myVersionDescription);134 program.version(myVersion, myVersionFlags, myVersionDescription);135136 const helpInformation = program.helpInformation();137138 expect(helpInformation.includes(myVersionFlags)).toBe(true);
2 unmodified lines
141142 test('when have .version+version and specify version then command called', () => {143 const actionMock = jest.fn();144 const program = new commander.Command();145 program146 .version('1.2.3')147 .command('version')148 .action(actionMock);145 program.version('1.2.3').command('version').action(actionMock);146147 program.parse(['node', 'test', 'version']);148149 expect(actionMock).toHaveBeenCalled();
26 unmodified lines
modified:tests/program.test.js+3 added-2 removed
7 unmodified lines
8 InvalidArgumentError,9 InvalidOptionArgumentError,10 createCommand,11 createOption,12 createArgument12 createArgument,13} = require('../index.js');1415// Do some testing of the default export(s).16// Similar tests to ts-imports.test.ts and esm-imports-test.js.
32 unmodified lines
49test('InvalidArgumentError', () => {50 checkClass(new InvalidArgumentError('failed'), 'InvalidArgumentError');51});5253test('InvalidOptionArgumentError', () => { // Deprecated53test('InvalidOptionArgumentError', () => {54 // Deprecated55 checkClass(new InvalidOptionArgumentError('failed'), 'InvalidArgumentError');56});5758test('createCommand', () => {
10 unmodified lines
modified:tests/ts-imports.test.ts+12 added-2 removed
1import { program, Command, Option, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Help, createCommand } from '../';1import {2 program,3 Command,4 Option,5 CommanderError,6 InvalidArgumentError,7 InvalidOptionArgumentError,8 Help,9 createCommand,10} from '../';1112// Do some simple checks that expected imports are available at runtime.13// Similar tests to esm-imports-test.js14
28 unmodified lines
43test('InvalidArgumentError', () => {44 checkClass(new InvalidArgumentError('failed'), 'InvalidArgumentError');45});4638test('InvalidOptionArgumentError', () => { // Deprecated47test('InvalidOptionArgumentError', () => {48 // Deprecated49 checkClass(new InvalidOptionArgumentError('failed'), 'InvalidArgumentError');50});5152test('Help', () => {
2 unmodified lines
modified:typings/index.d.ts+87 added-21 removed
9 unmodified lines
10// References:11// - https://github.com/microsoft/TypeScript/issues/2972912// - https://github.com/sindresorhus/type-fest/blob/main/source/literal-union.d.ts13// - https://github.com/sindresorhus/type-fest/blob/main/source/primitive.d.ts14type LiteralUnion<LiteralType, BaseType extends string | number> = LiteralType | (BaseType & Record<never, never>);14type LiteralUnion<LiteralType, BaseType extends string | number> =15 | LiteralType16 | (BaseType & Record<never, never>);1718export class CommanderError extends Error {19 code: string;20 exitCode: number;
19 unmodified lines
40 constructor(message: string);41}42export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name4342export interface ErrorOptions { // optional parameter for error()44export interface ErrorOptions {45 // optional parameter for error()46 /** an id string representing the error */47 code?: string;48 /** suggested exit code which could be used with process.exit */49 exitCode?: number;
209 unmodified lines
259 /**260 * Wrap the given string to width characters per line, with lines after the first indented.261 * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.262 */260 wrap(str: string, width: number, indent: number, minColumnWidth?: number): string;263 wrap(264 str: string,265 width: number,266 indent: number,267 minColumnWidth?: number,268 ): string;269270 /** Generate the built-in help text. */271 formatHelp(cmd: Command, helper: Help): string;272}
1 unmodified line
274275export interface ParseOptions {276 from: 'node' | 'electron' | 'user';277}270export interface HelpContext { // optional parameter for .help() and .outputHelp()278export interface HelpContext {279 // optional parameter for .help() and .outputHelp()280 error: boolean;281}273export interface AddHelpTextContext { // passed to text function used with .addHelpText()282export interface AddHelpTextContext {283 // passed to text function used with .addHelpText()284 error: boolean;285 command: Command;286}287export interface OutputConfiguration {
1 unmodified line
289 writeErr?(str: string): void;290 getOutHelpWidth?(): number;291 getErrHelpWidth?(): number;292 outputError?(str: string, write: (str: string) => void): void;283293}294295export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';296export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';297// The source is a string so author can define their own too.289export type OptionValueSource = LiteralUnion<'default' | 'config' | 'env' | 'cli' | 'implied', string> | undefined;298export type OptionValueSource =299 | LiteralUnion<'default' | 'config' | 'env' | 'cli' | 'implied', string>300 | undefined;301302export type OptionValues = Record<string, any>;303304export class Command {
39 unmodified lines
344 * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`345 * @param opts - configuration options346 * @returns new command347 */337 command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>;348 command(349 nameAndArgs: string,350 opts?: CommandOptions,351 ): ReturnType<this['createCommand']>;352 /**353 * Define a command, implemented in a separate executable file.354 *355 * @remarks
10 unmodified lines
366 * @param description - description of executable command367 * @param opts - configuration options368 * @returns `this` command for chaining369 */356 command(nameAndArgs: string, description: string, opts?: ExecutableCommandOptions): this;370 command(371 nameAndArgs: string,372 description: string,373 opts?: ExecutableCommandOptions,374 ): this;375376 /**377 * Factory routine to create a new unattached command.378 *
32 unmodified lines
411 * ```412 *413 * @returns `this` command for chaining414 */397 argument<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;415 argument<T>(416 flags: string,417 description: string,418 fn: (value: string, previous: T) => T,419 defaultValue?: T,420 ): this;421 argument(name: string, description?: string, defaultValue?: unknown): this;422423 /**424 * Define argument syntax for command, adding a prepared argument.
41 unmodified lines
466467 /**468 * Add hook for life cycle event.469 */447 hook(event: HookEvent, listener: (thisCommand: Command, actionCommand: Command) => void | Promise<void>): this;470 hook(471 event: HookEvent,472 listener: (473 thisCommand: Command,474 actionCommand: Command,475 ) => void | Promise<void>,476 ): this;477478 /**479 * Register callback to use as replacement for calling process.exit.480 */
91 unmodified lines
572 * ```573 *574 * @returns `this` command for chaining575 */547 option(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;548 option<T>(flags: string, description: string, parseArg: (value: string, previous: T) => T, defaultValue?: T): this;576 option(577 flags: string,578 description?: string,579 defaultValue?: string | boolean | string[],580 ): this;581 option<T>(582 flags: string,583 description: string,584 parseArg: (value: string, previous: T) => T,585 defaultValue?: T,586 ): this;587 /** @deprecated since v7, instead use choices or a custom function */550 option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this;588 option(589 flags: string,590 description: string,591 regexp: RegExp,592 defaultValue?: string | boolean | string[],593 ): this;594595 /**596 * Define a required option, which must have a value after parsing. This usually means597 * the option must be specified on the command line. (Otherwise the same as .option().)598 *599 * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.600 */558 requiredOption(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;559 requiredOption<T>(flags: string, description: string, parseArg: (value: string, previous: T) => T, defaultValue?: T): this;601 requiredOption(602 flags: string,603 description?: string,604 defaultValue?: string | boolean | string[],605 ): this;606 requiredOption<T>(607 flags: string,608 description: string,609 parseArg: (value: string, previous: T) => T,610 defaultValue?: T,611 ): this;612 /** @deprecated since v7, instead use choices or a custom function */561 requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this;613 requiredOption(614 flags: string,615 description: string,616 regexp: RegExp,617 defaultValue?: string | boolean | string[],618 ): this;619620 /**621 * Factory routine to create a new unattached option.622 *
16 unmodified lines
639 *640 * @returns `this` command for chaining641 */642 storeOptionsAsProperties<T extends OptionValues>(): this & T;586 storeOptionsAsProperties<T extends OptionValues>(storeAsProperties: true): this & T;643 storeOptionsAsProperties<T extends OptionValues>(644 storeAsProperties: true,645 ): this & T;646 storeOptionsAsProperties(storeAsProperties?: boolean): this;647648 /**649 * Retrieve option value.
7 unmodified lines
657658 /**659 * Store option value and where the value came from.660 */602 setOptionValueWithSource(key: string, value: unknown, source: OptionValueSource): this;661 setOptionValueWithSource(662 key: string,663 value: unknown,664 source: OptionValueSource,665 ): this;666667 /**668 * Get source of option value.669 */670 getOptionValueSource(key: string): OptionValueSource | undefined;671672 /**610 * Get source of option value. See also .optsWithGlobals().673 * Get source of option value. See also .optsWithGlobals().674 */675 getOptionValueSourceWithGlobals(key: string): OptionValueSource | undefined;676677 /**
253 unmodified lines
931 * Position is 'before' or 'after' to affect just this command,932 * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.933 */934 addHelpText(position: AddHelpTextPosition, text: string): this;872 addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string): this;935 addHelpText(936 position: AddHelpTextPosition,937 text: (context: AddHelpTextContext) => string,938 ): this;939940 /**941 * Add a listener (callback) for when events occur. (Implemented using EventEmitter.)942 */
23 unmodified lines
modified:typings/index.test-d.ts+288 added-98 removed
15 unmodified lines
16// Check export classes and functions exist17expectType<commander.Command>(new commander.Command());18expectType<commander.Command>(new commander.Command('name'));19expectType<commander.Option>(new commander.Option('-f'));20expectType<commander.CommanderError>(new commander.CommanderError(1, 'code', 'message'));21expectType<commander.InvalidArgumentError>(new commander.InvalidArgumentError('message'));22expectType<commander.InvalidArgumentError>(new commander.InvalidOptionArgumentError('message'));20expectType<commander.CommanderError>(21 new commander.CommanderError(1, 'code', 'message'),22);23expectType<commander.InvalidArgumentError>(24 new commander.InvalidArgumentError('message'),25);26expectType<commander.InvalidArgumentError>(27 new commander.InvalidOptionArgumentError('message'),28);29expectType<commander.Command>(commander.createCommand());30expectType<commander.Option>(commander.createOption('--demo'));31expectType<commander.Argument>(commander.createArgument('<foo>'));32
8 unmodified lines
4142// version43expectType<commander.Command>(program.version('1.2.3'));44expectType<commander.Command>(program.version('1.2.3', '-r,--revision'));39expectType<commander.Command>(program.version('1.2.3', '-r,--revision', 'show revision information'));45expectType<commander.Command>(46 program.version('1.2.3', '-r,--revision', 'show revision information'),47);48expectType<string | undefined>(program.version());4950// command (and CommandOptions)51expectType<commander.Command>(program.command('action'));44expectType<commander.Command>(program.command('action', { isDefault: true, hidden: true, noHelp: true }));52expectType<commander.Command>(53 program.command('action', { isDefault: true, hidden: true, noHelp: true }),54);55expectType<commander.Command>(program.command('exec', 'exec description'));46expectType<commander.Command>(program.command('exec', 'exec description', { isDefault: true, hidden: true, noHelp: true, executableFile: 'foo' }));56expectType<commander.Command>(57 program.command('exec', 'exec description', {58 isDefault: true,59 hidden: true,60 noHelp: true,61 executableFile: 'foo',62 }),63);6465// addCommand66expectType<commander.Command>(program.addCommand(new commander.Command('abc')));6768// argument69expectType<commander.Command>(program.argument('<value>'));70expectType<commander.Command>(program.argument('<value>', 'description'));54expectType<commander.Command>(program.argument('[value]', 'description', 'default'));55expectType<commander.Command>(program.argument('[value]', 'description', parseFloat));56expectType<commander.Command>(program.argument('[value]', 'description', parseFloat, 1.23));71expectType<commander.Command>(72 program.argument('[value]', 'description', 'default'),73);74expectType<commander.Command>(75 program.argument('[value]', 'description', parseFloat),76);77expectType<commander.Command>(78 program.argument('[value]', 'description', parseFloat, 1.23),79);8081// arguments82expectType<commander.Command>(program.arguments('<cmd> [env]'));8384// addHelpCommand62expectType<commander.Command>(program.addHelpCommand(new commander.Command('assist')));85expectType<commander.Command>(86 program.addHelpCommand(new commander.Command('assist')),87);88// Deprecated uses89expectType<commander.Command>(program.addHelpCommand());90expectType<commander.Command>(program.addHelpCommand(false));91expectType<commander.Command>(program.addHelpCommand(true));92expectType<commander.Command>(program.addHelpCommand('assist [cmd]'));68expectType<commander.Command>(program.addHelpCommand('assist [file]', 'display help'));93expectType<commander.Command>(94 program.addHelpCommand('assist [file]', 'display help'),95);9697// helpCommand98expectType<commander.Command>(program.helpCommand(false));99expectType<commander.Command>(program.helpCommand(true));100expectType<commander.Command>(program.helpCommand('assist [cmd]'));74expectType<commander.Command>(program.helpCommand('assist [file]', 'display help'));101expectType<commander.Command>(102 program.helpCommand('assist [file]', 'display help'),103);104105// exitOverride106expectType<commander.Command>(program.exitOverride());107expectType<commander.Command>(108 program.exitOverride((err): never => {109 return process.exit(err.exitCode);78expectType<commander.Command>(program.exitOverride((err): never => {79 return process.exit(err.exitCode);80}));81expectType<commander.Command>(program.exitOverride((err): void => {82 if (err.code !== 'commander.executeSubCommandAsync') {83 throw err;84 } else {85 // Async callback from spawn events, not useful to throw.86 }87}));110 }),111);112expectType<commander.Command>(113 program.exitOverride((err): void => {114 if (err.code !== 'commander.executeSubCommandAsync') {115 throw err;116 } else {117 // Async callback from spawn events, not useful to throw.118 }119 }),120);121122// error123expectType<never>(program.error('Goodbye'));124expectType<never>(program.error('Goodbye', { code: 'my.error' }));
2 unmodified lines
127128// hook129expectType<commander.Command>(program.hook('preAction', () => {}));130expectType<commander.Command>(program.hook('postAction', () => {}));98expectType<commander.Command>(program.hook('preAction', async() => {}));99expectType<commander.Command>(program.hook('preAction', (thisCommand, actionCommand) => {100 // implicit parameter types101 expectType<commander.Command>(thisCommand);102 expectType<commander.Command>(actionCommand);103}));131expectType<commander.Command>(program.hook('preAction', async () => {}));132expectType<commander.Command>(133 program.hook('preAction', (thisCommand, actionCommand) => {134 // implicit parameter types135 expectType<commander.Command>(thisCommand);136 expectType<commander.Command>(actionCommand);137 }),138);139expectType<commander.Command>(program.hook('preSubcommand', () => {}));140expectType<commander.Command>(105expectType<commander.Command>(program.hook('preSubcommand', (thisCommand, subcommand) => {106 // implicit parameter types107 expectType<commander.Command>(thisCommand);108 expectType<commander.Command>(subcommand);109}));141 program.hook('preSubcommand', (thisCommand, subcommand) => {142 // implicit parameter types143 expectType<commander.Command>(thisCommand);144 expectType<commander.Command>(subcommand);145 }),146);147148// action149expectType<commander.Command>(program.action(() => {}));113expectType<commander.Command>(program.action(async() => {}));150expectType<commander.Command>(program.action(async () => {}));151152// option153expectType<commander.Command>(program.option('-a,--alpha'));154expectType<commander.Command>(program.option('-p, --peppers', 'Add peppers'));118expectType<commander.Command>(program.option('-s, --string [value]', 'default string', 'value'));119expectType<commander.Command>(program.option('-b, --boolean', 'default boolean', false));120expectType<commander.Command>(program.option('--drink <size', 'drink size', /small|medium|large/)); // deprecated155expectType<commander.Command>(156 program.option('-s, --string [value]', 'default string', 'value'),157);158expectType<commander.Command>(159 program.option('-b, --boolean', 'default boolean', false),160);161expectType<commander.Command>(162 program.option('--drink <size', 'drink size', /small|medium|large/),163); // deprecated164165// example coercion functions from README166167function myParseInt(value: string): number {
11 unmodified lines
179function commaSeparatedList(value: string): string[] {180 return value.split(',');181}182140expectType<commander.Command>(program.option('-f, --float <number>', 'float argument', parseFloat));141expectType<commander.Command>(program.option('-f, --float <number>', 'float argument', parseFloat, 3.2));142expectType<commander.Command>(program.option('-i, --integer <number>', 'integer argument', myParseInt));143expectType<commander.Command>(program.option('-i, --integer <number>', 'integer argument', myParseInt, 5));144expectType<commander.Command>(program.option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0));145expectType<commander.Command>(program.option('-c, --collect <value>', 'repeatable value', collect, []));146expectType<commander.Command>(program.option('-l, --list <items>', 'comma separated list', commaSeparatedList));183expectType<commander.Command>(184 program.option('-f, --float <number>', 'float argument', parseFloat),185);186expectType<commander.Command>(187 program.option('-f, --float <number>', 'float argument', parseFloat, 3.2),188);189expectType<commander.Command>(190 program.option('-i, --integer <number>', 'integer argument', myParseInt),191);192expectType<commander.Command>(193 program.option('-i, --integer <number>', 'integer argument', myParseInt, 5),194);195expectType<commander.Command>(196 program.option(197 '-v, --verbose',198 'verbosity that can be increased',199 increaseVerbosity,200 0,201 ),202);203expectType<commander.Command>(204 program.option('-c, --collect <value>', 'repeatable value', collect, []),205);206expectType<commander.Command>(207 program.option(208 '-l, --list <items>',209 'comma separated list',210 commaSeparatedList,211 ),212);213214// requiredOption, same tests as option215expectType<commander.Command>(program.requiredOption('-a,--alpha'));150expectType<commander.Command>(program.requiredOption('-p, --peppers', 'Add peppers'));151expectType<commander.Command>(program.requiredOption('-s, --string [value]', 'default string', 'value'));152expectType<commander.Command>(program.requiredOption('-b, --boolean', 'default boolean', false));153expectType<commander.Command>(program.requiredOption('--drink <size', 'drink size', /small|medium|large/)); // deprecated216expectType<commander.Command>(217 program.requiredOption('-p, --peppers', 'Add peppers'),218);219expectType<commander.Command>(220 program.requiredOption('-s, --string [value]', 'default string', 'value'),221);222expectType<commander.Command>(223 program.requiredOption('-b, --boolean', 'default boolean', false),224);225expectType<commander.Command>(226 program.requiredOption('--drink <size', 'drink size', /small|medium|large/),227); // deprecated228155expectType<commander.Command>(program.requiredOption('-f, --float <number>', 'float argument', parseFloat));156expectType<commander.Command>(program.requiredOption('-f, --float <number>', 'float argument', parseFloat, 3.2));157expectType<commander.Command>(program.requiredOption('-i, --integer <number>', 'integer argument', myParseInt));158expectType<commander.Command>(program.requiredOption('-i, --integer <number>', 'integer argument', myParseInt, 5));159expectType<commander.Command>(program.requiredOption('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0));160expectType<commander.Command>(program.requiredOption('-c, --collect <value>', 'repeatable value', collect, []));161expectType<commander.Command>(program.requiredOption('-l, --list <items>', 'comma separated list', commaSeparatedList));229expectType<commander.Command>(230 program.requiredOption('-f, --float <number>', 'float argument', parseFloat),231);232expectType<commander.Command>(233 program.requiredOption(234 '-f, --float <number>',235 'float argument',236 parseFloat,237 3.2,238 ),239);240expectType<commander.Command>(241 program.requiredOption(242 '-i, --integer <number>',243 'integer argument',244 myParseInt,245 ),246);247expectType<commander.Command>(248 program.requiredOption(249 '-i, --integer <number>',250 'integer argument',251 myParseInt,252 5,253 ),254);255expectType<commander.Command>(256 program.requiredOption(257 '-v, --verbose',258 'verbosity that can be increased',259 increaseVerbosity,260 0,261 ),262);263expectType<commander.Command>(264 program.requiredOption(265 '-c, --collect <value>',266 'repeatable value',267 collect,268 [],269 ),270);271expectType<commander.Command>(272 program.requiredOption(273 '-l, --list <items>',274 'comma separated list',275 commaSeparatedList,276 ),277);278279// createOption280expectType<commander.Option>(program.createOption('a, --alpha'));281expectType<commander.Option>(program.createOption('a, --alpha', 'description'));282283// addOption168expectType<commander.Command>(program.addOption(new commander.Option('-s,--simple')));284expectType<commander.Command>(285 program.addOption(new commander.Option('-s,--simple')),286);287288// storeOptionsAsProperties171expectType<commander.Command & commander.OptionValues>(program.storeOptionsAsProperties());172expectType<commander.Command & commander.OptionValues>(program.storeOptionsAsProperties(true));289expectType<commander.Command & commander.OptionValues>(290 program.storeOptionsAsProperties(),291);292expectType<commander.Command & commander.OptionValues>(293 program.storeOptionsAsProperties(true),294);295expectType<commander.Command>(program.storeOptionsAsProperties(false));296297// getOptionValue298void program.getOptionValue('example');
2 unmodified lines
301expectType<commander.Command>(program.setOptionValue('example', 'value'));302expectType<commander.Command>(program.setOptionValue('example', true));303304// setOptionValueWithSource183expectType<commander.Command>(program.setOptionValueWithSource('example', [], 'cli'));305expectType<commander.Command>(306 program.setOptionValueWithSource('example', [], 'cli'),307);308309// getOptionValueSource186expectType<commander.OptionValueSource | undefined>(program.getOptionValueSource('example'));310expectType<commander.OptionValueSource | undefined>(311 program.getOptionValueSource('example'),312);313314// getOptionValueSourceWithGlobals189expectType<commander.OptionValueSource | undefined>(program.getOptionValueSourceWithGlobals('example'));315expectType<commander.OptionValueSource | undefined>(316 program.getOptionValueSourceWithGlobals('example'),317);318319// combineFlagAndOptionalValue320expectType<commander.Command>(program.combineFlagAndOptionalValue());321expectType<commander.Command>(program.combineFlagAndOptionalValue(false));
16 unmodified lines
338339// parse340expectType<commander.Command>(program.parse());341expectType<commander.Command>(program.parse(process.argv));214expectType<commander.Command>(program.parse(['node', 'script.js'], { from: 'node' }));215expectType<commander.Command>(program.parse(['node', 'script.js'], { from: 'electron' }));342expectType<commander.Command>(343 program.parse(['node', 'script.js'], { from: 'node' }),344);345expectType<commander.Command>(346 program.parse(['node', 'script.js'], { from: 'electron' }),347);348expectType<commander.Command>(program.parse(['--option'], { from: 'user' }));349expectType<commander.Command>(program.parse(['node', 'script.js'] as const));350351// parseAsync, same tests as parse352expectType<Promise<commander.Command>>(program.parseAsync());353expectType<Promise<commander.Command>>(program.parseAsync(process.argv));222expectType<Promise<commander.Command>>(program.parseAsync(['node', 'script.js'], { from: 'node' }));223expectType<Promise<commander.Command>>(program.parseAsync(['node', 'script.js'], { from: 'electron' }));224expectType<Promise<commander.Command>>(program.parseAsync(['--option'], { from: 'user' }));225expectType<Promise<commander.Command>>(program.parseAsync(['node', 'script.js'] as const));354expectType<Promise<commander.Command>>(355 program.parseAsync(['node', 'script.js'], { from: 'node' }),356);357expectType<Promise<commander.Command>>(358 program.parseAsync(['node', 'script.js'], { from: 'electron' }),359);360expectType<Promise<commander.Command>>(361 program.parseAsync(['--option'], { from: 'user' }),362);363expectType<Promise<commander.Command>>(364 program.parseAsync(['node', 'script.js'] as const),365);366367// parseOptions (and ParseOptionsResult)228expectType<{ operands: string[]; unknown: string[] }>(program.parseOptions(['node', 'script.js', 'hello']));368expectType<{ operands: string[]; unknown: string[] }>(369 program.parseOptions(['node', 'script.js', 'hello']),370);371372// opts373const opts = program.opts();374expectType<commander.OptionValues>(opts);
23 unmodified lines
398399// description400expectType<commander.Command>(program.description('my description'));401expectType<string>(program.description());260expectType<commander.Command>(program.description('my description of command with arg foo', { foo: 'foo description' })); // deprecated402expectType<commander.Command>(403 program.description('my description of command with arg foo', {404 foo: 'foo description',405 }),406); // deprecated407408// summary409expectType<commander.Command>(program.summary('my summary'));410expectType<string>(program.summary());
3 unmodified lines
414expectType<string>(program.alias());415416// aliases417expectType<commander.Command>(program.aliases(['first-alias', 'second-alias']));272expectType<commander.Command>(program.aliases(['first-alias', 'second-alias'] as const));418expectType<commander.Command>(419 program.aliases(['first-alias', 'second-alias'] as const),420);421expectType<string[]>(program.aliases());422423// usage424expectType<commander.Command>(program.usage('my usage'));
13 unmodified lines
438// outputHelp439// eslint-disable-next-line @typescript-eslint/no-invalid-void-type, @typescript-eslint/no-confusing-void-expression440expectType<void>(program.outputHelp());441// eslint-disable-next-line @typescript-eslint/no-invalid-void-type, @typescript-eslint/no-confusing-void-expression294expectType<void>(program.outputHelp((str: string) => { return str; }));442expectType<void>(443 program.outputHelp((str: string) => {444 return str;445 }),446);447// eslint-disable-next-line @typescript-eslint/no-invalid-void-type, @typescript-eslint/no-confusing-void-expression448expectType<void>(program.outputHelp({ error: true }));449450// help451expectType<never>(program.help());300expectType<never>(program.help((str: string) => { return str; }));452expectType<never>(453 program.help((str: string) => {454 return str;455 }),456);457expectType<never>(program.help({ error: true }));458459// helpInformation460expectType<string>(program.helpInformation());461expectType<string>(program.helpInformation({ error: true }));462463// helpOption464expectType<commander.Command>(program.helpOption('-h,--help'));309expectType<commander.Command>(program.helpOption('-h,--help', 'custom description'));310expectType<commander.Command>(program.helpOption(undefined, 'custom description'));465expectType<commander.Command>(466 program.helpOption('-h,--help', 'custom description'),467);468expectType<commander.Command>(469 program.helpOption(undefined, 'custom description'),470);471expectType<commander.Command>(program.helpOption(false));472473// addHelpOption314expectType<commander.Command>(program.addHelpOption(new commander.Option('-h,--help')));474expectType<commander.Command>(475 program.addHelpOption(new commander.Option('-h,--help')),476);477478// addHelpText479expectType<commander.Command>(program.addHelpText('after', 'text'));480expectType<commander.Command>(program.addHelpText('afterAll', 'text'));481expectType<commander.Command>(program.addHelpText('before', () => 'before'));482expectType<commander.Command>(320expectType<commander.Command>(program.addHelpText('beforeAll', (context) => {321 expectType<boolean>(context.error);322 expectType<commander.Command>(context.command);323 return '';324}));483 program.addHelpText('beforeAll', (context) => {484 expectType<boolean>(context.error);485 expectType<commander.Command>(context.command);486 return '';487 }),488);489490// on491expectType<commander.Command>(program.on('command:foo', () => {}));492
14 unmodified lines
507expectType<MyCommand>(myProgram.command('sub'));508509// configureHelp510expectType<commander.Help>(program.createHelp());511expectType<commander.Command>(347expectType<commander.Command>(program.configureHelp({348 sortSubcommands: true, // override property349 visibleCommands: () => [] // override method350}));512 program.configureHelp({513 sortSubcommands: true, // override property514 visibleCommands: () => [], // override method515 }),516);517expectType<commander.HelpConfiguration>(program.configureHelp());518519// copyInheritedSettings354expectType<commander.Command>(program.copyInheritedSettings(new commander.Command()));520expectType<commander.Command>(521 program.copyInheritedSettings(new commander.Command()),522);523524// showHelpAfterError525expectType<commander.Command>(program.showHelpAfterError());526expectType<commander.Command>(program.showHelpAfterError(true));
3 unmodified lines
530expectType<commander.Command>(program.showSuggestionAfterError());531expectType<commander.Command>(program.showSuggestionAfterError(false));532533// configureOutput366expectType<commander.Command>(program.configureOutput({ }));534expectType<commander.Command>(program.configureOutput({}));535expectType<commander.OutputConfiguration>(program.configureOutput());536369expectType<commander.Command>(program.configureOutput({370 writeOut: (str: string) => { console.log(str); },371 writeErr: (str: string) => { console.error(str); },372 getOutHelpWidth: () => 80,373 getErrHelpWidth: () => 80,374 outputError: (str: string, write: (str: string) => void) => { write(str); }375}));537expectType<commander.Command>(538 program.configureOutput({539 writeOut: (str: string) => {540 console.log(str);541 },542 writeErr: (str: string) => {543 console.error(str);544 },545 getOutHelpWidth: () => 80,546 getErrHelpWidth: () => 80,547 outputError: (str: string, write: (str: string) => void) => {548 write(str);549 },550 }),551);552553// Help554const helper = new commander.Help();555const helperCommand = new commander.Command();
64 unmodified lines
620// fullDescription621expectType<string>(baseOption.fullDescription());622623// argParser448expectType<commander.Option>(baseOption.argParser((value: string) => parseInt(value)));449expectType<commander.Option>(baseOption.argParser((value: string, previous: string[]) => { return previous.concat(value); }));624expectType<commander.Option>(625 baseOption.argParser((value: string) => parseInt(value)),626);627expectType<commander.Option>(628 baseOption.argParser((value: string, previous: string[]) => {629 return previous.concat(value);630 }),631);632633// makeOptionMandatory634expectType<commander.Option>(baseOption.makeOptionMandatory());635expectType<commander.Option>(baseOption.makeOptionMandatory(true));
11 unmodified lines
647expectType<commander.Option>(baseOption.conflicts('a'));648expectType<commander.Option>(baseOption.conflicts(['a', 'b']));649650// implies469expectType<commander.Option>(baseOption.implies({ option: 'VALUE', colour: false }));651expectType<commander.Option>(652 baseOption.implies({ option: 'VALUE', colour: false }),653);654655// name656expectType<string>(baseOption.name());657
22 unmodified lines
680expectType<commander.Argument>(baseArgument.default(3));681expectType<commander.Argument>(baseArgument.default(60, 'one minute'));682683// argParser500expectType<commander.Argument>(baseArgument.argParser((value: string) => parseInt(value)));501expectType<commander.Argument>(baseArgument.argParser((value: string, previous: string[]) => { return previous.concat(value); }));684expectType<commander.Argument>(685 baseArgument.argParser((value: string) => parseInt(value)),686);687expectType<commander.Argument>(688 baseArgument.argParser((value: string, previous: string[]) => {689 return previous.concat(value);690 }),691);692693// choices694expectType<commander.Argument>(baseArgument.choices(['a', 'b']));695expectType<commander.Argument>(baseArgument.choices(['a', 'b'] as const));
10 unmodified lines
modified:eslint.config.js+14 added-14 removed
12 unmodified lines
13 files: tsconfigJsFiles,14 languageOptions: {15 parserOptions: { project: './tsconfig.js.json' },16 },17 extends: [18 ...tseslint.configs.recommended,19 ],17 extends: [...tseslint.configs.recommended],18 rules: {19 '@typescript-eslint/no-var-requires': 'off', // (tseslint does not autodetect commonjs context )20 },23 }, {21 },22 {23 files: tsconfigTsFiles,24 languageOptions: {25 parserOptions: { project: './tsconfig.ts.json' },26 },28 extends: [29 ...tseslint.configs.recommended,30 ],27 extends: [...tseslint.configs.recommended],28 },29);3031module.exports = [
23 unmodified lines
55 {56 files: ['**/*.test.{js,mjs,cjs}'],57 rules: {58 'no-unused-vars': 'off', // lots in tests, minimise churn for now62 }59 },60 },61 {62 files: [...tsconfigTsFiles, ...tsconfigJsFiles],63 rules: {64 '@typescript-eslint/ban-ts-comment': [65 'error',67 '@typescript-eslint/ban-ts-comment': ['error', {68 'ts-expect-error': 'allow-with-description',69 'ts-ignore': 'allow-with-description',70 'ts-nocheck': true,71 'ts-check': true,72 }],66 {67 'ts-expect-error': 'allow-with-description',68 'ts-ignore': 'allow-with-description',69 'ts-nocheck': true,70 'ts-check': true,71 },72 ],73 },74 },75];
modified:esm.mjs+1 added-1 removed
10 unmodified lines
11 InvalidOptionArgumentError, // deprecated old name12 Command,13 Argument,14 Option,15 Help15 Help,16} = commander;
modified:jest.config.js+2 added-4 removed
1const config = {2 testEnvironment: 'node',3 collectCoverage: true,4 transform: {5 '^.+\\.tsx?$': ['ts-jest', { tsconfig: 'tsconfig.ts.json' }]5 '^.+\\.tsx?$': ['ts-jest', { tsconfig: 'tsconfig.ts.json' }],6 },7 testPathIgnorePatterns: [8 '/node_modules/'9 ]7 testPathIgnorePatterns: ['/node_modules/'],8};910module.exports = config;
modified:tsconfig.js.json+4 added-3 removed
1{ /* 1{2 /* 3 Simple override including just JavaScript files.4 Used by npm run-script typecheck:js5 */6 /* Visit https://aka.ms/tsconfig to read more about tsconfig configuration. */7 "extends": "./tsconfig.json",8 "include": [9 /* All JavaScript targets from tsconfig.json include. */10 "*.js",10 ".prettierrc.js", /* missed by above pattern */11 ".prettierrc.js" /* missed by above pattern */,12 "*.mjs",12 "lib/**/*.js"13 "lib/**/*.js",14 ],15}
modified:tsconfig.json+10 added-15 removed
14 unmodified lines
15 "target": "es2021",1617 "allowJs": true,18 "checkJs": true,19 1920 /* Strict by default, but dial it down to reduce churn in our JavaScript code. */21 "strict": true,22 "noImplicitAny": false, 22 "noImplicitAny": false,23 "strictNullChecks": false,24 "useUnknownInCatchVariables": false,2526 "types": [27 "node",28 "jest"29 ],30 "noEmit": true, /* just type checking and not emitting transpiled files */31 "skipLibCheck": false, /* we want to check our hand crafted definitions */26 "types": ["node", "jest"],27 "noEmit": true /* just type checking and not emitting transpiled files */,28 "skipLibCheck": false /* we want to check our hand crafted definitions */,29 "forceConsistentCasingInFileNames": true,33 "esModuleInterop": true, /* common TypeScript config */34 "resolveJsonModule": true, /* needed for globals in node_modules?! */30 "esModuleInterop": true /* common TypeScript config */,31 "resolveJsonModule": true /* needed for globals in node_modules?! */,32 },33 "include": [34 /* JavaScript. Should match includes in tsconfig.js.json. */35 "*.js",39 ".prettierrc.js", /* missed by above pattern */36 ".prettierrc.js" /* missed by above pattern */,37 "*.mjs",38 "lib/**/*.js",39 /* TypeScript. Should match includes in tsconfig.ts.json. */40 "**/*.ts",44 "**/*.mts"41 "**/*.mts",42 ],46 "exclude": [47 "node_modules"48 ]43 "exclude": ["node_modules"],44}
modified:tsconfig.ts.json+4 added-3 removed
1{ /* 1{2 /* 3 Override to include just TypeScript files and use stricter settings than we do with JavaScript.4 Used by:5 - npm run-script typecheck:ts6 */7 /* Visit https://aka.ms/tsconfig to read more about tsconfig configuration. */8 "extends": "./tsconfig.json",9 "compilerOptions": {10 /* Full strict is fine for the TypeScript files, so turn back on the checks we turned off for mixed-use. */10 "noImplicitAny": true, 11 "noImplicitAny": true,12 "strictNullChecks": true,13 "useUnknownInCatchVariables": true,14 },15 "include": [16 /* All TypeScript targets from tsconfig.json include. */17 "**/*.ts",17 "**/*.mts"18 "**/*.mts",19 ],20}