summaryrefslogtreecommitdiff
path: root/node_modules/commander
diff options
context:
space:
mode:
Diffstat (limited to 'node_modules/commander')
-rw-r--r--node_modules/commander/CHANGELOG.md419
-rw-r--r--node_modules/commander/Readme.md1222
-rw-r--r--node_modules/commander/index.js1225
-rw-r--r--node_modules/commander/package.json74
-rw-r--r--node_modules/commander/typings/index.d.ts1177
5 files changed, 1914 insertions, 2203 deletions
diff --git a/node_modules/commander/CHANGELOG.md b/node_modules/commander/CHANGELOG.md
deleted file mode 100644
index 7dce779d..00000000
--- a/node_modules/commander/CHANGELOG.md
+++ /dev/null
@@ -1,419 +0,0 @@
-2.20.3 / 2019-10-11
-==================
-
- * Support Node.js 0.10 (Revert #1059)
- * Ran "npm unpublish commander@2.20.2". There is no 2.20.2.
-
-2.20.1 / 2019-09-29
-==================
-
- * Improve executable subcommand tracking
- * Update dev dependencies
-
-2.20.0 / 2019-04-02
-==================
-
- * fix: resolve symbolic links completely when hunting for subcommands (#935)
- * Update index.d.ts (#930)
- * Update Readme.md (#924)
- * Remove --save option as it isn't required anymore (#918)
- * Add link to the license file (#900)
- * Added example of receiving args from options (#858)
- * Added missing semicolon (#882)
- * Add extension to .eslintrc (#876)
-
-2.19.0 / 2018-10-02
-==================
-
- * Removed newline after Options and Commands headers (#864)
- * Bugfix - Error output (#862)
- * Fix to change default value to string (#856)
-
-2.18.0 / 2018-09-07
-==================
-
- * Standardize help output (#853)
- * chmod 644 travis.yml (#851)
- * add support for execute typescript subcommand via ts-node (#849)
-
-2.17.1 / 2018-08-07
-==================
-
- * Fix bug in command emit (#844)
-
-2.17.0 / 2018-08-03
-==================
-
- * fixed newline output after help information (#833)
- * Fix to emit the action even without command (#778)
- * npm update (#823)
-
-2.16.0 / 2018-06-29
-==================
-
- * Remove Makefile and `test/run` (#821)
- * Make 'npm test' run on Windows (#820)
- * Add badge to display install size (#807)
- * chore: cache node_modules (#814)
- * chore: remove Node.js 4 (EOL), add Node.js 10 (#813)
- * fixed typo in readme (#812)
- * Fix types (#804)
- * Update eslint to resolve vulnerabilities in lodash (#799)
- * updated readme with custom event listeners. (#791)
- * fix tests (#794)
-
-2.15.0 / 2018-03-07
-==================
-
- * Update downloads badge to point to graph of downloads over time instead of duplicating link to npm
- * Arguments description
-
-2.14.1 / 2018-02-07
-==================
-
- * Fix typing of help function
-
-2.14.0 / 2018-02-05
-==================
-
- * only register the option:version event once
- * Fixes issue #727: Passing empty string for option on command is set to undefined
- * enable eqeqeq rule
- * resolves #754 add linter configuration to project
- * resolves #560 respect custom name for version option
- * document how to override the version flag
- * document using options per command
-
-2.13.0 / 2018-01-09
-==================
-
- * Do not print default for --no-
- * remove trailing spaces in command help
- * Update CI's Node.js to LTS and latest version
- * typedefs: Command and Option types added to commander namespace
-
-2.12.2 / 2017-11-28
-==================
-
- * fix: typings are not shipped
-
-2.12.1 / 2017-11-23
-==================
-
- * Move @types/node to dev dependency
-
-2.12.0 / 2017-11-22
-==================
-
- * add attributeName() method to Option objects
- * Documentation updated for options with --no prefix
- * typings: `outputHelp` takes a string as the first parameter
- * typings: use overloads
- * feat(typings): update to match js api
- * Print default value in option help
- * Fix translation error
- * Fail when using same command and alias (#491)
- * feat(typings): add help callback
- * fix bug when description is add after command with options (#662)
- * Format js code
- * Rename History.md to CHANGELOG.md (#668)
- * feat(typings): add typings to support TypeScript (#646)
- * use current node
-
-2.11.0 / 2017-07-03
-==================
-
- * Fix help section order and padding (#652)
- * feature: support for signals to subcommands (#632)
- * Fixed #37, --help should not display first (#447)
- * Fix translation errors. (#570)
- * Add package-lock.json
- * Remove engines
- * Upgrade package version
- * Prefix events to prevent conflicts between commands and options (#494)
- * Removing dependency on graceful-readlink
- * Support setting name in #name function and make it chainable
- * Add .vscode directory to .gitignore (Visual Studio Code metadata)
- * Updated link to ruby commander in readme files
-
-2.10.0 / 2017-06-19
-==================
-
- * Update .travis.yml. drop support for older node.js versions.
- * Fix require arguments in README.md
- * On SemVer you do not start from 0.0.1
- * Add missing semi colon in readme
- * Add save param to npm install
- * node v6 travis test
- * Update Readme_zh-CN.md
- * Allow literal '--' to be passed-through as an argument
- * Test subcommand alias help
- * link build badge to master branch
- * Support the alias of Git style sub-command
- * added keyword commander for better search result on npm
- * Fix Sub-Subcommands
- * test node.js stable
- * Fixes TypeError when a command has an option called `--description`
- * Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets.
- * Add chinese Readme file
-
-2.9.0 / 2015-10-13
-==================
-
- * Add option `isDefault` to set default subcommand #415 @Qix-
- * Add callback to allow filtering or post-processing of help text #434 @djulien
- * Fix `undefined` text in help information close #414 #416 @zhiyelee
-
-2.8.1 / 2015-04-22
-==================
-
- * Back out `support multiline description` Close #396 #397
-
-2.8.0 / 2015-04-07
-==================
-
- * Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee
- * Fix bug in Git-style sub-commands #372 @zhiyelee
- * Allow commands to be hidden from help #383 @tonylukasavage
- * When git-style sub-commands are in use, yet none are called, display help #382 @claylo
- * Add ability to specify arguments syntax for top-level command #258 @rrthomas
- * Support multiline descriptions #208 @zxqfox
-
-2.7.1 / 2015-03-11
-==================
-
- * Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367.
-
-2.7.0 / 2015-03-09
-==================
-
- * Fix git-style bug when installed globally. Close #335 #349 @zhiyelee
- * Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage
- * Add support for camelCase on `opts()`. Close #353 @nkzawa
- * Add node.js 0.12 and io.js to travis.yml
- * Allow RegEx options. #337 @palanik
- * Fixes exit code when sub-command failing. Close #260 #332 @pirelenito
- * git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee
-
-2.6.0 / 2014-12-30
-==================
-
- * added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee
- * Add application description to the help msg. Close #112 @dalssoft
-
-2.5.1 / 2014-12-15
-==================
-
- * fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee
-
-2.5.0 / 2014-10-24
-==================
-
- * add support for variadic arguments. Closes #277 @whitlockjc
-
-2.4.0 / 2014-10-17
-==================
-
- * fixed a bug on executing the coercion function of subcommands option. Closes #270
- * added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage
- * added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage
- * fixed a bug on subcommand name. Closes #248 @jonathandelgado
- * fixed function normalize doesn’t honor option terminator. Closes #216 @abbr
-
-2.3.0 / 2014-07-16
-==================
-
- * add command alias'. Closes PR #210
- * fix: Typos. Closes #99
- * fix: Unused fs module. Closes #217
-
-2.2.0 / 2014-03-29
-==================
-
- * add passing of previous option value
- * fix: support subcommands on windows. Closes #142
- * Now the defaultValue passed as the second argument of the coercion function.
-
-2.1.0 / 2013-11-21
-==================
-
- * add: allow cflag style option params, unit test, fixes #174
-
-2.0.0 / 2013-07-18
-==================
-
- * remove input methods (.prompt, .confirm, etc)
-
-1.3.2 / 2013-07-18
-==================
-
- * add support for sub-commands to co-exist with the original command
-
-1.3.1 / 2013-07-18
-==================
-
- * add quick .runningCommand hack so you can opt-out of other logic when running a sub command
-
-1.3.0 / 2013-07-09
-==================
-
- * add EACCES error handling
- * fix sub-command --help
-
-1.2.0 / 2013-06-13
-==================
-
- * allow "-" hyphen as an option argument
- * support for RegExp coercion
-
-1.1.1 / 2012-11-20
-==================
-
- * add more sub-command padding
- * fix .usage() when args are present. Closes #106
-
-1.1.0 / 2012-11-16
-==================
-
- * add git-style executable subcommand support. Closes #94
-
-1.0.5 / 2012-10-09
-==================
-
- * fix `--name` clobbering. Closes #92
- * fix examples/help. Closes #89
-
-1.0.4 / 2012-09-03
-==================
-
- * add `outputHelp()` method.
-
-1.0.3 / 2012-08-30
-==================
-
- * remove invalid .version() defaulting
-
-1.0.2 / 2012-08-24
-==================
-
- * add `--foo=bar` support [arv]
- * fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus]
-
-1.0.1 / 2012-08-03
-==================
-
- * fix issue #56
- * fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode())
-
-1.0.0 / 2012-07-05
-==================
-
- * add support for optional option descriptions
- * add defaulting of `.version()` to package.json's version
-
-0.6.1 / 2012-06-01
-==================
-
- * Added: append (yes or no) on confirmation
- * Added: allow node.js v0.7.x
-
-0.6.0 / 2012-04-10
-==================
-
- * Added `.prompt(obj, callback)` support. Closes #49
- * Added default support to .choose(). Closes #41
- * Fixed the choice example
-
-0.5.1 / 2011-12-20
-==================
-
- * Fixed `password()` for recent nodes. Closes #36
-
-0.5.0 / 2011-12-04
-==================
-
- * Added sub-command option support [itay]
-
-0.4.3 / 2011-12-04
-==================
-
- * Fixed custom help ordering. Closes #32
-
-0.4.2 / 2011-11-24
-==================
-
- * Added travis support
- * Fixed: line-buffered input automatically trimmed. Closes #31
-
-0.4.1 / 2011-11-18
-==================
-
- * Removed listening for "close" on --help
-
-0.4.0 / 2011-11-15
-==================
-
- * Added support for `--`. Closes #24
-
-0.3.3 / 2011-11-14
-==================
-
- * Fixed: wait for close event when writing help info [Jerry Hamlet]
-
-0.3.2 / 2011-11-01
-==================
-
- * Fixed long flag definitions with values [felixge]
-
-0.3.1 / 2011-10-31
-==================
-
- * Changed `--version` short flag to `-V` from `-v`
- * Changed `.version()` so it's configurable [felixge]
-
-0.3.0 / 2011-10-31
-==================
-
- * Added support for long flags only. Closes #18
-
-0.2.1 / 2011-10-24
-==================
-
- * "node": ">= 0.4.x < 0.7.0". Closes #20
-
-0.2.0 / 2011-09-26
-==================
-
- * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs]
-
-0.1.0 / 2011-08-24
-==================
-
- * Added support for custom `--help` output
-
-0.0.5 / 2011-08-18
-==================
-
- * Changed: when the user enters nothing prompt for password again
- * Fixed issue with passwords beginning with numbers [NuckChorris]
-
-0.0.4 / 2011-08-15
-==================
-
- * Fixed `Commander#args`
-
-0.0.3 / 2011-08-15
-==================
-
- * Added default option value support
-
-0.0.2 / 2011-08-15
-==================
-
- * Added mask support to `Command#password(str[, mask], fn)`
- * Added `Command#password(str, fn)`
-
-0.0.1 / 2010-01-03
-==================
-
- * Initial release
diff --git a/node_modules/commander/Readme.md b/node_modules/commander/Readme.md
index c846e7a2..095e2aef 100644
--- a/node_modules/commander/Readme.md
+++ b/node_modules/commander/Readme.md
@@ -1,428 +1,1134 @@
# Commander.js
-
-[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js)
+[![Build Status](https://github.com/tj/commander.js/workflows/build/badge.svg)](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
-[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
-
- The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
- [API documentation](http://tj.github.com/commander.js/)
+The complete solution for [node.js](http://nodejs.org) command-line interfaces.
+
+Read this in other languages: English | [简体中文](./Readme_zh-CN.md)
+
+- [Commander.js](#commanderjs)
+ - [Installation](#installation)
+ - [Quick Start](#quick-start)
+ - [Declaring _program_ variable](#declaring-program-variable)
+ - [Options](#options)
+ - [Common option types, boolean and value](#common-option-types-boolean-and-value)
+ - [Default option value](#default-option-value)
+ - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)
+ - [Required option](#required-option)
+ - [Variadic option](#variadic-option)
+ - [Version option](#version-option)
+ - [More configuration](#more-configuration)
+ - [Custom option processing](#custom-option-processing)
+ - [Commands](#commands)
+ - [Command-arguments](#command-arguments)
+ - [More configuration](#more-configuration-1)
+ - [Custom argument processing](#custom-argument-processing)
+ - [Action handler](#action-handler)
+ - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)
+ - [Life cycle hooks](#life-cycle-hooks)
+ - [Automated help](#automated-help)
+ - [Custom help](#custom-help)
+ - [Display help after errors](#display-help-after-errors)
+ - [Display help from code](#display-help-from-code)
+ - [.name](#name)
+ - [.usage](#usage)
+ - [.description and .summary](#description-and-summary)
+ - [.helpOption(flags, description)](#helpoptionflags-description)
+ - [.addHelpCommand()](#addhelpcommand)
+ - [More configuration](#more-configuration-2)
+ - [Custom event listeners](#custom-event-listeners)
+ - [Bits and pieces](#bits-and-pieces)
+ - [.parse() and .parseAsync()](#parse-and-parseasync)
+ - [Parsing Configuration](#parsing-configuration)
+ - [Legacy options as properties](#legacy-options-as-properties)
+ - [TypeScript](#typescript)
+ - [createCommand()](#createcommand)
+ - [Node options such as `--harmony`](#node-options-such-as---harmony)
+ - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)
+ - [Display error](#display-error)
+ - [Override exit and output handling](#override-exit-and-output-handling)
+ - [Additional documentation](#additional-documentation)
+ - [Support](#support)
+ - [Commander for enterprise](#commander-for-enterprise)
+
+For information about terms used in this document see: [terminology](./docs/terminology.md)
## Installation
- $ npm install commander
+```sh
+npm install commander
+```
+
+## Quick Start
+
+You write code to describe your command line interface.
+Commander looks after parsing the arguments into options and command-arguments,
+displays usage errors for problems, and implements a help system.
-## Option parsing
+Commander is strict and displays an error for unrecognised options.
+The two most used option types are a boolean option, and an option which takes its value from the following argument.
-Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.
+Example file: [split.js](./examples/split.js)
```js
-#!/usr/bin/env node
+const { program } = require('commander');
+
+program
+ .option('--first')
+ .option('-s, --separator <char>');
+
+program.parse();
+
+const options = program.opts();
+const limit = options.first ? 1 : undefined;
+console.log(program.args[0].split(options.separator, limit));
+```
+
+```console
+$ node split.js -s / --fits a/b/c
+error: unknown option '--fits'
+(Did you mean --first?)
+$ node split.js -s / --first a/b/c
+[ 'a' ]
+```
+
+Here 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).
-/**
- * Module dependencies.
- */
+Example file: [string-util.js](./examples/string-util.js)
-var program = require('commander');
+```js
+const { Command } = require('commander');
+const program = new Command();
program
- .version('0.1.0')
- .option('-p, --peppers', 'Add peppers')
- .option('-P, --pineapple', 'Add pineapple')
- .option('-b, --bbq-sauce', 'Add bbq sauce')
- .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
- .parse(process.argv);
+ .name('string-util')
+ .description('CLI to some JavaScript string utilities')
+ .version('0.8.0');
+
+program.command('split')
+ .description('Split a string into substrings and display as an array')
+ .argument('<string>', 'string to split')
+ .option('--first', 'display just the first substring')
+ .option('-s, --separator <char>', 'separator character', ',')
+ .action((str, options) => {
+ const limit = options.first ? 1 : undefined;
+ console.log(str.split(options.separator, limit));
+ });
-console.log('you ordered a pizza with:');
-if (program.peppers) console.log(' - peppers');
-if (program.pineapple) console.log(' - pineapple');
-if (program.bbqSauce) console.log(' - bbq');
-console.log(' - %s cheese', program.cheese);
+program.parse();
```
-Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.
+```console
+$ node string-util.js help split
+Usage: string-util split [options] <string>
+
+Split a string into substrings and display as an array.
+
+Arguments:
+ string string to split
+
+Options:
+ --first display just the first substring
+ -s, --separator <char> separator character (default: ",")
+ -h, --help display help for command
+
+$ node string-util.js split --separator=/ a/b/c
+[ 'a', 'b', 'c' ]
+```
-Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false.
+More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
+
+## Declaring _program_ variable
+
+Commander exports a global object which is convenient for quick programs.
+This is used in the examples in this README for brevity.
+
+```js
+// CommonJS (.cjs)
+const { program } = require('commander');
+```
+
+For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
```js
-#!/usr/bin/env node
+// CommonJS (.cjs)
+const { Command } = require('commander');
+const program = new Command();
+```
+
+```js
+// ECMAScript (.mjs)
+import { Command } from 'commander';
+const program = new Command();
+```
+
+```ts
+// TypeScript (.ts)
+import { Command } from 'commander';
+const program = new Command();
+```
+
+## Options
+
+Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|').
+
+The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.
+
+Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.
+
+An 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.
+
+```sh
+serve -p 80
+serve -p80
+serve --port 80
+serve --port=80
+```
+
+You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.
+
+By default options on the command line are not positional, and can be specified before or after other arguments.
-/**
- * Module dependencies.
- */
+There are additional related routines for when `.opts()` is not enough:
-var program = require('commander');
+- `.optsWithGlobals()` returns merged local and global option values
+- `.getOptionValue()` and `.setOptionValue()` work with a single option value
+- `.getOptionValueSource()` and `.setOptionValueWithSource()` include where the option value came from
+### Common option types, boolean and value
+
+The two most used option types are a boolean option, and an option which takes its value
+from the following argument (declared with angle brackets like `--expect <value>`). Both are `undefined` unless specified on command line.
+
+Example file: [options-common.js](./examples/options-common.js)
+
+```js
+program
+ .option('-d, --debug', 'output extra debugging')
+ .option('-s, --small', 'small pizza size')
+ .option('-p, --pizza-type <type>', 'flavour of pizza');
+
+program.parse(process.argv);
+
+const options = program.opts();
+if (options.debug) console.log(options);
+console.log('pizza details:');
+if (options.small) console.log('- small pizza size');
+if (options.pizzaType) console.log(`- ${options.pizzaType}`);
+```
+
+```console
+$ pizza-options -p
+error: option '-p, --pizza-type <type>' argument missing
+$ pizza-options -d -s -p vegetarian
+{ debug: true, small: true, pizzaType: 'vegetarian' }
+pizza details:
+- small pizza size
+- vegetarian
+$ pizza-options --pizza-type=cheese
+pizza details:
+- cheese
+```
+
+Multiple boolean short options may be combined together following the dash, and may be followed by a single short option taking a value.
+For example `-d -s -p cheese` may be written as `-ds -p cheese` or even `-dsp cheese`.
+
+Options with an expected option-argument are greedy and will consume the following argument whatever the value.
+So `--id -xyz` reads `-xyz` as the option-argument.
+
+`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`.
+
+### Default option value
+
+You can specify a default value for an option.
+
+Example file: [options-defaults.js](./examples/options-defaults.js)
+
+```js
+program
+ .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');
+
+program.parse();
+
+console.log(`cheese: ${program.opts().cheese}`);
+```
+
+```console
+$ pizza-options
+cheese: blue
+$ pizza-options --cheese stilton
+cheese: stilton
+```
+
+### Other option types, negatable boolean and boolean|value
+
+You can define a boolean option long name with a leading `no-` to set the option value to false when used.
+Defined alone this also makes the option true by default.
+
+If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
+otherwise be.
+
+Example file: [options-negatable.js](./examples/options-negatable.js)
+
+```js
program
.option('--no-sauce', 'Remove sauce')
- .parse(process.argv);
+ .option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
+ .option('--no-cheese', 'plain with no cheese')
+ .parse();
+
+const options = program.opts();
+const sauceStr = options.sauce ? 'sauce' : 'no sauce';
+const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`;
+console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
+```
-console.log('you ordered a pizza');
-if (program.sauce) console.log(' with sauce');
-else console.log(' without sauce');
+```console
+$ pizza-options
+You ordered a pizza with sauce and mozzarella cheese
+$ pizza-options --sauce
+error: unknown option '--sauce'
+$ pizza-options --cheese=blue
+You ordered a pizza with sauce and blue cheese
+$ pizza-options --no-sauce --no-cheese
+You ordered a pizza with no sauce and no cheese
```
-To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs.
+You can specify an option which may be used as a boolean option but may optionally take an option-argument
+(declared with square brackets like `--optional [value]`).
-e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```
+Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)
-Then to access the input if it was passed in.
+```js
+program
+ .option('-c, --cheese [type]', 'Add cheese with optional type');
-e.g. ```var myInput = program.myarg```
+program.parse(process.argv);
+
+const options = program.opts();
+if (options.cheese === undefined) console.log('no cheese');
+else if (options.cheese === true) console.log('add cheese');
+else console.log(`add cheese type ${options.cheese}`);
+```
-**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.
+```console
+$ pizza-options
+no cheese
+$ pizza-options --cheese
+add cheese
+$ pizza-options --cheese mozzarella
+add cheese type mozzarella
+```
+Options with an optional option-argument are not greedy and will ignore arguments starting with a dash.
+So `id` behaves as a boolean option for `--id -5`, but you can use a combined form if needed like `--id=-5`.
-## Version option
+For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
-Calling the `version` implicitly adds the `-V` and `--version` options to the command.
-When either of these options is present, the command prints the version number and exits.
+### Required option
- $ ./examples/pizza -V
- 0.0.1
+You 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 (say from environment). The method is otherwise the same as `.option()` in format, taking flags and description, and optional default value or custom processing.
-If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method.
+Example file: [options-required.js](./examples/options-required.js)
```js
program
- .version('0.0.1', '-v, --version')
+ .requiredOption('-c, --cheese <type>', 'pizza must have cheese');
+
+program.parse();
```
-The version flags can be named anything, but the long option is required.
+```console
+$ pizza
+error: required option '-c, --cheese <type>' not specified
+```
-## Command-specific options
+### Variadic option
-You can attach options to a command.
+You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you
+can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments
+are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value
+is specified in the same argument as the option then no further values are read.
+
+Example file: [options-variadic.js](./examples/options-variadic.js)
```js
-#!/usr/bin/env node
+program
+ .option('-n, --number <numbers...>', 'specify numbers')
+ .option('-l, --letter [letters...]', 'specify letters');
-var program = require('commander');
+program.parse();
+console.log('Options: ', program.opts());
+console.log('Remaining arguments: ', program.args);
+```
+
+```console
+$ collect -n 1 2 3 --letter a b c
+Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }
+Remaining arguments: []
+$ collect --letter=A -n80 operand
+Options: { number: [ '80' ], letter: [ 'A' ] }
+Remaining arguments: [ 'operand' ]
+$ collect --letter -n 1 -n 2 3 -- operand
+Options: { number: [ '1', '2', '3' ], letter: true }
+Remaining arguments: [ 'operand' ]
+```
+
+For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
+
+### Version option
+
+The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.
+
+```js
+program.version('0.0.1');
+```
+
+```console
+$ ./examples/pizza -V
+0.0.1
+```
+
+You may change the flags and description by passing additional parameters to the `version` method, using
+the same syntax for flags as the `option` method.
+
+```js
+program.version('0.0.1', '-v, --vers', 'output the current version');
+```
+
+### More configuration
+
+You can add most options using the `.option()` method, but there are some additional features available
+by constructing an `Option` explicitly for less common cases.
+
+Example 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)
+
+```js
program
- .command('rm <dir>')
- .option('-r, --recursive', 'Remove recursively')
- .action(function (dir, cmd) {
- console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
- })
+ .addOption(new Option('-s, --secret').hideHelp())
+ .addOption(new Option('-t, --timeout <delay>', 'timeout in seconds').default(60, 'one minute'))
+ .addOption(new Option('-d, --drink <size>', 'drink size').choices(['small', 'medium', 'large']))
+ .addOption(new Option('-p, --port <number>', 'port number').env('PORT'))
+ .addOption(new Option('--donate [amount]', 'optional donation in dollars').preset('20').argParser(parseFloat))
+ .addOption(new Option('--disable-server', 'disables the server').conflicts('port'))
+ .addOption(new Option('--free-drink', 'small drink included free ').implies({ drink: 'small' }));
+```
+
+```console
+$ extra --help
+Usage: help [options]
-program.parse(process.argv)
+Options:
+ -t, --timeout <delay> timeout in seconds (default: one minute)
+ -d, --drink <size> drink cup size (choices: "small", "medium", "large")
+ -p, --port <number> port number (env: PORT)
+ --donate [amount] optional donation in dollars (preset: "20")
+ --disable-server disables the server
+ --free-drink small drink included free
+ -h, --help display help for command
+
+$ extra --drink huge
+error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large.
+
+$ PORT=80 extra --donate --free-drink
+Options: { timeout: 60, donate: 20, port: '80', freeDrink: true, drink: 'small' }
+
+$ extra --disable-server --port 8000
+error: option '--disable-server' cannot be used with option '-p, --port <number>'
```
-A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.
+Specify a required (mandatory) option using the `Option` method `.makeOptionMandatory()`. This matches the `Command` method [.requiredOption()](#required-option).
+
+### Custom option processing
+
+You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,
+the user specified option-argument and the previous value for the option. It returns the new value for the option.
+
+This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.
-## Coercion
+You can optionally specify the default/starting value for the option after the function parameter.
+
+Example file: [options-custom-processing.js](./examples/options-custom-processing.js)
```js
-function range(val) {
- return val.split('..').map(Number);
+function myParseInt(value, dummyPrevious) {
+ // parseInt takes a string and a radix
+ const parsedValue = parseInt(value, 10);
+ if (isNaN(parsedValue)) {
+ throw new commander.InvalidArgumentError('Not a number.');
+ }
+ return parsedValue;
}
-function list(val) {
- return val.split(',');
+function increaseVerbosity(dummyValue, previous) {
+ return previous + 1;
}
-function collect(val, memo) {
- memo.push(val);
- return memo;
+function collect(value, previous) {
+ return previous.concat([value]);
}
-function increaseVerbosity(v, total) {
- return total + 1;
+function commaSeparatedList(value, dummyPrevious) {
+ return value.split(',');
}
program
- .version('0.1.0')
- .usage('[options] <file ...>')
- .option('-i, --integer <n>', 'An integer argument', parseInt)
- .option('-f, --float <n>', 'A float argument', parseFloat)
- .option('-r, --range <a>..<b>', 'A range', range)
- .option('-l, --list <items>', 'A list', list)
- .option('-o, --optional [value]', 'An optional value')
- .option('-c, --collect [value]', 'A repeatable value', collect, [])
- .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
- .parse(process.argv);
-
-console.log(' int: %j', program.integer);
-console.log(' float: %j', program.float);
-console.log(' optional: %j', program.optional);
-program.range = program.range || [];
-console.log(' range: %j..%j', program.range[0], program.range[1]);
-console.log(' list: %j', program.list);
-console.log(' collect: %j', program.collect);
-console.log(' verbosity: %j', program.verbose);
-console.log(' args: %j', program.args);
-```
-
-## Regular Expression
+ .option('-f, --float <number>', 'float argument', parseFloat)
+ .option('-i, --integer <number>', 'integer argument', myParseInt)
+ .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
+ .option('-c, --collect <value>', 'repeatable value', collect, [])
+ .option('-l, --list <items>', 'comma separated list', commaSeparatedList)
+;
+
+program.parse();
+
+const options = program.opts();
+if (options.float !== undefined) console.log(`float: ${options.float}`);
+if (options.integer !== undefined) console.log(`integer: ${options.integer}`);
+if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);
+if (options.collect.length > 0) console.log(options.collect);
+if (options.list !== undefined) console.log(options.list);
+```
+
+```console
+$ custom -f 1e2
+float: 100
+$ custom --integer 2
+integer: 2
+$ custom -v -v -v
+verbose: 3
+$ custom -c a -c b -c c
+[ 'a', 'b', 'c' ]
+$ custom --list x,y,z
+[ 'x', 'y', 'z' ]
+```
+
+## Commands
+
+You 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 (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)).
+
+In 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...`.
+
+You can use `.addCommand()` to add an already configured subcommand to the program.
+
+For example:
+
```js
+// Command implemented using action handler (description is supplied separately to `.command`)
+// Returns new command for configuring.
program
- .version('0.1.0')
- .option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
- .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
- .parse(process.argv);
+ .command('clone <source> [destination]')
+ .description('clone a repository into a newly created directory')
+ .action((source, destination) => {
+ console.log('clone command called');
+ });
+
+// Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`.
+// Returns `this` for adding more commands.
+program
+ .command('start <service>', 'start named service')
+ .command('stop [service]', 'stop named service, or all if no name supplied');
-console.log(' size: %j', program.size);
-console.log(' drink: %j', program.drink);
+// Command prepared separately.
+// Returns `this` for adding more commands.
+program
+ .addCommand(build.makeBuildCommand());
```
-## Variadic arguments
+Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will
+remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other
+subcommand is specified ([example](./examples/defaultCommand.js)).
- The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
- append `...` to the argument name. Here is an example:
+You can add alternative names for a command with `.alias()`. ([example](./examples/alias.js))
-```js
-#!/usr/bin/env node
+For 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.
+
+### Command-arguments
-/**
- * Module dependencies.
- */
+For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This
+is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands
+you can instead use the following method.
-var program = require('commander');
+To configure a command, you can use `.argument()` to specify each expected command-argument.
+You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.
+You can specify a default value for an optional command-argument.
+Example file: [argument.js](./examples/argument.js)
+
+```js
program
.version('0.1.0')
- .command('rmdir <dir> [otherDirs...]')
- .action(function (dir, otherDirs) {
- console.log('rmdir %s', dir);
- if (otherDirs) {
- otherDirs.forEach(function (oDir) {
- console.log('rmdir %s', oDir);
- });
- }
+ .argument('<username>', 'user to login')
+ .argument('[password]', 'password for user, if required', 'no password given')
+ .action((username, password) => {
+ console.log('username:', username);
+ console.log('password:', password);
});
+```
-program.parse(process.argv);
+ The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
+ append `...` to the argument name. A variadic argument is passed to the action handler as an array. For example:
+
+```js
+program
+ .version('0.1.0')
+ .command('rmdir')
+ .argument('<dirs...>')
+ .action(function (dirs) {
+ dirs.forEach((dir) => {
+ console.log('rmdir %s', dir);
+ });
+ });
+```
+
+There is a convenience method to add multiple arguments at once, but without descriptions:
+
+```js
+program
+ .arguments('<username> <password>');
+```
+
+#### More configuration
+
+There are some additional features available by constructing an `Argument` explicitly for less common cases.
+
+Example file: [arguments-extra.js](./examples/arguments-extra.js)
+
+```js
+program
+ .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))
+ .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))
```
- An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
- to your action as demonstrated above.
+#### Custom argument processing
+
+You may specify a function to do custom processing of command-arguments (like for option-arguments).
+The callback function receives two parameters, the user specified command-argument and the previous value for the argument.
+It returns the new value for the argument.
+
+The processed argument values are passed to the action handler, and saved as `.processedArgs`.
-## Specify the argument syntax
+You can optionally specify the default/starting value for the argument after the function parameter.
+
+Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)
```js
-#!/usr/bin/env node
+program
+ .command('add')
+ .argument('<first>', 'integer argument', myParseInt)
+ .argument('[second]', 'integer argument', myParseInt, 1000)
+ .action((first, second) => {
+ console.log(`${first} + ${second} = ${first + second}`);
+ })
+;
+```
+
+### Action handler
-var program = require('commander');
+The action handler gets passed a parameter for each command-argument you declared, and two additional parameters
+which are the parsed options and the command object itself.
+Example file: [thank.js](./examples/thank.js)
+
+```js
program
- .version('0.1.0')
- .arguments('<cmd> [env]')
- .action(function (cmd, env) {
- cmdValue = cmd;
- envValue = env;
+ .argument('<name>')
+ .option('-t, --title <honorific>', 'title to use before name')
+ .option('-d, --debug', 'display some debugging')
+ .action((name, options, command) => {
+ if (options.debug) {
+ console.error('Called %s with options %o', command.name(), options);
+ }
+ const title = options.title ? `${options.title} ` : '';
+ console.log(`Thank-you ${title}${name}`);
});
+```
-program.parse(process.argv);
+If you prefer, you can work with the command directly and skip declaring the parameters for the action handler. The `this` keyword is set to the running command and can be used from a function expression (but not from an arrow function).
-if (typeof cmdValue === 'undefined') {
- console.error('no command given!');
- process.exit(1);
-}
-console.log('command:', cmdValue);
-console.log('environment:', envValue || "no environment given");
+Example file: [action-this.js](./examples/action-this.js)
+
+```js
+program
+ .command('serve')
+ .argument('<script>')
+ .option('-p, --port <number>', 'port number', 80)
+ .action(function() {
+ console.error('Run script %s on port %s', this.args[0], this.opts().port);
+ });
```
-Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.
-## Git-style sub-commands
+You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
```js
-// file: ./examples/pm
-var program = require('commander');
+async function run() { /* code goes here */ }
+
+async function main() {
+ program
+ .command('run')
+ .action(run);
+ await program.parseAsync(process.argv);
+}
+```
+
+A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments will be reported as an error. You can suppress the unknown option checks with `.allowUnknownOption()`. By default it is not an error to
+pass more arguments than declared, but you can make this an error with `.allowExcessArguments(false)`.
+
+### Stand-alone executable (sub)commands
+When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.
+Commander 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`.
+You may specify a custom name (and path) with the `executableFile` configuration option.
+You may specify a custom search directory for subcommands with `.executableDir()`.
+
+You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
+
+Example file: [pm](./examples/pm)
+
+```js
program
+ .name('pm')
.version('0.1.0')
.command('install [name]', 'install one or more packages')
.command('search [query]', 'search with optional query')
- .command('list', 'list packages installed', {isDefault: true})
- .parse(process.argv);
+ .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })
+ .command('list', 'list packages installed', { isDefault: true });
+
+program.parse(process.argv);
```
-When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.
-The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.
+If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
-Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the subcommand from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.
+### Life cycle hooks
-If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
+You can add callback hooks to a command for life cycle events.
-### `--harmony`
+Example file: [hook.js](./examples/hook.js)
-You can enable `--harmony` option in two ways:
-* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern.
-* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.
+```js
+program
+ .option('-t, --trace', 'display trace statements for commands')
+ .hook('preAction', (thisCommand, actionCommand) => {
+ if (thisCommand.opts().trace) {
+ console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);
+ console.log('arguments: %O', actionCommand.args);
+ console.log('options: %o', actionCommand.opts());
+ }
+ });
+```
+
+The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.
+
+The supported events are:
-## Automated --help
+| event name | when hook called | callback parameters |
+| :-- | :-- | :-- |
+| `preAction`, `postAction` | before/after action handler for this command and its nested subcommands | `(thisCommand, actionCommand)` |
+| `preSubcommand` | before parsing direct subcommand | `(thisCommand, subcommand)` |
- The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
+For an overview of the life cycle events see [parsing life cycle and hooks](./docs/parsing-and-hooks.md).
-```
-$ ./examples/pizza --help
+## Automated help
+
+The help information is auto-generated based on the information commander already knows about your program. The default
+help option is `-h,--help`.
+
+Example file: [pizza](./examples/pizza)
+
+```console
+$ node ./examples/pizza --help
Usage: pizza [options]
-An application for pizzas ordering
+An application for pizza ordering
Options:
- -h, --help output usage information
- -V, --version output the version number
-p, --peppers Add peppers
- -P, --pineapple Add pineapple
- -b, --bbq Add bbq sauce
- -c, --cheese <type> Add the specified type of cheese [marble]
+ -c, --cheese <type> Add the specified type of cheese (default: "marble")
-C, --no-cheese You do not want any cheese
+ -h, --help display help for command
```
-## Custom help
+A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show
+further help for the subcommand. These are effectively the same if the `shell` program has implicit help:
- You can display arbitrary `-h, --help` information
- by listening for "--help". Commander will automatically
- exit once you are done so that the remainder of your program
- does not execute causing undesired behaviors, for example
- in the following executable "stuff" will not output when
- `--help` is used.
+```sh
+shell help
+shell --help
-```js
-#!/usr/bin/env node
+shell help spawn
+shell spawn --help
+```
+
+Long 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.)
-/**
- * Module dependencies.
- */
+### Custom help
-var program = require('commander');
+You can add extra text to be displayed along with the built-in help.
+Example file: [custom-help](./examples/custom-help)
+
+```js
program
- .version('0.1.0')
- .option('-f, --foo', 'enable some foo')
- .option('-b, --bar', 'enable some bar')
- .option('-B, --baz', 'enable some baz');
-
-// must be before .parse() since
-// node's emit() is immediate
-
-program.on('--help', function(){
- console.log('')
- console.log('Examples:');
- console.log(' $ custom-help --help');
- console.log(' $ custom-help -h');
-});
+ .option('-f, --foo', 'enable some foo');
-program.parse(process.argv);
+program.addHelpText('after', `
-console.log('stuff');
+Example call:
+ $ custom-help --help`);
```
-Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
+Yields the following help output:
-```
+```Text
Usage: custom-help [options]
Options:
- -h, --help output usage information
- -V, --version output the version number
- -f, --foo enable some foo
- -b, --bar enable some bar
- -B, --baz enable some baz
+ -f, --foo enable some foo
+ -h, --help display help for command
-Examples:
+Example call:
$ custom-help --help
- $ custom-help -h
```
-## .outputHelp(cb)
+The positions in order displayed are:
+
+- `beforeAll`: add to the program for a global banner or header
+- `before`: display extra information before built-in help
+- `after`: display extra information after built-in help
+- `afterAll`: add to the program for a global footer (epilog)
+
+The positions "beforeAll" and "afterAll" apply to the command and all its subcommands.
+
+The 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:
+
+- error: a boolean for whether the help is being displayed due to a usage error
+- command: the Command which is displaying the help
-Output help information without exiting.
-Optional callback cb allows post-processing of help text before it is displayed.
+### Display help after errors
-If you want to display help by default (e.g. if no command was provided), you can use something like:
+The default behaviour for usage errors is to just display a short error message.
+You can change the behaviour to show the full help or a custom help message after an error.
```js
-var program = require('commander');
-var colors = require('colors');
+program.showHelpAfterError();
+// or
+program.showHelpAfterError('(add --help for additional information)');
+```
+
+```console
+$ pizza --unknown
+error: unknown option '--unknown'
+(add --help for additional information)
+```
+The default behaviour is to suggest correct spelling after an error for an unknown command or option. You
+can disable this.
+
+```js
+program.showSuggestionAfterError(false);
+```
+
+```console
+$ pizza --hepl
+error: unknown option '--hepl'
+(Did you mean --help?)
+```
+
+### Display help from code
+
+`.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.
+
+`.outputHelp()`: output help information without exiting. You can optionally pass `{ error: true }` to display on stderr.
+
+`.helpInformation()`: get the built-in command help information as a string for processing or displaying yourself.
+
+### .name
+
+The command name appears in the help, and is also used for locating stand-alone executable subcommands.
+
+You may specify the program name using `.name()` or in the Command constructor. For the program, Commander will
+fallback to using the script name from the full arguments passed into `.parse()`. However, the script name varies
+depending on how your program is launched so you may wish to specify it explicitly.
+
+```js
+program.name('pizza');
+const pm = new Command('pm');
+```
+
+Subcommands get a name when specified using `.command()`. If you create the subcommand yourself to use with `.addCommand()`,
+then set the name using `.name()` or in the Command constructor.
+
+### .usage
+
+This allows you to customise the usage description in the first line of the help. Given:
+
+```js
program
- .version('0.1.0')
- .command('getstream [url]', 'get stream URL')
- .parse(process.argv);
+ .name("my-command")
+ .usage("[global options] command")
+```
-if (!process.argv.slice(2).length) {
- program.outputHelp(make_red);
-}
+The help will start with:
-function make_red(txt) {
- return colors.red(txt); //display the help text in red on the console
-}
+```Text
+Usage: my-command [global options] command
```
-## .help(cb)
+### .description and .summary
+
+The description appears in the help for the command. You can optionally supply a shorter
+summary to use when listed as a subcommand of the program.
- Output help information and exit immediately.
- Optional callback cb allows post-processing of help text before it is displayed.
+```js
+program
+ .command("duplicate")
+ .summary("make a copy")
+ .description(`Make a copy of the current project.
+This may require additional disk space.
+ `);
+```
+### .helpOption(flags, description)
-## Custom event listeners
- You can execute custom actions by listening to command and option events.
+By 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.
```js
-program.on('option:verbose', function () {
- process.env.VERBOSE = this.verbose;
+program
+ .helpOption('-e, --HELP', 'read more information');
+```
+
+### .addHelpCommand()
+
+A help command is added by default if your command has subcommands. You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.
+
+You can both turn on and customise the help command by supplying the name and description:
+
+```js
+program.addHelpCommand('assist [command]', 'show assistance');
+```
+
+### More configuration
+
+The built-in help is formatted using the Help class.
+You can configure the Help behaviour by modifying data properties and methods using `.configureHelp()`, or by subclassing using `.createHelp()` if you prefer.
+
+The data properties are:
+
+- `helpWidth`: specify the wrap width, useful for unit tests
+- `sortSubcommands`: sort the subcommands alphabetically
+- `sortOptions`: sort the options alphabetically
+- `showGlobalOptions`: show a section with the global options from the parent command(s)
+
+You can override any method on the [Help](./lib/help.js) class. There are methods getting the visible lists of arguments, options, and subcommands. There are methods for formatting the items in the lists, with each item having a _term_ and _description_. Take a look at `.formatHelp()` to see how they are used.
+
+Example file: [configure-help.js](./examples/configure-help.js)
+
+```js
+program.configureHelp({
+ sortSubcommands: true,
+ subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage.
});
+```
+
+## Custom event listeners
+
+You can execute custom actions by listening to command and option events.
-// error on unknown commands
-program.on('command:*', function () {
- console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
- process.exit(1);
+```js
+program.on('option:verbose', function () {
+ process.env.VERBOSE = this.opts().verbose;
});
```
-## Examples
+## Bits and pieces
+
+### .parse() and .parseAsync()
+
+The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`.
+
+If the arguments follow different conventions than node you can pass a `from` option in the second parameter:
+
+- 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that
+- 'electron': `argv[1]` varies depending on whether the electron application is packaged
+- 'user': all of the arguments from the user
+
+For example:
```js
-var program = require('commander');
+program.parse(process.argv); // Explicit, node conventions
+program.parse(); // Implicit, and auto-detect electron
+program.parse(['-f', 'filename'], { from: 'user' });
+```
-program
- .version('0.1.0')
- .option('-C, --chdir <path>', 'change the working directory')
- .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
- .option('-T, --no-tests', 'ignore test hook');
+### Parsing Configuration
-program
- .command('setup [env]')
- .description('run setup commands for all envs')
- .option("-s, --setup_mode [mode]", "Which setup mode to use")
- .action(function(env, options){
- var mode = options.setup_mode || "normal";
- env = env || 'all';
- console.log('setup for %s env(s) with %s mode', env, mode);
- });
+If the default parsing does not suit your needs, there are some behaviours to support other usage patterns.
+
+By default program options are recognised before and after subcommands. To only look for program options before subcommands, use `.enablePositionalOptions()`. This lets you use
+an option for a different purpose in subcommands.
+
+Example file: [positional-options.js](./examples/positional-options.js)
+
+With positional options, the `-b` is a program option in the first line and a subcommand option in the second line:
+```sh
+program -b subcommand
+program subcommand -b
+```
+
+By default options are recognised before and after command-arguments. To only process options that come
+before the command-arguments, use `.passThroughOptions()`. This lets you pass the arguments and following options through to another program
+without needing to use `--` to end the option processing.
+To use pass through options in a subcommand, the program needs to enable positional options.
+
+Example file: [pass-through-options.js](./examples/pass-through-options.js)
+
+With 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:
+
+```sh
+program --port=80 arg
+program arg --port=80
+```
+
+By 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.
+
+By default the argument processing does not display an error for more command-arguments than expected.
+To display an error for excess arguments, use`.allowExcessArguments(false)`.
+
+### Legacy options as properties
+
+Before Commander 7, the option values were stored as properties on the command.
+This was convenient to code but the downside was possible clashes with
+existing properties of `Command`. You can revert to the old behaviour to run unmodified legacy code by using `.storeOptionsAsProperties()`.
+
+```js
program
- .command('exec <cmd>')
- .alias('ex')
- .description('execute the given remote cmd')
- .option("-e, --exec_mode <mode>", "Which exec mode to use")
- .action(function(cmd, options){
- console.log('exec "%s" using %s mode', cmd, options.exec_mode);
- }).on('--help', function() {
- console.log('');
- console.log('Examples:');
- console.log('');
- console.log(' $ deploy exec sequential');
- console.log(' $ deploy exec async');
+ .storeOptionsAsProperties()
+ .option('-d, --debug')
+ .action((commandAndOptions) => {
+ if (commandAndOptions.debug) {
+ console.error(`Called ${commandAndOptions.name()}`);
+ }
});
+```
+
+### TypeScript
+
+extra-typings: There is an optional project to infer extra type information from the option and argument definitions.
+This adds strong typing to the options returned by `.opts()` and the parameters to `.action()`.
+See [commander-js/extra-typings](https://github.com/commander-js/extra-typings) for more.
+
+```
+import { Command } from '@commander-js/extra-typings';
+```
+
+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.
+
+```sh
+node -r ts-node/register pm.ts
+```
+
+### createCommand()
+
+This factory function creates a new command. It is exported and may be used instead of using `new`, like:
+
+```js
+const { createCommand } = require('commander');
+const program = createCommand();
+```
+
+`createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally
+when creating subcommands using `.command()`, and you may override it to
+customise the new subcommand (example file [custom-command-class.js](./examples/custom-command-class.js)).
+
+### Node options such as `--harmony`
+
+You can enable `--harmony` option in two ways:
+
+- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.)
+- Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand process.
+
+### Debugging stand-alone executable subcommands
+
+An executable subcommand is launched as a separate child process.
+
+If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al,
+the inspector port is incremented by 1 for the spawned subcommand.
+
+If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.
+
+### Display error
+
+This routine is available to invoke the Commander error handling for your own error conditions. (See also the next section about exit handling.)
+
+As well as the error message, you can optionally specify the `exitCode` (used with `process.exit`)
+and `code` (used with `CommanderError`).
+
+```js
+program.error('Password must be longer than four characters');
+program.error('Custom processing has failed', { exitCode: 2, code: 'my.custom.error' });
+```
+
+### Override exit and output handling
+
+By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override
+this behaviour and optionally supply a callback. The default override throws a `CommanderError`.
+
+The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help
+is not affected by the override which is called after the display.
+
+```js
+program.exitOverride();
+
+try {
+ program.parse(process.argv);
+} catch (err) {
+ // custom processing...
+}
+```
+
+By default Commander is configured for a command-line application and writes to stdout and stderr.
+You can modify this behaviour for custom applications. In addition, you can modify the display of error messages.
+
+Example file: [configure-output.js](./examples/configure-output.js)
+
+```js
+function errorColor(str) {
+ // Add ANSI escape codes to display text in red.
+ return `\x1b[31m${str}\x1b[0m`;
+}
program
- .command('*')
- .action(function(env){
- console.log('deploying "%s"', env);
+ .configureOutput({
+ // Visibly override write routines as example!
+ writeOut: (str) => process.stdout.write(`[OUT] ${str}`),
+ writeErr: (str) => process.stdout.write(`[ERR] ${str}`),
+ // Highlight errors in color.
+ outputError: (str, write) => write(errorColor(str))
});
-
-program.parse(process.argv);
```
-More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
+### Additional documentation
+
+There is more information available about:
+
+- [deprecated](./docs/deprecated.md) features still supported for backwards compatibility
+- [options taking varying arguments](./docs/options-taking-varying-arguments.md)
+- [parsing life cycle and hooks](./docs/parsing-and-hooks.md)
+
+## Support
+
+The current version of Commander is fully supported on Long Term Support versions of Node.js, and requires at least v14.
+(For older versions of Node.js, use an older version of Commander.)
+
+The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.
+
+### Commander for enterprise
-## License
+Available as part of the Tidelift Subscription
-[MIT](https://github.com/tj/commander.js/blob/master/LICENSE)
+The 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)
diff --git a/node_modules/commander/index.js b/node_modules/commander/index.js
index ec1d61d5..7563b1ba 100644
--- a/node_modules/commander/index.js
+++ b/node_modules/commander/index.js
@@ -1,1224 +1,27 @@
-/**
- * Module dependencies.
- */
-
-var EventEmitter = require('events').EventEmitter;
-var spawn = require('child_process').spawn;
-var path = require('path');
-var dirname = path.dirname;
-var basename = path.basename;
-var fs = require('fs');
-
-/**
- * Inherit `Command` from `EventEmitter.prototype`.
- */
+const { Argument } = require('./lib/argument.js');
+const { Command } = require('./lib/command.js');
+const { CommanderError, InvalidArgumentError } = require('./lib/error.js');
+const { Help } = require('./lib/help.js');
+const { Option } = require('./lib/option.js');
-require('util').inherits(Command, EventEmitter);
+// @ts-check
/**
* Expose the root command.
*/
exports = module.exports = new Command();
+exports.program = exports; // More explicit access to global command.
+// Implicit export of createArgument, createCommand, and createOption.
/**
- * Expose `Command`.
+ * Expose classes
*/
+exports.Argument = Argument;
exports.Command = Command;
-
-/**
- * Expose `Option`.
- */
-
+exports.CommanderError = CommanderError;
+exports.Help = Help;
+exports.InvalidArgumentError = InvalidArgumentError;
+exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated
exports.Option = Option;
-
-/**
- * Initialize a new `Option` with the given `flags` and `description`.
- *
- * @param {String} flags
- * @param {String} description
- * @api public
- */
-
-function Option(flags, description) {
- this.flags = flags;
- this.required = flags.indexOf('<') >= 0;
- this.optional = flags.indexOf('[') >= 0;
- this.bool = flags.indexOf('-no-') === -1;
- flags = flags.split(/[ ,|]+/);
- if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();
- this.long = flags.shift();
- this.description = description || '';
-}
-
-/**
- * Return option name.
- *
- * @return {String}
- * @api private
- */
-
-Option.prototype.name = function() {
- return this.long
- .replace('--', '')
- .replace('no-', '');
-};
-
-/**
- * Return option name, in a camelcase format that can be used
- * as a object attribute key.
- *
- * @return {String}
- * @api private
- */
-
-Option.prototype.attributeName = function() {
- return camelcase(this.name());
-};
-
-/**
- * Check if `arg` matches the short or long flag.
- *
- * @param {String} arg
- * @return {Boolean}
- * @api private
- */
-
-Option.prototype.is = function(arg) {
- return this.short === arg || this.long === arg;
-};
-
-/**
- * Initialize a new `Command`.
- *
- * @param {String} name
- * @api public
- */
-
-function Command(name) {
- this.commands = [];
- this.options = [];
- this._execs = {};
- this._allowUnknownOption = false;
- this._args = [];
- this._name = name || '';
-}
-
-/**
- * Add command `name`.
- *
- * The `.action()` callback is invoked when the
- * command `name` is specified via __ARGV__,
- * and the remaining arguments are applied to the
- * function for access.
- *
- * When the `name` is "*" an un-matched command
- * will be passed as the first arg, followed by
- * the rest of __ARGV__ remaining.
- *
- * Examples:
- *
- * program
- * .version('0.0.1')
- * .option('-C, --chdir <path>', 'change the working directory')
- * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
- * .option('-T, --no-tests', 'ignore test hook')
- *
- * program
- * .command('setup')
- * .description('run remote setup commands')
- * .action(function() {
- * console.log('setup');
- * });
- *
- * program
- * .command('exec <cmd>')
- * .description('run the given remote command')
- * .action(function(cmd) {
- * console.log('exec "%s"', cmd);
- * });
- *
- * program
- * .command('teardown <dir> [otherDirs...]')
- * .description('run teardown commands')
- * .action(function(dir, otherDirs) {
- * console.log('dir "%s"', dir);
- * if (otherDirs) {
- * otherDirs.forEach(function (oDir) {
- * console.log('dir "%s"', oDir);
- * });
- * }
- * });
- *
- * program
- * .command('*')
- * .description('deploy the given env')
- * .action(function(env) {
- * console.log('deploying "%s"', env);
- * });
- *
- * program.parse(process.argv);
- *
- * @param {String} name
- * @param {String} [desc] for git-style sub-commands
- * @return {Command} the new command
- * @api public
- */
-
-Command.prototype.command = function(name, desc, opts) {
- if (typeof desc === 'object' && desc !== null) {
- opts = desc;
- desc = null;
- }
- opts = opts || {};
- var args = name.split(/ +/);
- var cmd = new Command(args.shift());
-
- if (desc) {
- cmd.description(desc);
- this.executables = true;
- this._execs[cmd._name] = true;
- if (opts.isDefault) this.defaultExecutable = cmd._name;
- }
- cmd._noHelp = !!opts.noHelp;
- this.commands.push(cmd);
- cmd.parseExpectedArgs(args);
- cmd.parent = this;
-
- if (desc) return this;
- return cmd;
-};
-
-/**
- * Define argument syntax for the top-level command.
- *
- * @api public
- */
-
-Command.prototype.arguments = function(desc) {
- return this.parseExpectedArgs(desc.split(/ +/));
-};
-
-/**
- * Add an implicit `help [cmd]` subcommand
- * which invokes `--help` for the given command.
- *
- * @api private
- */
-
-Command.prototype.addImplicitHelpCommand = function() {
- this.command('help [cmd]', 'display help for [cmd]');
-};
-
-/**
- * Parse expected `args`.
- *
- * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
- *
- * @param {Array} args
- * @return {Command} for chaining
- * @api public
- */
-
-Command.prototype.parseExpectedArgs = function(args) {
- if (!args.length) return;
- var self = this;
- args.forEach(function(arg) {
- var argDetails = {
- required: false,
- name: '',
- variadic: false
- };
-
- switch (arg[0]) {
- case '<':
- argDetails.required = true;
- argDetails.name = arg.slice(1, -1);
- break;
- case '[':
- argDetails.name = arg.slice(1, -1);
- break;
- }
-
- if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
- argDetails.variadic = true;
- argDetails.name = argDetails.name.slice(0, -3);
- }
- if (argDetails.name) {
- self._args.push(argDetails);
- }
- });
- return this;
-};
-
-/**
- * Register callback `fn` for the command.
- *
- * Examples:
- *
- * program
- * .command('help')
- * .description('display verbose help')
- * .action(function() {
- * // output help here
- * });
- *
- * @param {Function} fn
- * @return {Command} for chaining
- * @api public
- */
-
-Command.prototype.action = function(fn) {
- var self = this;
- var listener = function(args, unknown) {
- // Parse any so-far unknown options
- args = args || [];
- unknown = unknown || [];
-
- var parsed = self.parseOptions(unknown);
-
- // Output help if necessary
- outputHelpIfNecessary(self, parsed.unknown);
-
- // If there are still any unknown options, then we simply
- // die, unless someone asked for help, in which case we give it
- // to them, and then we die.
- if (parsed.unknown.length > 0) {
- self.unknownOption(parsed.unknown[0]);
- }
-
- // Leftover arguments need to be pushed back. Fixes issue #56
- if (parsed.args.length) args = parsed.args.concat(args);
-
- self._args.forEach(function(arg, i) {
- if (arg.required && args[i] == null) {
- self.missingArgument(arg.name);
- } else if (arg.variadic) {
- if (i !== self._args.length - 1) {
- self.variadicArgNotLast(arg.name);
- }
-
- args[i] = args.splice(i);
- }
- });
-
- // Always append ourselves to the end of the arguments,
- // to make sure we match the number of arguments the user
- // expects
- if (self._args.length) {
- args[self._args.length] = self;
- } else {
- args.push(self);
- }
-
- fn.apply(self, args);
- };
- var parent = this.parent || this;
- var name = parent === this ? '*' : this._name;
- parent.on('command:' + name, listener);
- if (this._alias) parent.on('command:' + this._alias, listener);
- return this;
-};
-
-/**
- * Define option with `flags`, `description` and optional
- * coercion `fn`.
- *
- * The `flags` string should contain both the short and long flags,
- * separated by comma, a pipe or space. The following are all valid
- * all will output this way when `--help` is used.
- *
- * "-p, --pepper"
- * "-p|--pepper"
- * "-p --pepper"
- *
- * Examples:
- *
- * // simple boolean defaulting to false
- * program.option('-p, --pepper', 'add pepper');
- *
- * --pepper
- * program.pepper
- * // => Boolean
- *
- * // simple boolean defaulting to true
- * program.option('-C, --no-cheese', 'remove cheese');
- *
- * program.cheese
- * // => true
- *
- * --no-cheese
- * program.cheese
- * // => false
- *
- * // required argument
- * program.option('-C, --chdir <path>', 'change the working directory');
- *
- * --chdir /tmp
- * program.chdir
- * // => "/tmp"
- *
- * // optional argument
- * program.option('-c, --cheese [type]', 'add cheese [marble]');
- *
- * @param {String} flags
- * @param {String} description
- * @param {Function|*} [fn] or default
- * @param {*} [defaultValue]
- * @return {Command} for chaining
- * @api public
- */
-
-Command.prototype.option = function(flags, description, fn, defaultValue) {
- var self = this,
- option = new Option(flags, description),
- oname = option.name(),
- name = option.attributeName();
-
- // default as 3rd arg
- if (typeof fn !== 'function') {
- if (fn instanceof RegExp) {
- var regex = fn;
- fn = function(val, def) {
- var m = regex.exec(val);
- return m ? m[0] : def;
- };
- } else {
- defaultValue = fn;
- fn = null;
- }
- }
-
- // preassign default value only for --no-*, [optional], or <required>
- if (!option.bool || option.optional || option.required) {
- // when --no-* we make sure default is true
- if (!option.bool) defaultValue = true;
- // preassign only if we have a default
- if (defaultValue !== undefined) {
- self[name] = defaultValue;
- option.defaultValue = defaultValue;
- }
- }
-
- // register the option
- this.options.push(option);
-
- // when it's passed assign the value
- // and conditionally invoke the callback
- this.on('option:' + oname, function(val) {
- // coercion
- if (val !== null && fn) {
- val = fn(val, self[name] === undefined ? defaultValue : self[name]);
- }
-
- // unassigned or bool
- if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') {
- // if no value, bool true, and we have a default, then use it!
- if (val == null) {
- self[name] = option.bool
- ? defaultValue || true
- : false;
- } else {
- self[name] = val;
- }
- } else if (val !== null) {
- // reassign
- self[name] = val;
- }
- });
-
- return this;
-};
-
-/**
- * Allow unknown options on the command line.
- *
- * @param {Boolean} arg if `true` or omitted, no error will be thrown
- * for unknown options.
- * @api public
- */
-Command.prototype.allowUnknownOption = function(arg) {
- this._allowUnknownOption = arguments.length === 0 || arg;
- return this;
-};
-
-/**
- * Parse `argv`, settings options and invoking commands when defined.
- *
- * @param {Array} argv
- * @return {Command} for chaining
- * @api public
- */
-
-Command.prototype.parse = function(argv) {
- // implicit help
- if (this.executables) this.addImplicitHelpCommand();
-
- // store raw args
- this.rawArgs = argv;
-
- // guess name
- this._name = this._name || basename(argv[1], '.js');
-
- // github-style sub-commands with no sub-command
- if (this.executables && argv.length < 3 && !this.defaultExecutable) {
- // this user needs help
- argv.push('--help');
- }
-
- // process argv
- var parsed = this.parseOptions(this.normalize(argv.slice(2)));
- var args = this.args = parsed.args;
-
- var result = this.parseArgs(this.args, parsed.unknown);
-
- // executable sub-commands
- var name = result.args[0];
-
- var aliasCommand = null;
- // check alias of sub commands
- if (name) {
- aliasCommand = this.commands.filter(function(command) {
- return command.alias() === name;
- })[0];
- }
-
- if (this._execs[name] === true) {
- return this.executeSubCommand(argv, args, parsed.unknown);
- } else if (aliasCommand) {
- // is alias of a subCommand
- args[0] = aliasCommand._name;
- return this.executeSubCommand(argv, args, parsed.unknown);
- } else if (this.defaultExecutable) {
- // use the default subcommand
- args.unshift(this.defaultExecutable);
- return this.executeSubCommand(argv, args, parsed.unknown);
- }
-
- return result;
-};
-
-/**
- * Execute a sub-command executable.
- *
- * @param {Array} argv
- * @param {Array} args
- * @param {Array} unknown
- * @api private
- */
-
-Command.prototype.executeSubCommand = function(argv, args, unknown) {
- args = args.concat(unknown);
-
- if (!args.length) this.help();
- if (args[0] === 'help' && args.length === 1) this.help();
-
- // <cmd> --help
- if (args[0] === 'help') {
- args[0] = args[1];
- args[1] = '--help';
- }
-
- // executable
- var f = argv[1];
- // name of the subcommand, link `pm-install`
- var bin = basename(f, path.extname(f)) + '-' + args[0];
-
- // In case of globally installed, get the base dir where executable
- // subcommand file should be located at
- var baseDir;
-
- var resolvedLink = fs.realpathSync(f);
-
- baseDir = dirname(resolvedLink);
-
- // prefer local `./<bin>` to bin in the $PATH
- var localBin = path.join(baseDir, bin);
-
- // whether bin file is a js script with explicit `.js` or `.ts` extension
- var isExplicitJS = false;
- if (exists(localBin + '.js')) {
- bin = localBin + '.js';
- isExplicitJS = true;
- } else if (exists(localBin + '.ts')) {
- bin = localBin + '.ts';
- isExplicitJS = true;
- } else if (exists(localBin)) {
- bin = localBin;
- }
-
- args = args.slice(1);
-
- var proc;
- if (process.platform !== 'win32') {
- if (isExplicitJS) {
- args.unshift(bin);
- // add executable arguments to spawn
- args = (process.execArgv || []).concat(args);
-
- proc = spawn(process.argv[0], args, { stdio: 'inherit', customFds: [0, 1, 2] });
- } else {
- proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] });
- }
- } else {
- args.unshift(bin);
- proc = spawn(process.execPath, args, { stdio: 'inherit' });
- }
-
- var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
- signals.forEach(function(signal) {
- process.on(signal, function() {
- if (proc.killed === false && proc.exitCode === null) {
- proc.kill(signal);
- }
- });
- });
- proc.on('close', process.exit.bind(process));
- proc.on('error', function(err) {
- if (err.code === 'ENOENT') {
- console.error('error: %s(1) does not exist, try --help', bin);
- } else if (err.code === 'EACCES') {
- console.error('error: %s(1) not executable. try chmod or run with root', bin);
- }
- process.exit(1);
- });
-
- // Store the reference to the child process
- this.runningCommand = proc;
-};
-
-/**
- * Normalize `args`, splitting joined short flags. For example
- * the arg "-abc" is equivalent to "-a -b -c".
- * This also normalizes equal sign and splits "--abc=def" into "--abc def".
- *
- * @param {Array} args
- * @return {Array}
- * @api private
- */
-
-Command.prototype.normalize = function(args) {
- var ret = [],
- arg,
- lastOpt,
- index;
-
- for (var i = 0, len = args.length; i < len; ++i) {
- arg = args[i];
- if (i > 0) {
- lastOpt = this.optionFor(args[i - 1]);
- }
-
- if (arg === '--') {
- // Honor option terminator
- ret = ret.concat(args.slice(i));
- break;
- } else if (lastOpt && lastOpt.required) {
- ret.push(arg);
- } else if (arg.length > 1 && arg[0] === '-' && arg[1] !== '-') {
- arg.slice(1).split('').forEach(function(c) {
- ret.push('-' + c);
- });
- } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {
- ret.push(arg.slice(0, index), arg.slice(index + 1));
- } else {
- ret.push(arg);
- }
- }
-
- return ret;
-};
-
-/**
- * Parse command `args`.
- *
- * When listener(s) are available those
- * callbacks are invoked, otherwise the "*"
- * event is emitted and those actions are invoked.
- *
- * @param {Array} args
- * @return {Command} for chaining
- * @api private
- */
-
-Command.prototype.parseArgs = function(args, unknown) {
- var name;
-
- if (args.length) {
- name = args[0];
- if (this.listeners('command:' + name).length) {
- this.emit('command:' + args.shift(), args, unknown);
- } else {
- this.emit('command:*', args);
- }
- } else {
- outputHelpIfNecessary(this, unknown);
-
- // If there were no args and we have unknown options,
- // then they are extraneous and we need to error.
- if (unknown.length > 0) {
- this.unknownOption(unknown[0]);
- }
- if (this.commands.length === 0 &&
- this._args.filter(function(a) { return a.required; }).length === 0) {
- this.emit('command:*');
- }
- }
-
- return this;
-};
-
-/**
- * Return an option matching `arg` if any.
- *
- * @param {String} arg
- * @return {Option}
- * @api private
- */
-
-Command.prototype.optionFor = function(arg) {
- for (var i = 0, len = this.options.length; i < len; ++i) {
- if (this.options[i].is(arg)) {
- return this.options[i];
- }
- }
-};
-
-/**
- * Parse options from `argv` returning `argv`
- * void of these options.
- *
- * @param {Array} argv
- * @return {Array}
- * @api public
- */
-
-Command.prototype.parseOptions = function(argv) {
- var args = [],
- len = argv.length,
- literal,
- option,
- arg;
-
- var unknownOptions = [];
-
- // parse options
- for (var i = 0; i < len; ++i) {
- arg = argv[i];
-
- // literal args after --
- if (literal) {
- args.push(arg);
- continue;
- }
-
- if (arg === '--') {
- literal = true;
- continue;
- }
-
- // find matching Option
- option = this.optionFor(arg);
-
- // option is defined
- if (option) {
- // requires arg
- if (option.required) {
- arg = argv[++i];
- if (arg == null) return this.optionMissingArgument(option);
- this.emit('option:' + option.name(), arg);
- // optional arg
- } else if (option.optional) {
- arg = argv[i + 1];
- if (arg == null || (arg[0] === '-' && arg !== '-')) {
- arg = null;
- } else {
- ++i;
- }
- this.emit('option:' + option.name(), arg);
- // bool
- } else {
- this.emit('option:' + option.name());
- }
- continue;
- }
-
- // looks like an option
- if (arg.length > 1 && arg[0] === '-') {
- unknownOptions.push(arg);
-
- // If the next argument looks like it might be
- // an argument for this option, we pass it on.
- // If it isn't, then it'll simply be ignored
- if ((i + 1) < argv.length && argv[i + 1][0] !== '-') {
- unknownOptions.push(argv[++i]);
- }
- continue;
- }
-
- // arg
- args.push(arg);
- }
-
- return { args: args, unknown: unknownOptions };
-};
-
-/**
- * Return an object containing options as key-value pairs
- *
- * @return {Object}
- * @api public
- */
-Command.prototype.opts = function() {
- var result = {},
- len = this.options.length;
-
- for (var i = 0; i < len; i++) {
- var key = this.options[i].attributeName();
- result[key] = key === this._versionOptionName ? this._version : this[key];
- }
- return result;
-};
-
-/**
- * Argument `name` is missing.
- *
- * @param {String} name
- * @api private
- */
-
-Command.prototype.missingArgument = function(name) {
- console.error("error: missing required argument `%s'", name);
- process.exit(1);
-};
-
-/**
- * `Option` is missing an argument, but received `flag` or nothing.
- *
- * @param {String} option
- * @param {String} flag
- * @api private
- */
-
-Command.prototype.optionMissingArgument = function(option, flag) {
- if (flag) {
- console.error("error: option `%s' argument missing, got `%s'", option.flags, flag);
- } else {
- console.error("error: option `%s' argument missing", option.flags);
- }
- process.exit(1);
-};
-
-/**
- * Unknown option `flag`.
- *
- * @param {String} flag
- * @api private
- */
-
-Command.prototype.unknownOption = function(flag) {
- if (this._allowUnknownOption) return;
- console.error("error: unknown option `%s'", flag);
- process.exit(1);
-};
-
-/**
- * Variadic argument with `name` is not the last argument as required.
- *
- * @param {String} name
- * @api private
- */
-
-Command.prototype.variadicArgNotLast = function(name) {
- console.error("error: variadic arguments must be last `%s'", name);
- process.exit(1);
-};
-
-/**
- * Set the program version to `str`.
- *
- * This method auto-registers the "-V, --version" flag
- * which will print the version number when passed.
- *
- * @param {String} str
- * @param {String} [flags]
- * @return {Command} for chaining
- * @api public
- */
-
-Command.prototype.version = function(str, flags) {
- if (arguments.length === 0) return this._version;
- this._version = str;
- flags = flags || '-V, --version';
- var versionOption = new Option(flags, 'output the version number');
- this._versionOptionName = versionOption.long.substr(2) || 'version';
- this.options.push(versionOption);
- this.on('option:' + this._versionOptionName, function() {
- process.stdout.write(str + '\n');
- process.exit(0);
- });
- return this;
-};
-
-/**
- * Set the description to `str`.
- *
- * @param {String} str
- * @param {Object} argsDescription
- * @return {String|Command}
- * @api public
- */
-
-Command.prototype.description = function(str, argsDescription) {
- if (arguments.length === 0) return this._description;
- this._description = str;
- this._argsDescription = argsDescription;
- return this;
-};
-
-/**
- * Set an alias for the command
- *
- * @param {String} alias
- * @return {String|Command}
- * @api public
- */
-
-Command.prototype.alias = function(alias) {
- var command = this;
- if (this.commands.length !== 0) {
- command = this.commands[this.commands.length - 1];
- }
-
- if (arguments.length === 0) return command._alias;
-
- if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
-
- command._alias = alias;
- return this;
-};
-
-/**
- * Set / get the command usage `str`.
- *
- * @param {String} str
- * @return {String|Command}
- * @api public
- */
-
-Command.prototype.usage = function(str) {
- var args = this._args.map(function(arg) {
- return humanReadableArgName(arg);
- });
-
- var usage = '[options]' +
- (this.commands.length ? ' [command]' : '') +
- (this._args.length ? ' ' + args.join(' ') : '');
-
- if (arguments.length === 0) return this._usage || usage;
- this._usage = str;
-
- return this;
-};
-
-/**
- * Get or set the name of the command
- *
- * @param {String} str
- * @return {String|Command}
- * @api public
- */
-
-Command.prototype.name = function(str) {
- if (arguments.length === 0) return this._name;
- this._name = str;
- return this;
-};
-
-/**
- * Return prepared commands.
- *
- * @return {Array}
- * @api private
- */
-
-Command.prototype.prepareCommands = function() {
- return this.commands.filter(function(cmd) {
- return !cmd._noHelp;
- }).map(function(cmd) {
- var args = cmd._args.map(function(arg) {
- return humanReadableArgName(arg);
- }).join(' ');
-
- return [
- cmd._name +
- (cmd._alias ? '|' + cmd._alias : '') +
- (cmd.options.length ? ' [options]' : '') +
- (args ? ' ' + args : ''),
- cmd._description
- ];
- });
-};
-
-/**
- * Return the largest command length.
- *
- * @return {Number}
- * @api private
- */
-
-Command.prototype.largestCommandLength = function() {
- var commands = this.prepareCommands();
- return commands.reduce(function(max, command) {
- return Math.max(max, command[0].length);
- }, 0);
-};
-
-/**
- * Return the largest option length.
- *
- * @return {Number}
- * @api private
- */
-
-Command.prototype.largestOptionLength = function() {
- var options = [].slice.call(this.options);
- options.push({
- flags: '-h, --help'
- });
- return options.reduce(function(max, option) {
- return Math.max(max, option.flags.length);
- }, 0);
-};
-
-/**
- * Return the largest arg length.
- *
- * @return {Number}
- * @api private
- */
-
-Command.prototype.largestArgLength = function() {
- return this._args.reduce(function(max, arg) {
- return Math.max(max, arg.name.length);
- }, 0);
-};
-
-/**
- * Return the pad width.
- *
- * @return {Number}
- * @api private
- */
-
-Command.prototype.padWidth = function() {
- var width = this.largestOptionLength();
- if (this._argsDescription && this._args.length) {
- if (this.largestArgLength() > width) {
- width = this.largestArgLength();
- }
- }
-
- if (this.commands && this.commands.length) {
- if (this.largestCommandLength() > width) {
- width = this.largestCommandLength();
- }
- }
-
- return width;
-};
-
-/**
- * Return help for options.
- *
- * @return {String}
- * @api private
- */
-
-Command.prototype.optionHelp = function() {
- var width = this.padWidth();
-
- // Append the help information
- return this.options.map(function(option) {
- return pad(option.flags, width) + ' ' + option.description +
- ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');
- }).concat([pad('-h, --help', width) + ' ' + 'output usage information'])
- .join('\n');
-};
-
-/**
- * Return command help documentation.
- *
- * @return {String}
- * @api private
- */
-
-Command.prototype.commandHelp = function() {
- if (!this.commands.length) return '';
-
- var commands = this.prepareCommands();
- var width = this.padWidth();
-
- return [
- 'Commands:',
- commands.map(function(cmd) {
- var desc = cmd[1] ? ' ' + cmd[1] : '';
- return (desc ? pad(cmd[0], width) : cmd[0]) + desc;
- }).join('\n').replace(/^/gm, ' '),
- ''
- ].join('\n');
-};
-
-/**
- * Return program help documentation.
- *
- * @return {String}
- * @api private
- */
-
-Command.prototype.helpInformation = function() {
- var desc = [];
- if (this._description) {
- desc = [
- this._description,
- ''
- ];
-
- var argsDescription = this._argsDescription;
- if (argsDescription && this._args.length) {
- var width = this.padWidth();
- desc.push('Arguments:');
- desc.push('');
- this._args.forEach(function(arg) {
- desc.push(' ' + pad(arg.name, width) + ' ' + argsDescription[arg.name]);
- });
- desc.push('');
- }
- }
-
- var cmdName = this._name;
- if (this._alias) {
- cmdName = cmdName + '|' + this._alias;
- }
- var usage = [
- 'Usage: ' + cmdName + ' ' + this.usage(),
- ''
- ];
-
- var cmds = [];
- var commandHelp = this.commandHelp();
- if (commandHelp) cmds = [commandHelp];
-
- var options = [
- 'Options:',
- '' + this.optionHelp().replace(/^/gm, ' '),
- ''
- ];
-
- return usage
- .concat(desc)
- .concat(options)
- .concat(cmds)
- .join('\n');
-};
-
-/**
- * Output help information for this command
- *
- * @api public
- */
-
-Command.prototype.outputHelp = function(cb) {
- if (!cb) {
- cb = function(passthru) {
- return passthru;
- };
- }
- process.stdout.write(cb(this.helpInformation()));
- this.emit('--help');
-};
-
-/**
- * Output help information and exit.
- *
- * @api public
- */
-
-Command.prototype.help = function(cb) {
- this.outputHelp(cb);
- process.exit();
-};
-
-/**
- * Camel-case the given `flag`
- *
- * @param {String} flag
- * @return {String}
- * @api private
- */
-
-function camelcase(flag) {
- return flag.split('-').reduce(function(str, word) {
- return str + word[0].toUpperCase() + word.slice(1);
- });
-}
-
-/**
- * Pad `str` to `width`.
- *
- * @param {String} str
- * @param {Number} width
- * @return {String}
- * @api private
- */
-
-function pad(str, width) {
- var len = Math.max(0, width - str.length);
- return str + Array(len + 1).join(' ');
-}
-
-/**
- * Output help information if necessary
- *
- * @param {Command} command to output help for
- * @param {Array} array of options to search for -h or --help
- * @api private
- */
-
-function outputHelpIfNecessary(cmd, options) {
- options = options || [];
- for (var i = 0; i < options.length; i++) {
- if (options[i] === '--help' || options[i] === '-h') {
- cmd.outputHelp();
- process.exit(0);
- }
- }
-}
-
-/**
- * Takes an argument an returns its human readable equivalent for help usage.
- *
- * @param {Object} arg
- * @return {String}
- * @api private
- */
-
-function humanReadableArgName(arg) {
- var nameOutput = arg.name + (arg.variadic === true ? '...' : '');
-
- return arg.required
- ? '<' + nameOutput + '>'
- : '[' + nameOutput + ']';
-}
-
-// for versions before node v0.8 when there weren't `fs.existsSync`
-function exists(file) {
- try {
- if (fs.statSync(file).isFile()) {
- return true;
- }
- } catch (e) {
- return false;
- }
-}
diff --git a/node_modules/commander/package.json b/node_modules/commander/package.json
index 0023c5cd..05767954 100644
--- a/node_modules/commander/package.json
+++ b/node_modules/commander/package.json
@@ -1,12 +1,16 @@
{
"name": "commander",
- "version": "2.20.3",
+ "version": "10.0.1",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"commander",
"command",
"option",
- "parser"
+ "parser",
+ "cli",
+ "argument",
+ "args",
+ "argv"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"license": "MIT",
@@ -15,24 +19,62 @@
"url": "https://github.com/tj/commander.js.git"
},
"scripts": {
- "lint": "eslint index.js",
- "test": "node test/run.js && npm run test-typings",
- "test-typings": "tsc -p tsconfig.json"
+ "lint": "npm run lint:javascript && npm run lint:typescript",
+ "lint:javascript": "eslint index.js esm.mjs \"lib/*.js\" \"tests/**/*.js\"",
+ "lint:typescript": "eslint typings/*.ts tests/*.ts",
+ "test": "jest && npm run test-typings",
+ "test-esm": "node ./tests/esm-imports-test.mjs",
+ "test-typings": "tsd",
+ "typescript-checkJS": "tsc --allowJS --checkJS index.js lib/*.js --noEmit",
+ "test-all": "npm run test && npm run lint && npm run typescript-checkJS && npm run test-esm"
},
- "main": "index",
"files": [
"index.js",
- "typings/index.d.ts"
+ "lib/*.js",
+ "esm.mjs",
+ "typings/index.d.ts",
+ "package-support.json"
],
- "dependencies": {},
+ "type": "commonjs",
+ "main": "./index.js",
+ "exports": {
+ ".": {
+ "types": "./typings/index.d.ts",
+ "require": "./index.js",
+ "import": "./esm.mjs"
+ },
+ "./esm.mjs": "./esm.mjs"
+ },
"devDependencies": {
- "@types/node": "^12.7.8",
- "eslint": "^6.4.0",
- "should": "^13.2.3",
- "sinon": "^7.5.0",
- "standard": "^14.3.1",
- "ts-node": "^8.4.1",
- "typescript": "^3.6.3"
+ "@types/jest": "^29.2.4",
+ "@types/node": "^18.11.18",
+ "@typescript-eslint/eslint-plugin": "^5.47.1",
+ "@typescript-eslint/parser": "^5.47.1",
+ "eslint": "^8.30.0",
+ "eslint-config-standard": "^17.0.0",
+ "eslint-config-standard-with-typescript": "^24.0.0",
+ "eslint-plugin-import": "^2.26.0",
+ "eslint-plugin-jest": "^27.1.7",
+ "eslint-plugin-n": "^15.6.0",
+ "eslint-plugin-promise": "^6.1.1",
+ "jest": "^29.3.1",
+ "ts-jest": "^29.0.3",
+ "tsd": "^0.25.0",
+ "typescript": "^4.9.4"
+ },
+ "types": "typings/index.d.ts",
+ "jest": {
+ "testEnvironment": "node",
+ "collectCoverage": true,
+ "transform": {
+ "^.+\\.tsx?$": "ts-jest"
+ },
+ "testPathIgnorePatterns": [
+ "/node_modules/"
+ ]
+ },
+ "engines": {
+ "node": ">=14"
},
- "typings": "typings/index.d.ts"
+ "support": true
}
diff --git a/node_modules/commander/typings/index.d.ts b/node_modules/commander/typings/index.d.ts
index bcda2771..695c3bd2 100644
--- a/node_modules/commander/typings/index.d.ts
+++ b/node_modules/commander/typings/index.d.ts
@@ -1,310 +1,889 @@
-// Type definitions for commander 2.11
-// Project: https://github.com/visionmedia/commander.js
-// Definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
-// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
-
-declare namespace local {
-
- class Option {
- flags: string;
- required: boolean;
- optional: boolean;
- bool: boolean;
- short?: string;
- long: string;
- description: string;
-
- /**
- * Initialize a new `Option` with the given `flags` and `description`.
- *
- * @param {string} flags
- * @param {string} [description]
- */
- constructor(flags: string, description?: string);
- }
-
- class Command extends NodeJS.EventEmitter {
- [key: string]: any;
-
- args: string[];
-
- /**
- * Initialize a new `Command`.
- *
- * @param {string} [name]
- */
- constructor(name?: string);
-
- /**
- * Set the program version to `str`.
- *
- * This method auto-registers the "-V, --version" flag
- * which will print the version number when passed.
- *
- * @param {string} str
- * @param {string} [flags]
- * @returns {Command} for chaining
- */
- version(str: string, flags?: string): Command;
-
- /**
- * Add command `name`.
- *
- * The `.action()` callback is invoked when the
- * command `name` is specified via __ARGV__,
- * and the remaining arguments are applied to the
- * function for access.
- *
- * When the `name` is "*" an un-matched command
- * will be passed as the first arg, followed by
- * the rest of __ARGV__ remaining.
- *
- * @example
- * program
- * .version('0.0.1')
- * .option('-C, --chdir <path>', 'change the working directory')
- * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
- * .option('-T, --no-tests', 'ignore test hook')
- *
- * program
- * .command('setup')
- * .description('run remote setup commands')
- * .action(function() {
- * console.log('setup');
- * });
- *
- * program
- * .command('exec <cmd>')
- * .description('run the given remote command')
- * .action(function(cmd) {
- * console.log('exec "%s"', cmd);
- * });
- *
- * program
- * .command('teardown <dir> [otherDirs...]')
- * .description('run teardown commands')
- * .action(function(dir, otherDirs) {
- * console.log('dir "%s"', dir);
- * if (otherDirs) {
- * otherDirs.forEach(function (oDir) {
- * console.log('dir "%s"', oDir);
- * });
- * }
- * });
- *
- * program
- * .command('*')
- * .description('deploy the given env')
- * .action(function(env) {
- * console.log('deploying "%s"', env);
- * });
- *
- * program.parse(process.argv);
- *
- * @param {string} name
- * @param {string} [desc] for git-style sub-commands
- * @param {CommandOptions} [opts] command options
- * @returns {Command} the new command
- */
- command(name: string, desc?: string, opts?: commander.CommandOptions): Command;
-
- /**
- * Define argument syntax for the top-level command.
- *
- * @param {string} desc
- * @returns {Command} for chaining
- */
- arguments(desc: string): Command;
-
- /**
- * Parse expected `args`.
- *
- * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
- *
- * @param {string[]} args
- * @returns {Command} for chaining
- */
- parseExpectedArgs(args: string[]): Command;
-
- /**
- * Register callback `fn` for the command.
- *
- * @example
- * program
- * .command('help')
- * .description('display verbose help')
- * .action(function() {
- * // output help here
- * });
- *
- * @param {(...args: any[]) => void} fn
- * @returns {Command} for chaining
- */
- action(fn: (...args: any[]) => void): Command;
-
- /**
- * Define option with `flags`, `description` and optional
- * coercion `fn`.
- *
- * The `flags` string should contain both the short and long flags,
- * separated by comma, a pipe or space. The following are all valid
- * all will output this way when `--help` is used.
- *
- * "-p, --pepper"
- * "-p|--pepper"
- * "-p --pepper"
- *
- * @example
- * // simple boolean defaulting to false
- * program.option('-p, --pepper', 'add pepper');
- *
- * --pepper
- * program.pepper
- * // => Boolean
- *
- * // simple boolean defaulting to true
- * program.option('-C, --no-cheese', 'remove cheese');
- *
- * program.cheese
- * // => true
- *
- * --no-cheese
- * program.cheese
- * // => false
- *
- * // required argument
- * program.option('-C, --chdir <path>', 'change the working directory');
- *
- * --chdir /tmp
- * program.chdir
- * // => "/tmp"
- *
- * // optional argument
- * program.option('-c, --cheese [type]', 'add cheese [marble]');
- *
- * @param {string} flags
- * @param {string} [description]
- * @param {((arg1: any, arg2: any) => void) | RegExp} [fn] function or default
- * @param {*} [defaultValue]
- * @returns {Command} for chaining
- */
- option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command;
- option(flags: string, description?: string, defaultValue?: any): Command;
-
- /**
- * Allow unknown options on the command line.
- *
- * @param {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options.
- * @returns {Command} for chaining
- */
- allowUnknownOption(arg?: boolean): Command;
-
- /**
- * Parse `argv`, settings options and invoking commands when defined.
- *
- * @param {string[]} argv
- * @returns {Command} for chaining
- */
- parse(argv: string[]): Command;
-
- /**
- * Parse options from `argv` returning `argv` void of these options.
- *
- * @param {string[]} argv
- * @returns {ParseOptionsResult}
- */
- parseOptions(argv: string[]): commander.ParseOptionsResult;
-
- /**
- * Return an object containing options as key-value pairs
- *
- * @returns {{[key: string]: any}}
- */
- opts(): { [key: string]: any };
-
- /**
- * Set the description to `str`.
- *
- * @param {string} str
- * @param {{[argName: string]: string}} argsDescription
- * @return {(Command | string)}
- */
- description(str: string, argsDescription?: {[argName: string]: string}): Command;
- description(): string;
-
- /**
- * Set an alias for the command.
- *
- * @param {string} alias
- * @return {(Command | string)}
- */
- alias(alias: string): Command;
- alias(): string;
-
- /**
- * Set or get the command usage.
- *
- * @param {string} str
- * @return {(Command | string)}
- */
- usage(str: string): Command;
- usage(): string;
-
- /**
- * Set the name of the command.
- *
- * @param {string} str
- * @return {Command}
- */
- name(str: string): Command;
-
- /**
- * Get the name of the command.
- *
- * @return {string}
- */
- name(): string;
-
- /**
- * Output help information for this command.
- *
- * @param {(str: string) => string} [cb]
- */
- outputHelp(cb?: (str: string) => string): void;
-
- /** Output help information and exit.
- *
- * @param {(str: string) => string} [cb]
- */
- help(cb?: (str: string) => string): never;
- }
+// Type definitions for commander
+// Original definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
+
+// Using method rather than property for method-signature-style, to document method overloads separately. Allow either.
+/* eslint-disable @typescript-eslint/method-signature-style */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+export class CommanderError extends Error {
+ code: string;
+ exitCode: number;
+ message: string;
+ nestedError?: string;
+
+ /**
+ * Constructs the CommanderError class
+ * @param exitCode - suggested exit code which could be used with process.exit
+ * @param code - an id string representing the error
+ * @param message - human-readable description of the error
+ * @constructor
+ */
+ constructor(exitCode: number, code: string, message: string);
+}
+export class InvalidArgumentError extends CommanderError {
+ /**
+ * Constructs the InvalidArgumentError class
+ * @param message - explanation of why argument is invalid
+ * @constructor
+ */
+ constructor(message: string);
}
+export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name
-declare namespace commander {
+export interface ErrorOptions { // optional parameter for error()
+ /** an id string representing the error */
+ code?: string;
+ /** suggested exit code which could be used with process.exit */
+ exitCode?: number;
+}
- type Command = local.Command
+export class Argument {
+ description: string;
+ required: boolean;
+ variadic: boolean;
+
+ /**
+ * Initialize a new command argument with the given name and description.
+ * The default is that the argument is required, and you can explicitly
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
+ */
+ constructor(arg: string, description?: string);
+
+ /**
+ * Return argument name.
+ */
+ name(): string;
+
+ /**
+ * Set the default value, and optionally supply the description to be displayed in the help.
+ */
+ default(value: unknown, description?: string): this;
+
+ /**
+ * Set the custom handler for processing CLI command arguments into argument values.
+ */
+ argParser<T>(fn: (value: string, previous: T) => T): this;
+
+ /**
+ * Only allow argument value to be one of choices.
+ */
+ choices(values: readonly string[]): this;
+
+ /**
+ * Make argument required.
+ */
+ argRequired(): this;
+
+ /**
+ * Make argument optional.
+ */
+ argOptional(): this;
+}
- type Option = local.Option
+export class Option {
+ flags: string;
+ description: string;
+
+ required: boolean; // A value must be supplied when the option is specified.
+ optional: boolean; // A value is optional when the option is specified.
+ variadic: boolean;
+ mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.
+ short?: string;
+ long?: string;
+ negate: boolean;
+ defaultValue?: any;
+ defaultValueDescription?: string;
+ parseArg?: <T>(value: string, previous: T) => T;
+ hidden: boolean;
+ argChoices?: string[];
+
+ constructor(flags: string, description?: string);
+
+ /**
+ * Set the default value, and optionally supply the description to be displayed in the help.
+ */
+ default(value: unknown, description?: string): this;
+
+ /**
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
+ * The custom processing (parseArg) is called.
+ *
+ * @example
+ * ```ts
+ * new Option('--color').default('GREYSCALE').preset('RGB');
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
+ * ```
+ */
+ preset(arg: unknown): this;
+
+ /**
+ * Add option name(s) that conflict with this option.
+ * An error will be displayed if conflicting options are found during parsing.
+ *
+ * @example
+ * ```ts
+ * new Option('--rgb').conflicts('cmyk');
+ * new Option('--js').conflicts(['ts', 'jsx']);
+ * ```
+ */
+ conflicts(names: string | string[]): this;
+
+ /**
+ * Specify implied option values for when this option is set and the implied options are not.
+ *
+ * The custom processing (parseArg) is not called on the implied values.
+ *
+ * @example
+ * program
+ * .addOption(new Option('--log', 'write logging information to file'))
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
+ */
+ implies(optionValues: OptionValues): this;
+
+ /**
+ * Set environment variable to check for option value.
+ *
+ * An environment variables is only used if when processed the current option value is
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
+ */
+ env(name: string): this;
+
+ /**
+ * Calculate the full description, including defaultValue etc.
+ */
+ fullDescription(): string;
+
+ /**
+ * Set the custom handler for processing CLI option arguments into option values.
+ */
+ argParser<T>(fn: (value: string, previous: T) => T): this;
+
+ /**
+ * Whether the option is mandatory and must have a value after parsing.
+ */
+ makeOptionMandatory(mandatory?: boolean): this;
+
+ /**
+ * Hide option in help.
+ */
+ hideHelp(hide?: boolean): this;
+
+ /**
+ * Only allow option value to be one of choices.
+ */
+ choices(values: readonly string[]): this;
+
+ /**
+ * Return option name.
+ */
+ name(): string;
+
+ /**
+ * Return option name, in a camelcase format that can be used
+ * as a object attribute key.
+ */
+ attributeName(): string;
+
+ /**
+ * Return whether a boolean option.
+ *
+ * Options are one of boolean, negated, required argument, or optional argument.
+ */
+ isBoolean(): boolean;
+}
- interface CommandOptions {
- noHelp?: boolean;
- isDefault?: boolean;
- }
+export class Help {
+ /** output helpWidth, long lines are wrapped to fit */
+ helpWidth?: number;
+ sortSubcommands: boolean;
+ sortOptions: boolean;
+ showGlobalOptions: boolean;
+
+ constructor();
+
+ /** Get the command term to show in the list of subcommands. */
+ subcommandTerm(cmd: Command): string;
+ /** Get the command summary to show in the list of subcommands. */
+ subcommandDescription(cmd: Command): string;
+ /** Get the option term to show in the list of options. */
+ optionTerm(option: Option): string;
+ /** Get the option description to show in the list of options. */
+ optionDescription(option: Option): string;
+ /** Get the argument term to show in the list of arguments. */
+ argumentTerm(argument: Argument): string;
+ /** Get the argument description to show in the list of arguments. */
+ argumentDescription(argument: Argument): string;
+
+ /** Get the command usage to be displayed at the top of the built-in help. */
+ commandUsage(cmd: Command): string;
+ /** Get the description for the command. */
+ commandDescription(cmd: Command): string;
+
+ /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */
+ visibleCommands(cmd: Command): Command[];
+ /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */
+ visibleOptions(cmd: Command): Option[];
+ /** Get an array of the visible global options. (Not including help.) */
+ visibleGlobalOptions(cmd: Command): Option[];
+ /** Get an array of the arguments which have descriptions. */
+ visibleArguments(cmd: Command): Argument[];
+
+ /** Get the longest command term length. */
+ longestSubcommandTermLength(cmd: Command, helper: Help): number;
+ /** Get the longest option term length. */
+ longestOptionTermLength(cmd: Command, helper: Help): number;
+ /** Get the longest global option term length. */
+ longestGlobalOptionTermLength(cmd: Command, helper: Help): number;
+ /** Get the longest argument term length. */
+ longestArgumentTermLength(cmd: Command, helper: Help): number;
+ /** Calculate the pad width from the maximum term length. */
+ padWidth(cmd: Command, helper: Help): number;
+
+ /**
+ * Wrap the given string to width characters per line, with lines after the first indented.
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
+ */
+ wrap(str: string, width: number, indent: number, minColumnWidth?: number): string;
+
+ /** Generate the built-in help text. */
+ formatHelp(cmd: Command, helper: Help): string;
+}
+export type HelpConfiguration = Partial<Help>;
- interface ParseOptionsResult {
- args: string[];
- unknown: string[];
- }
+export interface ParseOptions {
+ from: 'node' | 'electron' | 'user';
+}
+export interface HelpContext { // optional parameter for .help() and .outputHelp()
+ error: boolean;
+}
+export interface AddHelpTextContext { // passed to text function used with .addHelpText()
+ error: boolean;
+ command: Command;
+}
+export interface OutputConfiguration {
+ writeOut?(str: string): void;
+ writeErr?(str: string): void;
+ getOutHelpWidth?(): number;
+ getErrHelpWidth?(): number;
+ outputError?(str: string, write: (str: string) => void): void;
- interface CommanderStatic extends Command {
- Command: typeof local.Command;
- Option: typeof local.Option;
- CommandOptions: CommandOptions;
- ParseOptionsResult: ParseOptionsResult;
- }
+}
+
+export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';
+export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';
+export type OptionValueSource = 'default' | 'config' | 'env' | 'cli' | 'implied';
+
+export type OptionValues = Record<string, any>;
+
+export class Command {
+ args: string[];
+ processedArgs: any[];
+ readonly commands: readonly Command[];
+ readonly options: readonly Option[];
+ parent: Command | null;
+
+ constructor(name?: string);
+
+ /**
+ * Set the program version to `str`.
+ *
+ * This method auto-registers the "-V, --version" flag
+ * which will print the version number when passed.
+ *
+ * You can optionally supply the flags and description to override the defaults.
+ */
+ version(str: string, flags?: string, description?: string): this;
+
+ /**
+ * Define a command, implemented using an action handler.
+ *
+ * @remarks
+ * The command description is supplied using `.description`, not as a parameter to `.command`.
+ *
+ * @example
+ * ```ts
+ * program
+ * .command('clone <source> [destination]')
+ * .description('clone a repository into a newly created directory')
+ * .action((source, destination) => {
+ * console.log('clone command called');
+ * });
+ * ```
+ *
+ * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
+ * @param opts - configuration options
+ * @returns new command
+ */
+ command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>;
+ /**
+ * Define a command, implemented in a separate executable file.
+ *
+ * @remarks
+ * The command description is supplied as the second parameter to `.command`.
+ *
+ * @example
+ * ```ts
+ * program
+ * .command('start <service>', 'start named service')
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
+ * ```
+ *
+ * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
+ * @param description - description of executable command
+ * @param opts - configuration options
+ * @returns `this` command for chaining
+ */
+ command(nameAndArgs: string, description: string, opts?: ExecutableCommandOptions): this;
+
+ /**
+ * Factory routine to create a new unattached command.
+ *
+ * See .command() for creating an attached subcommand, which uses this routine to
+ * create the command. You can override createCommand to customise subcommands.
+ */
+ createCommand(name?: string): Command;
+
+ /**
+ * Add a prepared subcommand.
+ *
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
+ *
+ * @returns `this` command for chaining
+ */
+ addCommand(cmd: Command, opts?: CommandOptions): this;
+
+ /**
+ * Factory routine to create a new unattached argument.
+ *
+ * See .argument() for creating an attached argument, which uses this routine to
+ * create the argument. You can override createArgument to return a custom argument.
+ */
+ createArgument(name: string, description?: string): Argument;
+
+ /**
+ * Define argument syntax for command.
+ *
+ * The default is that the argument is required, and you can explicitly
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
+ *
+ * @example
+ * ```
+ * program.argument('<input-file>');
+ * program.argument('[output-file]');
+ * ```
+ *
+ * @returns `this` command for chaining
+ */
+ argument<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
+ argument(name: string, description?: string, defaultValue?: unknown): this;
+
+ /**
+ * Define argument syntax for command, adding a prepared argument.
+ *
+ * @returns `this` command for chaining
+ */
+ addArgument(arg: Argument): this;
+
+ /**
+ * Define argument syntax for command, adding multiple at once (without descriptions).
+ *
+ * See also .argument().
+ *
+ * @example
+ * ```
+ * program.arguments('<cmd> [env]');
+ * ```
+ *
+ * @returns `this` command for chaining
+ */
+ arguments(names: string): this;
+
+ /**
+ * Override default decision whether to add implicit help command.
+ *
+ * @example
+ * ```
+ * addHelpCommand() // force on
+ * addHelpCommand(false); // force off
+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
+ * ```
+ *
+ * @returns `this` command for chaining
+ */
+ addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this;
+
+ /**
+ * Add hook for life cycle event.
+ */
+ hook(event: HookEvent, listener: (thisCommand: Command, actionCommand: Command) => void | Promise<void>): this;
+
+ /**
+ * Register callback to use as replacement for calling process.exit.
+ */
+ exitOverride(callback?: (err: CommanderError) => never | void): this;
+
+ /**
+ * Display error message and exit (or call exitOverride).
+ */
+ error(message: string, errorOptions?: ErrorOptions): never;
+
+ /**
+ * You can customise the help with a subclass of Help by overriding createHelp,
+ * or by overriding Help properties using configureHelp().
+ */
+ createHelp(): Help;
+
+ /**
+ * You can customise the help by overriding Help properties using configureHelp(),
+ * or with a subclass of Help by overriding createHelp().
+ */
+ configureHelp(configuration: HelpConfiguration): this;
+ /** Get configuration */
+ configureHelp(): HelpConfiguration;
+
+ /**
+ * The default output goes to stdout and stderr. You can customise this for special
+ * applications. You can also customise the display of errors by overriding outputError.
+ *
+ * The configuration properties are all functions:
+ * ```
+ * // functions to change where being written, stdout and stderr
+ * writeOut(str)
+ * writeErr(str)
+ * // matching functions to specify width for wrapping help
+ * getOutHelpWidth()
+ * getErrHelpWidth()
+ * // functions based on what is being written out
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
+ * ```
+ */
+ configureOutput(configuration: OutputConfiguration): this;
+ /** Get configuration */
+ configureOutput(): OutputConfiguration;
+
+ /**
+ * Copy settings that are useful to have in common across root command and subcommands.
+ *
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
+ */
+ copyInheritedSettings(sourceCommand: Command): this;
+
+ /**
+ * Display the help or a custom message after an error occurs.
+ */
+ showHelpAfterError(displayHelp?: boolean | string): this;
+
+ /**
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
+ */
+ showSuggestionAfterError(displaySuggestion?: boolean): this;
+
+ /**
+ * Register callback `fn` for the command.
+ *
+ * @example
+ * ```
+ * program
+ * .command('serve')
+ * .description('start service')
+ * .action(function() {
+ * // do work here
+ * });
+ * ```
+ *
+ * @returns `this` command for chaining
+ */
+ action(fn: (...args: any[]) => void | Promise<void>): this;
+
+ /**
+ * Define option with `flags`, `description` and optional
+ * coercion `fn`.
+ *
+ * The `flags` string contains the short and/or long flags,
+ * separated by comma, a pipe or space. The following are all valid
+ * all will output this way when `--help` is used.
+ *
+ * "-p, --pepper"
+ * "-p|--pepper"
+ * "-p --pepper"
+ *
+ * @example
+ * ```
+ * // simple boolean defaulting to false
+ * program.option('-p, --pepper', 'add pepper');
+ *
+ * --pepper
+ * program.pepper
+ * // => Boolean
+ *
+ * // simple boolean defaulting to true
+ * program.option('-C, --no-cheese', 'remove cheese');
+ *
+ * program.cheese
+ * // => true
+ *
+ * --no-cheese
+ * program.cheese
+ * // => false
+ *
+ * // required argument
+ * program.option('-C, --chdir <path>', 'change the working directory');
+ *
+ * --chdir /tmp
+ * program.chdir
+ * // => "/tmp"
+ *
+ * // optional argument
+ * program.option('-c, --cheese [type]', 'add cheese [marble]');
+ * ```
+ *
+ * @returns `this` command for chaining
+ */
+ option(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;
+ option<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
+ /** @deprecated since v7, instead use choices or a custom function */
+ option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this;
+
+ /**
+ * Define a required option, which must have a value after parsing. This usually means
+ * the option must be specified on the command line. (Otherwise the same as .option().)
+ *
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
+ */
+ requiredOption(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;
+ requiredOption<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
+ /** @deprecated since v7, instead use choices or a custom function */
+ requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this;
+
+ /**
+ * Factory routine to create a new unattached option.
+ *
+ * See .option() for creating an attached option, which uses this routine to
+ * create the option. You can override createOption to return a custom option.
+ */
+
+ createOption(flags: string, description?: string): Option;
+
+ /**
+ * Add a prepared Option.
+ *
+ * See .option() and .requiredOption() for creating and attaching an option in a single call.
+ */
+ addOption(option: Option): this;
+
+ /**
+ * Whether to store option values as properties on command object,
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
+ *
+ * @returns `this` command for chaining
+ */
+ storeOptionsAsProperties<T extends OptionValues>(): this & T;
+ storeOptionsAsProperties<T extends OptionValues>(storeAsProperties: true): this & T;
+ storeOptionsAsProperties(storeAsProperties?: boolean): this;
+
+ /**
+ * Retrieve option value.
+ */
+ getOptionValue(key: string): any;
+
+ /**
+ * Store option value.
+ */
+ setOptionValue(key: string, value: unknown): this;
+
+ /**
+ * Store option value and where the value came from.
+ */
+ setOptionValueWithSource(key: string, value: unknown, source: OptionValueSource): this;
+
+ /**
+ * Get source of option value.
+ */
+ getOptionValueSource(key: string): OptionValueSource | undefined;
+
+ /**
+ * Get source of option value. See also .optsWithGlobals().
+ */
+ getOptionValueSourceWithGlobals(key: string): OptionValueSource | undefined;
+
+ /**
+ * Alter parsing of short flags with optional values.
+ *
+ * @example
+ * ```
+ * // for `.option('-f,--flag [value]'):
+ * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
+ * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
+ * ```
+ *
+ * @returns `this` command for chaining
+ */
+ combineFlagAndOptionalValue(combine?: boolean): this;
+
+ /**
+ * Allow unknown options on the command line.
+ *
+ * @returns `this` command for chaining
+ */
+ allowUnknownOption(allowUnknown?: boolean): this;
+
+ /**
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
+ *
+ * @returns `this` command for chaining
+ */
+ allowExcessArguments(allowExcess?: boolean): this;
+
+ /**
+ * Enable positional options. Positional means global options are specified before subcommands which lets
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
+ *
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
+ *
+ * @returns `this` command for chaining
+ */
+ enablePositionalOptions(positional?: boolean): this;
+
+ /**
+ * Pass through options that come after command-arguments rather than treat them as command-options,
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
+ * positional options to have been enabled on the program (parent commands).
+ *
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
+ *
+ * @returns `this` command for chaining
+ */
+ passThroughOptions(passThrough?: boolean): this;
+
+ /**
+ * Parse `argv`, setting options and invoking commands when defined.
+ *
+ * The default expectation is that the arguments are from node and have the application as argv[0]
+ * and the script being run in argv[1], with user parameters after that.
+ *
+ * @example
+ * ```
+ * program.parse(process.argv);
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
+ * ```
+ *
+ * @returns `this` command for chaining
+ */
+ parse(argv?: readonly string[], options?: ParseOptions): this;
+
+ /**
+ * Parse `argv`, setting options and invoking commands when defined.
+ *
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
+ *
+ * The default expectation is that the arguments are from node and have the application as argv[0]
+ * and the script being run in argv[1], with user parameters after that.
+ *
+ * @example
+ * ```
+ * program.parseAsync(process.argv);
+ * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
+ * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
+ * ```
+ *
+ * @returns Promise
+ */
+ parseAsync(argv?: readonly string[], options?: ParseOptions): Promise<this>;
+
+ /**
+ * Parse options from `argv` removing known options,
+ * and return argv split into operands and unknown arguments.
+ *
+ * argv => operands, unknown
+ * --known kkk op => [op], []
+ * op --known kkk => [op], []
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
+ */
+ parseOptions(argv: string[]): ParseOptionsResult;
+
+ /**
+ * Return an object containing local option values as key-value pairs
+ */
+ opts<T extends OptionValues>(): T;
+
+ /**
+ * Return an object containing merged local and global option values as key-value pairs.
+ */
+ optsWithGlobals<T extends OptionValues>(): T;
+
+ /**
+ * Set the description.
+ *
+ * @returns `this` command for chaining
+ */
+
+ description(str: string): this;
+ /** @deprecated since v8, instead use .argument to add command argument with description */
+ description(str: string, argsDescription: Record<string, string>): this;
+ /**
+ * Get the description.
+ */
+ description(): string;
+
+ /**
+ * Set the summary. Used when listed as subcommand of parent.
+ *
+ * @returns `this` command for chaining
+ */
+
+ summary(str: string): this;
+ /**
+ * Get the summary.
+ */
+ summary(): string;
+
+ /**
+ * Set an alias for the command.
+ *
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
+ *
+ * @returns `this` command for chaining
+ */
+ alias(alias: string): this;
+ /**
+ * Get alias for the command.
+ */
+ alias(): string;
+
+ /**
+ * Set aliases for the command.
+ *
+ * Only the first alias is shown in the auto-generated help.
+ *
+ * @returns `this` command for chaining
+ */
+ aliases(aliases: readonly string[]): this;
+ /**
+ * Get aliases for the command.
+ */
+ aliases(): string[];
+
+ /**
+ * Set the command usage.
+ *
+ * @returns `this` command for chaining
+ */
+ usage(str: string): this;
+ /**
+ * Get the command usage.
+ */
+ usage(): string;
+
+ /**
+ * Set the name of the command.
+ *
+ * @returns `this` command for chaining
+ */
+ name(str: string): this;
+ /**
+ * Get the name of the command.
+ */
+ name(): string;
+
+ /**
+ * Set the name of the command from script filename, such as process.argv[1],
+ * or require.main.filename, or __filename.
+ *
+ * (Used internally and public although not documented in README.)
+ *
+ * @example
+ * ```ts
+ * program.nameFromFilename(require.main.filename);
+ * ```
+ *
+ * @returns `this` command for chaining
+ */
+ nameFromFilename(filename: string): this;
+
+ /**
+ * Set the directory for searching for executable subcommands of this command.
+ *
+ * @example
+ * ```ts
+ * program.executableDir(__dirname);
+ * // or
+ * program.executableDir('subcommands');
+ * ```
+ *
+ * @returns `this` command for chaining
+ */
+ executableDir(path: string): this;
+ /**
+ * Get the executable search directory.
+ */
+ executableDir(): string;
+
+ /**
+ * Output help information for this command.
+ *
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
+ *
+ */
+ outputHelp(context?: HelpContext): void;
+ /** @deprecated since v7 */
+ outputHelp(cb?: (str: string) => string): void;
+
+ /**
+ * Return command help documentation.
+ */
+ helpInformation(context?: HelpContext): string;
+
+ /**
+ * You can pass in flags and a description to override the help
+ * flags and help description for your command. Pass in false
+ * to disable the built-in help option.
+ */
+ helpOption(flags?: string | boolean, description?: string): this;
+
+ /**
+ * Output help information and exit.
+ *
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
+ */
+ help(context?: HelpContext): never;
+ /** @deprecated since v7 */
+ help(cb?: (str: string) => string): never;
+
+ /**
+ * Add additional text to be displayed with the built-in help.
+ *
+ * Position is 'before' or 'after' to affect just this command,
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
+ */
+ addHelpText(position: AddHelpTextPosition, text: string): this;
+ addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string): this;
+
+ /**
+ * Add a listener (callback) for when events occur. (Implemented using EventEmitter.)
+ */
+ on(event: string | symbol, listener: (...args: any[]) => void): this;
+}
+export interface CommandOptions {
+ hidden?: boolean;
+ isDefault?: boolean;
+ /** @deprecated since v7, replaced by hidden */
+ noHelp?: boolean;
+}
+export interface ExecutableCommandOptions extends CommandOptions {
+ executableFile?: string;
}
-declare const commander: commander.CommanderStatic;
-export = commander;
+export interface ParseOptionsResult {
+ operands: string[];
+ unknown: string[];
+}
+
+export function createCommand(name?: string): Command;
+export function createOption(flags: string, description?: string): Option;
+export function createArgument(name: string, description?: string): Argument;
+
+export const program: Command;