Skip to content
Myr

Readme.md

This file

Path

Readme.md

1,172 lines · 42.2 KiB · Markdown

Last changed by

Update changelog and version and engine for prerelease (#2484)John Geebefore adoption3f00f5b

History of this file

Take it

The walk stopped after 200 commits: lines older than 471ec40 point at it.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1–39why, one step back
1# Commander.js
23[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)4[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)5[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)6[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)78The complete solution for [node.js](http://nodejs.org) command-line interfaces.910Read this in other languages: English | [简体中文](./Readme_zh-CN.md)1112- [Commander.js](#commanderjs)13 - [Installation](#installation)14 - [Quick Start](#quick-start)15 - [Declaring _program_ variable](#declaring-program-variable)16 - [Options](#options)17 - [Common option types, boolean and value](#common-option-types-boolean-and-value)18 - [Default option value](#default-option-value)19 - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)20 - [Required option](#required-option)21 - [Variadic option](#variadic-option)22 - [Version option](#version-option)23 - [More configuration](#more-configuration)24 - [Custom option processing](#custom-option-processing)25 - [Commands](#commands)26 - [Command-arguments](#command-arguments)27 - [More configuration](#more-configuration-1)28 - [Custom argument processing](#custom-argument-processing)29 - [Action handler](#action-handler)30 - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)31 - [Life cycle hooks](#life-cycle-hooks)32 - [Automated help](#automated-help)33 - [Custom help](#custom-help)34 - [Display help after errors](#display-help-after-errors)35 - [Display help from code](#display-help-from-code)36 - [.name](#name)37 - [.usage](#usage)38 - [.description and .summary](#description-and-summary)39 - [.helpOption(flags, description)](#helpoptionflags-description)

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 40why, one step back
40 - [.helpCommand()](#helpcommand)

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

line 41why, one step back
41 - [Help Groups](#help-groups)

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 42–51why, one step back
42 - [More configuration](#more-configuration-2)
43 - [Custom event listeners](#custom-event-listeners)44 - [Bits and pieces](#bits-and-pieces)45 - [.parse() and .parseAsync()](#parse-and-parseasync)46 - [Parsing Configuration](#parsing-configuration)47 - [Legacy options as properties](#legacy-options-as-properties)48 - [TypeScript](#typescript)49 - [createCommand()](#createcommand)50 - [Node options such as `--harmony`](#node-options-such-as---harmony)51 - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)

Add npm run-script to README (#1872)John Geebefore adoption60958df

line 52why, one step back
52 - [npm run-script](#npm-run-script)

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 53–78why, one step back
53 - [Display error](#display-error)
54 - [Override exit and output handling](#override-exit-and-output-handling)55 - [Additional documentation](#additional-documentation)56 - [Support](#support)57 - [Commander for enterprise](#commander-for-enterprise)5859For information about terms used in this document see: [terminology](./docs/terminology.md)6061## Installation6263```sh64npm install commander65```6667## Quick Start6869You write code to describe your command line interface.70Commander looks after parsing the arguments into options and command-arguments,71displays usage errors for problems, and implements a help system.7273Commander is strict and displays an error for unrecognised options.74The two most used option types are a boolean option, and an option which takes its value from the following argument.7576Example file: [split.js](./examples/split.js)7778```js

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 79why, one step back
79import { program } from 'commander';

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 80–82why, one step back
80
81program82 .option('--first')

Update README and examples for allowExcessArguments change (#2266)John Geebefore adoption2c9051a

lines 83–84why, one step back
83 .option('-s, --separator <char>')
84 .argument('<string>');

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 85–93why, one step back
85
86program.parse();8788const options = program.opts();89const limit = options.first ? 1 : undefined;90console.log(program.args[0].split(options.separator, limit));91```9293```console

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 94why, one step back
94$ node split.js -s - --fits a-b-c

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 95–96why, one step back
95error: unknown option '--fits'
96(Did you mean --first?)

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 97why, one step back
97$ node split.js -s - --first a-b-c

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 98–105why, one step back
98[ 'a' ]
99```100101Here is a more complete program using a subcommand and with descriptions for the help. In a multi-command program, you have an action handler for each command (or stand-alone executables for the commands).102103Example file: [string-util.js](./examples/string-util.js)104105```js

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 106why, one step back
106import { Command } from 'commander';

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 107–140why, one step back
107const program = new Command();
108109program110 .name('string-util')111 .description('CLI to some JavaScript string utilities')112 .version('0.8.0');113114program.command('split')115 .description('Split a string into substrings and display as an array')116 .argument('<string>', 'string to split')117 .option('--first', 'display just the first substring')118 .option('-s, --separator <char>', 'separator character', ',')119 .action((str, options) => {120 const limit = options.first ? 1 : undefined;121 console.log(str.split(options.separator, limit));122 });123124program.parse();125```126127```console128$ node string-util.js help split129Usage: string-util split [options] <string>130131Split a string into substrings and display as an array.132133Arguments:134 string string to split135136Options:137 --first display just the first substring138 -s, --separator <char> separator character (default: ",")139 -h, --help display help for command140

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 141why, one step back
141$ node string-util.js split --separator=- a-b-c

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 142–149why, one step back
142[ 'a', 'b', 'c' ]
143```144145More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.146147## Declaring _program_ variable148149Commander exports a global object which is convenient for quick programs.

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 150why, one step back
150This is used in some examples in this README for brevity.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 151–152why, one step back
151
152```js

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 153why, one step back
153import { program } from 'commander';

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 154–155why, one step back
154```
155

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 156why, one step back
156For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local `Command` object to use.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 157–177why, one step back
157
158```js159// CommonJS (.cjs)160const { Command } = require('commander');161const program = new Command();162```163164```js165// ECMAScript (.mjs)166import { Command } from 'commander';167const program = new Command();168```169170```ts171// TypeScript (.ts)172import { Command } from 'commander';173const program = new Command();174```175176## Options177

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 178why, one step back
178Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma, a space, or a vertical bar (`|`). To allow a wider range of short-ish flags than just single characters, you may also have two long options.

Add support for dual long options when no short option (#2312)John Geebefore adoption8263b7f

lines 179–185why, one step back
179
180```js181program182 .option('-p, --port <number>', 'server port number')183 .option('--trace', 'add extra debugging output')184 .option('--ws, --workspace <name>', 'use a custom workspace')185```

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 186–188why, one step back
186
187The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.188

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 189why, one step back
189Multi-word options like `--template-engine` are normalized to camelCase option names, resulting in properties such as `program.opts().templateEngine`.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 190why, one step back
190

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 191why, one step back
191An option and its option-argument can be separated by a space, or combined into the same argument. The option-argument can follow the short option directly, or follow an `=` for a long option.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 192–201why, one step back
192
193```sh194serve -p 80195serve -p80196serve --port 80197serve --port=80198```199200You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.201

Merge branch 'fix/grammar' of github.com:aweebit/commander.js into aweebit-fix/grammarJohn Geebefore adoption591fc4b

line 202why, one step back
202By default, options on the command line are not positional, and can be specified before or after other arguments.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 203–244why, one step back
203
204There are additional related routines for when `.opts()` is not enough:205206- `.optsWithGlobals()` returns merged local and global option values207- `.getOptionValue()` and `.setOptionValue()` work with a single option value208- `.getOptionValueSource()` and `.setOptionValueWithSource()` include where the option value came from209210### Common option types, boolean and value211212The two most used option types are a boolean option, and an option which takes its value213from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.214215Example file: [options-common.js](./examples/options-common.js)216217```js218program219 .option('-d, --debug', 'output extra debugging')220 .option('-s, --small', 'small pizza size')221 .option('-p, --pizza-type <type>', 'flavour of pizza');222223program.parse(process.argv);224225const options = program.opts();226if (options.debug) console.log(options);227console.log('pizza details:');228if (options.small) console.log('- small pizza size');229if (options.pizzaType) console.log(`- ${options.pizzaType}`);230```231232```console233$ pizza-options -p234error: option '-p, --pizza-type <type>' argument missing235$ pizza-options -d -s -p vegetarian236{ debug: true, small: true, pizzaType: 'vegetarian' }237pizza details:238- small pizza size239- vegetarian240$ pizza-options --pizza-type=cheese241pizza details:242- cheese243```244

Merge branch 'fix/grammar' of github.com:aweebit/commander.js into aweebit-fix/grammarJohn Geebefore adoption591fc4b

line 245why, one step back
245Multiple boolean short options may be combined following the dash, and may be followed by a single short option taking a value.

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 246why, one step back
246For example, `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 247–276why, one step back
247
248Options with an expected option-argument are greedy and will consume the following argument whatever the value.249So `--id -xyz` reads `-xyz` as the option-argument.250251`program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array. The parameter is optional and defaults to `process.argv`.252253### Default option value254255You can specify a default value for an option.256257Example file: [options-defaults.js](./examples/options-defaults.js)258259```js260program261 .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');262263program.parse();264265console.log(`cheese: ${program.opts().cheese}`);266```267268```console269$ pizza-options270cheese: blue271$ pizza-options --cheese stilton272cheese: stilton273```274275### Other option types, negatable boolean and boolean|value276

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 277–278why, one step back
277You can define a boolean option long name with a leading `no-` to set the option value to `false` when used.
278Defined alone without a matching positive option, this also makes the option `true` by default.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 279–306why, one step back
279
280Example file: [options-negatable.js](./examples/options-negatable.js)281282```js283program284 .option('--no-sauce', 'Remove sauce')285 .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')286 .option('--no-cheese', 'plain with no cheese')287 .parse();288289const options = program.opts();290const sauceStr = options.sauce ? 'sauce' : 'no sauce';291const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;292console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);293```294295```console296$ pizza-options297You ordered a pizza with sauce and mozzarella cheese298$ pizza-options --sauce299error: unknown option '--sauce'300$ pizza-options --cheese=blue301You ordered a pizza with sauce and blue cheese302$ pizza-options --no-sauce --no-cheese303You ordered a pizza with no sauce and no cheese304```305306You can specify an option which may be used as a boolean option but may optionally take an option-argument

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 307why, one step back
307(declared with square brackets, like `--optional [value]`).

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 308–332why, one step back
308
309Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)310311```js312program313 .option('-c, --cheese [type]', 'Add cheese with optional type');314315program.parse(process.argv);316317const options = program.opts();318if (options.cheese === undefined) console.log('no cheese');319else if (options.cheese === true) console.log('add cheese');320else console.log(`add cheese type ${options.cheese}`);321```322323```console324$ pizza-options325no cheese326$ pizza-options --cheese327add cheese328$ pizza-options --cheese mozzarella329add cheese type mozzarella330```331332Options with an optional option-argument are not greedy and will ignore arguments starting with a dash.

Allow negative numbers as optional optional arguments and command arguments when unambiguous (#2339)John Geebefore adoptionf6302de

lines 333–334why, one step back
333So `id` behaves as a boolean option for `--id -ABCD`, but you can use a combined form if needed like `--id=-ABCD`.
334Negative numbers are special and are accepted as an option-argument.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 335why, one step back
335

Refactor headings (#2028)John Geebefore adoption03dea00

line 336why, one step back
336For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 337–339why, one step back
337
338### Required option339

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 340why, one step back
340You may specify a required (mandatory) option using `.requiredOption()`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (e.g., from environment).

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 341why, one step back
341

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 342–343why, one step back
342The method is otherwise the same as `.option()` in format, taking flags and description, and optional default value or custom processing.
343

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 344–362why, one step back
344Example file: [options-required.js](./examples/options-required.js)
345346```js347program348 .requiredOption('-c, --cheese <type>', 'pizza must have cheese');349350program.parse();351```352353```console354$ pizza355error: required option '-c, --cheese <type>' not specified356```357358### Variadic option359360You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you361can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments362are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 363why, one step back
363is specified in the same argument as the option, then no further values are read.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 364–389why, one step back
364
365Example file: [options-variadic.js](./examples/options-variadic.js)366367```js368program369 .option('-n, --number <numbers...>', 'specify numbers')370 .option('-l, --letter [letters...]', 'specify letters');371372program.parse();373374console.log('Options: ', program.opts());375console.log('Remaining arguments: ', program.args);376```377378```console379$ collect -n 1 2 3 --letter a b c380Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }381Remaining arguments: []382$ collect --letter=A -n80 operand383Options: { number: [ '80' ], letter: [ 'A' ] }384Remaining arguments: [ 'operand' ]385$ collect --letter -n 1 -n 2 3 -- operand386Options: { number: [ '1', '2', '3' ], letter: true }387Remaining arguments: [ 'operand' ]388```389

Refactor headings (#2028)John Geebefore adoption03dea00

line 390why, one step back
390For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 391–393why, one step back
391
392### Version option393

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 394why, one step back
394The optional `.version()` method adds handling for displaying the command version. The default option flags are `-V` and `--version`. When used, the command prints the version number and exits.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 395–404why, one step back
395
396```js397program.version('0.0.1');398```399400```console401$ ./examples/pizza -V4020.0.1403```404

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 405–406why, one step back
405You may change the flags and description by passing additional parameters to the `.version()` method, using
406the same syntax for flags as the `.option()` method.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 407–452why, one step back
407
408```js409program.version('0.0.1', '-v, --vers', 'output the current version');410```411412### More configuration413414You can add most options using the `.option()` method, but there are some additional features available415by constructing an `Option` explicitly for less common cases.416417Example files: [options-extra.js](./examples/options-extra.js), [options-env.js](./examples/options-env.js), [options-conflicts.js](./examples/options-conflicts.js), [options-implies.js](./examples/options-implies.js)418419```js420program421 .addOption(new Option('-s, --secret').hideHelp())422 .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))423 .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))424 .addOption(new Option('-p, --port <number>', 'port number').env('PORT'))425 .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat))426 .addOption(new Option('--disable-server', 'disables the server').conflicts('port'))427 .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' }));428```429430```console431$ extra --help432Usage: help [options]433434Options:435 -t, --timeout <delay> timeout in seconds (default: one minute)436 -d, --drink <size> drink cup size (choices: "small", "medium", "large")437 -p, --port <number> port number (env: PORT)438 --donate [amount] optional donation in dollars (preset: "20")439 --disable-server disables the server440 --free-drink small drink included free441 -h, --help display help for command442443$ extra --drink huge444error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.445446$ PORT=80 extra --donate --free-drink447Options: { timeout: 60, donate: 20, port: '80', freeDrink: true, drink: 'small' }448449$ extra --disable-server --port 8000450error: option '--disable-server' cannot be used with option '-p, --port <number>'451```452

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 453why, one step back
453Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [`.requiredOption()`](#required-option).

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 454–520why, one step back
454
455### Custom option processing456457You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,458the user specified option-argument and the previous value for the option. It returns the new value for the option.459460This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.461462You can optionally specify the default/starting value for the option after the function parameter.463464Example file: [options-custom-processing.js](./examples/options-custom-processing.js)465466```js467function myParseInt(value, dummyPrevious) {468 // parseInt takes a string and a radix469 const parsedValue = parseInt(value, 10);470 if (isNaN(parsedValue)) {471 throw new commander.InvalidArgumentError('Not a number.');472 }473 return parsedValue;474}475476function increaseVerbosity(dummyValue, previous) {477 return previous + 1;478}479480function collect(value, previous) {481 return previous.concat([value]);482}483484function commaSeparatedList(value, dummyPrevious) {485 return value.split(',');486}487488program489 .option('-f, --float <number>', 'float argument', parseFloat)490 .option('-i, --integer <number>', 'integer argument', myParseInt)491 .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)492 .option('-c, --collect <value>', 'repeatable value', collect, [])493 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)494;495496program.parse();497498const options = program.opts();499if (options.float !== undefined) console.log(`float: ${options.float}`);500if (options.integer !== undefined) console.log(`integer: ${options.integer}`);501if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);502if (options.collect.length > 0) console.log(options.collect);503if (options.list !== undefined) console.log(options.list);504```505506```console507$ custom -f 1e2508float: 100509$ custom --integer 2510integer: 2511$ custom -v -v -v512verbose: 3513$ custom -c a -c b -c c514[ 'a', 'b', 'c' ]515$ custom --list x,y,z516[ 'x', 'y', 'z' ]517```518519## Commands520

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 521why, one step back
521You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an `.action()` handler attached to the command; or as a stand-alone executable file. (More detail about this later.)

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 522why, one step back
522

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 523–524why, one step back
523Subcommands may be nested. Example file: [nestedCommands.js](./examples/nestedCommands.js).
524

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 525–554why, one step back
525In the first parameter to `.command()` you specify the command name. You may append the command-arguments after the command name, or specify them separately using `.argument()`. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.
526527You can use `.addCommand()` to add an already configured subcommand to the program.528529For example:530531```js532// Command implemented using action handler (description is supplied separately to `.command`)533// Returns new command for configuring.534program535 .command('clone <source> [destination]')536 .description('clone a repository into a newly created directory')537 .action((source, destination) => {538 console.log('clone command called');539 });540541// Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`.542// Returns `this` for adding more commands.543program544 .command('start <service>', 'start named service')545 .command('stop [service]', 'stop named service, or all if no name supplied');546547// Command prepared separately.548// Returns `this` for adding more commands.549program550 .addCommand(build.makeBuildCommand());551```552553Configuration 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 other

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 555why, one step back
555subcommand is specified. (Example file: [defaultCommand.js](./examples/defaultCommand.js).)

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 556why, one step back
556

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 557why, one step back
557You can add alternative names for a command with `.alias()`. (Example file: [alias.cjs](./examples/alias.cjs).)

Merge branch 'master' into release/10.xJohn Geebefore adoption2bdd631

line 558why, one step back
558

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 559why, one step back
559`.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.

Add note on inherited settings to docsaweebitbefore adoption2e2f139

line 560why, one step back
560

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 561–565why, one step back
561For 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.
562563### Command-arguments564565For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 566why, one step back
566is the only method usable for subcommands implemented using a stand-alone executable.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 567why, one step back
567

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 568why, one step back
568Alternatively, you can instead use the following method. To configure a command, you can use `.argument()` to specify each expected command-argument.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 569–584why, one step back
569You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.
570You can specify a default value for an optional command-argument.571572Example file: [argument.js](./examples/argument.js)573574```js575program576 .version('0.1.0')577 .argument('<username>', 'user to login')578 .argument('[password]', 'password for user, if required', 'no password given')579 .action((username, password) => {580 console.log('username:', username);581 console.log('password:', password);582 });583```584

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 585–586why, one step back
585The last argument of a command can be variadic, and _only_ the last argument. To make an argument variadic, simply
586append `...` to the argument name.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 587why, one step back
587

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 588–589why, one step back
588A variadic argument is passed to the action handler as an array.
589

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 590–664why, one step back
590```js
591program592 .version('0.1.0')593 .command('rmdir')594 .argument('<dirs...>')595 .action(function (dirs) {596 dirs.forEach((dir) => {597 console.log('rmdir %s', dir);598 });599 });600```601602There is a convenience method to add multiple arguments at once, but without descriptions:603604```js605program606 .arguments('<username> <password>');607```608609#### More configuration610611There are some additional features available by constructing an `Argument` explicitly for less common cases.612613Example file: [arguments-extra.js](./examples/arguments-extra.js)614615```js616program617 .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))618 .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))619```620621#### Custom argument processing622623You may specify a function to do custom processing of command-arguments (like for option-arguments).624The callback function receives two parameters, the user specified command-argument and the previous value for the argument.625It returns the new value for the argument.626627The processed argument values are passed to the action handler, and saved as `.processedArgs`.628629You can optionally specify the default/starting value for the argument after the function parameter.630631Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)632633```js634program635 .command('add')636 .argument('<first>', 'integer argument', myParseInt)637 .argument('[second]', 'integer argument', myParseInt, 1000)638 .action((first, second) => {639 console.log(`${first} + ${second} = ${first + second}`);640 })641;642```643644### Action handler645646The action handler gets passed a parameter for each command-argument you declared, and two additional parameters647which are the parsed options and the command object itself.648649Example file: [thank.js](./examples/thank.js)650651```js652program653 .argument('<name>')654 .option('-t, --title <honorific>', 'title to use before name')655 .option('-d, --debug', 'display some debugging')656 .action((name, options, command) => {657 if (options.debug) {658 console.error('Called %s with options %o', command.name(), options);659 }660 const title = options.title ? `${options.title} ` : '';661 console.log(`Thank-you ${title}${name}`);662 });663```664

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 665why, one step back
665If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. If you use a function expression (but not an arrow function), the `this` keyword is set to the running command.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 666–678why, one step back
666
667Example file: [action-this.js](./examples/action-this.js)668669```js670program671 .command('serve')672 .argument('<script>')673 .option('-p, --port <number>', 'port number', 80)674 .action(function() {675 console.error('Run script %s on port %s', this.args[0], this.opts().port);676 });677```678

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 679why, one step back
679You may supply an `async` action handler, in which case you call `.parseAsync()` rather than `.parse()`.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 680–691why, one step back
680
681```js682async function run() { /* code goes here */ }683684async function main() {685 program686 .command('run')687 .action(run);688 await program.parseAsync(process.argv);689}690```691

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 692why, one step back
692A command's options and arguments on the command line are validated when the command is used. Any unknown options, missing arguments, or excess arguments will be reported as an error.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 693why, one step back
693

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 694–695why, one step back
694You can suppress the unknown option check with `.allowUnknownOption()`. You can suppress the excess arguments check with `.allowExcessArguments()`.
695

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 696–698why, one step back
696### Stand-alone executable (sub)commands
697698When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 699why, one step back
699Commander will search the files in the directory of the entry script for a file with the name combination `command-subcommand` (like `pm-install` or `pm-search` in the example below). The search includes trying common file extensions, like `.js`.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 700–710why, one step back
700You may specify a custom name (and path) with the `executableFile` configuration option.
701You may specify a custom search directory for subcommands with `.executableDir()`.702703You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.704705Example file: [pm](./examples/pm)706707```js708program709 .name('pm')710 .version('0.1.0')

Update README and examples for allowExcessArguments change (#2266)John Geebefore adoption2c9051a

line 711why, one step back
711 .command('install [package-names...]', 'install one or more packages')

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 712–738why, one step back
712 .command('search [query]', 'search with optional query')
713 .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })714 .command('list', 'list packages installed', { isDefault: true });715716program.parse(process.argv);717```718719If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.720721### Life cycle hooks722723You can add callback hooks to a command for life cycle events.724725Example file: [hook.js](./examples/hook.js)726727```js728program729 .option('-t, --trace', 'display trace statements for commands')730 .hook('preAction', (thisCommand, actionCommand) => {731 if (thisCommand.opts().trace) {732 console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);733 console.log('arguments: %O', actionCommand.args);734 console.log('options: %o', actionCommand.opts());735 }736 });737```738

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 739why, one step back
739The callback hook can be `async`, in which case you call `.parseAsync()` rather than `.parse()`. You can add multiple hooks per event.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 740–747why, one step back
740
741The supported events are:742743| event name | when hook called | callback parameters |744| :-- | :-- | :-- |745| `preAction`, `postAction` | before/after action handler for this command and its nested subcommands | `(thisCommand, actionCommand)` |746| `preSubcommand` | before parsing direct subcommand | `(thisCommand, subcommand)` |747

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 748why, one step back
748For an overview of the life cycle events, see [parsing life cycle and hooks](./docs/parsing-and-hooks.md).

Add new documentation to READMEJohn Geebefore adoption5fbf83a

line 749why, one step back
749

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 750–780why, one step back
750## Automated help
751752The help information is auto-generated based on the information commander already knows about your program. The default753help option is `-h,--help`.754755Example file: [pizza](./examples/pizza)756757```console758$ node ./examples/pizza --help759Usage: pizza [options]760761An application for pizza ordering762763Options:764 -p, --peppers Add peppers765 -c, --cheese <type> Add the specified type of cheese (default: "marble")766 -C, --no-cheese You do not want any cheese767 -h, --help display help for command768```769770A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show771further help for the subcommand. These are effectively the same if the `shell` program has implicit help:772773```sh774shell help775shell --help776777shell help spawn778shell spawn --help779```780

Merge branch 'fix/grammar' of github.com:aweebit/commander.js into aweebit-fix/grammarJohn Geebefore adoption591fc4b

line 781why, one step back
781Long descriptions are wrapped to fit the available width. (However, a description that includes a line-break followed by whitespace is assumed to be pre-formatted and not wrapped.)

Describe help description wrappingJohn Geebefore adoption1aa5271

line 782why, one step back
782

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 783–822why, one step back
783### Custom help
784785You can add extra text to be displayed along with the built-in help.786787Example file: [custom-help](./examples/custom-help)788789```js790program791 .option('-f, --foo', 'enable some foo');792793program.addHelpText('after', `794795Example call:796 $ custom-help --help`);797```798799Yields the following help output:800801```Text802Usage: custom-help [options]803804Options:805 -f, --foo enable some foo806 -h, --help display help for command807808Example call:809 $ custom-help --help810```811812The positions in order displayed are:813814- `beforeAll`: add to the program for a global banner or header815- `before`: display extra information before built-in help816- `after`: display extra information after built-in help817- `afterAll`: add to the program for a global footer (epilog)818819The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.820821The second parameter can be a string, or a function returning a string. The function is passed a context object for your convenience. The properties are:822

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 823–824why, one step back
823- `error`: a boolean for whether the help is being displayed due to a usage error
824- `command`: the `Command` which is displaying the help

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 825–867why, one step back
825
826### Display help after errors827828The default behaviour for usage errors is to just display a short error message.829You can change the behaviour to show the full help or a custom help message after an error.830831```js832program.showHelpAfterError();833// or834program.showHelpAfterError('(add --help for additional information)');835```836837```console838$ pizza --unknown839error: unknown option '--unknown'840(add --help for additional information)841```842843The default behaviour is to suggest correct spelling after an error for an unknown command or option. You844can disable this.845846```js847program.showSuggestionAfterError(false);848```849850```console851$ pizza --hepl852error: unknown option '--hepl'853(Did you mean --help?)854```855856### Display help from code857858`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.859860`.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.861862`.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.863864### .name865866The command name appears in the help, and is also used for locating stand-alone executable subcommands.867

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 868why, one step back
868You may specify the program name using `.name()` or in the `Command` constructor. For the program, Commander will

Merge branch 'fix/grammar' of github.com:aweebit/commander.js into aweebit-fix/grammarJohn Geebefore adoption591fc4b

lines 869–870why, one step back
869fall back to using the script name from the full arguments passed into `.parse()`. However, the script name varies
870depending on how your program is launched, so you may wish to specify it explicitly.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 871–877why, one step back
871
872```js873program.name('pizza');874const pm = new Command('pm');875```876877Subcommands get a name when specified using `.command()`. If you create the subcommand yourself to use with `.addCommand()`,

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 878why, one step back
878then set the name using `.name()` or in the `Command` constructor.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 879–911why, one step back
879
880### .usage881882This allows you to customise the usage description in the first line of the help. Given:883884```js885program886 .name("my-command")887 .usage("[global options] command")888```889890The help will start with:891892```Text893Usage: my-command [global options] command894```895896### .description and .summary897898The description appears in the help for the command. You can optionally supply a shorter899summary to use when listed as a subcommand of the program.900901```js902program903 .command("duplicate")904 .summary("make a copy")905 .description(`Make a copy of the current project.906This may require additional disk space.907 `);908```909910### .helpOption(flags, description)911

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 912why, one step back
912By default, every command has a help option. You may change the default help flags and description. Pass `false` to disable the built-in help option.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 913–918why, one step back
913
914```js915program916 .helpOption('-e, --HELP', 'read more information');917```918

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 919why, one step back
919Alternatively, use `.addHelpOption()` to add an option you construct yourself.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 920why, one step back
920

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 921why, one step back
921### .helpCommand()

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 922why, one step back
922

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 923why, one step back
923A help command is added by default if your command has subcommands. You can explicitly turn the implicit help command on or off with `.helpCommand(true)` and `.helpCommand(false)`.

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 924why, one step back
924

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 925–927why, one step back
925You can both turn on and customise the help command by supplying the name and description:
926927```js

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 928why, one step back
928program.helpCommand('assist [command]', 'show assistance');

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 929–930why, one step back
929```
930

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 931why, one step back
931Alternatively, use `.addHelpCommand()` to add a command you construct yourself.

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 932–935why, one step back
932
933### Help Groups934935The help by default lists options under the the heading `Options:` and commands under `Commands:`. You can create your own groups

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 936why, one step back
936with different headings.

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

line 937why, one step back
937

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 938–940why, one step back
938- The high-level way is to set the desired group heading while adding the options and commands, using `.optionsGroup()` and `.commandsGroup()`.
939- The low-level way is using `.helpGroup()` on an individual `Option` or `Command`.940

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

line 941why, one step back
941Example file: [help-groups.js](./examples/help-groups.js)

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 942why, one step back
942

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 943–944why, one step back
943### More configuration
944

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 945–946why, one step back
945The built-in help is formatted using the `Help` class.
946You can configure the help by modifying data properties and methods using `.configureHelp()`, or by subclassing `Help` using `.createHelp()` .

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 947why, one step back
947

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 948why, one step back
948Simple properties include `sortSubcommands`, `sortOptions`, and `showGlobalOptions`. You can add color using the style methods like `.styleTitle()`.

Add clues about what help configuration is available to help with searches and encourage people to look further (#2294)John Geebefore adoption02c603e

line 949why, one step back
949

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 950why, one step back
950For more detail and examples of changing the displayed text, color, and layout, see: [Help in Depth](./docs/help-in-depth.md).

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 951–953why, one step back
951
952## Custom event listeners953

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 954why, one step back
954You can execute custom actions by listening to `command` and `option` events.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 955–965why, one step back
955
956```js957program.on('option:verbose', function () {958 process.env.VERBOSE = this.opts().verbose;959});960```961962## Bits and pieces963964### .parse() and .parseAsync()965

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

line 966why, one step back
966Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 967why, one step back
967

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 968why, one step back
968Or, call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 969why, one step back
969

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 970–972why, one step back
970- `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
971- `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged972- `'user'`: just user arguments

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 973–976why, one step back
973
974For example:975976```js

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

lines 977–979why, one step back
977program.parse(); // parse process.argv and auto-detect electron and special node flags
978program.parse(process.argv); // assume argv[0] is app and argv[1] is script979program.parse(['--port', '80'], { from: 'user' }); // just user supplied arguments, nothing special about argv[0]

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 980why, one step back
980```

Add auto-detection of args when node evaluating script code on command-line (#2164)John Geebefore adoptionb9ca390

line 981why, one step back
981

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 982why, one step back
982Use `.parseAsync()` instead of `.parse()` if any of your action handlers are async.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 983–987why, one step back
983
984### Parsing Configuration985986If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.987

Merge branch 'fix/grammar' of github.com:aweebit/commander.js into aweebit-fix/grammarJohn Geebefore adoption591fc4b

line 988why, one step back
988By default, program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 989–999why, one step back
989an option for a different purpose in subcommands.
990991Example file: [positional-options.js](./examples/positional-options.js)992993With positional options, the `-b` is a program option in the first line and a subcommand option in the second line:994995```sh996program -b subcommand997program subcommand -b998```999

Merge branch 'fix/grammar' of github.com:aweebit/commander.js into aweebit-fix/grammarJohn Geebefore adoption591fc4b

lines 1000–1001why, one step back
1000By default, options are recognised before and after command-arguments. To only process options that come
1001before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1002–1013why, one step back
1002without needing to use `--` to end the option processing.
1003To use pass through options in a subcommand, the program needs to enable positional options.10041005Example file: [pass-through-options.js](./examples/pass-through-options.js)10061007With pass through options, the `--port=80` is a program option in the first line and passed through as a command-argument in the second line:10081009```sh1010program --port=80 arg1011program arg --port=801012```1013

Merge branch 'fix/grammar' of github.com:aweebit/commander.js into aweebit-fix/grammarJohn Geebefore adoption591fc4b

line 1014why, one step back
1014By default, the option processing shows an error for an unknown option. To have an unknown option treated as an ordinary command-argument and continue looking for options, use `.allowUnknownOption()`. This lets you mix known and unknown options.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1015why, one step back
1015

Update more of README with opt-in allowExcessArguments() (#2327)John Geebefore adoptionb8fe4f1

line 1016why, one step back
1016By default, the argument processing displays an error for more command-arguments than expected.

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1017why, one step back
1017To suppress the error for excess arguments, use `.allowExcessArguments()`.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1018–1021why, one step back
1018
1019### Legacy options as properties10201021Before Commander 7, the option values were stored as properties on the command.

Merge branch 'fix/grammar' of github.com:aweebit/commander.js into aweebit-fix/grammarJohn Geebefore adoption591fc4b

line 1022why, one step back
1022This was convenient to code, but the downside was possible clashes with

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1023why, one step back
1023existing properties of `Command`.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1024why, one step back
1024

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 1025–1026why, one step back
1025You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.
1026

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1027–1039why, one step back
1027```js
1028program1029 .storeOptionsAsProperties()1030 .option('-d, --debug')1031 .action((commandAndOptions) => {1032 if (commandAndOptions.debug) {1033 console.error(`Called ${commandAndOptions.name()}`);1034 }1035 });1036```10371038### TypeScript1039

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1040why, one step back
1040**extra-typings:** There is an optional project to infer extra type information from the option and argument definitions.

Merge remote-tracking branch 'origin/develop' into release/10.xJohn Geebefore adoptione0f6173

line 1041why, one step back
1041This adds strong typing to the options returned by `.opts()` and the parameters to `.action()`.

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1042why, one step back
1042For more, see the repo: [commander-js/extra-typings](https://github.com/commander-js/extra-typings).

Merge remote-tracking branch 'origin/develop' into release/10.xJohn Geebefore adoptione0f6173

line 1043why, one step back
1043

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1044why, one step back
1044```ts

Merge remote-tracking branch 'origin/develop' into release/10.xJohn Geebefore adoptione0f6173

lines 1045–1047why, one step back
1045import { Command } from '@commander-js/extra-typings';
1046```1047

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1048why, one step back
1048**ts-node:** If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly, e.g.:

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1049–1058why, one step back
1049
1050```sh1051node -r ts-node/register pm.ts1052```10531054### createCommand()10551056This factory function creates a new command. It is exported and may be used instead of using `new`, like:10571058```js

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 1059why, one step back
1059import { createCommand } from 'commander';

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1060–1062why, one step back
1060const program = createCommand();
1061```1062

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1063why, one step back
1063`createCommand()` is also a method of the `Command` object, and creates a new command rather than a subcommand. This gets used internally

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1064why, one step back
1064when creating subcommands using `.command()`, and you may override it to

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1065why, one step back
1065customise the new subcommand. Example file: [custom-command-class.js](./examples/custom-command-class.js).

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1066–1070why, one step back
1066
1067### Node options such as `--harmony`10681069You can enable `--harmony` option in two ways:1070

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 1071–1072why, one step back
1071- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note: Windows does not support this pattern.)
1072- Use the `--harmony` option when calling the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand processes.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1073–1077why, one step back
1073
1074### Debugging stand-alone executable subcommands10751076An executable subcommand is launched as a separate child process.1077

Merge branch 'fix/grammar' of github.com:aweebit/commander.js into aweebit-fix/grammarJohn Geebefore adoption591fc4b

line 1078why, one step back
1078If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al.,

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1079–1080why, one step back
1079the inspector port is incremented by 1 for the spawned subcommand.
1080

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1081why, one step back
1081If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your `launch.json` configuration.

Add npm run-script to README (#1872)John Geebefore adoption60958df

lines 1082–1084why, one step back
1082
1083### npm run-script1084

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1085why, one step back
1085By default, when you call your program using `run-script`, `npm` will parse any options on the command-line and they will not reach your program. Use

Add npm run-script to README (#1872)John Geebefore adoption60958df

lines 1086–1087why, one step back
1086 `--` to stop the npm option parsing and pass through all the arguments.
1087

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1088why, one step back
1088 The synopsis for [`npm run-script`](https://docs.npmjs.com/cli/v9/commands/npm-run-script) explicitly shows the `--` for this reason:

Add npm run-script to README (#1872)John Geebefore adoption60958df

lines 1089–1092why, one step back
1089
1090```console1091npm run-script <command> [-- <args>]1092```

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1093–1097why, one step back
1093
1094### Display error10951096This routine is available to invoke the Commander error handling for your own error conditions. (See also the next section about exit handling.)1097

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1098why, one step back
1098As well as the error message, you can optionally specify the `exitCode` (used with `process.exit()`)

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1099–1107why, one step back
1099and `code` (used with `CommanderError`).
11001101```js1102program.error('Password must be longer than four characters');1103program.error('Custom processing has failed', { exitCode: 2, code: 'my.custom.error' });1104```11051106### Override exit and output handling1107

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1108why, one step back
1108By default, Commander calls `process.exit()` when it detects errors, or after displaying the help or version. You can override

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1109–1110why, one step back
1109this behaviour and optionally supply a callback. The default override throws a `CommanderError`.
1110

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 1111–1114why, one step back
1111The override callback is passed a `CommanderError` with the properties:
1112- `exitCode`: number1113- `code`: string 1114- `message`: string

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 1115why, one step back
1115

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 1116–1118why, one step back
1116Commander expects the callback to terminate the normal program flow, and will call `process.exit()` if the callback returns.
1117The normal display of error messages or version or help is not affected by the override, which is called after the display.1118

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1119–1128why, one step back
1119```js
1120program.exitOverride();11211122try {1123 program.parse(process.argv);1124} catch (err) {1125 // custom processing...1126}1127```1128

Merge branch 'fix/grammar' of github.com:aweebit/commander.js into aweebit-fix/grammarJohn Geebefore adoption591fc4b

line 1129why, one step back
1129By default, Commander is configured for a command-line application and writes to stdout and stderr.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1130–1154why, one step back
1130You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.
11311132Example file: [configure-output.js](./examples/configure-output.js)11331134```js1135function errorColor(str) {1136 // Add ANSI escape codes to display text in red.1137 return `\x1b[31m${str}\x1b[0m`;1138}11391140program1141 .configureOutput({1142 // Visibly override write routines as example!1143 writeOut: (str) => process.stdout.write(`[OUT] ${str}`),1144 writeErr: (str) => process.stdout.write(`[ERR] ${str}`),1145 // Highlight errors in color.1146 outputError: (str, write) => write(errorColor(str))1147 });1148```11491150### Additional documentation11511152There is more information available about:11531154- [deprecated](./docs/deprecated.md) features still supported for backwards compatibility

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1155why, one step back
1155- [Help in Depth](./docs/help-in-depth.md) configuring help output

Refactor headings (#2028)John Geebefore adoption03dea00

line 1156why, one step back
1156- [options taking varying arguments](./docs/options-in-depth.md)

Add new documentation to READMEJohn Geebefore adoption5fbf83a

line 1157why, one step back
1157- [parsing life cycle and hooks](./docs/parsing-and-hooks.md)

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 1158why, one step back
1158- [Release Policy](./docs/release-policy.md)

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1159–1161why, one step back
1159
1160## Support1161

Update changelog and version and engine for prerelease (#2484)John Geebefore adoption3f00f5b

line 1162why, one step back
1162The current version of Commander is fully supported on Long Term Support versions of Node.js, and requires at least v22.12.0.

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 1163–1164why, one step back
1163
1164Older major versions of Commander receive security updates for 12 months. For more see: [Release Policy](./docs/release-policy.md).

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 1165–1172why, one step back
1165
1166The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.11671168### Commander for enterprise11691170Available as part of the Tidelift Subscription11711172The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)