Skip to content
Myr

Switching to esm-only (#2464)

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

* Change to explicit .mjs for implementation files * Remove stale jest.config.js * move esm.mjs to deprecated and GONE * Convert tests to esm, and use .js file extension for esm * Replace __filename and __dirname usage * Fix color issues in tests by not rendering arrays using console.log * Convert examples to erm * Fix URL in comment * Update samples to esm in README * Fix version in deprecation notes * Run tests using mocks of node module methods in cjs where better supported * Add migration tips and examples for require(esm) * Rename files so Jest tests in examples not run with Commander tests

authored by John Gee · committed by GitHub · parent b51c0ea · Browse files · 191 files+1455 added−1194 removed
This commit

State

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

Diff stats

191 files+1455 added−1194 removed

  • tests:+1050 added−950 removed
  • other:+405 added−244 removed

191 files+1455 added−1194 removed

modified:docs/deprecated.md+19 added-17 removed
10 unmodified lines
11 - [.on('command:\*')](#oncommand)12 - [.command('\*')](#command)13 - [cmd.description(cmdDescription, argDescriptions)](#cmddescriptioncmddescription-argdescriptions)14 - [InvalidOptionArgumentError](#invalidoptionargumenterror)15 - [Import from `commander/esm.mjs`](#import-from-commanderesmmjs)15 - [cmd.\_args](#cmd_args)16 - [.addHelpCommand(string|boolean|undefined)](#addhelpcommandstringbooleanundefined)17 - [Removed](#removed)18 - [Short option flag longer than a single character](#short-option-flag-longer-than-a-single-character)19 - [Default import of global Command object](#default-import-of-global-command-object)20 - [Import from `commander/esm.mjs`](#import-from-commanderesmmjs)2122### RegExp .option() parameter2324The `.option()` method allowed a RegExp as the third parameter to restrict what values were accepted.
142 unmodified lines
167```168169Deprecated from Commander v8.170171### Import from `commander/esm.mjs`172173The first support for named imports required an explicit entry file.174175```js176import { Command } from 'commander/esm.mjs';177```178179This is no longer required, just import directly from the module.180181```js182import { Command } from 'commander';183```184185README updated in Commander v9. Deprecated from Commander v9.186171### cmd._args172173This was always private, but was previously the only way to access the command `Argument` array.174
64 unmodified lines
239- Removed from README in Commander v5.240- Deprecated from Commander v7.241- Removed from TypeScript declarations in Commander v8.242- Removed from CommonJS in Commander v12. Deprecated and gone!243244### Import from `commander/esm.mjs`245246The first support for named imports required an explicit entry file.247248```js249import { Command } from 'commander/esm.mjs';250```251252This is no longer required, just import directly from the module.253254```js255import { Command } from 'commander';256```257258- README updated in Commander v9. Deprecated from Commander v9.259- Deleted in Command v15. Deprecated and gone!260
added:examples/using-esm-from-commonjs/jest-javascript/.gitignore+4 added
1node_modules/23# Save space, do not commit package-lock.json with all the Jest dependencies!4package-lock.json
added:examples/using-esm-from-commonjs/jest-javascript/babel.config.js+3 added
added:examples/using-esm-from-commonjs/jest-javascript/index.spec.cjs+9 added
added:examples/using-esm-from-commonjs/jest-javascript/jest.config.js+6 added
added:examples/using-esm-from-commonjs/jest-javascript/package.json+17 added
added:examples/using-esm-from-commonjs/jest-javascript/README.md+40 added
added:examples/using-esm-from-commonjs/jest-typescript/.gitignore+4 added
1node_modules/23# Save space, do not commit package-lock.json with all the Jest dependencies!4package-lock.json
added:examples/using-esm-from-commonjs/jest-typescript/index.spec.cts+9 added
1import { Command } from 'commander';2import { test, expect } from '@jest/globals';34test('when set command name then get command name', () => {5 const program = new Command();6 const name = 'my-cli';7 program.name(name);8 expect(program.name()).toBe(name);9});
added:examples/using-esm-from-commonjs/jest-typescript/jest.config.js+16 added
1// List the dependencies that are pure esm and need transformation.2const esmModules = ['commander'].join('|'); // redundant join in case you have others34module.exports = {5 // 1. tell ts-jest to (also) handle .js and .mjs files6 transform: {7 '^.+\\.[cm]?[tj]sx?$': [8 'ts-jest',9 {10 useESM: false, // want CJS for Jest11 },12 ],13 },14 // 2. allow transformation of specific node_modules15 transformIgnorePatterns: [`node_modules/(?!(${esmModules})/)`],16};
added:examples/using-esm-from-commonjs/jest-typescript/package.json+18 added
1{2 "name": "jest-typescript",3 "version": "1.0.0",4 "description": "",5 "scripts": {6 "test": "jest"7 },8 "license": "MIT",9 "type": "commonjs",10 "dependencies": {11 "commander": "^15.0.0"12 },13 "devDependencies": {14 "jest": "^30.2.0",15 "ts-jest": "^29.4.6",16 "typescript": "^5.9.3"17 }18}
added:examples/using-esm-from-commonjs/jest-typescript/README.md+34 added
1# Example configuration for Jest 30 running CommonJS from TypeScript23This project shows using `ts-jest` to transform Commander ESM to CommonJS.45Example error message when requiring ESM-only Commander in a Jest test with default configuration:67```8$ npm run --silent test9 FAIL ./index.test.ts10 ● Test suite failed to run1112 Jest encountered an unexpected token1314 Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.1516 [more detail omitted, check output for up-to-date suggestions]17...18 import { Command } from 'commander';19 ^^^^^^2021 SyntaxError: Cannot use import statement outside a module22...23```2425Additional setup:2627- see two tweaks in `jest.config.js` to use `ts-jest` to convert Commander ESM to CommonJS2829Running test:3031```console32npm install33npm test34```
added:examples/using-esm-from-commonjs/jest-typescript/tsconfig.json+44 added
1{2 // Visit https://aka.ms/tsconfig to read more about this file3 "compilerOptions": {4 // File Layout5 // "rootDir": "./src",6 // "outDir": "./dist",78 // Environment Settings9 // See also https://aka.ms/tsconfig/module10 "module": "nodenext",11 "target": "esnext",12 "types": [],13 // For nodejs:14 // "lib": ["esnext"],15 // "types": ["node"],16 // and npm install -D @types/node1718 // Other Outputs19 "sourceMap": true,20 "declaration": true,21 "declarationMap": true,2223 // Stricter Typechecking Options24 "noUncheckedIndexedAccess": true,25 "exactOptionalPropertyTypes": true,2627 // Style Options28 // "noImplicitReturns": true,29 // "noImplicitOverride": true,30 // "noUnusedLocals": true,31 // "noUnusedParameters": true,32 // "noFallthroughCasesInSwitch": true,33 // "noPropertyAccessFromIndexSignature": true,3435 // Recommended Options36 "strict": true,37 "jsx": "react-jsx",38 "verbatimModuleSyntax": false, // we want import to be output as require, not verbatim39 "isolatedModules": true,40 "noUncheckedSideEffectImports": true,41 "moduleDetection": "force",42 "skipLibCheck": true,43 },44}
modified:examples/action-this.js+1 added-1 removed
1#!/usr/bin/env node23// This example is used as an example in the README for the action handler.45const { Command } = require('commander');5import { Command } from 'commander';6const program = new Command();78program9 .command('serve')
10 unmodified lines
added:examples/alias.cjs+36 added
1#!/usr/bin/env node23// This example shows giving alternative names for a command.45const { Command } = require('commander');6const program = new Command();78program9 .command('exec')10 .argument('<script>')11 .alias('ex')12 .action((script) => {13 console.log(`execute: ${script}`);14 });1516program17 .command('print')18 .argument('<file>')19 // Multiple aliases is unusual but supported! You can call alias multiple times,20 // and/or add multiple aliases at once. Only the first alias is displayed in the help.21 .alias('p')22 .alias('pr')23 .aliases(['display', 'show'])24 .action((file) => {25 console.log(`print: ${file}`);26 });2728program.parse();2930// Try the following:31// node alias.cjs --help32// node alias.cjs exec script33// node alias.cjs ex script34// node alias.cjs print file35// node alias.cjs pr file36// node alias.cjs show file
deleted:examples/alias.js-36 removed
1#!/usr/bin/env node23// This example shows giving alternative names for a command.45const { Command } = require('commander');6const program = new Command();78program9 .command('exec')10 .argument('<script>')11 .alias('ex')12 .action((script) => {13 console.log(`execute: ${script}`);14 });1516program17 .command('print')18 .argument('<file>')19 // Multiple aliases is unusual but supported! You can call alias multiple times,20 // and/or add multiple aliases at once. Only the first alias is displayed in the help.21 .alias('p')22 .alias('pr')23 .aliases(['display', 'show'])24 .action((file) => {25 console.log(`print: ${file}`);26 });2728program.parse();2930// Try the following:31// node alias.js --help32// node alias.js exec script33// node alias.js ex script34// node alias.js print file35// node alias.js pr file36// node alias.js show file
modified:examples/argument.js+1 added-1 removed
1#!/usr/bin/env node23// This example shows specifying the command arguments using argument() function.45const { Command } = require('commander');5import { Command } from 'commander';6const program = new Command();78program9 .name('connect')
14 unmodified lines
modified:examples/arguments-custom-processing.js+3 added-3 removed
2 unmodified lines
3// This is used as an example in the README for:4// Custom argument processing5// You may specify a function to do custom processing of argument values.67const commander = require('commander');8const program = new commander.Command();7import { Command, InvalidArgumentError } from 'commander';8const program = new Command();910function myParseInt(value) {11 // parseInt takes a string and a radix12 const parsedValue = parseInt(value, 10);13 if (isNaN(parsedValue)) {14 throw new commander.InvalidArgumentError('Not a number.');14 throw new InvalidArgumentError('Not a number.');15 }16 return parsedValue;17}18
28 unmodified lines
modified:examples/arguments-extra.js+4 added-7 removed
1#!/usr/bin/env node23// This is used as an example in the README for extra argument features.45const commander = require('commander');6const program = new commander.Command();5import { Command, Argument } from 'commander';6const program = new Command();78program9 .addArgument(10 new commander.Argument('<drink-size>', 'drink cup size').choices([10 new Argument('<drink-size>', 'drink cup size').choices([11 'small',12 'medium',13 'large',14 ]),15 )16 .addArgument(17 new commander.Argument('[timeout]', 'timeout in seconds').default(18 60,19 'one minute',20 ),17 new Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'),18 )19 .action((drinkSize, timeout) => {20 console.log(`Drink size: ${drinkSize}`);21 console.log(`Timeout (s): ${timeout}`);
9 unmodified lines
modified:examples/configure-help.js+2 added-2 removed
1const commander = require('commander');2const program = new commander.Command();1import { Command } from 'commander';2const program = new Command();34// This example shows a simple use of configureHelp.5// This is used as an example in the README.6// Any method on the Help class can be overridden
24 unmodified lines
modified:examples/configure-output.js+2 added-2 removed
1const commander = require('commander');2const program = new commander.Command();1import { Command } from 'commander';2const program = new Command();34function errorColor(str) {5 // Add ANSI escape codes to display text in red.6 return `\x1b[31m${str}\x1b[0m`;
19 unmodified lines
modified:examples/custom-command-class.js+3 added-3 removed
1#!/usr/bin/env node2const commander = require('commander');2import { Command } from 'commander';34// Use a class override to customise the command and its subcommands.56class CommandWithTrace extends commander.Command {6class CommandWithTrace extends Command {7 createCommand(name) {8 const cmd = new CommandWithTrace(name);9 // Add an option to subcommands created using `.command()`10 cmd.option('-t, --trace', 'display extra information when run command');
8 unmodified lines
19 console.log('opts: %o', command.opts());20}2122const program = new CommandWithTrace('program')23 .option('-v, ---verbose')23 .option('-v, --verbose')24 .action((options, command) => {25 inspectCommand(command);26 });27
19 unmodified lines
modified:examples/custom-help+1 added-1 removed
1 unmodified line
23// This example shows a simple use of addHelpText.4// This is used as an example in the README.56const { Command } = require('commander');6import { Command } from 'commander';7const program = new Command();89program.option('-f, --foo', 'enable some foo');10
12 unmodified lines
modified:examples/custom-help-description+1 added-1 removed
1#!/usr/bin/env node23// This example shows changing the flags and description for the help option.45const { Command } = require('commander');5import { Command } from 'commander';6const program = new Command();78program9 .helpOption('-c, --HELP', 'custom help message')
15 unmodified lines
modified:examples/custom-help-text.js+1 added-1 removed
1#!/usr/bin/env node23// This example shows using addHelpText.45const { Command } = require('commander');5import { Command } from 'commander';6const program = new Command();78program.name('awesome');9
26 unmodified lines
modified:examples/custom-version+1 added-1 removed
1#!/usr/bin/env node23// This example shows changing the flags and description for the version option.45const { Command } = require('commander');5import { Command } from 'commander';6const program = new Command();78program9 .version('0.0.1', '-v, --VERSION', 'new version message')
8 unmodified lines
modified:examples/defaultCommand.js+2 added-2 removed
1#!/usr/bin/env node23const commander = require('commander');4const program = new commander.Command();3import { Command } from 'commander';4const program = new Command();56// Example program using the command configuration option isDefault to specify the default command.78program
27 unmodified lines
modified:examples/deploy+1 added-1 removed
1#!/usr/bin/env node23const { Command } = require('commander');3import { Command } from 'commander';4const program = new Command();56program7 .name('deploy')
36 unmodified lines
modified:examples/description+1 added-1 removed
1#!/usr/bin/env node23// This example shows adding a description which is displayed in the help.45const { Command } = require('commander');5import { Command } from 'commander';6const program = new Command();78program9 .version('0.0.1')
14 unmodified lines
modified:examples/global-options-added.js+1 added-1 removed
7 unmodified lines
8//9// (A different pattern for a "global" option is to add it to the root command, rather10// than to the subcommand. See global-options-nested.js.)1112const { Command } = require('commander');12import { Command } from 'commander';1314// Common options can be added when subcommands are created by using a custom subclass.15// If the options are unsorted in the help, these will appear first.16class MyRootCommand extends Command {
36 unmodified lines
modified:examples/global-options-nested.js+1 added-1 removed
4 unmodified lines
5//6// (A different pattern for a "global" option is to add it to the subcommands, rather7// than to the program. See global-options-added.js.)89const { Command } = require('commander');9import { Command } from 'commander';10const program = new Command();1112program.configureHelp({ showGlobalOptions: true }).option('-g, --global');13
15 unmodified lines
modified:examples/help-groups.js+1 added-1 removed
1const { Command, Option } = require('commander');1import { Command, Option } from 'commander';23// Show the two approaches for adding help groups, and how to customise the built-in help and version.45const program = new Command();
70 unmodified lines
modified:examples/help-subcommands-usage.js+2 added-2 removed
1const commander = require('commander');1import { Command } from 'commander';23// By default the subcommand list includes a fairly simple usage. If you have added a custom usage4// to the subcommands you may wish to configure the help to show these instead.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().configureHelp({9const program = new Command().configureHelp({10 subcommandTerm: (cmd) => cmd.name() + ' ' + cmd.usage(),11});1213program
20 unmodified lines
modified:examples/hook.js+1 added-1 removed
1#!/usr/bin/env node23const { Command, Option } = require('commander');3import { Command, Option } from 'commander';4const program = new Command();56// This example shows using some hooks for life cycle events.7
64 unmodified lines
modified:examples/nestedCommands.js+3 added-3 removed
1#!/usr/bin/env node23const commander = require('commander');4const program = new commander.Command();3import { Command } from 'commander';4const program = new Command();56// Commander supports nested subcommands.7// .command() can add a subcommand with an action handler or an executable.8// .addCommand() adds a prepared command with an action handler.
9 unmodified lines
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');22 const heat = new Command('heat');23 heat.command('jug').action(() => {24 console.log('heat jug');25 });26 heat.command('pot').action(() => {
11 unmodified lines
modified:examples/options-boolean-or-value.js+2 added-2 removed
2 unmodified lines
3// This is used as an example in the README for:4// Other option types, flag|value5// You can specify an option which functions as a flag but may also take a value (declared using square brackets).67const commander = require('commander');8const program = new commander.Command();7import { Command } from 'commander';8const program = new Command();910program.option('-c, --cheese [type]', 'Add cheese with optional type');1112program.parse(process.argv);
10 unmodified lines
modified:examples/options-common.js+2 added-2 removed
1 unmodified line
23// This is used as an example in the README for:4// Common option types, boolean and value56const commander = require('commander');7const program = new commander.Command();6import { Command } from 'commander';7const program = new Command();89program10 .option('-d, --debug', 'output extra debugging')11 .option('-s, --small', 'small pizza size')
14 unmodified lines
modified:examples/options-conflicts.js+1 added-1 removed
1#!/usr/bin/env node2const { Command, Option } = require('commander');2import { Command, Option } from 'commander';3const program = new Command();45// You can use .conflicts() with a single string, which is the camel-case name of the conflicting option.6program
80 unmodified lines
modified:examples/options-custom-processing.js+3 added-3 removed
2 unmodified lines
3// This is used as an example in the README for:4// Custom option processing5// You may specify a function to do custom processing of option values.67const commander = require('commander');8const program = new commander.Command();7import { Command, InvalidArgumentError } from 'commander';8const program = new Command();910function myParseInt(value) {11 // parseInt takes a string and a radix12 const parsedValue = parseInt(value, 10);13 if (isNaN(parsedValue)) {14 throw new commander.InvalidArgumentError('Not a number.');14 throw new InvalidArgumentError('Not a number.');15 }16 return parsedValue;17}18
39 unmodified lines
modified:examples/options-defaults.js+2 added-2 removed
1 unmodified line
23// This is used as an example in the README for:4// Default option value56const commander = require('commander');7const program = new commander.Command();6import { Command } from 'commander';7const program = new Command();89program.option(10 '-c, --cheese <type>',11 'Add the specified type of cheese',
10 unmodified lines
modified:examples/options-env.js+1 added-1 removed
1#!/usr/bin/env node2const { Command, Option } = require('commander');2import { Command, Option } from 'commander';3const program = new Command();45program.addOption(6 new Option('-p, --port <number>', 'specify port number')
33 unmodified lines
modified:examples/options-extra.js+1 added-1 removed
2 unmodified lines
3// This is used as an example in the README for extra option features.4// See also options-env.js for more extensive env examples,5// and options-conflicts.js for more details about .conflicts().67const { Command, Option } = require('commander');7import { Command, Option } from 'commander';8const program = new Command();910program11 .addOption(new Option('-s, --secret').hideHelp())
40 unmodified lines
modified:examples/options-implies.js+1 added-1 removed
1#!/usr/bin/env node2const { Command, Option } = require('commander');2import { Command, Option } from 'commander';3const program = new Command();45program6 .addOption(new Option('--quiet').implies({ logLevel: 'off' }))
27 unmodified lines
modified:examples/options-negatable.js+2 added-2 removed
2 unmodified lines
3// This is used as an example in the README for:4// Other option types, negatable boolean5// You can specify a boolean option long name with a leading `no-` to make it true by default and able to be negated.67const commander = require('commander');8const program = new commander.Command();7import { Command } from 'commander';8const program = new Command();910program11 .option('--no-sauce', 'Remove sauce')12 .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
15 unmodified lines
modified:examples/options-required.js+2 added-2 removed
3 unmodified lines
4// Required option5// You may specify a required (mandatory) option using `.requiredOption`.6// The option must be specified on the command line, or by having a default value.78const commander = require('commander');9const program = new commander.Command();8import { Command } from 'commander';9const program = new Command();1011program.requiredOption('-c, --cheese <type>', 'pizza must have cheese');1213program.parse();
6 unmodified lines
modified:examples/options-variadic.js+2 added-2 removed
1#!/usr/bin/env node23// This is used as an example in the README for variadic options.45const commander = require('commander');6const program = new commander.Command();5import { Command } from 'commander';6const program = new Command();78program9 .option('-n, --number <value...>', 'specify numbers')10 .option('-l, --letter [value...]', 'specify letters');
10 unmodified lines
modified:examples/pass-through-options.js+1 added-1 removed
1#!/usr/bin/env node23const { Command } = require('commander');3import { Command } from 'commander';4const program = new Command();56program7 .argument('<utility>')
15 unmodified lines
modified:examples/pizza+2 added-2 removed
1#!/usr/bin/env node23const { Command } = require('commander');3import { Command } from 'commander';4const program = new Command();56program7 .description('An application for pizza ordering')
12 unmodified lines
20// Try the following on macOS or Linux:21// ./pizza --help22//23// Try the following:24// ./pizza --help24// node pizza --help25// node pizza --peppers --cheese=blue26// node pizza --no-cheese
modified:examples/pm+1 added-1 removed
1#!/usr/bin/env node23const { Command } = require('commander');3import { Command } from 'commander';4const program = new Command();56// Example of subcommands which are implemented as stand-alone executable files.7//
29 unmodified lines
modified:examples/pm-install+1 added-1 removed
1#!/usr/bin/env node23const { Command } = require('commander');3import { Command } from 'commander';4const program = new Command();56program.option('-f, --force', 'force installation');7program.argument('[package-names...]');
16 unmodified lines
modified:examples/positional-options.js+1 added-1 removed
1#!/usr/bin/env node23const { Command } = require('commander');3import { Command } from 'commander';4const program = new Command();56program.enablePositionalOptions().option('-p, --progress');7
16 unmodified lines
modified:examples/split.js+1 added-1 removed
1const { program } = require('commander');1import { program } from 'commander';23// This is used as an example in the README for the Quick Start.45program.option('--first').option('-s, --separator <char>').argument('<string>');
11 unmodified lines
modified:examples/string-util.js+1 added-1 removed
1const { Command } = require('commander');1import { Command } from 'commander';2const program = new Command();34// This is used as an example in the README for the Quick Start.5
33 unmodified lines
modified:examples/thank.js+1 added-1 removed
1#!/usr/bin/env node23// This example is used as an example in the README for the action handler.45const { Command } = require('commander');5import { Command } from 'commander';6const program = new Command();78program9 .argument('<name>')
16 unmodified lines
modified:lib/argument.js+3 added-6 removed
1const { InvalidArgumentError } = require('./error.js');1import { InvalidArgumentError } from './error.js';23class Argument {3export class Argument {4 /**5 * Initialize a new command argument with the given name and description.6 * The default is that the argument is required, and you can explicitly7 * indicate this with <> around the name. Put [] around the name for an optional argument.
131 unmodified lines
139 * @return {string}140 * @private141 */142143function humanReadableArgName(arg) {143export function humanReadableArgName(arg) {144 const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');145146 return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';147}148149exports.Argument = Argument;150exports.humanReadableArgName = humanReadableArgName;
modified:lib/command.js+17 added-18 removed
1const EventEmitter = require('node:events').EventEmitter;2const childProcess = require('node:child_process');3const path = require('node:path');4const fs = require('node:fs');5const process = require('node:process');1import { EventEmitter } from 'node:events';2import childProcess from 'node:child_process';3import path from 'node:path';4import fs from 'node:fs';5import process from 'node:process';67const { Argument, humanReadableArgName } = require('./argument.js');8const { CommanderError } = require('./error.js');9const { Help, stripColor } = require('./help.js');10const { Option, DualOptions } = require('./option.js');11const { suggestSimilar } = require('./suggestSimilar');7import { Argument, humanReadableArgName } from './argument.js';8import { CommanderError } from './error.js';9import { Help, stripColor } from './help.js';10import { Option, DualOptions } from './option.js';11import { suggestSimilar } from './suggestSimilar.js';1213class Command extends EventEmitter {13export class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *17 * @param {string} [name]
2400 unmodified lines
2418 }24192420 /**2421 * Set the name of the command from script filename, such as process.argv[1],2422 * or require.main.filename, or __filename.2422 * or import.meta.filename.2423 *2424 * (Used internally and public although not documented in README.)2425 *2426 * @example2427 * program.nameFromFilename(require.main.filename);2427 * program.nameFromFilename(import.meta.filename);2428 *2429 * @param {string} filename2430 * @return {Command}2431 */
7 unmodified lines
2439 /**2440 * Get or set the directory for searching for executable subcommands of this command.2441 *2442 * @example2443 * program.executableDir(__dirname);2443 * program.executableDir(import.meta.dirname);2444 * // or2445 * program.executableDir('subcommands');2446 *2447 * @param {string} [path]
311 unmodified lines
2759 });2760}27612762/**2763 * Exported for using from tests, not otherwise used outside this file.2764 *2765 * @returns {boolean | undefined}2766 * @package2767 */2766function useColor() {2768export function useColor() {2769 // Test for common conventions.2770 // NB: the observed behaviour is in combination with how author adds color! For example:2771 // - we do not test NODE_DISABLE_COLORS, but util:styletext does2772 // - we do test NO_COLOR, but Chalk does not
14 unmodified lines
2787 if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== undefined)2788 return true;2789 return undefined;2790}27892790exports.Command = Command;2791exports.useColor = useColor; // exporting for tests
modified:lib/error.js+2 added-5 removed
1/**2 * CommanderError class3 */4class CommanderError extends Error {4export class CommanderError extends Error {5 /**6 * Constructs the CommanderError class7 * @param {number} exitCode suggested exit code which could be used with process.exit8 * @param {string} code an id string representing the error
12 unmodified lines
2122/**23 * InvalidArgumentError class24 */25class InvalidArgumentError extends CommanderError {25export class InvalidArgumentError extends CommanderError {26 /**27 * Constructs the InvalidArgumentError class28 * @param {string} [message] explanation of why argument is invalid29 */
3 unmodified lines
33 Error.captureStackTrace(this, this.constructor);34 this.name = this.constructor.name;35 }36}3738exports.CommanderError = CommanderError;39exports.InvalidArgumentError = InvalidArgumentError;
modified:lib/help.js+3 added-6 removed
1const { humanReadableArgName } = require('./argument.js');1import { humanReadableArgName } from './argument.js';23/**4 * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`5 * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
2 unmodified lines
8 * @typedef { import("./option.js").Option } Option9 */1011// Although this is a class, methods are static in style to allow override using subclass or just functions.12class Help {12export class Help {13 constructor() {14 this.helpWidth = undefined;15 this.minWidthToWrap = 40;16 this.sortSubcommands = false;
719 unmodified lines
736 * @returns {string}737 * @package738 */739740function stripColor(str) {740export function stripColor(str) {741 // eslint-disable-next-line no-control-regex742 const sgrPattern = /\x1b\[\d*(;\d*)*m/g;743 return str.replace(sgrPattern, '');744}745746exports.Help = Help;747exports.stripColor = stripColor;
modified:lib/option.js+3 added-6 removed
1const { InvalidArgumentError } = require('./error.js');1import { InvalidArgumentError } from './error.js';23class Option {3export class Option {4 /**5 * Initialize a new `Option` with the given `flags` and `description`.6 *7 * @param {string} flags
256 unmodified lines
264 * like `--build` and `--no-build`, which share a single option value. This works nicely for some265 * use cases, but is tricky for others where we want separate behaviours despite266 * the single shared option value.267 */268class DualOptions {268export class DualOptions {269 /**270 * @param {Option[]} options271 */272 constructor(options) {
101 unmodified lines
374 );375376 return { shortFlag, longFlag };377}378379exports.Option = Option;380exports.DualOptions = DualOptions;
modified:lib/suggestSimilar.js+1 added-3 removed
51 unmodified lines
52 * @param {string[]} candidates53 * @returns {string}54 */5556function suggestSimilar(word, candidates) {56export function suggestSimilar(word, candidates) {57 if (!candidates || candidates.length === 0) return '';58 // remove possible duplicates59 candidates = Array.from(new Set(candidates));60
35 unmodified lines
96 return `\n(Did you mean ${similar[0]}?)`;97 }98 return '';99}100101exports.suggestSimilar = suggestSimilar;
modified:tests/fixtures/inspect-sub.js+1 added-1 removed
1console.log(process.execArgv);1console.log(JSON.stringify(process.execArgv));
modified:tests/fixtures/inspect.js+1 added-3 removed
1#!/usr/bin/env node23const { program } = require('../../');3import { program } from '../../index.js';45process.env.FORCE_COLOR = 0; // work-around bug in Jest: https://github.com/jestjs/jest/issues/1439165program.command('sub', 'install one or more packages').parse(process.argv);
modified:tests/fixtures/pm+4 added-6 removed
1#!/usr/bin/env node23const path = require('node:path');4const { program } = require('../../');3import * as path from 'node:path';4import { program } from '../../index.js';56process.env.FORCE_COLOR = 0; // work-around bug in Jest: https://github.com/jestjs/jest/issues/1439176program7 .version('0.0.1')8 .command('install [name]', 'install one or more packages')9 .alias('i')
24 unmodified lines
34 .exitOverride((err) => {35 process.exit(err.exitCode);36 })37 .command('fail', 'exit with non-zero status code', {40 executableFile: path.join(__dirname, 'pm-fail.js'),38 executableFile: path.join(import.meta.dirname, 'pm-fail.js'),39 })40 .command('terminate', 'terminate due to signal', {43 executableFile: path.join(__dirname, 'pm-terminate.js'),41 executableFile: path.join(import.meta.dirname, 'pm-terminate.js'),42 });4344program.parse(process.argv);
modified:tests/fixtures/pm-cache.js+1 added-1 removed
1const { program } = require('../../');1import { program } from '../../index.js';23program4 .command('clear', 'clear the cache')5 .command('validate', 'validate the cache', { isDefault: true })
1 unmodified line
modified:tests/fixtures/pm-default+1 added-1 removed
1#!/usr/bin/env node2console.log('default');3if (process.argv.length > 2) {4 console.log(process.argv.slice(2));4 console.log(JSON.stringify(process.argv.slice(2)));5}
modified:tests/fixtures/pm-echo.js+1 added-1 removed
1console.log(process.argv.slice(2));1console.log(JSON.stringify(process.argv.slice(2)));
modified:tests/fixtures-extensions/pm.js+1 added-1 removed
1#!/usr/bin/env node23const { program } = require('../../');3import { program } from '../../index.js';45program6 .command('try-ts', 'test file extension lookup')7 .command('try-cjs', 'test file extension lookup')
2 unmodified lines
modified:tests/args.literal.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Utility Conventions: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_026//7// 12.2 Utility Syntax Guidelines, Guideline 10:
27 unmodified lines
modified:tests/args.variadic.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Testing variadic arguments.67describe('Command variadic argument using .arguments() or .command()', () => {
71 unmodified lines
modified:tests/argument.chain.test.js+3 added-3 removed
1const { Argument } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Argument } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Argument methods that should return this for chaining', () => {6 test('when call .default() then returns this', () => {7 const argument = new Argument('<value>');
28 unmodified lines
modified:tests/argument.choices.test.js+4 added-4 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56describe('Argument.choices()', () => {7 test('when command argument in choices then argument set', () => {8 const program = createTestCommand();
49 unmodified lines
modified:tests/argument.custom-processing.test.js+4 added-4 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56// Testing default value and custom processing behaviours.7// Some double assertions in tests to check action argument and .processedArg8
187 unmodified lines
modified:tests/argument.required.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Low-level tests of setting Argument.required.6// Higher level tests of optional/required arguments elsewhere.7
31 unmodified lines
modified:tests/argument.variadic.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Testing variadic arguments. Testing all the action arguments, but could test just variadicArg.67describe('Command variadic argument using .argument()', (t) => {
113 unmodified lines
modified:tests/command.action.test.js+4 added-4 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56// Test some behaviours of .action not covered in more specific tests.78describe('Command.action()', () => {
158 unmodified lines
modified:tests/command.addCommand.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Command.addCommand()', () => {6 // simple sanity check subcommand works7 test('when addCommand and specify subcommand then called', (t) => {
54 unmodified lines
modified:tests/command.addHelpOption.test.js+4 added-4 removed
1const { Option } = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import { Option } from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56// More complete tests are in command.helpOption.test.js.78describe('Command.addHelpOption()', () => {
33 unmodified lines
modified:tests/command.addHelpText.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe, beforeEach } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe, beforeEach } from 'node:test';3import assert from 'node:assert/strict';45// Using outputHelp to simplify testing.67describe('Command.addHelpText(): program calls to addHelpText', () => {
232 unmodified lines
modified:tests/command.alias.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Running alias commands is tested in command.executableSubcommand.lookup.test.js6// Test various other behaviours for .alias7
103 unmodified lines
modified:tests/command.allowExcessArguments.test.js+3 added-3 removed
1const { createTestCommand } = require('./testHelpers');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { createTestCommand } from './testHelpers.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Not testing output, just testing whether an error is detected.67describe('Command.allowExcessArguments()', () => {
108 unmodified lines
modified:tests/command.allowUnknownOption.test.js+3 added-3 removed
1const { createTestCommand } = require('./testHelpers');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { createTestCommand } from './testHelpers.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Not testing output, just testing whether an error is detected.67describe('Command.allowUnknownOption()', () => {
72 unmodified lines
modified:tests/command.argumentVariations.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Do some low-level checks that the multiple ways of specifying command arguments produce same internal result,6// and not exhaustively testing all methods elsewhere.7
128 unmodified lines
modified:tests/command.asterisk.test.js+4 added-4 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56// .command('*') is the old main/default command handler. It adds a listener7// for 'command:*'. It has been somewhat replaced by the program action handler,8// so most uses are probably old code. Current plan is keep the code backwards compatible
126 unmodified lines
modified:tests/command.chain.test.js+3 added-3 removed
1const { Command, Option, Argument } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Command, Option, Argument } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Testing the functions which should chain.6// parse and parseAsync are tested in command.parse.test.js7
273 unmodified lines
modified:tests/command.commandHelp.test.js+3 added-3 removed
1const commander = require('../');2const { test } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test } from 'node:test';3import assert from 'node:assert/strict';45// This is a ported legacy test.67test('when program has command then appears in help', () => {
12 unmodified lines
modified:tests/command.configureHelp.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Command.configureHelp()', () => {6 test('when configure program then affects program helpInformation', () => {7 const program = new commander.Command();
36 unmodified lines
modified:tests/command.configureOutput.test.js+4 added-4 removed
1const { test, describe } = require('node:test');2const assert = require('node:assert/strict');3const commander = require('../');4const process = require('node:process');1import { test, describe } from 'node:test';2import assert from 'node:assert/strict';3import * as commander from '../index.js';4import process from 'node:process';56describe('Command.configureOutput()', () => {7 test('when default writeErr() then error on stderr', (t) => {8 const writeSpy = t.mock.method(process.stderr, 'write', () => {});
337 unmodified lines
modified:tests/command.copySettings.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Tests some private properties as simpler than pure tests of observable behaviours.6// Testing before and after values in some cases, to ensure value actually changes (when copied).7
143 unmodified lines
modified:tests/command.createArgument.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45class MyArgument extends commander.Argument {6 constructor(name, description) {7 super(name, description);
37 unmodified lines
modified:tests/command.createHelp.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Command.createHelp() override in subclass', () => {6 test('when override createCommand then affects help', () => {7 class MyHelp extends commander.Help {
15 unmodified lines
modified:tests/command.createOption.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45class MyOption extends commander.Option {6 constructor(flags, description) {7 super(flags, description);
39 unmodified lines
modified:tests/command.default.test.js+9 added-9 removed
1const childProcess = require('child_process');2const commander = require('../');3const path = require('path');4const util = require('util');5const { test, describe } = require('node:test');6const assert = require('node:assert/strict');1import * as childProcess from 'child_process';2import * as commander from '../index.js';3import * as path from 'path';4import * as util from 'util';5import { test, describe } from 'node:test';6import assert from 'node:assert/strict';78const execFileAsync = util.promisify(childProcess.execFile);910describe('default executable command', () => {11 // Calling node explicitly so pm works without file suffix cross-platform.12 const pm = path.join(__dirname, './fixtures/pm');12 const pm = path.join(import.meta.dirname, './fixtures/pm');1314 test('when default subcommand and no command then call default', async () => {15 const { stdout } = await execFileAsync('node', [pm]);16 assert.equal(stdout, 'default\n');17 });1819 test('when default subcommand and unrecognised argument then call default with argument', async () => {20 const { stdout } = await execFileAsync('node', [pm, 'an-argument']);21 assert.equal(stdout, "default\n[ 'an-argument' ]\n");21 assert.equal(stdout, 'default\n["an-argument"]\n');22 });2324 test('when default subcommand and unrecognised option then call default with option', async () => {25 const { stdout } = await execFileAsync('node', [pm, '--an-option']);26 assert.equal(stdout, "default\n[ '--an-option' ]\n");26 assert.equal(stdout, 'default\n["--an-option"]\n');27 });28});2930describe('default action command', () => {
63 unmodified lines
modified:tests/command.description.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Command description()', () => {6 test('when set description then get description', () => {7 const program = new commander.Command();
5 unmodified lines
modified:tests/command.error.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Command.error()', () => {6 test('when error called with message then message displayed on stderr', (t) => {7 t.mock.method(process, 'exit', () => {});
52 unmodified lines
modified:tests/command.executableSubcommand.inspect.test.js+17 added-13 removed
1const childProcess = require('child_process');2const path = require('path');3const util = require('util');4const { test, describe } = require('node:test');5const assert = require('node:assert/strict');1import * as childProcess from 'child_process';2import * as path from 'path';3import * as util from 'util';4import { test, describe } from 'node:test';5import assert from 'node:assert/strict';67const execFileAsync = util.promisify(childProcess.execFile);89// Test the special handling for --inspect to increment fixed debug port numbers.10// If we reuse port we can get conflicts because port not released fast enough.1112const inspectCommand = path.join(__dirname, './fixtures', 'inspect.js');12const inspectCommand = path.join(13 import.meta.dirname,14 './fixtures',15 'inspect.js',16);1718describe('executable subcommand support for --inspect ', () => {19 test('when execArgv empty then spawn execArgs empty', async () => {20 const { stdout } = await execFileAsync('node', [inspectCommand, 'sub']);
5 unmodified lines
26 '--harmony',27 inspectCommand,28 'sub',29 ]);26 assert.equal(stdout, "[ '--harmony' ]\n");30 assert.equal(stdout, '["--harmony"]\n');31 });3233 // --inspect defaults to 127.0.0.1:9229, port should be incremented34 test('when execArgv --inspect then spawn execArgs using port 9230', async () => {
1 unmodified line
36 '--inspect',37 inspectCommand,38 'sub',39 ]);36 assert.equal(stdout, "[ '--inspect=127.0.0.1:9230' ]\n");40 assert.equal(stdout, '["--inspect=127.0.0.1:9230"]\n');41 });4243 // custom port44 test('when execArgv --inspect=9240 then spawn execArgs using port 9241', async () => {
1 unmodified line
46 '--inspect=9240',47 inspectCommand,48 'sub',49 ]);46 assert.equal(stdout, "[ '--inspect=127.0.0.1:9241' ]\n");50 assert.equal(stdout, '["--inspect=127.0.0.1:9241"]\n');51 });5253 // zero is special, random port54 test('when execArgv --inspect=0 then spawn execArgs --inspect=0', async () => {
1 unmodified line
56 '--inspect=0',57 inspectCommand,58 'sub',59 ]);56 assert.equal(stdout, "[ '--inspect=0' ]\n");60 assert.equal(stdout, '["--inspect=0"]\n');61 });6263 // ip address64 test('when execArgv --inspect=127.0.0.1:9250 then spawn execArgs --inspect=127.0.0.1:9251', async () => {
1 unmodified line
66 '--inspect=127.0.0.1:9250',67 inspectCommand,68 'sub',69 ]);66 assert.equal(stdout, "[ '--inspect=127.0.0.1:9251' ]\n");70 assert.equal(stdout, '["--inspect=127.0.0.1:9251"]\n');71 });7273 // localhost74 test('when execArgv --inspect=localhost:9260 then spawn execArgs --inspect=localhost:9261', async () => {
1 unmodified line
76 '--inspect=localhost:9260',77 inspectCommand,78 'sub',79 ]);76 assert.equal(stdout, "[ '--inspect=localhost:9261' ]\n");80 assert.equal(stdout, '["--inspect=localhost:9261"]\n');81 });8283 // --inspect-port, just test most likely format84 test('when execArgv --inspect-port=9270 then spawn execArgs --inspect-port=127.0.0.1:9271', async () => {
1 unmodified line
86 '--inspect-port=9270',87 inspectCommand,88 'sub',89 ]);86 assert.equal(stdout, "[ '--inspect-port=127.0.0.1:9271' ]\n");90 assert.equal(stdout, '["--inspect-port=127.0.0.1:9271"]\n');91 });92});
modified:tests/command.executableSubcommand.lookup.test.js+30 added-12 removed
1const childProcess = require('child_process');2const path = require('path');3const util = require('util');1import * as childProcess from 'child_process';2import * as path from 'path';3import * as util from 'util';4const execFileAsync = util.promisify(childProcess.execFile);5const { test, describe } = require('node:test');6const assert = require('node:assert/strict');5import { test, describe } from 'node:test';6import assert from 'node:assert/strict';78// Calling node explicitly so pm works without file suffix cross-platform.9// This file does end-to-end tests actually spawning program.10// See also command.executableSubcommand.search.test.js1112// Suppress false positive warnings due to use of testOrSkipOnWindows1314const testOrSkipOnWindows = process.platform === 'win32' ? test.skip : test;15const pm = path.join(__dirname, './fixtures/pm');15const pm = path.join(import.meta.dirname, './fixtures/pm');1617describe('executable subcommand lookup ', () => {18 test('when subcommand file missing then error', () => {19 return execFileAsync('node', [pm, 'list']).catch((err) => {
49 unmodified lines
6970 testOrSkipOnWindows(71 'when subcommand file is symlink then lookup succeeds',72 async () => {73 const pmlink = path.join(__dirname, 'fixtures', 'pmlink');73 const pmlink = path.join(import.meta.dirname, 'fixtures', 'pmlink');74 const { stdout } = await execFileAsync('node', [pmlink, 'install']);75 assert.equal(stdout, 'install\n');76 },77 );7879 testOrSkipOnWindows(80 'when subcommand file is double symlink then lookup succeeds',81 async () => {82 const pmlink = path.join(__dirname, 'fixtures', 'another-dir', 'pm');82 const pmlink = path.join(83 import.meta.dirname,84 'fixtures',85 'another-dir',86 'pm',87 );88 const { stdout } = await execFileAsync('node', [pmlink, 'install']);89 assert.equal(stdout, 'install\n');90 },91 );9293 // This test currently fails on Node 20 when run as ESM because Node does not execute .ts files as JavaScript by default.88 test('when subcommand suffix is .ts then lookup succeeds', async () => {94 test.skip('when subcommand suffix is .ts then lookup succeeds', async () => {95 // We support looking for ts files for ts-node in particular, but don't need to test ts-node itself.96 // The subcommand is both plain JavaScript code for this test.91 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');97 const binLinkTs = path.join(98 import.meta.dirname,99 'fixtures-extensions',100 'pm.js',101 );102 // childProcess.execFile('node', ['-r', 'ts-node/register', binLinkTs, 'install'], function(_error, stdout, stderr) {103 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-ts']);104 assert.equal(stdout, 'found .ts\n');105 });106107 test('when subcommand suffix is .cjs then lookup succeeds', async () => {98 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');108 const binLinkTs = path.join(109 import.meta.dirname,110 'fixtures-extensions',111 'pm.js',112 );113 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-cjs']);114 assert.equal(stdout, 'found .cjs\n');115 });116117 test('when subcommand suffix is .mjs then lookup succeeds', async () => {104 const binLinkTs = path.join(__dirname, 'fixtures-extensions', 'pm.js');118 const binLinkTs = path.join(119 import.meta.dirname,120 'fixtures-extensions',121 'pm.js',122 );123 const { stdout } = await execFileAsync('node', [binLinkTs, 'try-mjs']);124 assert.equal(stdout, 'found .mjs\n');125 });126
5 unmodified lines
added:tests/command.executableSubcommand.mock.test.cjs+103 added
1const commander = require('../');2const childProcess = require('child_process');3const EventEmitter = require('events');4const { test, describe } = require('node:test');5const assert = require('node:assert/strict');67// Using mocking of child_process.spawn. Not fully supported yet in esm by node:test so run as cjs.89// Using mock to allow try/catch around what is otherwise out-of-stack error handling.10// Injecting errors, these are not end-to-end tests.1112function makeSystemError(code) {13 // We can not make an actual SystemError, but our usage is lightweight so easy to match.14 const err = new Error();15 err.code = code;16 return err;17}1819// Suppress false positive warnings due to use of testOrSkipOnWindows2021const testOrSkipOnWindows = process.platform === 'win32' ? test.skip : test;2223describe('executable subcommand missing file handling ', () => {24 testOrSkipOnWindows(25 'when subcommand executable missing (ENOENT) then throw custom message',26 (t) => {27 // If the command is not found, we show a custom error with an explanation and offer28 // some advice for possible fixes.29 const mockProcess = new EventEmitter();30 t.mock.method(childProcess, 'spawn', () => {31 return mockProcess;32 });33 const program = new commander.Command();34 program.exitOverride();35 program.command('executable', 'executable description');36 program.parse(['executable'], { from: 'user' });37 assert.throws(() => {38 mockProcess.emit('error', makeSystemError('ENOENT'));39 }, /use the executableFile option to supply a custom name/); // part of custom message40 },41 );4243 testOrSkipOnWindows(44 'when subcommand executable not executable (EACCES) then throw custom message',45 (t) => {46 const mockProcess = new EventEmitter();47 t.mock.method(childProcess, 'spawn', () => {48 return mockProcess;49 });50 const program = new commander.Command();51 program.exitOverride();52 program.command('executable', 'executable description');53 program.parse(['executable'], { from: 'user' });54 assert.throws(() => {55 mockProcess.emit('error', makeSystemError('EACCES'));56 }, /not executable/); // part of custom message57 },58 );5960 test('when subcommand executable fails with other error and exitOverride then return in custom wrapper', (t) => {61 // The existing behaviour is to just silently fail for unexpected errors, as it is happening62 // asynchronously in spawned process and client can not catch errors.63 const mockProcess = new EventEmitter();64 t.mock.method(childProcess, 'spawn', () => {65 return mockProcess;66 });67 const program = new commander.Command();68 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn69 program.exitOverride((err) => {70 throw err;71 });72 program.command('executable', 'executable description');73 program.parse(['executable'], { from: 'user' });74 assert.throws(75 () => {76 mockProcess.emit('error', makeSystemError('OTHER'));77 },78 (err) => {79 assert.equal(err.code, 'commander.executeSubCommandAsync');80 assert.equal(err.nestedError.code, 'OTHER');81 return true;82 },83 );84 });8586 test('when subcommand executable fails with other error then exit', (t) => {87 // The existing behaviour is to just silently fail for unexpected errors, as it is happening88 // asynchronously in spawned process and client can not catch errors.89 const mockProcess = new EventEmitter();90 t.mock.method(childProcess, 'spawn', () => {91 return mockProcess;92 });93 const exitSpy = t.mock.method(process, 'exit', () => {});94 const program = new commander.Command();95 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn96 program.command('executable', 'executable description');97 program.parse(['executable'], { from: 'user' });98 mockProcess.emit('error', makeSystemError('OTHER'));99 assert.equal(exitSpy.mock.callCount(), 1);100 const callArgs = exitSpy.mock.calls[0].arguments;101 assert.equal(callArgs[0], 1);102 });103});
deleted:tests/command.executableSubcommand.mock.test.js-101 removed
1const commander = require('../');2const childProcess = require('child_process');3const EventEmitter = require('events');4const { test, describe } = require('node:test');5const assert = require('node:assert/strict');67// Using mock to allow try/catch around what is otherwise out-of-stack error handling.8// Injecting errors, these are not end-to-end tests.910function makeSystemError(code) {11 // We can not make an actual SystemError, but our usage is lightweight so easy to match.12 const err = new Error();13 err.code = code;14 return err;15}1617// Suppress false positive warnings due to use of testOrSkipOnWindows1819const testOrSkipOnWindows = process.platform === 'win32' ? test.skip : test;2021describe('executable subcommand missing file handling ', () => {22 testOrSkipOnWindows(23 'when subcommand executable missing (ENOENT) then throw custom message',24 (t) => {25 // If the command is not found, we show a custom error with an explanation and offer26 // some advice for possible fixes.27 const mockProcess = new EventEmitter();28 t.mock.method(childProcess, 'spawn', () => {29 return mockProcess;30 });31 const program = new commander.Command();32 program.exitOverride();33 program.command('executable', 'executable description');34 program.parse(['executable'], { from: 'user' });35 assert.throws(() => {36 mockProcess.emit('error', makeSystemError('ENOENT'));37 }, /use the executableFile option to supply a custom name/); // part of custom message38 },39 );4041 testOrSkipOnWindows(42 'when subcommand executable not executable (EACCES) then throw custom message',43 (t) => {44 const mockProcess = new EventEmitter();45 t.mock.method(childProcess, 'spawn', () => {46 return mockProcess;47 });48 const program = new commander.Command();49 program.exitOverride();50 program.command('executable', 'executable description');51 program.parse(['executable'], { from: 'user' });52 assert.throws(() => {53 mockProcess.emit('error', makeSystemError('EACCES'));54 }, /not executable/); // part of custom message55 },56 );5758 test('when subcommand executable fails with other error and exitOverride then return in custom wrapper', (t) => {59 // The existing behaviour is to just silently fail for unexpected errors, as it is happening60 // asynchronously in spawned process and client can not catch errors.61 const mockProcess = new EventEmitter();62 t.mock.method(childProcess, 'spawn', () => {63 return mockProcess;64 });65 const program = new commander.Command();66 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn67 program.exitOverride((err) => {68 throw err;69 });70 program.command('executable', 'executable description');71 program.parse(['executable'], { from: 'user' });72 assert.throws(73 () => {74 mockProcess.emit('error', makeSystemError('OTHER'));75 },76 (err) => {77 assert.equal(err.code, 'commander.executeSubCommandAsync');78 assert.equal(err.nestedError.code, 'OTHER');79 return true;80 },81 );82 });8384 test('when subcommand executable fails with other error then exit', (t) => {85 // The existing behaviour is to just silently fail for unexpected errors, as it is happening86 // asynchronously in spawned process and client can not catch errors.87 const mockProcess = new EventEmitter();88 t.mock.method(childProcess, 'spawn', () => {89 return mockProcess;90 });91 const exitSpy = t.mock.method(process, 'exit', () => {});92 const program = new commander.Command();93 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn94 program.command('executable', 'executable description');95 program.parse(['executable'], { from: 'user' });96 mockProcess.emit('error', makeSystemError('OTHER'));97 assert.equal(exitSpy.mock.callCount(), 1);98 const callArgs = exitSpy.mock.calls[0].arguments;99 assert.equal(callArgs[0], 1);100 });101});
added:tests/command.executableSubcommand.search.test.cjs+317 added
1const childProcess = require('child_process');2const fs = require('fs');3const path = require('path');4const commander = require('../');5const { test, describe } = require('node:test');6const assert = require('node:assert/strict');78// Using mocking of child_process.spawn. Not fully supported yet in esm by node:test so run as cjs.910// This file does in-process mocking. Bit clumsy but faster and less external clutter than using fixtures.11// See also command.executableSubcommand.lookup.test.js for tests using fixtures.1213const gLocalDirectory = path.resolve(__dirname, 'fixtures'); // Real directory, although not actually searching for files in it.1415function extractMockSpawnArgs(spawnSpy) {16 assert.equal(spawnSpy.mock.callCount() > 0, true);17 // This is very fragile on implementation details of how subcommand spawned.18 // non-Win Jest, launchWithNode: childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });19 // Win Jest always: childProcess.spawn(process.execPath, args, { stdio: 'inherit' });20 // node:test passes wild number of node args on front!2122 const callArgs = spawnSpy.mock.calls[0].arguments;23 return callArgs[1].slice(-1); // fingers crossed last arg is filename!24}2526function extractMockSpawnCommand(spawnSpy) {27 assert.equal(spawnSpy.mock.callCount() > 0, true);28 // child_process.spawn(command[, args][, options])29 const callArgs = spawnSpy.mock.calls[0].arguments;30 return callArgs[0];31}3233const describeOrSkipOnWindows =34 process.platform === 'win32' ? describe.skip : describe;3536describe('executable subcommand search behaviour', () => {37 function makeSpies(t, existsFn) {38 const spawnSpy = t.mock.method(childProcess, 'spawn', () => {39 return {40 on: () => {},41 killed: true,42 };43 });44 const existsSpy = t.mock.method(fs, 'existsSync', existsFn);45 return { spawnSpy, existsSpy };46 }4748 // fs.existsSync gets called on Windows outside the search, so skip the tests (or come up with a different way of checking).49 describe('whether perform search for local files', () => {50 test('when no script arg or executableDir then no search for local file', (t) => {51 const { existsSpy } = makeSpies(t, () => false);52 const program = new commander.Command();53 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn54 program.name('pm');55 program.command('sub', 'executable description');56 program.parse(['sub'], { from: 'user' });5758 assert.equal(existsSpy.mock.callCount(), 0);59 });6061 test('when script arg then search for local files', (t) => {62 const { existsSpy } = makeSpies(t, () => false);63 const program = new commander.Command();64 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn65 program.name('pm');66 program.command('sub', 'executable description');67 program.parse(['node', 'script-name', 'sub']);6869 assert.equal(existsSpy.mock.callCount() > 0, true);70 });7172 test('when executableDir then search for local files)', (t) => {73 const { existsSpy } = makeSpies(t, () => false);74 const program = new commander.Command();75 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn76 program.name('pm');77 program.executableDir(__dirname);78 program.command('sub', 'executable description');79 program.parse(['sub'], { from: 'user' });8081 assert.equal(existsSpy.mock.callCount() > 0, true);82 });83 });8485 // We always use node on Windows, and don't spawn executable as the command (which may be a feature or a shortcoming!?).86 describeOrSkipOnWindows(87 'subcommand command name with no matching local file (non-Windows)',88 () => {89 test('when named pm and no script arg or executableDir then spawn pm-sub as command', (t) => {90 const { spawnSpy } = makeSpies(t, () => false);91 const program = new commander.Command();92 program.name('pm');93 program.command('sub', 'executable description');94 program.parse(['sub'], { from: 'user' });9596 assert.equal(extractMockSpawnCommand(spawnSpy), 'pm-sub');97 });9899 test('when named pm and script arg then still spawn pm-sub as command', (t) => {100 const { spawnSpy } = makeSpies(t, () => false);101 const program = new commander.Command();102 program.name('pm');103 program.command('sub', 'executable description');104 program.parse(['node', 'script-name', 'sub']);105106 assert.equal(extractMockSpawnCommand(spawnSpy), 'pm-sub');107 });108109 test('when no name and script arg then spawn script-sub as command', (t) => {110 const { spawnSpy } = makeSpies(t, () => false);111 const program = new commander.Command();112 program.command('sub', 'executable description');113 program.parse(['node', 'script.js', 'sub']);114115 assert.equal(extractMockSpawnCommand(spawnSpy), 'script-sub');116 });117118 test('when named pm and script arg and executableFile then spawn executableFile as command', (t) => {119 const { spawnSpy } = makeSpies(t, () => false);120 const program = new commander.Command();121 program.command('sub', 'executable description', {122 executableFile: 'myExecutable',123 });124 program.parse(['node', 'script.js', 'sub']);125126 assert.equal(extractMockSpawnCommand(spawnSpy), 'myExecutable');127 });128 },129 );130131 describe('subcommand command name with matching local file', () => {132 test('when construct with name pm and script arg then spawn local pm-sub.js', (t) => {133 const program = new commander.Command('pm');134 program.command('sub', 'executable description');135136 const localPath = path.resolve(gLocalDirectory, 'pm-sub.js');137 const { spawnSpy } = makeSpies(t, (path) => path === localPath);138 program.parse([139 'node',140 path.resolve(gLocalDirectory, 'script.js'),141 'sub',142 ]);143144 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);145 });146147 test('when name pm and script arg then spawn local pm-sub.js', (t) => {148 const program = new commander.Command();149 program.name('pm');150 program.command('sub', 'executable description');151152 const localPath = path.resolve(gLocalDirectory, 'pm-sub.js');153 const { spawnSpy } = makeSpies(t, (path) => path === localPath);154 program.parse([155 'node',156 path.resolve(gLocalDirectory, 'script.js'),157 'sub',158 ]);159160 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);161 });162163 test('when script arg then spawn local script-sub.js', (t) => {164 const program = new commander.Command();165 program.command('sub', 'executable description');166167 const localPath = path.resolve(gLocalDirectory, 'script-sub.js');168 const { spawnSpy } = makeSpies(t, (path) => path === localPath);169 program.parse([170 'node',171 path.resolve(gLocalDirectory, 'script.js'),172 'sub',173 ]);174175 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);176 });177178 test('when name pm and script arg and only script-sub.js then fallback to spawn local script-sub.js', (t) => {179 const program = new commander.Command();180 program.name('pm');181 program.command('sub', 'executable description');182183 // Fallback for compatibility with Commander <= v8184 const localPath = path.resolve(gLocalDirectory, 'script-sub.js');185 const { spawnSpy } = makeSpies(t, (path) => path === localPath);186 program.parse([187 'node',188 path.resolve(gLocalDirectory, 'script.js'),189 'sub',190 ]);191192 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);193 });194195 test('when name pm and executableDir then spawn local pm-sub.js', (t) => {196 const program = new commander.Command();197 program.name('pm');198 program.command('sub', 'executable description');199200 const execDir = path.resolve(gLocalDirectory, 'exec-dir');201 program.executableDir(execDir);202 const localPath = path.resolve(execDir, 'pm-sub.js');203 const { spawnSpy } = makeSpies(t, (path) => path === localPath);204 program.parse(['sub'], { from: 'user' });205206 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);207 });208209 test('when script arg and relative executableDir then spawn relative script-sub.js', (t) => {210 const program = new commander.Command();211 program.command('sub', 'executable description');212213 const execDir = 'exec-dir';214 program.executableDir(execDir);215 const localPath = path.resolve(gLocalDirectory, execDir, 'script-sub.js');216 const { spawnSpy } = makeSpies(t, (path) => path === localPath);217 program.parse(['node', path.resolve(gLocalDirectory, 'script'), 'sub']);218219 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);220 });221222 test('when script arg and absolute executableDir then spawn absolute script-sub.js', (t) => {223 const program = new commander.Command();224 program.command('sub', 'executable description');225226 const execDir = path.resolve(gLocalDirectory, 'exec-dir');227 program.executableDir(execDir);228 const localPath = path.resolve(execDir, 'script-sub.js');229 const { spawnSpy } = makeSpies(t, (path) => path === localPath);230 program.parse([231 'node',232 path.resolve(gLocalDirectory, 'script-Dir', 'script'),233 'sub',234 ]);235236 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);237 });238239 test('when script arg is link and and link-sub relative to link target then spawn local link-sub', (t) => {240 const program = new commander.Command();241 program.command('sub', 'executable description');242243 const linkPath = path.resolve(gLocalDirectory, 'link', 'link');244 const scriptPath = path.resolve(gLocalDirectory, 'script', 'script.js');245 const scriptSubPath = path.resolve(246 gLocalDirectory,247 'script',248 'link-sub.js',249 );250 t.mock.method(fs, 'realpathSync', (path) => {251 return path === linkPath ? scriptPath : linkPath;252 });253 const { spawnSpy } = makeSpies(t, (path) => path === scriptSubPath);254 program.parse(['node', linkPath, 'sub']);255256 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [scriptSubPath]);257 });258259 test('when name pm and script arg and relative executableFile then spawn local exec.js', (t) => {260 const program = new commander.Command('pm');261 const localPath = path.join('relative', 'exec.js');262 const absolutePath = path.resolve(gLocalDirectory, localPath);263 program.command('sub', 'executable description', {264 executableFile: localPath,265 });266267 const { spawnSpy } = makeSpies(t, (path) => path === absolutePath);268 program.parse([269 'node',270 path.resolve(gLocalDirectory, 'script.js'),271 'sub',272 ]);273274 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [absolutePath]);275 });276277 test('when name pm and script arg and absolute executableFile then spawn local exec.js', (t) => {278 const program = new commander.Command('pm');279 const localPath = path.resolve(gLocalDirectory, 'absolute', 'exec.js');280 program.command('sub', 'executable description', {281 executableFile: localPath,282 });283284 const { spawnSpy } = makeSpies(t, (path) => path === localPath);285 program.parse([286 'node',287 path.resolve(gLocalDirectory, 'script.js'),288 'sub',289 ]);290291 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);292 });293 });294295 describe('search for local file', () => {296 test('when script arg then search for local script-sub.js, .ts, .tsx, .mpjs, .cjs', (t) => {297 const { existsSpy } = makeSpies(t, () => false);298 const program = new commander.Command();299 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn300 program.command('sub', 'executable description');301 const scriptPath = path.resolve(gLocalDirectory, 'script');302 program.parse(['node', scriptPath, 'sub']);303 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];304 sourceExt.forEach((ext) => {305 const expectedPath = path.resolve(gLocalDirectory, `script-sub${ext}`);306 const wasCalled = existsSpy.mock.calls.some(307 (call) => call.arguments[0] === expectedPath,308 );309 assert.equal(310 wasCalled,311 true,312 `Expected existsSpy to be called with ${expectedPath}`,313 );314 });315 });316 });317});
deleted:tests/command.executableSubcommand.search.test.js-315 removed
1const childProcess = require('child_process');2const fs = require('fs');3const path = require('path');4const commander = require('../');5const { test, describe } = require('node:test');6const assert = require('node:assert/strict');78// This file does in-process mocking. Bit clumsy but faster and less external clutter than using fixtures.9// See also command.executableSubcommand.lookup.test.js for tests using fixtures.1011const gLocalDirectory = path.resolve(__dirname, 'fixtures'); // Real directory, although not actually searching for files in it.1213function extractMockSpawnArgs(spawnSpy) {14 assert.equal(spawnSpy.mock.callCount() > 0, true);15 // This is very fragile on implementation details of how subcommand spawned.16 // non-Win Jest, launchWithNode: childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });17 // Win Jest always: childProcess.spawn(process.execPath, args, { stdio: 'inherit' });18 // node:test passes wild number of node args on front!1920 const callArgs = spawnSpy.mock.calls[0].arguments;21 return callArgs[1].slice(-1); // fingers crossed last arg is filename!22}2324function extractMockSpawnCommand(spawnSpy) {25 assert.equal(spawnSpy.mock.callCount() > 0, true);26 // child_process.spawn(command[, args][, options])27 const callArgs = spawnSpy.mock.calls[0].arguments;28 return callArgs[0];29}3031const describeOrSkipOnWindows =32 process.platform === 'win32' ? describe.skip : describe;3334describe('executable subcommand search behaviour', () => {35 function makeSpies(t, existsFn) {36 const spawnSpy = t.mock.method(childProcess, 'spawn', () => {37 return {38 on: () => {},39 killed: true,40 };41 });42 const existsSpy = t.mock.method(fs, 'existsSync', existsFn);43 return { spawnSpy, existsSpy };44 }4546 // fs.existsSync gets called on Windows outside the search, so skip the tests (or come up with a different way of checking).47 describe('whether perform search for local files', () => {48 test('when no script arg or executableDir then no search for local file', (t) => {49 const { existsSpy } = makeSpies(t, () => false);50 const program = new commander.Command();51 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn52 program.name('pm');53 program.command('sub', 'executable description');54 program.parse(['sub'], { from: 'user' });5556 assert.equal(existsSpy.mock.callCount(), 0);57 });5859 test('when script arg then search for local files', (t) => {60 const { existsSpy } = makeSpies(t, () => false);61 const program = new commander.Command();62 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn63 program.name('pm');64 program.command('sub', 'executable description');65 program.parse(['node', 'script-name', 'sub']);6667 assert.equal(existsSpy.mock.callCount() > 0, true);68 });6970 test('when executableDir then search for local files)', (t) => {71 const { existsSpy } = makeSpies(t, () => false);72 const program = new commander.Command();73 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn74 program.name('pm');75 program.executableDir(__dirname);76 program.command('sub', 'executable description');77 program.parse(['sub'], { from: 'user' });7879 assert.equal(existsSpy.mock.callCount() > 0, true);80 });81 });8283 // We always use node on Windows, and don't spawn executable as the command (which may be a feature or a shortcoming!?).84 describeOrSkipOnWindows(85 'subcommand command name with no matching local file (non-Windows)',86 () => {87 test('when named pm and no script arg or executableDir then spawn pm-sub as command', (t) => {88 const { spawnSpy } = makeSpies(t, () => false);89 const program = new commander.Command();90 program.name('pm');91 program.command('sub', 'executable description');92 program.parse(['sub'], { from: 'user' });9394 assert.equal(extractMockSpawnCommand(spawnSpy), 'pm-sub');95 });9697 test('when named pm and script arg then still spawn pm-sub as command', (t) => {98 const { spawnSpy } = makeSpies(t, () => false);99 const program = new commander.Command();100 program.name('pm');101 program.command('sub', 'executable description');102 program.parse(['node', 'script-name', 'sub']);103104 assert.equal(extractMockSpawnCommand(spawnSpy), 'pm-sub');105 });106107 test('when no name and script arg then spawn script-sub as command', (t) => {108 const { spawnSpy } = makeSpies(t, () => false);109 const program = new commander.Command();110 program.command('sub', 'executable description');111 program.parse(['node', 'script.js', 'sub']);112113 assert.equal(extractMockSpawnCommand(spawnSpy), 'script-sub');114 });115116 test('when named pm and script arg and executableFile then spawn executableFile as command', (t) => {117 const { spawnSpy } = makeSpies(t, () => false);118 const program = new commander.Command();119 program.command('sub', 'executable description', {120 executableFile: 'myExecutable',121 });122 program.parse(['node', 'script.js', 'sub']);123124 assert.equal(extractMockSpawnCommand(spawnSpy), 'myExecutable');125 });126 },127 );128129 describe('subcommand command name with matching local file', () => {130 test('when construct with name pm and script arg then spawn local pm-sub.js', (t) => {131 const program = new commander.Command('pm');132 program.command('sub', 'executable description');133134 const localPath = path.resolve(gLocalDirectory, 'pm-sub.js');135 const { spawnSpy } = makeSpies(t, (path) => path === localPath);136 program.parse([137 'node',138 path.resolve(gLocalDirectory, 'script.js'),139 'sub',140 ]);141142 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);143 });144145 test('when name pm and script arg then spawn local pm-sub.js', (t) => {146 const program = new commander.Command();147 program.name('pm');148 program.command('sub', 'executable description');149150 const localPath = path.resolve(gLocalDirectory, 'pm-sub.js');151 const { spawnSpy } = makeSpies(t, (path) => path === localPath);152 program.parse([153 'node',154 path.resolve(gLocalDirectory, 'script.js'),155 'sub',156 ]);157158 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);159 });160161 test('when script arg then spawn local script-sub.js', (t) => {162 const program = new commander.Command();163 program.command('sub', 'executable description');164165 const localPath = path.resolve(gLocalDirectory, 'script-sub.js');166 const { spawnSpy } = makeSpies(t, (path) => path === localPath);167 program.parse([168 'node',169 path.resolve(gLocalDirectory, 'script.js'),170 'sub',171 ]);172173 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);174 });175176 test('when name pm and script arg and only script-sub.js then fallback to spawn local script-sub.js', (t) => {177 const program = new commander.Command();178 program.name('pm');179 program.command('sub', 'executable description');180181 // Fallback for compatibility with Commander <= v8182 const localPath = path.resolve(gLocalDirectory, 'script-sub.js');183 const { spawnSpy } = makeSpies(t, (path) => path === localPath);184 program.parse([185 'node',186 path.resolve(gLocalDirectory, 'script.js'),187 'sub',188 ]);189190 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);191 });192193 test('when name pm and executableDir then spawn local pm-sub.js', (t) => {194 const program = new commander.Command();195 program.name('pm');196 program.command('sub', 'executable description');197198 const execDir = path.resolve(gLocalDirectory, 'exec-dir');199 program.executableDir(execDir);200 const localPath = path.resolve(execDir, 'pm-sub.js');201 const { spawnSpy } = makeSpies(t, (path) => path === localPath);202 program.parse(['sub'], { from: 'user' });203204 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);205 });206207 test('when script arg and relative executableDir then spawn relative script-sub.js', (t) => {208 const program = new commander.Command();209 program.command('sub', 'executable description');210211 const execDir = 'exec-dir';212 program.executableDir(execDir);213 const localPath = path.resolve(gLocalDirectory, execDir, 'script-sub.js');214 const { spawnSpy } = makeSpies(t, (path) => path === localPath);215 program.parse(['node', path.resolve(gLocalDirectory, 'script'), 'sub']);216217 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);218 });219220 test('when script arg and absolute executableDir then spawn absolute script-sub.js', (t) => {221 const program = new commander.Command();222 program.command('sub', 'executable description');223224 const execDir = path.resolve(gLocalDirectory, 'exec-dir');225 program.executableDir(execDir);226 const localPath = path.resolve(execDir, 'script-sub.js');227 const { spawnSpy } = makeSpies(t, (path) => path === localPath);228 program.parse([229 'node',230 path.resolve(gLocalDirectory, 'script-Dir', 'script'),231 'sub',232 ]);233234 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);235 });236237 test('when script arg is link and and link-sub relative to link target then spawn local link-sub', (t) => {238 const program = new commander.Command();239 program.command('sub', 'executable description');240241 const linkPath = path.resolve(gLocalDirectory, 'link', 'link');242 const scriptPath = path.resolve(gLocalDirectory, 'script', 'script.js');243 const scriptSubPath = path.resolve(244 gLocalDirectory,245 'script',246 'link-sub.js',247 );248 t.mock.method(fs, 'realpathSync', (path) => {249 return path === linkPath ? scriptPath : linkPath;250 });251 const { spawnSpy } = makeSpies(t, (path) => path === scriptSubPath);252 program.parse(['node', linkPath, 'sub']);253254 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [scriptSubPath]);255 });256257 test('when name pm and script arg and relative executableFile then spawn local exec.js', (t) => {258 const program = new commander.Command('pm');259 const localPath = path.join('relative', 'exec.js');260 const absolutePath = path.resolve(gLocalDirectory, localPath);261 program.command('sub', 'executable description', {262 executableFile: localPath,263 });264265 const { spawnSpy } = makeSpies(t, (path) => path === absolutePath);266 program.parse([267 'node',268 path.resolve(gLocalDirectory, 'script.js'),269 'sub',270 ]);271272 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [absolutePath]);273 });274275 test('when name pm and script arg and absolute executableFile then spawn local exec.js', (t) => {276 const program = new commander.Command('pm');277 const localPath = path.resolve(gLocalDirectory, 'absolute', 'exec.js');278 program.command('sub', 'executable description', {279 executableFile: localPath,280 });281282 const { spawnSpy } = makeSpies(t, (path) => path === localPath);283 program.parse([284 'node',285 path.resolve(gLocalDirectory, 'script.js'),286 'sub',287 ]);288289 assert.deepEqual(extractMockSpawnArgs(spawnSpy), [localPath]);290 });291 });292293 describe('search for local file', () => {294 test('when script arg then search for local script-sub.js, .ts, .tsx, .mpjs, .cjs', (t) => {295 const { existsSpy } = makeSpies(t, () => false);296 const program = new commander.Command();297 program._checkForMissingExecutable = () => {}; // suppress error, call mocked spawn298 program.command('sub', 'executable description');299 const scriptPath = path.resolve(gLocalDirectory, 'script');300 program.parse(['node', scriptPath, 'sub']);301 const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];302 sourceExt.forEach((ext) => {303 const expectedPath = path.resolve(gLocalDirectory, `script-sub${ext}`);304 const wasCalled = existsSpy.mock.calls.some(305 (call) => call.arguments[0] === expectedPath,306 );307 assert.equal(308 wasCalled,309 true,310 `Expected existsSpy to be called with ${expectedPath}`,311 );312 });313 });314 });315});
modified:tests/command.executableSubcommand.signals.test.js+5 added-5 removed
1const childProcess = require('child_process');2const path = require('path');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as childProcess from 'child_process';2import * as path from 'path';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56const pmPath = path.join(__dirname, 'fixtures', 'pm');6const pmPath = path.join(import.meta.dirname, 'fixtures', 'pm');78// Disabling some tests on Windows as:9// "Windows does not support sending signals"10// https://nodejs.org/api/process.html#process_signal_events
52 unmodified lines
modified:tests/command.executableSubcommand.test.js+3 added-3 removed
1const { createTestCommand } = require('./testHelpers');2const { test } = require('node:test');3const assert = require('node:assert/strict');1import { createTestCommand } from './testHelpers.js';2import { test } from 'node:test';3import assert from 'node:assert/strict';45// Executable subcommand tests that didn't fit in elsewhere.67// This is the default behaviour when no default command and no action handlers
12 unmodified lines
modified:tests/command.exitOverride.test.js+5 added-5 removed
1const commander = require('../');2const path = require('path');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import * as path from 'path';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56// Test details of the exitOverride errors.7// The important checks are the exitCode and code which are intended to be stable for8// semver minor versions. For now, also testing the error.message and that output occurred
246 unmodified lines
255 expectCommanderError(caughtErr, 0, 'commander.version', myVersion);256 });257258 test('when executableSubcommand succeeds then call exitOverride', async () => {259 const pm = path.join(__dirname, 'fixtures/pm');259 const pm = path.join(import.meta.dirname, 'fixtures/pm');260 const program = new commander.Command();261 await new Promise((resolve) => {262 program263 .exitOverride((err) => {
194 unmodified lines
modified:tests/command.help.test.js+4 added-4 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56// Testing various help incantations.7//8// Note there are also specific help tests included in many of the feature tests,
309 unmodified lines
modified:tests/command.helpCommand.test.js+4 added-4 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56describe('help handling of subcommands', () => {7 describe('help command listed in helpInformation', () => {8 test('when program has no subcommands then no automatic help command', () => {
163 unmodified lines
modified:tests/command.helpOption.test.js+4 added-4 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56describe('Command.helpOption()', () => {7 test('when helpOption has custom flags then custom short flag invokes help', (t) => {8 const program = createTestCommand();
119 unmodified lines
modified:tests/command.hook.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Command.hook()', () => {6 test('when hook event wrong then throw', () => {7 const program = new commander.Command();
410 unmodified lines
modified:tests/command.name.test.js+6 added-6 removed
1const path = require('path');2const commander = require('../');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as path from 'path';2import * as commander from '../index.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56describe('Command.name()', () => {7 test('when construct with name then name is set', () => {8 const program = new commander.Command('foo');
39 unmodified lines
48 program.nameFromFilename(path.resolve(process.cwd(), 'foo.js'));49 assert.equal(program.name(), 'foo');50 });5152 test('when pass __filename to nameFromFilename then name is plain name of this file', () => {52 test('when pass import.meta.filename to nameFromFilename then name is plain name of this file', () => {53 const program = new commander.Command();54 program.nameFromFilename(__filename);54 program.nameFromFilename(import.meta.filename);55 assert.equal(program.name(), 'command.name.test');56 });57});
modified:tests/command.nested.test.js+3 added-3 removed
1const commander = require('../');2const { test } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test } from 'node:test';3import assert from 'node:assert/strict';45test('when call nested subcommand then runs', (t) => {6 const program = new commander.Command();7 const leafAction = t.mock.fn();
4 unmodified lines
modified:tests/command.onCommand.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// The action handler used to be implemented using command events and listeners.6// Now, this is mostly just for backwards compatibility.7
30 unmodified lines
modified:tests/command.option-misuse.test.js+3 added-3 removed
1const { Command, Option } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Command, Option } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// It is a reasonable and easy mistake to pass Option to .option(). Detect this6// and offer advice.7
26 unmodified lines
modified:tests/command.parse.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Testing some Electron conventions but not directly using Electron to avoid overheads.6// https://github.com/electron/electron/issues/4690#issuecomment-2174352227// https://www.electronjs.org/docs/api/process#processdefaultapp-readonly
435 unmodified lines
modified:tests/command.parseOptions.test.js+8 added-8 removed
1const childProcess = require('child_process');2const commander = require('../');3const path = require('path');4const util = require('util');5const { test, describe } = require('node:test');6const assert = require('node:assert/strict');1import * as childProcess from 'child_process';2import * as commander from '../index.js';3import * as path from 'path';4import * as util from 'util';5import { test, describe } from 'node:test';6import assert from 'node:assert/strict';78const execFileAsync = util.promisify(childProcess.execFile);910// Combination of parse and parseOptions tests which are more about details
26 unmodified lines
37 });3839 // https://github.com/tj/commander.js/issues/50840 test('when arguments to executable include option flags then argument order preserved', async () => {41 const pm = path.join(__dirname, 'fixtures/pm');41 const pm = path.join(import.meta.dirname, 'fixtures/pm');42 const { stdout } = await execFileAsync('node', [43 pm,44 'echo',45 '1',
3 unmodified lines
49 '4',50 '5',51 '6',52 ]);53 assert.equal(stdout, "[ '1', '2', '--dry-run', '3', '4', '5', '6' ]\n");53 assert.equal(stdout, '["1","2","--dry-run","3","4","5","6"]\n');54 });55});5657describe('Command.parseOptions()', () => {
278 unmodified lines
modified:tests/command.positionalOptions.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// The changes to parsing for positional options are subtle, and took extra care to work with6// implicit help and default commands. Lots of tests.7
527 unmodified lines
modified:tests/command.registerClash.test.js+3 added-3 removed
1const { Command } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Command } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('registering clashing subcommands', () => {6 test('when command name conflicts with existing name then throw', () => {7 assert.throws(
64 unmodified lines
modified:tests/command.showHelpAfterError.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe, mock } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe, mock } from 'node:test';3import assert from 'node:assert/strict';45describe('Command.showHelpAfterError(message)', () => {6 const customHelpMessage = 'See --help';7
132 unmodified lines
modified:tests/command.showSuggestionAfterError.test.js+3 added-3 removed
1const { Command } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Command } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45function getSuggestion(program, arg) {6 let message = '';7 program.exitOverride().configureOutput({
47 unmodified lines
modified:tests/command.summary.test.js+3 added-3 removed
1const commander = require('../');2const { test } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test } from 'node:test';3import assert from 'node:assert/strict';45test('Command.summary(): when set summary then get summary', () => {6 const program = new commander.Command();7 const summary = 'abcdef';
3 unmodified lines
modified:tests/command.unknownCommand.test.js+3 added-3 removed
1const { createTestCommand } = require('./testHelpers');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { createTestCommand } from './testHelpers.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('parsing unknown command', () => {6 test('when unknown argument in simple program then error', () => {7 const program = createTestCommand();
47 unmodified lines
modified:tests/command.unknownOption.test.js+3 added-3 removed
1const { createTestCommand } = require('./testHelpers');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { createTestCommand } from './testHelpers.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Checking for detection of unknown options, including regression tests for some past issues.67describe('parsing unknown option', () => {
71 unmodified lines
modified:tests/command.usage.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('command Usage section in help', () => {6 test('when default usage and check program help then starts with default usage', () => {7 const program = new commander.Command();
85 unmodified lines
modified:tests/commander.storeOptionsAsProperties.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Mostly testing direct on program, limited check that (sub)command working same.67describe('Command.storeOptionsAsProperties()', () => {
92 unmodified lines
modified:tests/createCommand.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Command.createCommand()', () => {6 test('when createCommand then unattached', () => {7 const program = new commander.Command();
33 unmodified lines
modified:tests/deprecated.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Test for backwards compatible behaviour of deprecated features that don't fit in elsewhere.6// We keep deprecated features working (when not too difficult) to avoid breaking existing code7// and reduce barriers to updating to latest version of Commander.
23 unmodified lines
modified:tests/help.argumentDescription.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// These are tests of the Help class, not of the Command help.67describe('Help.argumentDescription()', () => {
42 unmodified lines
modified:tests/help.boxWrap.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Help.boxWrap()', () => {6 test('when empty string then return empty string', () => {7 const helper = new commander.Help();
115 unmodified lines
modified:tests/help.commandTerm.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
38 unmodified lines
modified:tests/help.commandUsage.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
38 unmodified lines
modified:tests/help.longestArgumentTermLength.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
29 unmodified lines
modified:tests/help.longestCommandTermLength.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
54 unmodified lines
modified:tests/help.longestOptionTermLength.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
31 unmodified lines
modified:tests/help.minWidthToWrap.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Help.minWidthToWrap()', () => {6 test('when enough width then wrap', () => {7 const program = new commander.Command('program');
42 unmodified lines
modified:tests/help.optionDescription.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
96 unmodified lines
modified:tests/help.optionTerm.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
29 unmodified lines
modified:tests/help.padWidth.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
40 unmodified lines
modified:tests/help.preformatted.test.js+3 added-3 removed
1const { Help, Command } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Help, Command } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Help.preformatted()', () => {6 test('when single line then false', () => {7 const helper = new Help();
65 unmodified lines
modified:tests/help.showGlobalOptions.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Help.showGlobalOptions()', () => {6 test('when default configuration then global options hidden', () => {7 const program = new commander.Command();
45 unmodified lines
modified:tests/help.sortCommands.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
28 unmodified lines
modified:tests/help.sortOptions.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
91 unmodified lines
modified:tests/help.stripAnsi.test.js+3 added-3 removed
1const { stripColor } = require('../lib/help');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { stripColor } from '../lib/help.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters67// Test the lowest level routine being used for SGR support.
62 unmodified lines
modified:tests/help.style.test.js+3 added-3 removed
1const { test, describe } = require('node:test');2const assert = require('node:assert/strict');3const { Command } = require('../');1import { test, describe } from 'node:test';2import assert from 'node:assert/strict';3import { Command } from '../index.js';45function red(str) {6 // Use plain characters so not stripped in failure messages. (Means displayWidth is bogus though.)7 return `RED ${str} DER`;
289 unmodified lines
modified:tests/help.subcommandDescription.test.js+3 added-3 removed
1const { test, describe } = require('node:test');2const assert = require('node:assert/strict');3const commander = require('../');1import { test, describe } from 'node:test';2import assert from 'node:assert/strict';3import * as commander from '../index.js';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
32 unmodified lines
modified:tests/help.suggestion.test.js+3 added-3 removed
1const { test, describe } = require('node:test');2const assert = require('node:assert/strict');3const { Command, Option } = require('../');1import { test, describe } from 'node:test';2import assert from 'node:assert/strict';3import { Command, Option } from '../index.js';45// Note: setting up shared command configuration in getSuggestion,6// and looking for possible subcommand 'sub'.7
244 unmodified lines
modified:tests/help.visibleArguments.test.js+3 added-3 removed
1const { test, describe } = require('node:test');2const assert = require('node:assert/strict');3const commander = require('../');1import { test, describe } from 'node:test';2import assert from 'node:assert/strict';3import * as commander from '../index.js';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
72 unmodified lines
modified:tests/help.visibleCommands.test.js+3 added-3 removed
1const { test, describe } = require('node:test');2const assert = require('node:assert/strict');3const commander = require('../');1import { test, describe } from 'node:test';2import assert from 'node:assert/strict';3import * as commander from '../index.js';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
30 unmodified lines
modified:tests/help.visibleGlobalOptions.test.js+3 added-3 removed
1const { test, describe } = require('node:test');2const assert = require('node:assert/strict');3const commander = require('../');1import { test, describe } from 'node:test';2import assert from 'node:assert/strict';3import * as commander from '../index.js';45describe('Help.visibleGlobalOptions()', () => {6 test('when default configuration then return empty array', () => {7 const program = new commander.Command();
40 unmodified lines
modified:tests/help.visibleOptions.test.js+3 added-3 removed
1const { test, describe } = require('node:test');2const assert = require('node:assert/strict');3const commander = require('../');1import { test, describe } from 'node:test';2import assert from 'node:assert/strict';3import * as commander from '../index.js';45// These are tests of the Help class, not of the Command help.6// There is some overlap with the higher level Command tests (which predate Help).7
71 unmodified lines
modified:tests/helpGroup.test.js+3 added-3 removed
1const { test, describe } = require('node:test');2const assert = require('node:assert/strict');3const { Command, Option } = require('../');1import { test, describe } from 'node:test';2import assert from 'node:assert/strict';3import { Command, Option } from '../index.js';45// Similar tests for Option.helpGroup() and Command.helpGroup(),6// and for Command.optionsGroup() and Command.commandsGroup().7
248 unmodified lines
modified:tests/imports.test.cjs+61 added-1 removed
9 unmodified lines
10 createCommand,11 createOption,12 createArgument,13} = require('../index.js');14const commander = require('../index.js');15const { describe, test } = require('node:test');16const assert = require('node:assert/strict');1718// Do some testing of the default export(s).
3 unmodified lines
22 assert.equal(typeof obj, 'object');23 assert.equal(obj.constructor.name, name);24}2525describe('imports from .cjs', () => {26describe('named imports from .cjs', () => {27 test('program', () => {28 checkClass(program, 'Command');29 });30
40 unmodified lines
71 test('createArgument', () => {72 checkClass(createArgument('<foo>', 'description'), 'Argument');73 });74});7576describe('unnamed imports from .cjs', () => {77 test('program', () => {78 checkClass(commander.program, 'Command');79 });8081 test('Command', () => {82 checkClass(new commander.Command('name'), 'Command');83 });8485 test('Option', () => {86 checkClass(new commander.Option('-e, --example', 'description'), 'Option');87 });8889 test('Argument', () => {90 checkClass(new commander.Argument('<foo>', 'description'), 'Argument');91 });9293 test('Help', () => {94 checkClass(new commander.Help(), 'Help');95 });9697 test('CommanderError', () => {98 checkClass(99 new commander.CommanderError(1, 'code', 'failed'),100 'CommanderError',101 );102 });103104 test('InvalidArgumentError', () => {105 checkClass(106 new commander.InvalidArgumentError('failed'),107 'InvalidArgumentError',108 );109 });110111 test('InvalidOptionArgumentError', () => {112 // Deprecated113 checkClass(114 new commander.InvalidOptionArgumentError('failed'),115 'InvalidArgumentError',116 );117 });118119 test('createCommand', () => {120 checkClass(commander.createCommand('foo'), 'Command');121 });122123 test('createOption', () => {124 checkClass(125 commander.createOption('-e, --example', 'description'),126 'Option',127 );128 });129130 test('createArgument', () => {131 checkClass(commander.createArgument('<foo>', 'description'), 'Argument');132 });133});
added:tests/incrementNodeInspectorPort.test.cjs+146 added
1const { test, describe, after } = require('node:test');2const assert = require('node:assert/strict');3const childProcess = require('child_process');4const path = require('path');5const commander = require('../');67// Using mocking of child_process.spawn. Not fully supported yet in esm by node:test so run as cjs.89describe('increment node inspector port in executable subcommands', () => {10 function makeSpies(t) {11 const spawnSpy = t.mock.method(childProcess, 'spawn', () => {12 return {13 on: () => {},14 };15 });16 const signalSpy = test.mock.method(process, 'on', () => {});17 return { spawnSpy, signalSpy };18 }1920 const oldExecArgv = process.execArgv;2122 after(() => {23 process.execArgv = oldExecArgv;24 });2526 function makeProgram() {27 const program = new commander.Command();28 const fileWhichExists = path.join(__dirname, './fixtures/pm-cache.js');29 program.command('cache', 'stand-alone command', {30 executableFile: fileWhichExists,31 });32 return program;33 }3435 function extractMockExecArgs(spawnSpy) {36 return spawnSpy.mock.calls[0].arguments[1].slice(0, -1);37 }3839 test('when --inspect then bump port', (t) => {40 const { spawnSpy } = makeSpies(t);41 const program = makeProgram();42 process.execArgv = ['--inspect'];43 program.parse(['node', 'test', 'cache']);44 const execArgs = extractMockExecArgs(spawnSpy);45 assert.deepEqual(execArgs, ['--inspect=127.0.0.1:9230']);46 });4748 test('when --inspect=100 then bump port', (t) => {49 const { spawnSpy } = makeSpies(t);50 const program = makeProgram();51 process.execArgv = ['--inspect=100'];52 program.parse(['node', 'test', 'cache']);53 const execArgs = extractMockExecArgs(spawnSpy);54 assert.deepEqual(execArgs, ['--inspect=127.0.0.1:101']);55 });5657 test('when --inspect=1.2.3.4:100 then bump port', (t) => {58 const { spawnSpy } = makeSpies(t);59 const program = makeProgram();60 process.execArgv = ['--inspect=1.2.3.4:100'];61 program.parse(['node', 'test', 'cache']);62 const execArgs = extractMockExecArgs(spawnSpy);63 assert.deepEqual(execArgs, ['--inspect=1.2.3.4:101']);64 });6566 test('when --inspect=1.2.3.4 then bump port', (t) => {67 const { spawnSpy } = makeSpies(t);68 const program = makeProgram();69 process.execArgv = ['--inspect=1.2.3.4'];70 program.parse(['node', 'test', 'cache']);71 const execArgs = extractMockExecArgs(spawnSpy);72 assert.deepEqual(execArgs, ['--inspect=1.2.3.4:9230']);73 });7475 test('when --inspect-brk then bump port', (t) => {76 const { spawnSpy } = makeSpies(t);77 const program = makeProgram();78 process.execArgv = ['--inspect-brk'];79 program.parse(['node', 'test', 'cache']);80 const execArgs = extractMockExecArgs(spawnSpy);81 assert.deepEqual(execArgs, ['--inspect-brk=127.0.0.1:9230']);82 });8384 test('when --inspect-brk=100 then bump port', (t) => {85 const { spawnSpy } = makeSpies(t);86 const program = makeProgram();87 process.execArgv = ['--inspect-brk=100'];88 program.parse(['node', 'test', 'cache']);89 const execArgs = extractMockExecArgs(spawnSpy);90 assert.deepEqual(execArgs, ['--inspect-brk=127.0.0.1:101']);91 });9293 test('when --inspect-brk=1.2.3.4 then bump port', (t) => {94 const { spawnSpy } = makeSpies(t);95 const program = makeProgram();96 process.execArgv = ['--inspect-brk=1.2.3.4'];97 program.parse(['node', 'test', 'cache']);98 const execArgs = extractMockExecArgs(spawnSpy);99 assert.deepEqual(execArgs, ['--inspect-brk=1.2.3.4:9230']);100 });101102 test('when --inspect-brk=1.2.3.4:100 then bump port', (t) => {103 const { spawnSpy } = makeSpies(t);104 const program = makeProgram();105 process.execArgv = ['--inspect-brk=1.2.3.4:100'];106 program.parse(['node', 'test', 'cache']);107 const execArgs = extractMockExecArgs(spawnSpy);108 assert.deepEqual(execArgs, ['--inspect-brk=1.2.3.4:101']);109 });110111 test('when --inspect-port=100 then bump port', (t) => {112 const { spawnSpy } = makeSpies(t);113 const program = makeProgram();114 process.execArgv = ['--inspect-port=100'];115 program.parse(['node', 'test', 'cache']);116 const execArgs = extractMockExecArgs(spawnSpy);117 assert.deepEqual(execArgs, ['--inspect-port=127.0.0.1:101']);118 });119120 test('when --inspect-port=1.2.3.4:100 then bump port', (t) => {121 const { spawnSpy } = makeSpies(t);122 const program = makeProgram();123 process.execArgv = ['--inspect-port=1.2.3.4:100'];124 program.parse(['node', 'test', 'cache']);125 const execArgs = extractMockExecArgs(spawnSpy);126 assert.deepEqual(execArgs, ['--inspect-port=1.2.3.4:101']);127 });128129 test('when --inspect-unexpected then unchanged', (t) => {130 const { spawnSpy } = makeSpies(t);131 const program = makeProgram();132 process.execArgv = ['--inspect-unexpected'];133 program.parse(['node', 'test', 'cache']);134 const execArgs = extractMockExecArgs(spawnSpy);135 assert.deepEqual(execArgs, ['--inspect-unexpected']);136 });137138 test('when --frozen-intrinsics then unchanged', (t) => {139 const { spawnSpy } = makeSpies(t);140 const program = makeProgram();141 process.execArgv = ['--frozen-intrinsics '];142 program.parse(['node', 'test', 'cache']);143 const execArgs = extractMockExecArgs(spawnSpy);144 assert.deepEqual(execArgs, ['--frozen-intrinsics ']);145 });146});
deleted:tests/incrementNodeInspectorPort.test.js-144 removed
1const { test, describe, after } = require('node:test');2const assert = require('node:assert/strict');3const childProcess = require('child_process');4const path = require('path');5const commander = require('../');67describe('increment node inspector port in executable subcommands', () => {8 function makeSpies(t) {9 const spawnSpy = t.mock.method(childProcess, 'spawn', () => {10 return {11 on: () => {},12 };13 });14 const signalSpy = test.mock.method(process, 'on', () => {});15 return { spawnSpy, signalSpy };16 }1718 const oldExecArgv = process.execArgv;1920 after(() => {21 process.execArgv = oldExecArgv;22 });2324 function makeProgram() {25 const program = new commander.Command();26 const fileWhichExists = path.join(__dirname, './fixtures/pm-cache.js');27 program.command('cache', 'stand-alone command', {28 executableFile: fileWhichExists,29 });30 return program;31 }3233 function extractMockExecArgs(spawnSpy) {34 return spawnSpy.mock.calls[0].arguments[1].slice(0, -1);35 }3637 test('when --inspect then bump port', (t) => {38 const { spawnSpy } = makeSpies(t);39 const program = makeProgram();40 process.execArgv = ['--inspect'];41 program.parse(['node', 'test', 'cache']);42 const execArgs = extractMockExecArgs(spawnSpy);43 assert.deepEqual(execArgs, ['--inspect=127.0.0.1:9230']);44 });4546 test('when --inspect=100 then bump port', (t) => {47 const { spawnSpy } = makeSpies(t);48 const program = makeProgram();49 process.execArgv = ['--inspect=100'];50 program.parse(['node', 'test', 'cache']);51 const execArgs = extractMockExecArgs(spawnSpy);52 assert.deepEqual(execArgs, ['--inspect=127.0.0.1:101']);53 });5455 test('when --inspect=1.2.3.4:100 then bump port', (t) => {56 const { spawnSpy } = makeSpies(t);57 const program = makeProgram();58 process.execArgv = ['--inspect=1.2.3.4:100'];59 program.parse(['node', 'test', 'cache']);60 const execArgs = extractMockExecArgs(spawnSpy);61 assert.deepEqual(execArgs, ['--inspect=1.2.3.4:101']);62 });6364 test('when --inspect=1.2.3.4 then bump port', (t) => {65 const { spawnSpy } = makeSpies(t);66 const program = makeProgram();67 process.execArgv = ['--inspect=1.2.3.4'];68 program.parse(['node', 'test', 'cache']);69 const execArgs = extractMockExecArgs(spawnSpy);70 assert.deepEqual(execArgs, ['--inspect=1.2.3.4:9230']);71 });7273 test('when --inspect-brk then bump port', (t) => {74 const { spawnSpy } = makeSpies(t);75 const program = makeProgram();76 process.execArgv = ['--inspect-brk'];77 program.parse(['node', 'test', 'cache']);78 const execArgs = extractMockExecArgs(spawnSpy);79 assert.deepEqual(execArgs, ['--inspect-brk=127.0.0.1:9230']);80 });8182 test('when --inspect-brk=100 then bump port', (t) => {83 const { spawnSpy } = makeSpies(t);84 const program = makeProgram();85 process.execArgv = ['--inspect-brk=100'];86 program.parse(['node', 'test', 'cache']);87 const execArgs = extractMockExecArgs(spawnSpy);88 assert.deepEqual(execArgs, ['--inspect-brk=127.0.0.1:101']);89 });9091 test('when --inspect-brk=1.2.3.4 then bump port', (t) => {92 const { spawnSpy } = makeSpies(t);93 const program = makeProgram();94 process.execArgv = ['--inspect-brk=1.2.3.4'];95 program.parse(['node', 'test', 'cache']);96 const execArgs = extractMockExecArgs(spawnSpy);97 assert.deepEqual(execArgs, ['--inspect-brk=1.2.3.4:9230']);98 });99100 test('when --inspect-brk=1.2.3.4:100 then bump port', (t) => {101 const { spawnSpy } = makeSpies(t);102 const program = makeProgram();103 process.execArgv = ['--inspect-brk=1.2.3.4:100'];104 program.parse(['node', 'test', 'cache']);105 const execArgs = extractMockExecArgs(spawnSpy);106 assert.deepEqual(execArgs, ['--inspect-brk=1.2.3.4:101']);107 });108109 test('when --inspect-port=100 then bump port', (t) => {110 const { spawnSpy } = makeSpies(t);111 const program = makeProgram();112 process.execArgv = ['--inspect-port=100'];113 program.parse(['node', 'test', 'cache']);114 const execArgs = extractMockExecArgs(spawnSpy);115 assert.deepEqual(execArgs, ['--inspect-port=127.0.0.1:101']);116 });117118 test('when --inspect-port=1.2.3.4:100 then bump port', (t) => {119 const { spawnSpy } = makeSpies(t);120 const program = makeProgram();121 process.execArgv = ['--inspect-port=1.2.3.4:100'];122 program.parse(['node', 'test', 'cache']);123 const execArgs = extractMockExecArgs(spawnSpy);124 assert.deepEqual(execArgs, ['--inspect-port=1.2.3.4:101']);125 });126127 test('when --inspect-unexpected then unchanged', (t) => {128 const { spawnSpy } = makeSpies(t);129 const program = makeProgram();130 process.execArgv = ['--inspect-unexpected'];131 program.parse(['node', 'test', 'cache']);132 const execArgs = extractMockExecArgs(spawnSpy);133 assert.deepEqual(execArgs, ['--inspect-unexpected']);134 });135136 test('when --frozen-intrinsics then unchanged', (t) => {137 const { spawnSpy } = makeSpies(t);138 const program = makeProgram();139 process.execArgv = ['--frozen-intrinsics '];140 program.parse(['node', 'test', 'cache']);141 const execArgs = extractMockExecArgs(spawnSpy);142 assert.deepEqual(execArgs, ['--frozen-intrinsics ']);143 });144});
modified:tests/negatives.test.js+4 added-4 removed
1const { Command } = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import { Command } from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56describe('negative numbers', () => {7 describe('negative numbers in args', () => {8 // boolean is whether is a consumable argument when negative numbers allowed
191 unmodified lines
modified:tests/option.bad-flags.test.js+3 added-3 removed
1const { Option } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Option } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Check that unsupported flags throw.6describe('when construct Option with unsupported flags then throw', () => {7 const flagsList = [
44 unmodified lines
modified:tests/option.chain.test.js+3 added-3 removed
1const { Option } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Option } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Option methods that should return this for chaining', () => {6 test('when call .default() then returns this', () => {7 const option = new Option('-e,--example <value>');
46 unmodified lines
modified:tests/options.bool.combo.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Test combination of flag and --no-flag6// (single flags tested in options.bool.test.js)7
188 unmodified lines
modified:tests/options.bool.small.combined.test.js+3 added-3 removed
1const commander = require('../');2const { test } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test } from 'node:test';3import assert from 'node:assert/strict';45test('when when multiple short flags specified then parsed as short option group', () => {6 const program = new commander.Command();7 program
8 unmodified lines
modified:tests/options.bool.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Test simple flag and negatable flag67// boolean option on program
131 unmodified lines
modified:tests/options.camelcase.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Capitalise the letters of words after dashes, but otherwise preserve case67describe('option property is camelCase of option name', () => {
42 unmodified lines
modified:tests/options.choices.test.js+4 added-4 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56describe('Option.choices()', () => {7 test('when option argument in choices then option set', () => {8 const program = new commander.Command();
48 unmodified lines
modified:tests/options.conflicts.test.js+6 added-6 removed
1const path = require('path');2const commander = require('../');3const { createTestCommand } = require('./testHelpers');4const { test, describe } = require('node:test');5const assert = require('node:assert/strict');1import * as path from 'path';2import * as commander from '../index.js';3import { createTestCommand } from './testHelpers.js';4import { test, describe } from 'node:test';5import assert from 'node:assert/strict';67describe('Option.conflicts()', () => {8 function makeProgram(t) {9 const actionMock = t.mock.fn();
370 unmodified lines
380381 program382 .addOption(new commander.Option('--black'))383 .addOption(new commander.Option('--white').conflicts('black'));384 const pm = path.join(__dirname, './fixtures/pm');384 const pm = path.join(import.meta.dirname, './fixtures/pm');385 program.command('ext', 'external command', { executableFile: pm });386387 try {388 program.parse('--white --black ext'.split(' '), { from: 'user' });
7 unmodified lines
modified:tests/options.custom-processing.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45function myParseInt(value, dummyPrevious) {6 // parseInt takes a string and a radix7 return parseInt(value, 10);
135 unmodified lines
modified:tests/options.default.test.js+3 added-3 removed
1const { Command, Option } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Command, Option } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Command.option() with default value and option not specified in parse', () => {6 test('when boolean option with boolean default then value is default', () => {7 const program = new Command();
188 unmodified lines
modified:tests/options.dual-options.test.js+4 added-4 removed
1const { Option, DualOptions } = require('../lib/option.js');2const { Command } = require('../');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import { Option, DualOptions } from '../lib/option.js';2import { Command } from '../index.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56// This tests an internal helper class which is not currently exposed on the package.78describe('DualOptions internal helper class', () => {
91 unmodified lines
modified:tests/options.env.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Option.env()', () => {6 // treating optional same as required, treat as option taking value rather than as boolean7 describe('option declared with value', () => {
364 unmodified lines
modified:tests/options.flags.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Test the various ways flags can be specified in the first parameter to `.option`67describe('option parsing', () => {
70 unmodified lines
modified:tests/options.getset.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Command.getOptionValue() and .setOptionValue()', () => {6 describe('storeOptionsAsProperties', () => {7 const storeOptionsAsPropertiesList = [true, false];
65 unmodified lines
modified:tests/options.implies.test.js+4 added-4 removed
1const { Command, Option } = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import { Command, Option } from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56describe('Option.implies()', () => {7 describe('check priorities', () => {8 test('when source undefined and implied undefined then implied is undefined', () => {
212 unmodified lines
modified:tests/options.mandatory.test.js+4 added-4 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56// Assuming mandatory options behave as normal options apart from the mandatory aspect, not retesting all behaviour.7// Likewise, not redoing all tests on subcommand after testing on program.8
215 unmodified lines
modified:tests/options.optional.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// option with optional value, no default6describe('option with optional value, no default', () => {7 test('when option not specified then value is undefined', () => {
64 unmodified lines
modified:tests/options.opts.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Test the `.opts()` way of accessing option values.6// Basic coverage of the main option types (leaving out negatable flags and options with optional values).7
67 unmodified lines
modified:tests/options.optsWithGlobals.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Testing optsWithGlobals and getOptionValueSourceWithGlobals with focus on globals.67describe('Command.optsWithGlobals()', () => {
109 unmodified lines
modified:tests/options.preset.test.js+3 added-3 removed
1const { Command, Option } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Command, Option } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('Option.preset()', () => {6 test('when boolean option with string preset used then value is preset', () => {7 const program = new Command();
56 unmodified lines
modified:tests/options.registerClash.test.js+3 added-3 removed
1const { Command, Option } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Command, Option } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45describe('registering clashing options', () => {6 test('when short option flag conflicts then throws', () => {7 assert.throws(
59 unmodified lines
modified:tests/options.required.test.js+4 added-4 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56// option with required value, no default7describe('option with required option-argument, no default', () => {8 test('when option not specified then value is undefined', () => {
62 unmodified lines
modified:tests/options.twice.test.js+3 added-3 removed
1const { Command, Option } = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import { Command, Option } from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Test that when option specified twice, second use wins.6// Seems pretty obvious for boolean options, but there was a bug before Commander v9.7
43 unmodified lines
modified:tests/options.values.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Test the ways values can be specified for options.6// See also references on "Utility Conventions" in command.parseOptions.test.js7
81 unmodified lines
modified:tests/options.variadic.test.js+4 added-4 removed
1const commander = require('../');2const { createTestCommand } = require('./testHelpers');3const { test, describe } = require('node:test');4const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { createTestCommand } from './testHelpers.js';3import { test, describe } from 'node:test';4import assert from 'node:assert/strict';56describe('variadic options', () => {7 describe('variadic option with required option-argument', () => {8 test('when variadic with value missing then error', () => {
175 unmodified lines
modified:tests/options.version.test.js+3 added-3 removed
1const commander = require('../');2const { test, describe } = require('node:test');3const assert = require('node:assert/strict');1import * as commander from '../index.js';2import { test, describe } from 'node:test';3import assert from 'node:assert/strict';45// Test .version. Using exitOverride to check behaviour (instead of mocking process.exit).67describe('Command.version()', () => {
176 unmodified lines
modified:tests/testHelpers.js+2 added-4 removed
1const { Command } = require('../');1import { Command } from '../index.js';23/**4 * Create a Command configured for using in tests.5 *
2 unmodified lines
8 *9 * @returns Command10 */1112function createTestCommand() {12export function createTestCommand() {13 const cmd = new Command();14 cmd15 .exitOverride() // So we get exceptions instead of process.exit16 .configureOutput({
1 unmodified line
18 writeErr: () => {},19 });20 return cmd;21}2223exports.createTestCommand = createTestCommand;
modified:tests/useColor.test.js+3 added-3 removed
1const { useColor } = require('../lib/command.js');2const { test, describe, beforeEach, after } = require('node:test');3const assert = require('node:assert/strict');1import { useColor } from '../lib/command.js';2import { test, describe, beforeEach, after } from 'node:test';3import assert from 'node:assert/strict';45describe('internal useColor environment variable support', () => {6 let holdNoColor = process.env.NO_COLOR;7 let holdForceColor = process.env.FORCE_COLOR;
83 unmodified lines
deleted:typings/esm.d.mts-3 removed
1// Just reexport the types from cjs2// This is a bit indirect. There is not an index.js, but TypeScript will look for index.d.ts for types.3export * from './index.js';
modified:typings/index.d.ts+3 added-3 removed
956 unmodified lines
957 name(): string;958959 /**960 * Set the name of the command from script filename, such as process.argv[1],961 * or require.main.filename, or __filename.961 * or import.meta.filename.962 *963 * (Used internally and public although not documented in README.)964 *965 * @example966 * ```ts967 * program.nameFromFilename(require.main.filename);967 * program.nameFromFilename(import.meta.filename);968 * ```969 *970 * @returns `this` command for chaining971 */
3 unmodified lines
975 * Set the directory for searching for executable subcommands of this command.976 *977 * @example978 * ```ts979 * program.executableDir(__dirname);979 * program.executableDir(import.meta.dirname);980 * // or981 * program.executableDir('subcommands');982 * ```983 *
130 unmodified lines
modified:typings/index.test-d.ts+3 added-3 removed
1import * as commander from './index';1import * as commander from './index.js';2import { expectType } from 'tsd';34// We are not just checking return types here, we are also implicitly checking that the expected syntax is allowed.5
437 unmodified lines
443expectType<commander.Command>(program.optionsGroup('My Group'));444expectType<string>(program.optionsGroup());445446// nameFromFilename447expectType<commander.Command>(program.nameFromFilename(__filename));447expectType<commander.Command>(program.nameFromFilename(import.meta.filename));448449// executableDir450expectType<commander.Command>(program.executableDir(__dirname));450expectType<commander.Command>(program.executableDir(import.meta.dirname));451expectType<string | null>(program.executableDir());452453// outputHelp454expectType<void>(program.outputHelp());
333 unmodified lines
modified:.prettierrc.js+1 added-3 removed
1const config = {1export default {2 singleQuote: true,3 overrides: [4 {5 files: ['tsconfig*.json'],6 options: { parser: 'jsonc' },7 },8 ],9};1011module.exports = config;
modified:CHANGELOG.md+39 added
6 unmodified lines
78<!-- markdownlint-disable MD024 -->9<!-- markdownlint-disable MD004 -->1011## [15.0.0] (2026-05-15)1213_date is placeholder, Node.js 20 EOL on 2026-04-30_1415Commander 15 is ESM only. This is expected to be seamless for ESM consumers, but some CommonJS consumers may hit issues with tooling requiring configuration for ESM-only dependencies. See Migration Tips below.1617The release of Commander 15 moves Commander 14 into maintenance. Commander 14 will get security updates for 12 months.18For more info see [Release Policy](./docs/release-policy.md).1920### Added2122### Fixed2324### Changed2526- *Breaking:* migrated Commander implementation from CommonJS to ESM ([#2464])27- *Breaking:* Commander 15 requires Node.js v20 or higher. To be more precise, `^20.19.0 || >=22.12.0` for `require(esm)`.28- dev: switch tests from Jest to `node:test` test runner ([#2463])2930### Deleted3132- *Breaking:* removed deprecated export of `commander/esm.mjs` ([#2464])3334### Migration Tips3536Commander 15 is ESM only, but this does not mean you need to migrate to ESM to use it. Importing ESM from CommonJS is37supported by Node.js, and Bun, and Deno. Hopefully it Just Works for you! However, you may be using a different runtime or38some other part of your setup that may not yet natively support importing ESM from CommonJS, such as your testing framework39or bundler.4041If you have problems using Commander 15 in your environment, one option is stay on Commander 14 for now. Commander 14 will42get security updates until May 2027 and things will hopefully improve for your setup in the meantime.4344To allow `require(esm)` from CommonJS you may be able to make small changes to your current setup. Some45examples for Jest are included in [examples/using-esm-from-commonjs](./examples/using-esm-from-commonjs).46(Commander was using Jest, so we have a special interest.)4748## [14.0.3] (2026-01-31)4950### Added51
1438 unmodified lines
1490[#2410]: https://github.com/tj/commander.js/pull/24101491[#2427]: https://github.com/tj/commander.js/pull/24271492[#2428]: https://github.com/tj/commander.js/pull/24281493[#2462]: https://github.com/tj/commander.js/pull/24621494[#2463]: https://github.com/tj/commander.js/pull/24631495[#2464]: https://github.com/tj/commander.js/pull/24641496[#2465]: https://github.com/tj/commander.js/pull/246514971498<!-- Referenced in 5.x -->1499[#1]: https://github.com/tj/commander.js/issues/1
135 unmodified lines
modified:eslint.config.js+5 added-5 removed
1const globals = require('globals');2const esLintjs = require('@eslint/js');3const tseslint = require('typescript-eslint');4const prettier = require('eslint-config-prettier');1import globals from 'globals';2import esLintjs from '@eslint/js';3import tseslint from 'typescript-eslint';4import prettier from 'eslint-config-prettier';56// Only run tseslint on the files that we have included for TypeScript.7const tsconfigTsFiles = ['**/*.{ts,mts}']; // match "include" in tsconfig.ts.json;8const tsconfigJsFiles = ['*.{js,mjs}', 'lib/**/*.{js,mjs}']; // match "include" in tsconfig.js.json910// Using tseslint.config adds some type safety and `extends` to simplify customising config array.11module.exports = tseslint.config(11export default tseslint.config(12 // Add recommended rules.13 esLintjs.configs.recommended,14 // tseslint with different setup for js/ts15 {
52 unmodified lines
deleted:esm.mjs-16 removed
1import commander from './index.js';23// wrapper to provide named exports for ESM.4export const {5 program,6 createCommand,7 createArgument,8 createOption,9 CommanderError,10 InvalidArgumentError,11 InvalidOptionArgumentError, // deprecated old name12 Command,13 Argument,14 Option,15 Help,16} = commander;
modified:index.js+14 added-17 removed
1const { Argument } = require('./lib/argument.js');2const { Command } = require('./lib/command.js');3const { CommanderError, InvalidArgumentError } = require('./lib/error.js');4const { Help } = require('./lib/help.js');5const { Option } = require('./lib/option.js');1import { Argument } from './lib/argument.js';2import { Command } from './lib/command.js';3import { CommanderError, InvalidArgumentError } from './lib/error.js';4import { Help } from './lib/help.js';5import { Option } from './lib/option.js';67exports.program = new Command();7export const program = new Command();89exports.createCommand = (name) => new Command(name);10exports.createOption = (flags, description) => new Option(flags, description);11exports.createArgument = (name, description) => new Argument(name, description);9export const createCommand = (name) => new Command(name);10export const createOption = (flags, description) =>11 new Option(flags, description);12export const createArgument = (name, description) =>13 new Argument(name, description);1415/**16 * Expose classes17 */1817exports.Command = Command;18exports.Option = Option;19exports.Argument = Argument;20exports.Help = Help;2122exports.CommanderError = CommanderError;23exports.InvalidArgumentError = InvalidArgumentError;24exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated19export { Command, Option, Argument, Help };20export { CommanderError, InvalidArgumentError };21export { InvalidArgumentError as InvalidOptionArgumentError }; // Deprecated
deleted:jest.config.js-10 removed
1const config = {2 testEnvironment: 'node',3 collectCoverage: true,4 transform: {5 '^.+\\.tsx?$': ['ts-jest', { tsconfig: 'tsconfig.ts.json' }],6 },7 testPathIgnorePatterns: ['/node_modules/'],8};910module.exports = config;
modified:package.json+3 added-16 removed
32 unmodified lines
33 },34 "files": [35 "index.js",36 "lib/*.js",37 "esm.mjs",37 "typings/index.d.ts",39 "typings/esm.d.mts",38 "package-support.json"39 ],42 "type": "commonjs",40 "type": "module",41 "main": "./index.js",42 "exports": {43 ".": {46 "require": {47 "types": "./typings/index.d.ts",44 "types": "./typings/index.d.ts",48 "default": "./index.js"49 },50 "import": {51 "types": "./typings/esm.d.mts",52 "default": "./esm.mjs"53 },45 "default": "./index.js"55 },56 "./esm.mjs": {57 "types": "./typings/esm.d.mts",58 "import": "./esm.mjs"46 }47 },48 "devDependencies": {49 "@eslint/js": "^9.4.0",
7 unmodified lines
57 "typescript-eslint": "^8.12.2"58 },59 "types": "typings/index.d.ts",60 "engines": {74 "node": ">=20"61 "node": "^20.19.0 || >=22.12.0"62 },63 "support": true64}
modified:Readme.md+6 added-7 removed
74 unmodified lines
7576Example file: [split.js](./examples/split.js)7778```js79const { program } = require('commander');79import { program } from 'commander';8081program82 .option('--first')83 .option('-s, --separator <char>')
18 unmodified lines
102103Example file: [string-util.js](./examples/string-util.js)104105```js106const { Command } = require('commander');106import { Command } from 'commander';107const program = new Command();108109program110 .name('string-util')
35 unmodified lines
146147## Declaring _program_ variable148149Commander exports a global object which is convenient for quick programs.150This is used in the examples in this README for brevity.150This is used in some examples in this README for brevity.151152```js153// CommonJS (.cjs)154const { program } = require('commander');153import { program } from 'commander';154```155156For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local `Command` object to use.157
395 unmodified lines
553Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will554remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other555subcommand is specified. (Example file: [defaultCommand.js](./examples/defaultCommand.js).)556558You can add alternative names for a command with `.alias()`. (Example file: [alias.js](./examples/alias.js).)557You can add alternative names for a command with `.alias()`. (Example file: [alias.cjs](./examples/alias.cjs).)558559`.command()` automatically copies the inherited settings from the parent command to the newly created subcommand. This is only done during creation; any later setting changes to the parent are not inherited.560561For safety, `.addCommand()` does not automatically copy the inherited settings from the parent command. There is a helper routine `.copyInheritedSettings()` for copying the settings when they are wanted.
493 unmodified lines
10551056This factory function creates a new command. It is exported and may be used instead of using `new`, like:10571058```js1060const { createCommand } = require('commander');1059import { createCommand } from 'commander';1060const program = createCommand();1061```10621063`createCommand()` is also a method of the `Command` object, and creates a new command rather than a subcommand. This gets used internally
109 unmodified lines