diff options
Diffstat (limited to 'node_modules/commander')
| -rw-r--r-- | node_modules/commander/CHANGELOG.md | 642 | ||||
| -rw-r--r-- | node_modules/commander/Readme.md | 814 | ||||
| -rw-r--r-- | node_modules/commander/esm.mjs | 4 | ||||
| -rw-r--r-- | node_modules/commander/index.js | 3278 | ||||
| -rw-r--r-- | node_modules/commander/package-support.json | 16 | ||||
| -rw-r--r-- | node_modules/commander/package.json | 59 | ||||
| -rw-r--r-- | node_modules/commander/typings/index.d.ts | 490 |
7 files changed, 2082 insertions, 3221 deletions
diff --git a/node_modules/commander/CHANGELOG.md b/node_modules/commander/CHANGELOG.md index 0b55881b..f00cb2b5 100644 --- a/node_modules/commander/CHANGELOG.md +++ b/node_modules/commander/CHANGELOG.md @@ -6,435 +6,431 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). (Format adopted after v3.0.0.) <!-- markdownlint-disable MD024 --> -<!-- markdownlint-disable MD004 --> -## [7.2.0] (2021-03-26) +## [4.1.1] (2020-02-02) -### Added - -- TypeScript typing for `parent` property on `Command` ([#1475]) -- TypeScript typing for `.attributeName()` on `Option` ([#1483]) -- support information in package ([#1477]) - -### Changed +### Fixed -- improvements to error messages, README, and tests -- update dependencies +* TypeScript definition for `.action()` should include Promise for async ([#1157]) -## [7.1.0] (2021-02-15) +## [4.1.0] (2020-01-06) ### Added -- support for named imports from ECMAScript modules ([#1440]) -- add `.cjs` to list of expected script file extensions ([#1449]) -- allow using option choices and variadic together ([#1454]) +* two routines to change how option values are handled, and eliminate name clashes with command properties ([#933] [#1102]) + * see storeOptionsAsProperties and passCommandToAction in README +* `.parseAsync` to use instead of `.parse` if supply async action handlers ([#806] [#1118]) ### Fixed -- replace use of deprecated `process.mainModule` ([#1448]) -- regression for legacy `command('*')` and call when command line includes options ([#1464]) -- regression for `on('command:*', ...)` and call when command line includes unknown options ([#1464]) -- display best error for combination of unknown command and unknown option (i.e. unknown command) ([#1464]) +* Remove trailing blanks from wrapped help text ([#1096]) ### Changed -- make TypeScript typings tests stricter ([#1453]) -- improvements to README and tests +* update dependencies +* extend security coverage for Commander 2.x to 2020-02-03 +* improvements to README +* improvements to TypeScript definition documentation +* move old versions out of main CHANGELOG +* removed explicit use of `ts-node` in tests + +## [4.0.1] (2019-11-12) + +### Fixed + +* display help when requested, even if there are missing required options ([#1091]) -## [7.0.0] (2021-01-15) +## [4.0.0] (2019-11-02) ### Added -- `.enablePositionalOptions()` to let program and subcommand reuse same option ([#1427]) -- `.passThroughOptions()` to pass options through to other programs without needing `--` ([#1427]) -- `.allowExcessArguments(false)` to show an error message if there are too many command-arguments on command line for the action handler ([#1409]) -- `.configureOutput()` to modify use of stdout and stderr or customise display of errors ([#1387]) -- use `.addHelpText()` to add text before or after the built-in help, for just current command or also for all subcommands ([#1296]) -- enhance Option class ([#1331]) - - allow hiding options from help - - allow restricting option arguments to a list of choices - - allow setting how default value is shown in help -- `.createOption()` to support subclassing of automatically created options (like `.createCommand()`) ([#1380]) -- refactor the code generating the help into a separate public Help class ([#1365]) - - support sorting subcommands and options in help - - support specifying wrap width (columns) - - allow subclassing Help class - - allow configuring Help class without subclassing +* automatically wrap and indent help descriptions for options and commands ([#1051]) +* `.exitOverride()` allows override of calls to `process.exit` for additional error handling and to keep program running ([#1040]) +* support for declaring required options with `.requiredOptions()` ([#1071]) +* GitHub Actions support ([#1027]) +* translation links in README ### Changed -- *Breaking:* options are stored safely by default, not as properties on the command ([#1409]) - - this especially affects accessing options on program, use `program.opts()` - - revert behaviour with `.storeOptionsAsProperties()` -- *Breaking:* action handlers are passed options and command separately ([#1409]) -- deprecated callback parameter to `.help()` and `.outputHelp()` (removed from README) ([#1296]) -- *Breaking:* errors now displayed using `process.stderr.write()` instead of `console.error()` -- deprecate `.on('--help')` (removed from README) ([#1296]) -- initialise the command description to empty string (previously undefined) ([#1365]) -- document and annotate deprecated routines ([#1349]) +* dev: switch tests from Sinon+Should to Jest with major rewrite of tests ([#1035]) +* call default subcommand even when there are unknown options ([#1047]) +* *Breaking* Commander is only officially supported on Node 8 and above, and requires Node 6 ([#1053]) ### Fixed -- wrapping bugs in help ([#1365]) - - first line of command description was wrapping two characters early - - pad width calculation was not including help option and help command - - pad width calculation was including hidden options and commands -- improve backwards compatibility for custom command event listeners ([#1403]) - -### Deleted - -- *Breaking:* `.passCommandToAction()` ([#1409]) - - no longer needed as action handler is passed options and command -- *Breaking:* "extra arguments" parameter to action handler ([#1409]) - - if being used to detect excess arguments, there is now an error available by setting `.allowExcessArguments(false)` +* *Breaking* keep command object out of program.args when action handler called ([#1048]) + * also, action handler now passed array of unknown arguments +* complain about unknown options when program argument supplied and action handler ([#1049]) + * this changes parameters to `command:*` event to include unknown arguments +* removed deprecated `customFds` option from call to `child_process.spawn` ([#1052]) +* rework TypeScript declarations to bring all types into imported namespace ([#1081]) ### Migration Tips -The biggest change is the parsed option values. Previously the options were stored by default as properties on the command object, and now the options are stored separately. - -If you wish to restore the old behaviour and get running quickly you can call `.storeOptionsAsProperties()`. -To allow you to move to the new code patterns incrementally, the action handler will be passed the command _twice_, -to match the new "options" and "command" parameters (see below). +#### Testing for no arguments -**program options** - -Use the `.opts()` method to access the options. This is available on any command but is used most with the program. +If you were previously using code like: ```js -program.option('-d, --debug'); -program.parse(); -// Old code before Commander 7 -if (program.debug) console.log(`Program name is ${program.name()}`); +if (!program.args.length) ... ``` +a partial replacement is: + ```js -// New code -const options = program.opts(); -if (options.debug) console.log(`Program name is ${program.name()}`); +if (program.rawArgs.length < 3) ... ``` -**action handler** +## [4.0.0-1] Prerelease (2019-10-08) -The action handler gets passed a parameter for each command-argument you declared. Previously by default the next parameter was the command object with the options as properties. Now the next two parameters are instead the options and the command. If you -only accessed the options there may be no code changes required. +(Released in 4.0.0) -```js -program - .command('compress <filename>') - .option('-t, --trace') - // Old code before Commander 7 - .action((filename, cmd)) => { - if (cmd.trace) console.log(`Command name is ${cmd.name()}`); - }); -``` +## [4.0.0-0] Prerelease (2019-10-01) -```js - // New code - .action((filename, options, command)) => { - if (options.trace) console.log(`Command name is ${command.name()}`); - }); -``` +(Released in 4.0.0) -If you already set `.storeOptionsAsProperties(false)` you may still need to adjust your code. +## [2.20.1] (2019-09-29) -```js -program - .command('compress <filename>') - .storeOptionsAsProperties(false) - .option('-t, --trace') - // Old code before Commander 7 - .action((filename, command)) => { - if (command.opts().trace) console.log(`Command name is ${command.name()}`); - }); -``` +### Fixed -```js - // New code - .action((filename, options, command)) => { - if (command.opts().trace) console.log(`Command name is ${command.name()}`); - }); -``` +* Improve tracking of executable subcommands. -## [7.0.0-2] (2020-12-14) +### Changed -(Released in 7.0.0) +* update development dependencies -## [7.0.0-1] (2020-11-21) +## [3.0.2] (2019-09-27) -(Released in 7.0.0) +### Fixed -## [7.0.0-0] (2020-10-25) +* Improve tracking of executable subcommands. -(Released in 7.0.0) +### Changed -## [6.2.1] (2020-12-13) +* update development dependencies -### Fixed +## [3.0.1] (2019-08-30) -- some tests failed if directory path included a space ([1390]) +### Added -## [6.2.0] (2020-10-25) +* .name and .usage to README ([#1010]) +* Table of Contents to README ([#1010]) +* TypeScript definition for `executableFile` in CommandOptions ([#1028]) -### Added +### Changed + +* consistently use `const` rather than `var` in README ([#1026]) -- added 'tsx' file extension for stand-alone executable subcommands ([#1368]) -- documented second parameter to `.description()` to describe command arguments ([#1353]) -- documentation of special cases with options taking varying numbers of option-arguments ([#1332]) -- documentation for terminology ([#1361]) - ### Fixed -- add missing TypeScript definition for `.addHelpCommand()' ([#1375]) -- removed blank line after "Arguments:" in help, to match "Options:" and "Commands:" ([#1360]) +* help for sub commands with custom executableFile ([#1018]) + +## [3.0.0] / 2019-08-08 + +* Add option to specify executable file name ([#999]) + * e.g. `.command('clone', 'clone description', { executableFile: 'myClone' })` +* Change docs for `.command` to contrast action handler vs git-style executable. ([#938] [#990]) +* **Breaking** Change TypeScript to use overloaded function for `.command`. ([#938] [#990]) +* Change to use straight quotes around strings in error messages (like 'this' instead of `this') ([#915]) +* Add TypeScript "reference types" for node ([#974]) +* Add support for hyphen as an option argument in subcommands ([#697]) +* Add support for a short option flag and its value to be concatenated for action handler subcommands ([#599]) + * e.g. `-p 80` can also be supplied as `-p80` +* Add executable arguments to spawn in win32, for git-style executables ([#611]) + * e.g. `node --harmony myCommand.js clone` +* Add parent command as prefix of subcommand in help ([#980]) +* Add optional custom description to `.version` ([#963]) + * e.g. `program.version('0.0.1', '-v, --vers', 'output the current version')` +* Add `.helpOption(flags, description)` routine to customise help flags and description ([#963]) + * e.g. `.helpOption('-e, --HELP', 'read more information')` +* Fix behavior of --no-* options ([#795]) + * can now define both `--foo` and `--no-foo` + * **Breaking** custom event listeners: `--no-foo` on cli now emits `option:no-foo` (previously `option:foo`) + * **Breaking** default value: defining `--no-foo` after defining `--foo` leaves the default value unchanged (previously set it to false) + * allow boolean default value, such as from environment ([#987]) +* Increment inspector port for spawned subcommands ([#991]) + * e.g. `node --inspect myCommand.js clone` -### Changed +### Migration Tips -- update dependencies +The custom event for a negated option like `--no-foo` is `option:no-foo` (previously `option:foo`). -## [6.1.0] (2020-08-28) +```js +program + .option('--no-foo') + .on('option:no-foo', () => { + console.log('removing foo'); + }); +``` -### Added +When using TypeScript, adding a command does not allow an explicit `undefined` for an unwanted executable description (e.g +for a command with an action handler). -- include URL to relevant section of README for error for potential conflict between Command properties and option values ([#1306]) -- `.combineFlagAndOptionalValue(false)` to ease upgrade path from older versions of Commander ([#1326]) -- allow disabling the built-in help option using `.helpOption(false)` ([#1325]) -- allow just some arguments in `argumentDescription` to `.description()` ([#1323]) +```js +program + .command('action1', undefined, { noHelp: true }) // No longer valid + .command('action2', { noHelp: true }) // Correct +``` -### Changed +## 3.0.0-0 Prerelease / 2019-07-28 -- tidy async test and remove lint override ([#1312]) +(Released as 3.0.0) -### Fixed +## 2.20.0 / 2019-04-02 -- executable subcommand launching when script path not known ([#1322]) +* 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) -## [6.0.0] (2020-07-21) +## 2.19.0 / 2018-10-02 -### Added +* Removed newline after Options and Commands headers (#864) +* Bugfix - Error output (#862) +* Fix to change default value to string (#856) -- add support for variadic options ([#1250]) -- allow options to be added with just a short flag ([#1256]) - - *Breaking* the option property has same case as flag. e.g. flag `-n` accessed as `opts().n` (previously uppercase) -- *Breaking* throw an error if there might be a clash between option name and a Command property, with advice on how to resolve ([#1275]) +## 2.18.0 / 2018-09-07 -### Fixed +* Standardize help output (#853) +* chmod 644 travis.yml (#851) +* add support for execute typescript subcommand via ts-node (#849) -- Options which contain -no- in the middle of the option flag should not be treated as negatable. ([#1301]) +## 2.17.1 / 2018-08-07 -## [6.0.0-0] (2020-06-20) +* 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) -(Released in 6.0.0) +## 2.15.0 / 2018-03-07 -## [5.1.0] (2020-04-25) +* Update downloads badge to point to graph of downloads over time instead of duplicating link to npm +* Arguments description -### Added +## 2.14.1 / 2018-02-07 -- support for multiple command aliases, the first of which is shown in the auto-generated help ([#531], [#1236]) -- configuration support in `addCommand()` for `hidden` and `isDefault` ([#1232]) +* Fix typing of help function -### Fixed +## 2.14.0 / 2018-02-05 -- omit masked help flags from the displayed help ([#645], [#1247]) -- remove old short help flag when change help flags using `helpOption` ([#1248]) +* 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 -### Changed +## 2.13.0 / 2018-01-09 -- remove use of `arguments` to improve auto-generated help in editors ([#1235]) -- rename `.command()` configuration `noHelp` to `hidden` (but not remove old support) ([#1232]) -- improvements to documentation -- update dependencies -- update tested versions of node -- eliminate lint errors in TypeScript ([#1208]) +* 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 -## [5.0.0] (2020-03-14) +## 2.12.2 / 2017-11-28 -### Added +* fix: typings are not shipped -* support for nested commands with action-handlers ([#1] [#764] [#1149]) -* `.addCommand()` for adding a separately configured command ([#764] [#1149]) -* allow a non-executable to be set as the default command ([#742] [#1149]) -* implicit help command when there are subcommands (previously only if executables) ([#1149]) -* customise implicit help command with `.addHelpCommand()` ([#1149]) -* display error message for unknown subcommand, by default ([#432] [#1088] [#1149]) -* display help for missing subcommand, by default ([#1088] [#1149]) -* combined short options as single argument may include boolean flags and value flag and value (e.g. `-a -b -p 80` can be written as `-abp80`) ([#1145]) -* `.parseOption()` includes short flag and long flag expansions ([#1145]) -* `.helpInformation()` returns help text as a string, previously a private routine ([#1169]) -* `.parse()` implicitly uses `process.argv` if arguments not specified ([#1172]) -* optionally specify where `.parse()` arguments "from", if not following node conventions ([#512] [#1172]) -* suggest help option along with unknown command error ([#1179]) -* TypeScript definition for `commands` property of `Command` ([#1184]) -* export `program` property ([#1195]) -* `createCommand` factory method to simplify subclassing ([#1191]) +## 2.12.1 / 2017-11-23 -### Fixed +* Move @types/node to dev dependency -* preserve argument order in subcommands ([#508] [#962] [#1138]) -* do not emit `command:*` for executable subcommands ([#809] [#1149]) -* action handler called whether or not there are non-option arguments ([#1062] [#1149]) -* combining option short flag and value in single argument now works for subcommands ([#1145]) -* only add implicit help command when it will not conflict with other uses of argument ([#1153] [#1149]) -* implicit help command works with command aliases ([#948] [#1149]) -* options are validated whether or not there is an action handler ([#1149]) +## 2.12.0 / 2017-11-22 -### Changed +* 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 -* *Breaking* `.args` contains command arguments with just recognised options removed ([#1032] [#1138]) -* *Breaking* display error if required argument for command is missing ([#995] [#1149]) -* tighten TypeScript definition of custom option processing function passed to `.option()` ([#1119]) -* *Breaking* `.allowUnknownOption()` ([#802] [#1138]) - * unknown options included in arguments passed to command action handler - * unknown options included in `.args` -* only recognised option short flags and long flags are expanded (e.g. `-ab` or `--foo=bar`) ([#1145]) -* *Breaking* `.parseOptions()` ([#1138]) - * `args` in returned result renamed `operands` and does not include anything after first unknown option - * `unknown` in returned result has arguments after first unknown option including operands, not just options and values -* *Breaking* `.on('command:*', callback)` and other command events passed (changed) results from `.parseOptions`, i.e. operands and unknown ([#1138]) -* refactor Option from prototype to class ([#1133]) -* refactor Command from prototype to class ([#1159]) -* changes to error handling ([#1165]) - * throw for author error, not just display message - * preflight for variadic error - * add tips to missing subcommand executable -* TypeScript fluent return types changed to be more subclass friendly, return `this` rather than `Command` ([#1180]) -* `.parseAsync` returns `Promise<this>` to be consistent with `.parse()` ([#1180]) -* update dependencies +## 2.11.0 / 2017-07-03 -### Removed +* 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 -* removed EventEmitter from TypeScript definition for Command, eliminating implicit peer dependency on `@types/node` ([#1146]) -* removed private function `normalize` (the functionality has been integrated into `parseOptions`) ([#1145]) -* `parseExpectedArgs` is now private ([#1149]) +## 2.10.0 / 2017-06-19 -### Migration Tips +* 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 -If you use `.on('command:*')` or more complicated tests to detect an unrecognised subcommand, you may be able to delete the code and rely on the default behaviour. +## 2.5.1 / 2014-12-15 -If you use `program.args` or more complicated tests to detect a missing subcommand, you may be able to delete the code and rely on the default behaviour. +* fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee -If you use `.command('*')` to add a default command, you may be be able to switch to `isDefault:true` with a named command. +## 2.5.0 / 2014-10-24 -If you want to continue combining short options with optional values as though they were boolean flags, set `combineFlagAndOptionalValue(false)` -to expand `-fb` to `-f -b` rather than `-f b`. +* add support for variadic arguments. Closes #277 @whitlockjc -## [5.0.0-4] (2020-03-03) +## 2.4.0 / 2014-10-17 -(Released in 5.0.0) +* 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 -## [5.0.0-3] (2020-02-20) +## 2.3.0 / 2014-07-16 -(Released in 5.0.0) +* add command alias'. Closes PR #210 +* fix: Typos. Closes #99 +* fix: Unused fs module. Closes #217 -## [5.0.0-2] (2020-02-10) +## 2.2.0 / 2014-03-29 -(Released in 5.0.0) +* 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. -## [5.0.0-1] (2020-02-08) +## 2.1.0 / 2013-11-21 -(Released in 5.0.0) +* add: allow cflag style option params, unit test, fixes #174 -## [5.0.0-0] (2020-02-02) +## 2.0.0 / 2013-07-18 -(Released in 5.0.0) +* remove input methods (.prompt, .confirm, etc) ## Older versions -* [4.x](./changelogs/CHANGELOG-4.md) -* [3.x](./changelogs/CHANGELOG-3.md) -* [2.x](./changelogs/CHANGELOG-2.md) * [1.x](./changelogs/CHANGELOG-1.md) * [0.x](./changelogs/CHANGELOG-0.md) -[#1]: https://github.com/tj/commander.js/issues/1 -[#432]: https://github.com/tj/commander.js/issues/432 -[#508]: https://github.com/tj/commander.js/issues/508 -[#512]: https://github.com/tj/commander.js/issues/512 -[#531]: https://github.com/tj/commander.js/issues/531 -[#645]: https://github.com/tj/commander.js/issues/645 -[#742]: https://github.com/tj/commander.js/issues/742 -[#764]: https://github.com/tj/commander.js/issues/764 -[#802]: https://github.com/tj/commander.js/issues/802 -[#809]: https://github.com/tj/commander.js/issues/809 -[#948]: https://github.com/tj/commander.js/issues/948 -[#962]: https://github.com/tj/commander.js/issues/962 -[#995]: https://github.com/tj/commander.js/issues/995 -[#1032]: https://github.com/tj/commander.js/issues/1032 -[#1062]: https://github.com/tj/commander.js/pull/1062 -[#1088]: https://github.com/tj/commander.js/issues/1088 -[#1119]: https://github.com/tj/commander.js/pull/1119 -[#1133]: https://github.com/tj/commander.js/pull/1133 -[#1138]: https://github.com/tj/commander.js/pull/1138 -[#1145]: https://github.com/tj/commander.js/pull/1145 -[#1146]: https://github.com/tj/commander.js/pull/1146 -[#1149]: https://github.com/tj/commander.js/pull/1149 -[#1153]: https://github.com/tj/commander.js/issues/1153 -[#1159]: https://github.com/tj/commander.js/pull/1159 -[#1165]: https://github.com/tj/commander.js/pull/1165 -[#1169]: https://github.com/tj/commander.js/pull/1169 -[#1172]: https://github.com/tj/commander.js/pull/1172 -[#1179]: https://github.com/tj/commander.js/pull/1179 -[#1180]: https://github.com/tj/commander.js/pull/1180 -[#1184]: https://github.com/tj/commander.js/pull/1184 -[#1191]: https://github.com/tj/commander.js/pull/1191 -[#1195]: https://github.com/tj/commander.js/pull/1195 -[#1208]: https://github.com/tj/commander.js/pull/1208 -[#1232]: https://github.com/tj/commander.js/pull/1232 -[#1235]: https://github.com/tj/commander.js/pull/1235 -[#1236]: https://github.com/tj/commander.js/pull/1236 -[#1247]: https://github.com/tj/commander.js/pull/1247 -[#1248]: https://github.com/tj/commander.js/pull/1248 -[#1250]: https://github.com/tj/commander.js/pull/1250 -[#1256]: https://github.com/tj/commander.js/pull/1256 -[#1275]: https://github.com/tj/commander.js/pull/1275 -[#1296]: https://github.com/tj/commander.js/pull/1296 -[#1301]: https://github.com/tj/commander.js/issues/1301 -[#1306]: https://github.com/tj/commander.js/pull/1306 -[#1312]: https://github.com/tj/commander.js/pull/1312 -[#1322]: https://github.com/tj/commander.js/pull/1322 -[#1323]: https://github.com/tj/commander.js/pull/1323 -[#1325]: https://github.com/tj/commander.js/pull/1325 -[#1326]: https://github.com/tj/commander.js/pull/1326 -[#1331]: https://github.com/tj/commander.js/pull/1331 -[#1332]: https://github.com/tj/commander.js/pull/1332 -[#1349]: https://github.com/tj/commander.js/pull/1349 -[#1353]: https://github.com/tj/commander.js/pull/1353 -[#1360]: https://github.com/tj/commander.js/pull/1360 -[#1361]: https://github.com/tj/commander.js/pull/1361 -[#1365]: https://github.com/tj/commander.js/pull/1365 -[#1368]: https://github.com/tj/commander.js/pull/1368 -[#1375]: https://github.com/tj/commander.js/pull/1375 -[#1380]: https://github.com/tj/commander.js/pull/1380 -[#1387]: https://github.com/tj/commander.js/pull/1387 -[#1390]: https://github.com/tj/commander.js/pull/1390 -[#1403]: https://github.com/tj/commander.js/pull/1403 -[#1409]: https://github.com/tj/commander.js/pull/1409 -[#1427]: https://github.com/tj/commander.js/pull/1427 -[#1440]: https://github.com/tj/commander.js/pull/1440 -[#1448]: https://github.com/tj/commander.js/pull/1448 -[#1449]: https://github.com/tj/commander.js/pull/1449 -[#1453]: https://github.com/tj/commander.js/pull/1453 -[#1454]: https://github.com/tj/commander.js/pull/1454 -[#1464]: https://github.com/tj/commander.js/pull/1464 -[#1475]: https://github.com/tj/commander.js/pull/1475 -[#1477]: https://github.com/tj/commander.js/pull/1477 -[#1483]: https://github.com/tj/commander.js/pull/1483 +[#599]: https://github.com/tj/commander.js/issues/599 +[#611]: https://github.com/tj/commander.js/issues/611 +[#697]: https://github.com/tj/commander.js/issues/697 +[#795]: https://github.com/tj/commander.js/issues/795 +[#806]: https://github.com/tj/commander.js/issues/806 +[#915]: https://github.com/tj/commander.js/issues/915 +[#938]: https://github.com/tj/commander.js/issues/938 +[#963]: https://github.com/tj/commander.js/issues/963 +[#974]: https://github.com/tj/commander.js/issues/974 +[#980]: https://github.com/tj/commander.js/issues/980 +[#987]: https://github.com/tj/commander.js/issues/987 +[#990]: https://github.com/tj/commander.js/issues/990 +[#991]: https://github.com/tj/commander.js/issues/991 +[#993]: https://github.com/tj/commander.js/issues/993 +[#999]: https://github.com/tj/commander.js/issues/999 +[#1010]: https://github.com/tj/commander.js/pull/1010 +[#1018]: https://github.com/tj/commander.js/pull/1018 +[#1026]: https://github.com/tj/commander.js/pull/1026 +[#1027]: https://github.com/tj/commander.js/pull/1027 +[#1028]: https://github.com/tj/commander.js/pull/1028 +[#1035]: https://github.com/tj/commander.js/pull/1035 +[#1040]: https://github.com/tj/commander.js/pull/1040 +[#1047]: https://github.com/tj/commander.js/pull/1047 +[#1048]: https://github.com/tj/commander.js/pull/1048 +[#1049]: https://github.com/tj/commander.js/pull/1049 +[#1051]: https://github.com/tj/commander.js/pull/1051 +[#1052]: https://github.com/tj/commander.js/pull/1052 +[#1053]: https://github.com/tj/commander.js/pull/1053 +[#1071]: https://github.com/tj/commander.js/pull/1071 +[#1081]: https://github.com/tj/commander.js/pull/1081 +[#1091]: https://github.com/tj/commander.js/pull/1091 +[#1096]: https://github.com/tj/commander.js/pull/1096 +[#1102]: https://github.com/tj/commander.js/pull/1102 +[#1118]: https://github.com/tj/commander.js/pull/1118 +[#1157]: https://github.com/tj/commander.js/pull/1157 [Unreleased]: https://github.com/tj/commander.js/compare/master...develop -[7.2.0]: https://github.com/tj/commander.js/compare/v7.1.0...v7.2.0 -[7.1.0]: https://github.com/tj/commander.js/compare/v7.0.0...v7.1.0 -[7.0.0]: https://github.com/tj/commander.js/compare/v6.2.1...v7.0.0 -[7.0.0-2]: https://github.com/tj/commander.js/compare/v7.0.0-1...v7.0.0-2 -[7.0.0-1]: https://github.com/tj/commander.js/compare/v7.0.0-0...v7.0.0-1 -[7.0.0-0]: https://github.com/tj/commander.js/compare/v6.2.0...v7.0.0-0 -[6.2.1]: https://github.com/tj/commander.js/compare/v6.2.0..v6.2.1 -[6.2.0]: https://github.com/tj/commander.js/compare/v6.1.0..v6.2.0 -[6.1.0]: https://github.com/tj/commander.js/compare/v6.0.0..v6.1.0 -[6.0.0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0 -[6.0.0-0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0-0 -[5.1.0]: https://github.com/tj/commander.js/compare/v5.0.0..v5.1.0 -[5.0.0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0 -[5.0.0-4]: https://github.com/tj/commander.js/compare/v5.0.0-3..v5.0.0-4 -[5.0.0-3]: https://github.com/tj/commander.js/compare/v5.0.0-2..v5.0.0-3 -[5.0.0-2]: https://github.com/tj/commander.js/compare/v5.0.0-1..v5.0.0-2 -[5.0.0-1]: https://github.com/tj/commander.js/compare/v5.0.0-0..v5.0.0-1 -[5.0.0-0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0-0 +[4.1.1]: https://github.com/tj/commander.js/compare/v4.0.0..v4.1.1 +[4.1.0]: https://github.com/tj/commander.js/compare/v4.0.1..v4.1.0 +[4.0.1]: https://github.com/tj/commander.js/compare/v4.0.0..v4.0.1 +[4.0.0]: https://github.com/tj/commander.js/compare/v3.0.2..v4.0.0 +[4.0.0-1]: https://github.com/tj/commander.js/compare/v4.0.0-0..v4.0.0-1 +[4.0.0-0]: https://github.com/tj/commander.js/compare/v3.0.2...v4.0.0-0 +[3.0.2]: https://github.com/tj/commander.js/compare/v3.0.1...v3.0.2 +[3.0.1]: https://github.com/tj/commander.js/compare/v3.0.0...v3.0.1 +[3.0.0]: https://github.com/tj/commander.js/compare/v2.20.1...v3.0.0 +[2.20.1]: https://github.com/tj/commander.js/compare/v2.20.0...v2.20.1 diff --git a/node_modules/commander/Readme.md b/node_modules/commander/Readme.md index d2a88a7b..aa4f42b5 100644 --- a/node_modules/commander/Readme.md +++ b/node_modules/commander/Readme.md @@ -1,54 +1,46 @@ # Commander.js -[](https://github.com/tj/commander.js/actions?query=workflow%3A%22build%22) +[](http://travis-ci.org/tj/commander.js) [](https://www.npmjs.org/package/commander) [](https://npmcharts.com/compare/commander?minimal=true) [](https://packagephobia.now.sh/result?p=commander) -The complete solution for [node.js](http://nodejs.org) command-line interfaces. +The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander). Read this in other languages: English | [简体中文](./Readme_zh-CN.md) - [Commander.js](#commanderjs) - [Installation](#installation) - - [Declaring _program_ variable](#declaring-program-variable) + - [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) + - [Other option types, negatable boolean and flag|value](#other-option-types-negatable-boolean-and-flagvalue) + - [Custom option processing](#custom-option-processing) - [Required option](#required-option) - - [Variadic option](#variadic-option) - [Version option](#version-option) - - [More configuration](#more-configuration) - - [Custom option processing](#custom-option-processing) - [Commands](#commands) - [Specify the argument syntax](#specify-the-argument-syntax) - - [Action handler](#action-handler) - - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands) - - [Automated help](#automated-help) + - [Action handler (sub)commands](#action-handler-subcommands) + - [Git-style executable (sub)commands](#git-style-executable-subcommands) + - [Automated --help](#automated---help) - [Custom help](#custom-help) - - [Display help from code](#display-help-from-code) - [.usage and .name](#usage-and-name) + - [.outputHelp(cb)](#outputhelpcb) - [.helpOption(flags, description)](#helpoptionflags-description) - - [.addHelpCommand()](#addhelpcommand) - - [More configuration](#more-configuration-1) + - [.help(cb)](#helpcb) - [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) + - [Avoiding option name clashes](#avoiding-option-name-clashes) - [TypeScript](#typescript) - - [createCommand()](#createcommand) - - [Node options such as `--harmony`](#node-options-such-as---harmony) - - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands) - - [Override exit and output handling](#override-exit-and-output-handling) - - [Additional documentation](#additional-documentation) + - [Node options such as --harmony](#node-options-such-as---harmony) + - [Node debugging](#node-debugging) + - [Override exit handling](#override-exit-handling) - [Examples](#examples) + - [License](#license) - [Support](#support) - [Commander for enterprise](#commander-for-enterprise) -For information about terms used in this document see: [terminology](./docs/terminology.md) - ## Installation ```bash @@ -61,56 +53,33 @@ Commander exports a global object which is convenient for quick programs. This is used in the examples in this README for brevity. ```js -const { program } = require('commander'); +const program = require('commander'); program.version('0.0.1'); ``` 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 -const { Command } = require('commander'); -const program = new Command(); -program.version('0.0.1'); -``` - -For named imports in ECMAScript modules, import from `commander/esm.mjs`. - -```js -// index.mjs -import { Command } from 'commander/esm.mjs'; -const program = new Command(); -``` - -And in TypeScript: - -```ts -// index.ts -import { Command } from 'commander'; -const program = new Command(); -``` - + ```js + const commander = require('commander'); + const program = new commander.Command(); + program.version('0.0.1'); + ``` ## 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. +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. -Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value). -For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`. +The options can be accessed as properties on the Command object. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. Multiple short flags may be combined as a single arg, for example `-abc` is equivalent to `-a -b -c`. -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. +See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes). ### 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) +The two most used option types are a boolean flag, and an option which takes a value (declared using angle brackets). Both are `undefined` unless specified on command line. ```js +const program = require('commander'); + program .option('-d, --debug', 'output extra debugging') .option('-s, --small', 'small pizza size') @@ -118,11 +87,10 @@ program program.parse(process.argv); -const options = program.opts(); -if (options.debug) console.log(options); +if (program.debug) console.log(program.opts()); console.log('pizza details:'); -if (options.small) console.log('- small pizza size'); -if (options.pizzaType) console.log(`- ${options.pizzaType}`); +if (program.small) console.log('- small pizza size'); +if (program.pizzaType) console.log(`- ${program.pizzaType}`); ``` ```bash @@ -141,21 +109,21 @@ pizza details: - cheese ``` -`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`. +`program.parse(arguments)` processes the arguments, leaving any args not consumed by the options as the `program.args` array. ### Default option value You can specify a default value for an option which takes a value. -Example file: [options-defaults.js](./examples/options-defaults.js) - ```js +const program = require('commander'); + program .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue'); -program.parse(); +program.parse(process.argv); -console.log(`cheese: ${program.opts().cheese}`); +console.log(`cheese: ${program.cheese}`); ``` ```bash @@ -165,26 +133,25 @@ $ pizza-options --cheese stilton cheese: stilton ``` -### Other option types, negatable boolean and boolean|value +### Other option types, negatable boolean and flag|value -You can define a boolean option long name with a leading `no-` to set the option value to false when used. +You can specify 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. You can specify a default boolean value for a boolean option and it can be overridden on command line. - -Example file: [options-negatable.js](./examples/options-negatable.js) +otherwise be. You can specify a default boolean value for a boolean flag and it can be overridden on command line. ```js +const program = require('commander'); + program .option('--no-sauce', 'Remove sauce') .option('--cheese <flavour>', 'cheese flavour', 'mozzarella') .option('--no-cheese', 'plain with no cheese') - .parse(); + .parse(process.argv); -const options = program.opts(); -const sauceStr = options.sauce ? 'sauce' : 'no sauce'; -const cheeseStr = (options.cheese === false) ? 'no cheese' : `${options.cheese} cheese`; +const sauceStr = program.sauce ? 'sauce' : 'no sauce'; +const cheeseStr = (program.cheese === false) ? 'no cheese' : `${program.cheese} cheese`; console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`); ``` @@ -199,21 +166,19 @@ $ pizza-options --no-sauce --no-cheese You ordered a pizza with no sauce and no cheese ``` -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]`). - -Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js) +You can specify an option which functions as a flag but may also take a value (declared using square brackets). ```js +const program = require('commander'); + program .option('-c, --cheese [type]', 'Add cheese with optional type'); 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}`); +if (program.cheese === undefined) console.log('no cheese'); +else if (program.cheese === true) console.log('add cheese'); +else console.log(`add cheese type ${program.cheese}`); ``` ```bash @@ -225,126 +190,21 @@ $ pizza-options --cheese mozzarella add cheese type mozzarella ``` -For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md). - -### Required option - -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. - -Example file: [options-required.js](./examples/options-required.js) - -```js -program - .requiredOption('-c, --cheese <type>', 'pizza must have cheese'); - -program.parse(); -``` - -```bash -$ pizza -error: required option '-c, --cheese <type>' not specified -``` - -### Variadic option - -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 -program - .option('-n, --number <numbers...>', 'specify numbers') - .option('-l, --letter [letters...]', 'specify letters'); - -program.parse(); - -console.log('Options: ', program.opts()); -console.log('Remaining arguments: ', program.args); -``` - -```bash -$ 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'); -``` - -```bash -$ ./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 file: [options-extra.js](./examples/options-extra.js) - -```js -program - .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'])); -``` - -```bash -$ extra --help -Usage: help [options] - -Options: - -t, --timeout <delay> timeout in seconds (default: one minute) - -d, --drink <size> drink cup size (choices: "small", "medium", "large") - -h, --help display help for command - -$ extra --drink huge -error: option '-d, --drink <size>' argument 'huge' is invalid. Allowed choices are small, medium, large. -``` - ### 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. +You may specify a function to do custom processing of option values. The callback function receives two parameters, the user specified value and the +previous value for the option. It returns the new value for the option. -You can optionally specify the default/starting value for the option after the function parameter. +This allows you to coerce the option value to the desired type, or accumulate values, or do entirely custom processing. -Example file: [options-custom-processing.js](./examples/options-custom-processing.js) +You can optionally specify the default/starting value for the option after the function. ```js +const program = require('commander'); + function myParseInt(value, dummyPrevious) { - // parseInt takes a string and a radix - const parsedValue = parseInt(value, 10); - if (isNaN(parsedValue)) { - throw new commander.InvalidOptionArgumentError('Not a number.'); - } - return parsedValue; + // parseInt takes a string and an optional radix + return parseInt(value); } function increaseVerbosity(dummyValue, previous) { @@ -367,14 +227,13 @@ program .option('-l, --list <items>', 'comma separated list', commaSeparatedList) ; -program.parse(); +program.parse(process.argv); -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); +if (program.float !== undefined) console.log(`float: ${program.float}`); +if (program.integer !== undefined) console.log(`integer: ${program.integer}`); +if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`); +if (program.collect.length > 0) console.log(program.collect); +if (program.list !== undefined) console.log(program.list); ``` ```bash @@ -390,13 +249,47 @@ $ custom --list x,y,z [ 'x', 'y', 'z' ] ``` -## Commands +### Required option -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)). +You may specify a required (mandatory) option using `.requiredOption`. The option must be specified on the command line, or by having a default value. The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing. -In the first parameter to `.command()` you specify the command name and any command-arguments. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`. +```js +const program = require('commander'); + +program + .requiredOption('-c, --cheese <type>', 'pizza must have cheese'); -You can use `.addCommand()` to add an already configured subcommand to the program. +program.parse(process.argv); +``` + +``` +$ pizza +error: required option '-c, --cheese <type>' not specified +``` + +### 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'); +``` + +```bash +$ ./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. The version flags can be named anything, but a long name is required. + +```js +program.version('0.0.1', '-v, --vers', 'output the current version'); +``` + +## Commands + +You can specify (sub)commands for your top-level command using `.command`. There are two ways these can be implemented: using an action handler attached to the command, or as a separate executable file (described in more detail later). In the first parameter to `.command` you specify the command name and any command arguments. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`. For example: @@ -410,80 +303,78 @@ program console.log('clone command called'); }); -// Command implemented using stand-alone executable file (description is second parameter to `.command`) -// Returns `this` for adding more commands. +// Command implemented using separate executable file (description is second parameter to `.command`) +// Returns top-level command for adding more commands. program .command('start <service>', 'start named service') .command('stop [service]', 'stop named service, or all if no name supplied'); - -// Command prepared separately. -// Returns `this` for adding more commands. -program - .addCommand(build.makeBuildCommand()); ``` -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)). - ### Specify the argument syntax -You use `.arguments` to specify the expected command-arguments for the top-level command, and for subcommands they are usually -included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required command-arguments. -Square brackets (e.g. `[optional]`) indicate optional command-arguments. -You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`. - -Example file: [arguments.js](./examples/arguments.js) +You use `.arguments` to specify the arguments for the top-level command, and for subcommands they are included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required input. Square brackets (e.g. `[optional]`) indicate optional input. ```js +const program = require('commander'); + program .version('0.1.0') - .arguments('<username> [password]') - .description('test command', { - username: 'user to login', - password: 'password for user, if required' - }) - .action((username, password) => { - console.log('username:', username); - console.log('environment:', password || 'no password given'); + .arguments('<cmd> [env]') + .action(function (cmd, env) { + cmdValue = cmd; + envValue = env; }); + +program.parse(process.argv); + +if (typeof cmdValue === 'undefined') { + console.error('no command given!'); + process.exit(1); +} +console.log('command:', cmdValue); +console.log('environment:', envValue || "no environment given"); ``` 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. For example: ```js +const program = require('commander'); + program .version('0.1.0') - .command('rmdir <dirs...>') - .action(function (dirs) { - dirs.forEach((dir) => { - console.log('rmdir %s', dir); - }); + .command('rmdir <dir> [otherDirs...]') + .action(function (dir, otherDirs) { + console.log('rmdir %s', dir); + if (otherDirs) { + otherDirs.forEach(function (oDir) { + console.log('rmdir %s', oDir); + }); + } }); -``` -The variadic argument is passed to the action handler as an array. +program.parse(process.argv); +``` -### Action handler +The variadic argument is passed to the action handler as an array. (And this also applies to `program.args`.) -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. +### Action handler (sub)commands -Example file: [thank.js](./examples/thank.js) +You can add options to a command that uses an action handler. +The action handler gets passed a parameter for each argument you declared, and one additional argument which is the +command object itself. This command argument has the values for the command-specific options added as properties. ```js +const program = require('commander'); + program - .arguments('<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}`); - }); + .command('rm <dir>') + .option('-r, --recursive', 'Remove recursively') + .action(function (dir, cmdObj) { + console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : '')) + }) + +program.parse(process.argv) ``` You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`. @@ -499,114 +390,108 @@ async function main() { } ``` -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)`. +A command's options on the command line 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. -### Stand-alone executable (sub)commands +Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. -When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands. +### Git-style executable (sub)commands + +When `.command()` is invoked with a description argument, this tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools. Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`. You can specify a custom name with the `executableFile` configuration option. 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 +// file: ./examples/pm +const program = require('commander'); + program .version('0.1.0') .command('install [name]', 'install one or more packages') .command('search [query]', 'search with optional query') - .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' }) - .command('list', 'list packages installed', { isDefault: true }); - -program.parse(process.argv); + .command('update', 'update installed packages', {executableFile: 'myUpdateSubCommand'}) + .command('list', 'list packages installed', {isDefault: true}) + .parse(process.argv); ``` -If the program is designed to be installed globally, make sure the executables have proper modes, like `755`. +Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified. +Specifying a name with `executableFile` will override the default constructed name. -## Automated help +If the program is designed to be installed globally, make sure the executables have proper modes, like `755`. -The help information is auto-generated based on the information commander already knows about your program. The default -help option is `-h,--help`. +## Automated --help -Example file: [pizza](./examples/pizza) + The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: ```bash -$ node ./examples/pizza --help +$ ./examples/pizza --help Usage: pizza [options] -An application for pizza ordering +An application for pizzas ordering Options: + -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 (default: "marble") -C, --no-cheese You do not want any cheese - -h, --help display help for command -``` - -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: - -```bash -shell help -shell --help - -shell help spawn -shell spawn --help + -h, --help output usage information ``` ### Custom help -You can add extra text to be displayed along with the built-in help. - -Example file: [custom-help](./examples/custom-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. ```js +#!/usr/bin/env node + +const program = require('commander'); + program - .option('-f, --foo', 'enable some foo'); + .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'); +}); -program.addHelpText('after', ` +program.parse(process.argv); -Example call: - $ custom-help --help`); +console.log('stuff'); ``` -Yields the following help output: +Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run: ```Text Usage: custom-help [options] Options: - -f, --foo enable some foo - -h, --help display help for command + -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 -Example call: +Examples: $ custom-help --help + $ custom-help -h ``` -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 - -### 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. - ### .usage and .name These allow you to customise the usage description in the first line of the help. The name is otherwise @@ -624,174 +509,128 @@ The help will start with: Usage: my-command [global options] command ``` -### .helpOption(flags, description) +### .outputHelp(cb) -By default every command has a help option. Override the default help flags and description. Pass false to disable the built-in help option. +Output help information without exiting. +Optional callback cb allows post-processing of help text before it is displayed. -```js -program - .helpOption('-e, --HELP', 'read more information'); -``` +If you want to display help by default (e.g. if no command was provided), you can use something like: -### .addHelpCommand() +```js +const program = require('commander'); +const colors = require('colors'); -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)`. +program + .version('0.1.0') + .command('getstream [url]', 'get stream URL') + .parse(process.argv); -You can both turn on and customise the help command by supplying the name and description: +if (!process.argv.slice(2).length) { + program.outputHelp(make_red); +} -```js -program.addHelpCommand('assist [command]', 'show assistance'); +function make_red(txt) { + return colors.red(txt); //display the help text in red on the console +} ``` -### 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: +### .helpOption(flags, description) -- `helpWidth`: specify the wrap width, useful for unit tests -- `sortSubcommands`: sort the subcommands alphabetically -- `sortOptions`: sort the options alphabetically + Override the default help flags and description. -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. +```js +program + .helpOption('-e, --HELP', 'read more information'); +``` -Example file: [configure-help.js](./examples/configure-help.js) +### .help(cb) -``` -program.configureHelp({ - sortSubcommands: true, - subcommandTerm: (cmd) => cmd.name() // Just show the name, instead of short usage. -}); -``` + Output help information and exit immediately. + Optional callback cb allows post-processing of help text before it is displayed. ## Custom event listeners -You can execute custom actions by listening to command and option events. + You can execute custom actions by listening to command and option events. ```js program.on('option:verbose', function () { - process.env.VERBOSE = this.opts().verbose; + process.env.VERBOSE = this.verbose; }); -program.on('command:*', function (operands) { - console.error(`error: unknown command '${operands[0]}'`); - const availableCommands = program.commands.map(cmd => cmd.name()); - mySuggestBestMatch(operands[0], availableCommands); - process.exitCode = 1; +// 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); }); ``` ## 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`. +### Avoiding option name clashes -If the arguments follow different conventions than node you can pass a `from` option in the second parameter: +The original and default behaviour is that the option values are stored +as properties on the program, and the action handler is passed a +command object with the options values stored as properties. +This is very convenient to code, but the downside is possible clashes with +existing properties of Command. -- '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 +There are two new routines to change the behaviour, and the default behaviour may change in the future: -For example: +- `storeOptionsAsProperties`: whether to store option values as properties on command object, or store separately (specify false) and access using `.opts()` +- `passCommandToAction`: whether to pass command to action handler, +or just the options (specify false) ```js -program.parse(process.argv); // Explicit, node conventions -program.parse(); // Implicit, and auto-detect electron -program.parse(['-f', 'filename'], { from: 'user' }); -``` - -### Parsing Configuration - -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 +// file: ./examples/storeOptionsAsProperties.action.js +program + .storeOptionsAsProperties(false) + .passCommandToAction(false); -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()`. +program + .name('my-program-name') + .option('-n,--name <name>'); -```js program - .storeOptionsAsProperties() - .option('-d, --debug') - .action((commandAndOptions) => { - if (commandAndOptions.debug) { - console.error(`Called ${commandAndOptions.name()}`); - } + .command('show') + .option('-a,--action <action>') + .action((options) => { + console.log(options.action); }); + +program.parse(process.argv); + +const programOptions = program.opts(); +console.log(programOptions.name); ``` ### TypeScript -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. +The Commander package includes its TypeScript Definition file, but also requires the node types which you need to install yourself. e.g. ```bash -node -r ts-node/register pm.ts +npm install commander +npm install --save-dev @types/node ``` -### createCommand() - -This factory function creates a new command. It is exported and may be used instead of using `new`, like: +If you use `ts-node` and git-style sub-commands written as `.ts` files, you need to call your program through node to get the sub-commands called correctly. e.g. -```js -const { createCommand } = require('commander'); -const program = createCommand(); +```bash +node -r ts-node/register pm.ts ``` -`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. +- Use `#! /usr/bin/env node --harmony` in the sub-commands 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 sub-command process. -### Debugging stand-alone executable subcommands +### Node debugging -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, +If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) git-style executable (sub)commands 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. - -### Override exit and output handling +### Override exit 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`. @@ -799,7 +638,7 @@ this behaviour and optionally supply a callback. The default override throws a ` 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 +``` js program.exitOverride(); try { @@ -809,104 +648,61 @@ try { } ``` -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 - .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)) - }); -``` - -### 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) - ## Examples -In a single command program, you might not need an action handler. - -Example file: [pizza](./examples/pizza) - -```js -const { program } = require('commander'); - -program - .description('An application for pizza ordering') - .option('-p, --peppers', 'Add peppers') - .option('-c, --cheese <type>', 'Add the specified type of cheese', 'marble') - .option('-C, --no-cheese', 'You do not want any cheese'); - -program.parse(); - -const options = program.opts(); -console.log('you ordered a pizza with:'); -if (options.peppers) console.log(' - peppers'); -const cheese = !options.cheese ? 'no' : options.cheese; -console.log(' - %s cheese', cheese); -``` - -In a multi-command program, you will have action handlers for each command (or stand-alone executables for the commands). - -Example file: [deploy](./examples/deploy) - ```js -const { Command } = require('commander'); -const program = new Command(); +const program = require('commander'); program - .version('0.0.1') - .option('-c, --config <path>', 'set config path', './deploy.conf'); + .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'); program .command('setup [env]') .description('run setup commands for all envs') - .option('-s, --setup_mode <mode>', 'Which setup mode to use', 'normal') - .action((env, options) => { + .option("-s, --setup_mode [mode]", "Which setup mode to use") + .action(function(env, options){ + const mode = options.setup_mode || "normal"; env = env || 'all'; - console.log('read config from %s', program.opts().config); - console.log('setup for %s env(s) with %s mode', env, options.setup_mode); + console.log('setup for %s env(s) with %s mode', env, mode); }); program - .command('exec <script>') + .command('exec <cmd>') .alias('ex') .description('execute the given remote cmd') - .option('-e, --exec_mode <mode>', 'Which exec mode to use', 'fast') - .action((script, options) => { - console.log('read config from %s', program.opts().config); - console.log('exec "%s" using %s mode and config %s', script, options.exec_mode, program.opts().config); - }).addHelpText('after', ` -Examples: - $ deploy exec sequential - $ deploy exec async` - ); - + .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'); + }); + +program + .command('*') + .action(function(env){ + console.log('deploying "%s"', env); + }); + program.parse(process.argv); ``` -More samples can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory. +More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory. + +## License + +[MIT](https://github.com/tj/commander.js/blob/master/LICENSE) ## Support -The current version of Commander is fully supported on Long Term Support versions of node, and requires at least node v10. -(For older versions of node, use an older version of Commander. Commander version 2.x has the widest support.) +Commander 4.x is supported on Node 8 and above, and is likely to work with Node 6 but not tested. +(For versions of Node below Node 6, use Commander 3.x or 2.x.) The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub. diff --git a/node_modules/commander/esm.mjs b/node_modules/commander/esm.mjs deleted file mode 100644 index 60bf2521..00000000 --- a/node_modules/commander/esm.mjs +++ /dev/null @@ -1,4 +0,0 @@ -import commander from './index.js'; - -// wrapper to provide named exports for ESM. -export const { program, Option, Command, CommanderError, InvalidOptionArgumentError, Help, createCommand } = commander; diff --git a/node_modules/commander/index.js b/node_modules/commander/index.js index 985a8cfc..37d20cc5 100644 --- a/node_modules/commander/index.js +++ b/node_modules/commander/index.js @@ -2,499 +2,91 @@ * Module dependencies. */ -const EventEmitter = require('events').EventEmitter; -const childProcess = require('child_process'); -const path = require('path'); -const fs = require('fs'); - -// @ts-check - -// Although this is a class, methods are static in style to allow override using subclass or just functions. -class Help { - constructor() { - this.helpWidth = undefined; - this.sortSubcommands = false; - this.sortOptions = false; - } - - /** - * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. - * - * @param {Command} cmd - * @returns {Command[]} - */ - - visibleCommands(cmd) { - const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden); - if (cmd._hasImplicitHelpCommand()) { - // Create a command matching the implicit help command. - const args = cmd._helpCommandnameAndArgs.split(/ +/); - const helpCommand = cmd.createCommand(args.shift()) - .helpOption(false); - helpCommand.description(cmd._helpCommandDescription); - helpCommand._parseExpectedArgs(args); - visibleCommands.push(helpCommand); - } - if (this.sortSubcommands) { - visibleCommands.sort((a, b) => { - return a.name().localeCompare(b.name()); - }); - } - return visibleCommands; - } - - /** - * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. - * - * @param {Command} cmd - * @returns {Option[]} - */ - - visibleOptions(cmd) { - const visibleOptions = cmd.options.filter((option) => !option.hidden); - // Implicit help - const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag); - const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag); - if (showShortHelpFlag || showLongHelpFlag) { - let helpOption; - if (!showShortHelpFlag) { - helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription); - } else if (!showLongHelpFlag) { - helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription); - } else { - helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription); - } - visibleOptions.push(helpOption); - } - if (this.sortOptions) { - const getSortKey = (option) => { - // WYSIWYG for order displayed in help with short before long, no special handling for negated. - return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, ''); - }; - visibleOptions.sort((a, b) => { - return getSortKey(a).localeCompare(getSortKey(b)); - }); - } - return visibleOptions; - } - - /** - * Get an array of the arguments which have descriptions. - * - * @param {Command} cmd - * @returns {{ term: string, description:string }[]} - */ - - visibleArguments(cmd) { - if (cmd._argsDescription && cmd._args.length) { - return cmd._args.map((argument) => { - return { term: argument.name, description: cmd._argsDescription[argument.name] || '' }; - }, 0); - } - return []; - } +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'); - /** - * Get the command term to show in the list of subcommands. - * - * @param {Command} cmd - * @returns {string} - */ - - subcommandTerm(cmd) { - // Legacy. Ignores custom usage string, and nested commands. - const args = cmd._args.map(arg => humanReadableArgName(arg)).join(' '); - return cmd._name + - (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + - (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option - (args ? ' ' + args : ''); - } - - /** - * Get the option term to show in the list of options. - * - * @param {Option} option - * @returns {string} - */ - - optionTerm(option) { - return option.flags; - } - - /** - * Get the longest command term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ - - longestSubcommandTermLength(cmd, helper) { - return helper.visibleCommands(cmd).reduce((max, command) => { - return Math.max(max, helper.subcommandTerm(command).length); - }, 0); - }; - - /** - * Get the longest option term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ - - longestOptionTermLength(cmd, helper) { - return helper.visibleOptions(cmd).reduce((max, option) => { - return Math.max(max, helper.optionTerm(option).length); - }, 0); - }; - - /** - * Get the longest argument term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ - - longestArgumentTermLength(cmd, helper) { - return helper.visibleArguments(cmd).reduce((max, argument) => { - return Math.max(max, argument.term.length); - }, 0); - }; - - /** - * Get the command usage to be displayed at the top of the built-in help. - * - * @param {Command} cmd - * @returns {string} - */ - - commandUsage(cmd) { - // Usage - let cmdName = cmd._name; - if (cmd._aliases[0]) { - cmdName = cmdName + '|' + cmd._aliases[0]; - } - let parentCmdNames = ''; - for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) { - parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; - } - return parentCmdNames + cmdName + ' ' + cmd.usage(); - } - - /** - * Get the description for the command. - * - * @param {Command} cmd - * @returns {string} - */ - - commandDescription(cmd) { - // @ts-ignore: overloaded return type - return cmd.description(); - } - - /** - * Get the command description to show in the list of subcommands. - * - * @param {Command} cmd - * @returns {string} - */ - - subcommandDescription(cmd) { - // @ts-ignore: overloaded return type - return cmd.description(); - } - - /** - * Get the option description to show in the list of options. - * - * @param {Option} option - * @return {string} - */ - - optionDescription(option) { - if (option.negate) { - return option.description; - } - const extraInfo = []; - if (option.argChoices) { - extraInfo.push( - // use stringify to match the display of the default value - `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`); - } - if (option.defaultValue !== undefined) { - extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`); - } - if (extraInfo.length > 0) { - return `${option.description} (${extraInfo.join(', ')})`; - } - return option.description; - }; - - /** - * Generate the built-in help text. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {string} - */ - - formatHelp(cmd, helper) { - const termWidth = helper.padWidth(cmd, helper); - const helpWidth = helper.helpWidth || 80; - const itemIndentWidth = 2; - const itemSeparatorWidth = 2; // between term and description - function formatItem(term, description) { - if (description) { - const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`; - return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth); - } - return term; - }; - function formatList(textArray) { - return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth)); - } - - // Usage - let output = [`Usage: ${helper.commandUsage(cmd)}`, '']; +/** + * Inherit `Command` from `EventEmitter.prototype`. + */ - // Description - const commandDescription = helper.commandDescription(cmd); - if (commandDescription.length > 0) { - output = output.concat([commandDescription, '']); - } +require('util').inherits(Command, EventEmitter); - // Arguments - const argumentList = helper.visibleArguments(cmd).map((argument) => { - return formatItem(argument.term, argument.description); - }); - if (argumentList.length > 0) { - output = output.concat(['Arguments:', formatList(argumentList), '']); - } +/** + * Expose the root command. + */ - // Options - const optionList = helper.visibleOptions(cmd).map((option) => { - return formatItem(helper.optionTerm(option), helper.optionDescription(option)); - }); - if (optionList.length > 0) { - output = output.concat(['Options:', formatList(optionList), '']); - } +exports = module.exports = new Command(); - // Commands - const commandList = helper.visibleCommands(cmd).map((cmd) => { - return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd)); - }); - if (commandList.length > 0) { - output = output.concat(['Commands:', formatList(commandList), '']); - } +/** + * Expose `Command`. + */ - return output.join('\n'); - } +exports.Command = Command; - /** - * Calculate the pad width from the maximum term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ +/** + * Expose `Option`. + */ - padWidth(cmd, helper) { - return Math.max( - helper.longestOptionTermLength(cmd, helper), - helper.longestSubcommandTermLength(cmd, helper), - helper.longestArgumentTermLength(cmd, helper) - ); - }; +exports.Option = Option; - /** - * 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. - * - * @param {string} str - * @param {number} width - * @param {number} indent - * @param {number} [minColumnWidth=40] - * @return {string} - * - */ +/** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {String} flags + * @param {String} description + * @api public + */ - wrap(str, width, indent, minColumnWidth = 40) { - // Detect manually wrapped and indented strings by searching for line breaks - // followed by multiple spaces/tabs. - if (str.match(/[\n]\s+/)) return str; - // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line). - const columnWidth = width - indent; - if (columnWidth < minColumnWidth) return str; - - const leadingStr = str.substr(0, indent); - const columnText = str.substr(indent); - - const indentString = ' '.repeat(indent); - const regex = new RegExp('.{1,' + (columnWidth - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); - const lines = columnText.match(regex) || []; - return leadingStr + lines.map((line, i) => { - if (line.slice(-1) === '\n') { - line = line.slice(0, line.length - 1); - } - return ((i > 0) ? indentString : '') + line.trimRight(); - }).join('\n'); - } +function Option(flags, description) { + this.flags = flags; + this.required = flags.indexOf('<') >= 0; // A value must be supplied when the option is specified. + this.optional = flags.indexOf('[') >= 0; // A value is optional when the option is specified. + this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. + this.negate = 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 || ''; } -class Option { - /** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {string} flags - * @param {string} [description] - */ - - constructor(flags, description) { - this.flags = flags; - this.description = description || ''; - - this.required = flags.includes('<'); // A value must be supplied when the option is specified. - this.optional = flags.includes('['); // A value is optional when the option is specified. - // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument - this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. - this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. - const optionFlags = _parseOptionFlags(flags); - this.short = optionFlags.shortFlag; - this.long = optionFlags.longFlag; - this.negate = false; - if (this.long) { - this.negate = this.long.startsWith('--no-'); - } - this.defaultValue = undefined; - this.defaultValueDescription = undefined; - this.parseArg = undefined; - this.hidden = false; - this.argChoices = undefined; - } - - /** - * Set the default value, and optionally supply the description to be displayed in the help. - * - * @param {any} value - * @param {string} [description] - * @return {Option} - */ - - default(value, description) { - this.defaultValue = value; - this.defaultValueDescription = description; - return this; - }; - - /** - * Set the custom handler for processing CLI option arguments into option values. - * - * @param {Function} [fn] - * @return {Option} - */ - - argParser(fn) { - this.parseArg = fn; - return this; - }; - - /** - * Whether the option is mandatory and must have a value after parsing. - * - * @param {boolean} [mandatory=true] - * @return {Option} - */ - - makeOptionMandatory(mandatory = true) { - this.mandatory = !!mandatory; - return this; - }; - - /** - * Hide option in help. - * - * @param {boolean} [hide=true] - * @return {Option} - */ - - hideHelp(hide = true) { - this.hidden = !!hide; - return this; - }; - - /** - * @api private - */ - - _concatValue(value, previous) { - if (previous === this.defaultValue || !Array.isArray(previous)) { - return [value]; - } - - return previous.concat(value); - } - - /** - * Only allow option value to be one of choices. - * - * @param {string[]} values - * @return {Option} - */ - - choices(values) { - this.argChoices = values; - this.parseArg = (arg, previous) => { - if (!values.includes(arg)) { - throw new InvalidOptionArgumentError(`Allowed choices are ${values.join(', ')}.`); - } - if (this.variadic) { - return this._concatValue(arg, previous); - } - return arg; - }; - return this; - }; - - /** - * Return option name. - * - * @return {string} - */ +/** + * Return option name. + * + * @return {String} + * @api private + */ - name() { - if (this.long) { - return this.long.replace(/^--/, ''); - } - return this.short.replace(/^-/, ''); - }; +Option.prototype.name = function() { + return this.long.replace(/^--/, ''); +}; - /** - * Return option name, in a camelcase format that can be used - * as a object attribute key. - * - * @return {string} - * @api private - */ +/** + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {String} + * @api private + */ - attributeName() { - return camelcase(this.name().replace(/^no-/, '')); - }; +Option.prototype.attributeName = function() { + return camelcase(this.name().replace(/^no-/, '')); +}; - /** - * Check if `arg` matches the short or long flag. - * - * @param {string} arg - * @return {boolean} - * @api private - */ +/** + * Check if `arg` matches the short or long flag. + * + * @param {String} arg + * @return {Boolean} + * @api private + */ - is(arg) { - return this.short === arg || this.long === arg; - }; -} +Option.prototype.is = function(arg) { + return this.short === arg || this.long === arg; +}; /** * CommanderError class @@ -503,9 +95,9 @@ class Option { class CommanderError extends Error { /** * Constructs the CommanderError class - * @param {number} exitCode suggested exit code which could be used with process.exit - * @param {string} code an id string representing the error - * @param {string} message human-readable description of the error + * @param {Number} exitCode suggested exit code which could be used with process.exit + * @param {String} code an id string representing the error + * @param {String} message human-readable description of the error * @constructor */ constructor(exitCode, code, message) { @@ -515,1619 +107,1470 @@ class CommanderError extends Error { this.name = this.constructor.name; this.code = code; this.exitCode = exitCode; - this.nestedError = undefined; } } +exports.CommanderError = CommanderError; + /** - * InvalidOptionArgumentError class - * @class + * Initialize a new `Command`. + * + * @param {String} [name] + * @api public */ -class InvalidOptionArgumentError extends CommanderError { - /** - * Constructs the InvalidOptionArgumentError class - * @param {string} [message] explanation of why argument is invalid - * @constructor - */ - constructor(message) { - super(1, 'commander.invalidOptionArgument', message); - // properly capture stack trace in Node.js - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - } -} -class Command extends EventEmitter { - /** - * Initialize a new `Command`. - * - * @param {string} [name] - */ +function Command(name) { + this.commands = []; + this.options = []; + this._execs = new Set(); + this._allowUnknownOption = false; + this._args = []; + this._name = name || ''; + this._optionValues = {}; + this._storeOptionsAsProperties = true; // backwards compatible by default + this._passCommandToAction = true; // backwards compatible by default + this._actionResults = []; + + this._helpFlags = '-h, --help'; + this._helpDescription = 'output usage information'; + this._helpShortFlag = '-h'; + this._helpLongFlag = '--help'; +} - constructor(name) { - super(); - this.commands = []; - this.options = []; - this.parent = null; - this._allowUnknownOption = false; - this._allowExcessArguments = true; - this._args = []; - this.rawArgs = null; - this._scriptPath = null; - this._name = name || ''; - this._optionValues = {}; - this._storeOptionsAsProperties = false; - this._actionResults = []; - this._actionHandler = null; - this._executableHandler = false; - this._executableFile = null; // custom name for executable - this._defaultCommandName = null; - this._exitCallback = null; - this._aliases = []; - this._combineFlagAndOptionalValue = true; - this._description = ''; - this._argsDescription = undefined; - this._enablePositionalOptions = false; - this._passThroughOptions = false; - - // see .configureOutput() for docs - this._outputConfiguration = { - writeOut: (str) => process.stdout.write(str), - writeErr: (str) => process.stderr.write(str), - getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : undefined, - getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : undefined, - outputError: (str, write) => write(str) - }; +/** + * Define a command. + * + * There are two styles of command: pay attention to where to put the description. + * + * Examples: + * + * // Command implemented using action handler (description is supplied separately to `.command`) + * program + * .command('clone <source> [destination]') + * .description('clone a repository into a newly created directory') + * .action((source, destination) => { + * console.log('clone command called'); + * }); + * + * // Command implemented using separate executable file (description is second parameter to `.command`) + * program + * .command('start <service>', 'start named service') + * .command('stop [service]', 'stop named service, or all if no name supplied'); + * + * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...` + * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) + * @param {Object} [execOpts] - configuration options (for executable) + * @return {Command} returns new command for action handler, or top-level command for executable command + * @api public + */ - this._hidden = false; - this._hasHelpOption = true; - this._helpFlags = '-h, --help'; - this._helpDescription = 'display help for command'; - this._helpShortFlag = '-h'; - this._helpLongFlag = '--help'; - this._addImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false - this._helpCommandName = 'help'; - this._helpCommandnameAndArgs = 'help [command]'; - this._helpCommandDescription = 'display help for command'; - this._helpConfiguration = {}; +Command.prototype.command = function(nameAndArgs, actionOptsOrExecDesc, execOpts) { + var desc = actionOptsOrExecDesc; + var opts = execOpts; + if (typeof desc === 'object' && desc !== null) { + opts = desc; + desc = null; + } + opts = opts || {}; + var args = nameAndArgs.split(/ +/); + var cmd = new Command(args.shift()); + + if (desc) { + cmd.description(desc); + this.executables = true; + this._execs.add(cmd._name); + if (opts.isDefault) this.defaultExecutable = cmd._name; } + cmd._noHelp = !!opts.noHelp; + cmd._helpFlags = this._helpFlags; + cmd._helpDescription = this._helpDescription; + cmd._helpShortFlag = this._helpShortFlag; + cmd._helpLongFlag = this._helpLongFlag; + cmd._exitCallback = this._exitCallback; + cmd._storeOptionsAsProperties = this._storeOptionsAsProperties; + cmd._passCommandToAction = this._passCommandToAction; + + cmd._executableFile = opts.executableFile; // Custom name for executable file + this.commands.push(cmd); + cmd.parseExpectedArgs(args); + cmd.parent = this; + + if (desc) return this; + return cmd; +}; - /** - * Define a command. - * - * There are two styles of command: pay attention to where to put the description. - * - * Examples: - * - * // Command implemented using action handler (description is supplied separately to `.command`) - * program - * .command('clone <source> [destination]') - * .description('clone a repository into a newly created directory') - * .action((source, destination) => { - * console.log('clone command called'); - * }); - * - * // Command implemented using separate executable file (description is second parameter to `.command`) - * program - * .command('start <service>', 'start named service') - * .command('stop [service]', 'stop named service, or all if no name supplied'); - * - * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...` - * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) - * @param {Object} [execOpts] - configuration options (for executable) - * @return {Command} returns new command for action handler, or `this` for executable command - */ +/** + * Define argument syntax for the top-level command. + * + * @api public + */ - command(nameAndArgs, actionOptsOrExecDesc, execOpts) { - let desc = actionOptsOrExecDesc; - let opts = execOpts; - if (typeof desc === 'object' && desc !== null) { - opts = desc; - desc = null; - } - opts = opts || {}; - const args = nameAndArgs.split(/ +/); - const cmd = this.createCommand(args.shift()); +Command.prototype.arguments = function(desc) { + return this.parseExpectedArgs(desc.split(/ +/)); +}; - if (desc) { - cmd.description(desc); - cmd._executableHandler = true; - } - if (opts.isDefault) this._defaultCommandName = cmd._name; - - cmd._outputConfiguration = this._outputConfiguration; - - cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden - cmd._hasHelpOption = this._hasHelpOption; - cmd._helpFlags = this._helpFlags; - cmd._helpDescription = this._helpDescription; - cmd._helpShortFlag = this._helpShortFlag; - cmd._helpLongFlag = this._helpLongFlag; - cmd._helpCommandName = this._helpCommandName; - cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs; - cmd._helpCommandDescription = this._helpCommandDescription; - cmd._helpConfiguration = this._helpConfiguration; - cmd._exitCallback = this._exitCallback; - cmd._storeOptionsAsProperties = this._storeOptionsAsProperties; - cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue; - cmd._allowExcessArguments = this._allowExcessArguments; - cmd._enablePositionalOptions = this._enablePositionalOptions; - - cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor - this.commands.push(cmd); - cmd._parseExpectedArgs(args); - cmd.parent = this; - - if (desc) return this; - return cmd; - }; +/** + * Add an implicit `help [cmd]` subcommand + * which invokes `--help` for the given command. + * + * @api private + */ - /** - * 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. - * - * @param {string} [name] - * @return {Command} new command - */ +Command.prototype.addImplicitHelpCommand = function() { + this.command('help [cmd]', 'display help for [cmd]'); +}; - createCommand(name) { - return new Command(name); - }; +/** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} for chaining + * @api public + */ - /** - * You can customise the help with a subclass of Help by overriding createHelp, - * or by overriding Help properties using configureHelp(). - * - * @return {Help} - */ +Command.prototype.parseExpectedArgs = function(args) { + if (!args.length) return; + var self = this; + args.forEach(function(arg) { + var argDetails = { + required: false, + name: '', + variadic: false + }; - createHelp() { - return Object.assign(new Help(), this.configureHelp()); - }; + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } - /** - * You can customise the help by overriding Help properties using configureHelp(), - * or with a subclass of Help by overriding createHelp(). - * - * @param {Object} [configuration] - configuration options - * @return {Command|Object} `this` command for chaining, or stored configuration - */ + 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; +}; - configureHelp(configuration) { - if (configuration === undefined) return this._helpConfiguration; +/** + * Register callback to use as replacement for calling process.exit. + * + * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing + * @return {Command} for chaining + * @api public + */ - this._helpConfiguration = configuration; - return this; +Command.prototype.exitOverride = function(fn) { + if (fn) { + this._exitCallback = fn; + } else { + this._exitCallback = function(err) { + if (err.code !== 'commander.executeSubCommandAsync') { + throw err; + } else { + // Async callback from spawn events, not useful to throw. + } + }; } + return this; +}; - /** - * 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 - * - * @param {Object} [configuration] - configuration options - * @return {Command|Object} `this` command for chaining, or stored configuration - */ - - configureOutput(configuration) { - if (configuration === undefined) return this._outputConfiguration; +/** + * Call process.exit, and _exitCallback if defined. + * + * @param {Number} exitCode exit code for using with process.exit + * @param {String} code an id string representing the error + * @param {String} message human-readable description of the error + * @return never + * @api private + */ - Object.assign(this._outputConfiguration, configuration); - return this; +Command.prototype._exit = function(exitCode, code, message) { + if (this._exitCallback) { + this._exitCallback(new CommanderError(exitCode, code, message)); + // Expecting this line is not reached. } + process.exit(exitCode); +}; - /** - * Add a prepared subcommand. - * - * See .command() for creating an attached subcommand which inherits settings from its parent. - * - * @param {Command} cmd - new subcommand - * @param {Object} [opts] - configuration options - * @return {Command} `this` command for chaining - */ +/** + * 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 + */ - addCommand(cmd, opts) { - if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name'); +Command.prototype.action = function(fn) { + var self = this; + var listener = function(args, unknown) { + // Parse any so-far unknown options + args = args || []; + unknown = unknown || []; - // To keep things simple, block automatic name generation for deeply nested executables. - // Fail fast and detect when adding rather than later when parsing. - function checkExplicitNames(commandArray) { - commandArray.forEach((cmd) => { - if (cmd._executableHandler && !cmd._executableFile) { - throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`); - } - checkExplicitNames(cmd.commands); - }); - } - checkExplicitNames(cmd.commands); + var parsed = self.parseOptions(unknown); - opts = opts || {}; - if (opts.isDefault) this._defaultCommandName = cmd._name; - if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation + // Output help if necessary + outputHelpIfRequested(self, parsed.unknown); + self._checkForMissingMandatoryOptions(); - this.commands.push(cmd); - cmd.parent = this; - return this; - }; + // 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]); + } - /** - * Define argument syntax for the command. - */ + // Leftover arguments need to be pushed back. Fixes issue #56 + if (parsed.args.length) args = parsed.args.concat(args); - arguments(desc) { - return this._parseExpectedArgs(desc.split(/ +/)); - }; + 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); + } - /** - * Override default decision whether to add implicit help command. - * - * addHelpCommand() // force on - * addHelpCommand(false); // force off - * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details - * - * @return {Command} `this` command for chaining - */ + args[i] = args.splice(i); + } + }); - addHelpCommand(enableOrNameAndArgs, description) { - if (enableOrNameAndArgs === false) { - this._addImplicitHelpCommand = false; + // The .action callback takes an extra parameter which is the command itself. + var expectedArgsCount = self._args.length; + var actionArgs = args.slice(0, expectedArgsCount); + if (self._passCommandToAction) { + actionArgs[expectedArgsCount] = self; } else { - this._addImplicitHelpCommand = true; - if (typeof enableOrNameAndArgs === 'string') { - this._helpCommandName = enableOrNameAndArgs.split(' ')[0]; - this._helpCommandnameAndArgs = enableOrNameAndArgs; - } - this._helpCommandDescription = description || this._helpCommandDescription; + actionArgs[expectedArgsCount] = self.opts(); + } + // Add the extra arguments so available too. + if (args.length > expectedArgsCount) { + actionArgs.push(args.slice(expectedArgsCount)); } - return this; - }; - - /** - * @return {boolean} - * @api private - */ - _hasImplicitHelpCommand() { - if (this._addImplicitHelpCommand === undefined) { - return this.commands.length && !this._actionHandler && !this._findCommand('help'); + const actionResult = fn.apply(self, actionArgs); + // Remember result in case it is async. Assume parseAsync getting called on root. + let rootCommand = self; + while (rootCommand.parent) { + rootCommand = rootCommand.parent; } - return this._addImplicitHelpCommand; + rootCommand._actionResults.push(actionResult); }; + 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; +}; - /** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} `this` command for chaining - * @api private - */ +/** + * Internal implementation shared by .option() and .requiredOption() + * + * @param {Object} config + * @param {String} flags + * @param {String} description + * @param {Function|*} [fn] - custom option processing function or default vaue + * @param {*} [defaultValue] + * @return {Command} for chaining + * @api private + */ - _parseExpectedArgs(args) { - if (!args.length) return; - args.forEach((arg) => { - const argDetails = { - required: false, - name: '', - variadic: false +Command.prototype._optionEx = function(config, flags, description, fn, defaultValue) { + var self = this, + option = new Option(flags, description), + oname = option.name(), + name = option.attributeName(); + option.mandatory = !!config.mandatory; + + // default as 3rd arg + if (typeof fn !== 'function') { + if (fn instanceof RegExp) { + // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing. + // No longer documented in README, but still present for backwards compatibility. + var regex = fn; + fn = function(val, def) { + var m = regex.exec(val); + return m ? m[0] : def; }; - - 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) { - this._args.push(argDetails); - } - }); - this._args.forEach((arg, i) => { - if (arg.variadic && i < this._args.length - 1) { - throw new Error(`only the last argument can be variadic '${arg.name}'`); - } - }); - return this; - }; - - /** - * Register callback to use as replacement for calling process.exit. - * - * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing - * @return {Command} `this` command for chaining - */ - - exitOverride(fn) { - if (fn) { - this._exitCallback = fn; } else { - this._exitCallback = (err) => { - if (err.code !== 'commander.executeSubCommandAsync') { - throw err; - } else { - // Async callback from spawn events, not useful to throw. - } - }; + defaultValue = fn; + fn = null; } - return this; - }; - - /** - * Call process.exit, and _exitCallback if defined. - * - * @param {number} exitCode exit code for using with process.exit - * @param {string} code an id string representing the error - * @param {string} message human-readable description of the error - * @return never - * @api private - */ + } - _exit(exitCode, code, message) { - if (this._exitCallback) { - this._exitCallback(new CommanderError(exitCode, code, message)); - // Expecting this line is not reached. + // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value + if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') { + // when --no-foo we make sure default is true, unless a --foo option is already defined + if (option.negate) { + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + defaultValue = self.optionFor(positiveLongFlag) ? self._getOptionValue(name) : true; } - process.exit(exitCode); - }; + // preassign only if we have a default + if (defaultValue !== undefined) { + self._setOptionValue(name, defaultValue); + option.defaultValue = defaultValue; + } + } - /** - * Register callback `fn` for the command. - * - * Examples: - * - * program - * .command('help') - * .description('display verbose help') - * .action(function() { - * // output help here - * }); - * - * @param {Function} fn - * @return {Command} `this` command for chaining - */ + // register the option + this.options.push(option); - action(fn) { - const listener = (args) => { - // The .action callback takes an extra parameter which is the command or options. - const expectedArgsCount = this._args.length; - const actionArgs = args.slice(0, expectedArgsCount); - if (this._storeOptionsAsProperties) { - actionArgs[expectedArgsCount] = this; // backwards compatible "options" - } else { - actionArgs[expectedArgsCount] = this.opts(); - } - actionArgs.push(this); + // 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._getOptionValue(name) === undefined ? defaultValue : self._getOptionValue(name)); + } - const actionResult = fn.apply(this, actionArgs); - // Remember result in case it is async. Assume parseAsync getting called on root. - let rootCommand = this; - while (rootCommand.parent) { - rootCommand = rootCommand.parent; + // unassigned or boolean value + if (typeof self._getOptionValue(name) === 'boolean' || typeof self._getOptionValue(name) === 'undefined') { + // if no value, negate false, and we have a default, then use it! + if (val == null) { + self._setOptionValue(name, option.negate + ? false + : defaultValue || true); + } else { + self._setOptionValue(name, val); } - rootCommand._actionResults.push(actionResult); - }; - this._actionHandler = listener; - return this; - }; + } else if (val !== null) { + // reassign + self._setOptionValue(name, option.negate ? false : val); + } + }); - /** - * 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. - * - * @param {string} flags - * @param {string} [description] - * @return {Option} new option - */ + return this; +}; - createOption(flags, description) { - return new Option(flags, description); - }; +/** + * 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 undefined + * program.option('-p, --pepper', 'add pepper'); + * + * program.pepper + * // => undefined + * + * --pepper + * program.pepper + * // => true + * + * // simple boolean defaulting to true (unless non-negated option is also defined) + * 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] - custom option processing function or default vaue + * @param {*} [defaultValue] + * @return {Command} for chaining + * @api public + */ - /** - * Add an option. - * - * @param {Option} option - * @return {Command} `this` command for chaining - */ - addOption(option) { - const oname = option.name(); - const name = option.attributeName(); - - let defaultValue = option.defaultValue; - - // preassign default value for --no-*, [optional], <required>, or plain flag if boolean value - if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') { - // when --no-foo we make sure default is true, unless a --foo option is already defined - if (option.negate) { - const positiveLongFlag = option.long.replace(/^--no-/, '--'); - defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true; - } - // preassign only if we have a default - if (defaultValue !== undefined) { - this._setOptionValue(name, defaultValue); - } - } +Command.prototype.option = function(flags, description, fn, defaultValue) { + return this._optionEx({}, flags, description, fn, defaultValue); +}; - // register the option - this.options.push(option); - - // when it's passed assign the value - // and conditionally invoke the callback - this.on('option:' + oname, (val) => { - const oldValue = this._getOptionValue(name); - - // custom processing - if (val !== null && option.parseArg) { - try { - val = option.parseArg(val, oldValue === undefined ? defaultValue : oldValue); - } catch (err) { - if (err.code === 'commander.invalidOptionArgument') { - const message = `error: option '${option.flags}' argument '${val}' is invalid. ${err.message}`; - this._displayError(err.exitCode, err.code, message); - } - throw err; - } - } else if (val !== null && option.variadic) { - val = option._concatValue(val, oldValue); - } +/* + * Add 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 should contain both the short and long flags, separated by comma, a pipe or space. + * + * @param {String} flags + * @param {String} description + * @param {Function|*} [fn] - custom option processing function or default vaue + * @param {*} [defaultValue] + * @return {Command} for chaining + * @api public + */ - // unassigned or boolean value - if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') { - // if no value, negate false, and we have a default, then use it! - if (val == null) { - this._setOptionValue(name, option.negate - ? false - : defaultValue || true); - } else { - this._setOptionValue(name, val); - } - } else if (val !== null) { - // reassign - this._setOptionValue(name, option.negate ? false : val); - } - }); +Command.prototype.requiredOption = function(flags, description, fn, defaultValue) { + return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); +}; - 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; +}; - /** - * Internal implementation shared by .option() and .requiredOption() - * - * @api private - */ - _optionEx(config, flags, description, fn, defaultValue) { - const option = this.createOption(flags, description); - option.makeOptionMandatory(!!config.mandatory); - if (typeof fn === 'function') { - option.default(defaultValue).argParser(fn); - } else if (fn instanceof RegExp) { - // deprecated - const regex = fn; - fn = (val, def) => { - const m = regex.exec(val); - return m ? m[0] : def; - }; - option.default(defaultValue).argParser(fn); - } else { - option.default(fn); - } +/** + * 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(). + * + * @param {boolean} value + * @return {Command} Command for chaining + * @api public + */ - return this.addOption(option); +Command.prototype.storeOptionsAsProperties = function(value) { + this._storeOptionsAsProperties = (value === undefined) || value; + if (this.options.length) { + // This is for programmer, not end user. + console.error('Commander usage error: call storeOptionsAsProperties before adding options'); } + return 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" - * - * Examples: - * - * // simple boolean defaulting to undefined - * program.option('-p, --pepper', 'add pepper'); - * - * program.pepper - * // => undefined - * - * --pepper - * program.pepper - * // => true - * - * // simple boolean defaulting to true (unless non-negated option is also defined) - * 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] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - */ - - option(flags, description, fn, defaultValue) { - return this._optionEx({}, flags, description, fn, defaultValue); - }; - - /** - * Add 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. +/** + * Whether to pass command to action handler, + * or just the options (specify false). * - * @param {string} flags - * @param {string} [description] - * @param {Function|*} [fn] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining + * @param {boolean} value + * @return {Command} Command for chaining + * @api public */ - requiredOption(flags, description, fn, defaultValue) { - return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); - }; +Command.prototype.passCommandToAction = function(value) { + this._passCommandToAction = (value === undefined) || value; + return this; +}; - /** - * Alter parsing of short flags with optional values. - * - * Examples: - * - * // 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` - * - * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag. - */ - combineFlagAndOptionalValue(combine = true) { - this._combineFlagAndOptionalValue = !!combine; - return this; - }; +/** + * Store option value + * + * @param {String} key + * @param {Object} value + * @api private + */ - /** - * Allow unknown options on the command line. - * - * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown - * for unknown options. - */ - allowUnknownOption(allowUnknown = true) { - this._allowUnknownOption = !!allowUnknown; - return this; - }; +Command.prototype._setOptionValue = function(key, value) { + if (this._storeOptionsAsProperties) { + this[key] = value; + } else { + this._optionValues[key] = value; + } +}; - /** - * Allow excess command-arguments on the command line. Pass false to make excess arguments an error. - * - * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown - * for excess arguments. - */ - allowExcessArguments(allowExcess = true) { - this._allowExcessArguments = !!allowExcess; - return this; - }; +/** + * Retrieve option value + * + * @param {String} key + * @return {Object} value + * @api private + */ - /** - * 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. - * - * @param {Boolean} [positional=true] - */ - enablePositionalOptions(positional = true) { - this._enablePositionalOptions = !!positional; - return this; - }; +Command.prototype._getOptionValue = function(key) { + if (this._storeOptionsAsProperties) { + return this[key]; + } + return this._optionValues[key]; +}; - /** - * 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. - * - * @param {Boolean} [passThrough=true] - * for unknown options. - */ - passThroughOptions(passThrough = true) { - this._passThroughOptions = !!passThrough; - if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) { - throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)'); - } - return this; - }; +/** + * Parse `argv`, setting options and invoking commands when defined. + * + * @param {Array} argv + * @return {Command} for chaining + * @api public + */ - /** - * 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(). - * - * @param {boolean} [storeAsProperties=true] - * @return {Command} `this` command for chaining - */ - - storeOptionsAsProperties(storeAsProperties = true) { - this._storeOptionsAsProperties = !!storeAsProperties; - if (this.options.length) { - throw new Error('call .storeOptionsAsProperties() before adding options'); - } - return this; - }; +Command.prototype.parse = function(argv) { + // implicit help + if (this.executables) this.addImplicitHelpCommand(); - /** - * Store option value - * - * @param {string} key - * @param {Object} value - * @api private - */ + // store raw args + this.rawArgs = argv; - _setOptionValue(key, value) { - if (this._storeOptionsAsProperties) { - this[key] = value; - } else { - this._optionValues[key] = value; - } - }; + // guess name + this._name = this._name || basename(argv[1], '.js'); - /** - * Retrieve option value - * - * @param {string} key - * @return {Object} value - * @api private - */ + // github-style sub-commands with no sub-command + if (this.executables && argv.length < 3 && !this.defaultExecutable) { + // this user needs help + argv.push(this._helpLongFlag); + } - _getOptionValue(key) { - if (this._storeOptionsAsProperties) { - return this[key]; - } - return this._optionValues[key]; - }; + // process argv + var normalized = this.normalize(argv.slice(2)); + var parsed = this.parseOptions(normalized); + var args = this.args = parsed.args; - /** - * 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. - * - * Examples: - * - * 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] - * - * @param {string[]} [argv] - optional, defaults to process.argv - * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron - * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' - * @return {Command} `this` command for chaining - */ + var result = this.parseArgs(this.args, parsed.unknown); - parse(argv, parseOptions) { - if (argv !== undefined && !Array.isArray(argv)) { - throw new Error('first parameter to parse must be array or undefined'); - } - parseOptions = parseOptions || {}; - - // Default to using process.argv - if (argv === undefined) { - argv = process.argv; - // @ts-ignore: unknown property - if (process.versions && process.versions.electron) { - parseOptions.from = 'electron'; - } - } - this.rawArgs = argv.slice(); - - // make it a little easier for callers by supporting various argv conventions - let userArgs; - switch (parseOptions.from) { - case undefined: - case 'node': - this._scriptPath = argv[1]; - userArgs = argv.slice(2); - break; - case 'electron': - // @ts-ignore: unknown property - if (process.defaultApp) { - this._scriptPath = argv[1]; - userArgs = argv.slice(2); - } else { - userArgs = argv.slice(1); - } - break; - case 'user': - userArgs = argv.slice(0); - break; - default: - throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`); - } - if (!this._scriptPath && require.main) { - this._scriptPath = require.main.filename; - } + if (args[0] === 'help' && args.length === 1) this.help(); - // Guess name, used in usage in help. - this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath))); + // Note for future: we could return early if we found an action handler in parseArgs, as none of following code needed? - // Let's go! - this._parseCommand([], userArgs); + // <cmd> --help + if (args[0] === 'help') { + args[0] = args[1]; + args[1] = this._helpLongFlag; + } else { + // If calling through to executable subcommand we could check for help flags before failing, + // but a somewhat unlikely case since program options not passed to executable subcommands. + // Wait for reports to see if check needed and what usage pattern is. + this._checkForMissingMandatoryOptions(); + } - return this; - }; + // executable sub-commands + // (Debugging note for future: args[0] is not right if an action has been called) + var name = result.args[0]; + var subCommand = null; - /** - * 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. - * - * Examples: - * - * 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] - * - * @param {string[]} [argv] - * @param {Object} [parseOptions] - * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' - * @return {Promise} - */ + // Look for subcommand + if (name) { + subCommand = this.commands.find(function(command) { + return command._name === name; + }); + } - parseAsync(argv, parseOptions) { - this.parse(argv, parseOptions); - return Promise.all(this._actionResults).then(() => this); - }; + // Look for alias + if (!subCommand && name) { + subCommand = this.commands.find(function(command) { + return command.alias() === name; + }); + if (subCommand) { + name = subCommand._name; + args[0] = name; + } + } - /** - * Execute a sub-command executable. - * - * @api private - */ + // Look for default subcommand + if (!subCommand && this.defaultExecutable) { + name = this.defaultExecutable; + args.unshift(name); + subCommand = this.commands.find(function(command) { + return command._name === name; + }); + } - _executeSubCommand(subcommand, args) { - args = args.slice(); - let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows. - const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs']; + if (this._execs.has(name)) { + return this.executeSubCommand(argv, args, parsed.unknown, subCommand ? subCommand._executableFile : undefined); + } - // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. - this._checkForMissingMandatoryOptions(); + return result; +}; - // Want the entry script as the reference for command name and directory for searching for other files. - let scriptPath = this._scriptPath; - // Fallback in case not set, due to how Command created or called. - if (!scriptPath && require.main) { - scriptPath = require.main.filename; - } +/** + * 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. + * + * @param {Array} argv + * @return {Promise} + * @api public + */ +Command.prototype.parseAsync = function(argv) { + this.parse(argv); + return Promise.all(this._actionResults); +}; - let baseDir; - try { - const resolvedLink = fs.realpathSync(scriptPath); - baseDir = path.dirname(resolvedLink); - } catch (e) { - baseDir = '.'; // dummy, probably not going to find executable! - } +/** + * Execute a sub-command executable. + * + * @param {Array} argv + * @param {Array} args + * @param {Array} unknown + * @param {String} executableFile + * @api private + */ - // name of the subcommand, like `pm-install` - let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name; - if (subcommand._executableFile) { - bin = subcommand._executableFile; - } +Command.prototype.executeSubCommand = function(argv, args, unknown, executableFile) { + args = args.concat(unknown); - const localBin = path.join(baseDir, bin); - if (fs.existsSync(localBin)) { - // prefer local `./<bin>` to bin in the $PATH - bin = localBin; - } else { - // Look for source files. - sourceExt.forEach((ext) => { - if (fs.existsSync(`${localBin}${ext}`)) { - bin = `${localBin}${ext}`; - } - }); - } - launchWithNode = sourceExt.includes(path.extname(bin)); + if (!args.length) this.help(); - let proc; - if (process.platform !== 'win32') { - if (launchWithNode) { - args.unshift(bin); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); + var isExplicitJS = false; // Whether to use node to launch "executable" - proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' }); - } else { - proc = childProcess.spawn(bin, args, { stdio: 'inherit' }); - } - } else { + // executable + var pm = argv[1]; + // name of the subcommand, like `pm-install` + var bin = basename(pm, path.extname(pm)) + '-' + args[0]; + if (executableFile != null) { + bin = executableFile; + // Check for same extensions as we scan for below so get consistent launch behaviour. + var executableExt = path.extname(executableFile); + isExplicitJS = executableExt === '.js' || executableExt === '.ts' || executableExt === '.mjs'; + } + + // In case of globally installed, get the base dir where executable + // subcommand file should be located at + var baseDir; + + var resolvedLink = fs.realpathSync(pm); + + 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 + if (exists(localBin + '.js')) { + bin = localBin + '.js'; + isExplicitJS = true; + } else if (exists(localBin + '.ts')) { + bin = localBin + '.ts'; + isExplicitJS = true; + } else if (exists(localBin + '.mjs')) { + bin = localBin + '.mjs'; + 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 = incrementNodeInspectorPort(process.execArgv).concat(args); - proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' }); + + proc = spawn(process.argv[0], args, { stdio: 'inherit' }); + } else { + proc = spawn(bin, args, { stdio: 'inherit' }); } + } else { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + proc = spawn(process.execPath, args, { stdio: 'inherit' }); + } - const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; - signals.forEach((signal) => { - // @ts-ignore - process.on(signal, () => { - if (proc.killed === false && proc.exitCode === null) { - proc.kill(signal); - } - }); + 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); + } }); + }); - // By default terminate process when spawned process terminates. - // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running! - const exitCallback = this._exitCallback; + // By default terminate process when spawned process terminates. + // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running! + const exitCallback = this._exitCallback; + if (!exitCallback) { + proc.on('close', process.exit.bind(process)); + } else { + proc.on('close', () => { + exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)')); + }); + } + 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); + } if (!exitCallback) { - proc.on('close', process.exit.bind(process)); + process.exit(1); } else { - proc.on('close', () => { - exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)')); - }); + const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); + wrappedError.nestedError = err; + exitCallback(wrappedError); } - proc.on('error', (err) => { - // @ts-ignore - if (err.code === 'ENOENT') { - const executableMissing = `'${bin}' does not exist - - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead - - if the default executable name is not suitable, use the executableFile option to supply a custom name`; - throw new Error(executableMissing); - // @ts-ignore - } else if (err.code === 'EACCES') { - throw new Error(`'${bin}' not executable`); - } - if (!exitCallback) { - process.exit(1); - } else { - const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); - wrappedError.nestedError = err; - exitCallback(wrappedError); - } - }); + }); - // Store the reference to the child process - this.runningCommand = proc; - }; + // Store the reference to the child process + this.runningCommand = proc; +}; - /** - * @api private - */ - _dispatchSubcommand(commandName, operands, unknown) { - const subCommand = this._findCommand(commandName); - if (!subCommand) this.help({ error: true }); +/** + * 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 + */ - if (subCommand._executableHandler) { - this._executeSubCommand(subCommand, operands.concat(unknown)); - } else { - subCommand._parseCommand(operands, unknown); +Command.prototype.normalize = function(args) { + var ret = [], + arg, + lastOpt, + index, + short, + opt; + + for (var i = 0, len = args.length; i < len; ++i) { + arg = args[i]; + if (i > 0) { + lastOpt = this.optionFor(args[i - 1]); } - }; - /** - * Process arguments in context of this command. - * - * @api private - */ - - _parseCommand(operands, unknown) { - const parsed = this.parseOptions(unknown); - operands = operands.concat(parsed.operands); - unknown = parsed.unknown; - this.args = operands.concat(unknown); - - if (operands && this._findCommand(operands[0])) { - this._dispatchSubcommand(operands[0], operands.slice(1), unknown); - } else if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) { - if (operands.length === 1) { - this.help(); + if (arg === '--') { + // Honor option terminator + ret = ret.concat(args.slice(i)); + break; + } else if (lastOpt && lastOpt.required) { + ret.push(arg); + } else if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { + short = arg.slice(0, 2); + opt = this.optionFor(short); + if (opt && (opt.required || opt.optional)) { + ret.push(short); + ret.push(arg.slice(2)); } else { - this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]); + arg.slice(1).split('').forEach(function(c) { + ret.push('-' + c); + }); } - } else if (this._defaultCommandName) { - outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command - this._dispatchSubcommand(this._defaultCommandName, operands, unknown); + } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { + ret.push(arg.slice(0, index), arg.slice(index + 1)); } else { - if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) { - // probably missing subcommand and no handler, user needs help - this.help({ error: true }); - } + ret.push(arg); + } + } - outputHelpIfRequested(this, parsed.unknown); - this._checkForMissingMandatoryOptions(); + return ret; +}; - // We do not always call this check to avoid masking a "better" error, like unknown command. - const checkForUnknownOptions = () => { - if (parsed.unknown.length > 0) { - this.unknownOption(parsed.unknown[0]); - } - }; +/** + * 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 + */ - const commandEvent = `command:${this.name()}`; - if (this._actionHandler) { - checkForUnknownOptions(); - // Check expected arguments and collect variadic together. - const args = this.args.slice(); - this._args.forEach((arg, i) => { - if (arg.required && args[i] == null) { - this.missingArgument(arg.name); - } else if (arg.variadic) { - args[i] = args.splice(i); - args.length = Math.min(i + 1, args.length); - } - }); - if (args.length > this._args.length) { - this._excessArguments(args); - } +Command.prototype.parseArgs = function(args, unknown) { + var name; - this._actionHandler(args); - if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy - } else if (this.parent && this.parent.listenerCount(commandEvent)) { - checkForUnknownOptions(); - this.parent.emit(commandEvent, operands, unknown); // legacy - } else if (operands.length) { - if (this._findCommand('*')) { // legacy default command - this._dispatchSubcommand('*', operands, unknown); - } else if (this.listenerCount('command:*')) { - // skip option check, emit event for possible misspelling suggestion - this.emit('command:*', operands, unknown); - } else if (this.commands.length) { - this.unknownCommand(); - } else { - checkForUnknownOptions(); - } - } else if (this.commands.length) { - // This command has subcommands and nothing hooked up at this level, so display help. - this.help({ error: true }); - } else { - checkForUnknownOptions(); - // fall through for caller to handle after calling .parse() - } + if (args.length) { + name = args[0]; + if (this.listeners('command:' + name).length) { + this.emit('command:' + args.shift(), args, unknown); + } else { + this.emit('command:*', args, unknown); } - }; + } else { + outputHelpIfRequested(this, unknown); - /** - * Find matching command. - * - * @api private - */ - _findCommand(name) { - if (!name) return undefined; - return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name)); - }; - - /** - * Return an option matching `arg` if any. - * - * @param {string} arg - * @return {Option} - * @api private - */ + // If there were no args and we have unknown options, + // then they are extraneous and we need to error. + if (unknown.length > 0 && !this.defaultExecutable) { + this.unknownOption(unknown[0]); + } + if (this.commands.length === 0 && + this._args.filter(function(a) { return a.required; }).length === 0) { + this.emit('command:*'); + } + } - _findOption(arg) { - return this.options.find(option => option.is(arg)); - }; + return this; +}; - /** - * Display an error message if a mandatory option does not have a value. - * Lazy calling after checking for help flags from leaf subcommand. - * - * @api private - */ +/** + * Return an option matching `arg` if any. + * + * @param {String} arg + * @return {Option} + * @api private + */ - _checkForMissingMandatoryOptions() { - // Walk up hierarchy so can call in subcommand after checking for displaying help. - for (let cmd = this; cmd; cmd = cmd.parent) { - cmd.options.forEach((anOption) => { - if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) { - cmd.missingMandatoryOptionValue(anOption); - } - }); +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` removing known options, - * and return argv split into operands and unknown arguments. - * - * Examples: - * - * 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], [] - * - * @param {String[]} argv - * @return {{operands: String[], unknown: String[]}} - */ +/** + * Display an error message if a mandatory option does not have a value. + * + * @api private + */ - parseOptions(argv) { - const operands = []; // operands, not options or values - const unknown = []; // first unknown option and remaining unknown args - let dest = operands; - const args = argv.slice(); +Command.prototype._checkForMissingMandatoryOptions = function() { + // Walk up hierarchy so can call from action handler after checking for displaying help. + for (var cmd = this; cmd; cmd = cmd.parent) { + cmd.options.forEach((anOption) => { + if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) { + cmd.missingMandatoryOptionValue(anOption); + } + }); + } +}; - function maybeOption(arg) { - return arg.length > 1 && arg[0] === '-'; - } +/** + * Parse options from `argv` returning `argv` + * void of these options. + * + * @param {Array} argv + * @return {{args: Array, unknown: Array}} + * @api public + */ - // parse options - let activeVariadicOption = null; - while (args.length) { - const arg = args.shift(); +Command.prototype.parseOptions = function(argv) { + var args = [], + len = argv.length, + literal, + option, + arg; - // literal - if (arg === '--') { - if (dest === unknown) dest.push(arg); - dest.push(...args); - break; - } + var unknownOptions = []; - if (activeVariadicOption && !maybeOption(arg)) { - this.emit(`option:${activeVariadicOption.name()}`, arg); - continue; - } - activeVariadicOption = null; - - if (maybeOption(arg)) { - const option = this._findOption(arg); - // recognised option, call listener to assign value with possible custom processing - if (option) { - if (option.required) { - const value = args.shift(); - if (value === undefined) this.optionMissingArgument(option); - this.emit(`option:${option.name()}`, value); - } else if (option.optional) { - let value = null; - // historical behaviour is optional value is following arg unless an option - if (args.length > 0 && !maybeOption(args[0])) { - value = args.shift(); - } - this.emit(`option:${option.name()}`, value); - } else { // boolean flag - this.emit(`option:${option.name()}`); - } - activeVariadicOption = option.variadic ? option : null; - continue; - } - } + // parse options + for (var i = 0; i < len; ++i) { + arg = argv[i]; - // Look for combo options following single dash, eat first one if known. - if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { - const option = this._findOption(`-${arg[1]}`); - if (option) { - if (option.required || (option.optional && this._combineFlagAndOptionalValue)) { - // option with value following in same argument - this.emit(`option:${option.name()}`, arg.slice(2)); - } else { - // boolean option, emit and put back remainder of arg for further processing - this.emit(`option:${option.name()}`); - args.unshift(`-${arg.slice(2)}`); - } - continue; - } - } + // literal args after -- + if (literal) { + args.push(arg); + continue; + } + + if (arg === '--') { + literal = true; + continue; + } - // Look for known long flag with value, like --foo=bar - if (/^--[^=]+=/.test(arg)) { - const index = arg.indexOf('='); - const option = this._findOption(arg.slice(0, index)); - if (option && (option.required || option.optional)) { - this.emit(`option:${option.name()}`, arg.slice(index + 1)); - 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); + // flag + } else { + this.emit('option:' + option.name()); } + continue; + } - // Not a recognised option by this command. - // Might be a command-argument, or subcommand option, or unknown option, or help command or option. + // looks like an option + if (arg.length > 1 && arg[0] === '-') { + unknownOptions.push(arg); - // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands. - if (maybeOption(arg)) { - dest = unknown; + // 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] !== '-' || argv[i + 1] === '-')) { + unknownOptions.push(argv[++i]); } + continue; + } - // If using positionalOptions, stop processing our options at subcommand. - if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) { - if (this._findCommand(arg)) { - operands.push(arg); - if (args.length > 0) unknown.push(...args); - break; - } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) { - operands.push(arg); - if (args.length > 0) operands.push(...args); - break; - } else if (this._defaultCommandName) { - unknown.push(arg); - if (args.length > 0) unknown.push(...args); - break; - } - } + // arg + args.push(arg); + } - // If using passThroughOptions, stop processing options at first command-argument. - if (this._passThroughOptions) { - dest.push(arg); - if (args.length > 0) dest.push(...args); - break; - } + return { args: args, unknown: unknownOptions }; +}; - // add arg - dest.push(arg); +/** + * Return an object containing options as key-value pairs + * + * @return {Object} + * @api public + */ +Command.prototype.opts = function() { + if (this._storeOptionsAsProperties) { + // Preserve original behaviour so backwards compatible when still using properties + 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; + } - return { operands, unknown }; - }; + return this._optionValues; +}; - /** - * Return an object containing options as key-value pairs - * - * @return {Object} - */ - opts() { - if (this._storeOptionsAsProperties) { - // Preserve original behaviour so backwards compatible when still using properties - const result = {}; - const len = this.options.length; - - for (let i = 0; i < len; i++) { - const 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 + */ - return this._optionValues; - }; +Command.prototype.missingArgument = function(name) { + const message = `error: missing required argument '${name}'`; + console.error(message); + this._exit(1, 'commander.missingArgument', message); +}; - /** - * Internal bottleneck for handling of parsing errors. - * - * @api private - */ - _displayError(exitCode, code, message) { - this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr); - this._exit(exitCode, code, message); +/** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {Option} option + * @param {String} [flag] + * @api private + */ + +Command.prototype.optionMissingArgument = function(option, flag) { + let message; + if (flag) { + message = `error: option '${option.flags}' argument missing, got '${flag}'`; + } else { + message = `error: option '${option.flags}' argument missing`; } + console.error(message); + this._exit(1, 'commander.optionMissingArgument', message); +}; - /** - * Argument `name` is missing. - * - * @param {string} name - * @api private - */ +/** + * `Option` does not have a value, and is a mandatory option. + * + * @param {Option} option + * @api private + */ - missingArgument(name) { - const message = `error: missing required argument '${name}'`; - this._displayError(1, 'commander.missingArgument', message); - }; +Command.prototype.missingMandatoryOptionValue = function(option) { + const message = `error: required option '${option.flags}' not specified`; + console.error(message); + this._exit(1, 'commander.missingMandatoryOptionValue', message); +}; - /** - * `Option` is missing an argument. - * - * @param {Option} option - * @api private - */ +/** + * Unknown option `flag`. + * + * @param {String} flag + * @api private + */ - optionMissingArgument(option) { - const message = `error: option '${option.flags}' argument missing`; - this._displayError(1, 'commander.optionMissingArgument', message); - }; +Command.prototype.unknownOption = function(flag) { + if (this._allowUnknownOption) return; + const message = `error: unknown option '${flag}'`; + console.error(message); + this._exit(1, 'commander.unknownOption', message); +}; - /** - * `Option` does not have a value, and is a mandatory option. - * - * @param {Option} option - * @api private - */ +/** + * Variadic argument with `name` is not the last argument as required. + * + * @param {String} name + * @api private + */ - missingMandatoryOptionValue(option) { - const message = `error: required option '${option.flags}' not specified`; - this._displayError(1, 'commander.missingMandatoryOptionValue', message); - }; +Command.prototype.variadicArgNotLast = function(name) { + const message = `error: variadic arguments must be last '${name}'`; + console.error(message); + this._exit(1, 'commander.variadicArgNotLast', message); +}; - /** - * Unknown option `flag`. - * - * @param {string} flag - * @api private - */ +/** + * 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. + * + * @param {String} str + * @param {String} [flags] + * @param {String} [description] + * @return {Command} for chaining + * @api public + */ - unknownOption(flag) { - if (this._allowUnknownOption) return; - const message = `error: unknown option '${flag}'`; - this._displayError(1, 'commander.unknownOption', message); - }; +Command.prototype.version = function(str, flags, description) { + if (arguments.length === 0) return this._version; + this._version = str; + flags = flags || '-V, --version'; + description = description || 'output the version number'; + var versionOption = new Option(flags, description); + this._versionOptionName = versionOption.long.substr(2) || 'version'; + this.options.push(versionOption); + var self = this; + this.on('option:' + this._versionOptionName, function() { + process.stdout.write(str + '\n'); + self._exit(0, 'commander.version', str); + }); + return this; +}; - /** - * Excess arguments, more than expected. - * - * @param {string[]} receivedArgs - * @api private - */ +/** + * Set the description to `str`. + * + * @param {String} str + * @param {Object} [argsDescription] + * @return {String|Command} + * @api public + */ - _excessArguments(receivedArgs) { - if (this._allowExcessArguments) return; +Command.prototype.description = function(str, argsDescription) { + if (arguments.length === 0) return this._description; + this._description = str; + this._argsDescription = argsDescription; + return this; +}; - const expected = this._args.length; - const s = (expected === 1) ? '' : 's'; - const forSubcommand = this.parent ? ` for '${this.name()}'` : ''; - const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`; - this._displayError(1, 'commander.excessArguments', message); - }; +/** + * Set an alias for the command + * + * @param {String} alias + * @return {String|Command} + * @api public + */ - /** - * Unknown command. - * - * @api private - */ +Command.prototype.alias = function(alias) { + var command = this; + if (this.commands.length !== 0) { + command = this.commands[this.commands.length - 1]; + } - unknownCommand() { - const partCommands = [this.name()]; - for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { - partCommands.unshift(parentCmd.name()); - } - const fullCommand = partCommands.join(' '); - const message = `error: unknown command '${this.args[0]}'.` + - (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : ''); - this._displayError(1, 'commander.unknownCommand', message); - }; + if (arguments.length === 0) return command._alias; - /** - * 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. - * - * @param {string} str - * @param {string} [flags] - * @param {string} [description] - * @return {this | string} `this` command for chaining, or version string if no arguments - */ + if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); - version(str, flags, description) { - if (str === undefined) return this._version; - this._version = str; - flags = flags || '-V, --version'; - description = description || 'output the version number'; - const versionOption = this.createOption(flags, description); - this._versionOptionName = versionOption.attributeName(); - this.options.push(versionOption); - this.on('option:' + versionOption.name(), () => { - this._outputConfiguration.writeOut(`${str}\n`); - this._exit(0, 'commander.version', str); - }); - return this; - }; + command._alias = alias; + return this; +}; - /** - * Set the description to `str`. - * - * @param {string} [str] - * @param {Object} [argsDescription] - * @return {string|Command} - */ - description(str, argsDescription) { - if (str === undefined && argsDescription === undefined) return this._description; - this._description = str; - this._argsDescription = argsDescription; - return this; - }; +/** + * Set / get the command usage `str`. + * + * @param {String} [str] + * @return {String|Command} + * @api public + */ - /** - * 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. - * - * @param {string} [alias] - * @return {string|Command} - */ +Command.prototype.usage = function(str) { + var args = this._args.map(function(arg) { + return humanReadableArgName(arg); + }); - alias(alias) { - if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility + var usage = '[options]' + + (this.commands.length ? ' [command]' : '') + + (this._args.length ? ' ' + args.join(' ') : ''); - let command = this; - if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) { - // assume adding alias for last added executable subcommand, rather than this - command = this.commands[this.commands.length - 1]; - } + if (arguments.length === 0) return this._usage || usage; + this._usage = str; - if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); + return this; +}; - command._aliases.push(alias); - return this; - }; +/** + * Get or set the name of the command + * + * @param {String} [str] + * @return {String|Command} + * @api public + */ - /** - * Set aliases for the command. - * - * Only the first alias is shown in the auto-generated help. - * - * @param {string[]} [aliases] - * @return {string[]|Command} - */ +Command.prototype.name = function(str) { + if (arguments.length === 0) return this._name; + this._name = str; + return this; +}; - aliases(aliases) { - // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). - if (aliases === undefined) return this._aliases; +/** + * Return prepared commands. + * + * @return {Array} + * @api private + */ - aliases.forEach((alias) => this.alias(alias)); - return this; - }; +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 + ]; + }); +}; - /** - * Set / get the command usage `str`. - * - * @param {string} [str] - * @return {String|Command} - */ +/** + * Return the largest command length. + * + * @return {Number} + * @api private + */ - usage(str) { - if (str === undefined) { - if (this._usage) return this._usage; +Command.prototype.largestCommandLength = function() { + var commands = this.prepareCommands(); + return commands.reduce(function(max, command) { + return Math.max(max, command[0].length); + }, 0); +}; - const args = this._args.map((arg) => { - return humanReadableArgName(arg); - }); - return [].concat( - (this.options.length || this._hasHelpOption ? '[options]' : []), - (this.commands.length ? '[command]' : []), - (this._args.length ? args : []) - ).join(' '); - } +/** + * Return the largest option length. + * + * @return {Number} + * @api private + */ - this._usage = str; - return this; - }; +Command.prototype.largestOptionLength = function() { + var options = [].slice.call(this.options); + options.push({ + flags: this._helpFlags + }); - /** - * Get or set the name of the command - * - * @param {string} [str] - * @return {string|Command} - */ + return options.reduce(function(max, option) { + return Math.max(max, option.flags.length); + }, 0); +}; - name(str) { - if (str === undefined) return this._name; - this._name = str; - return this; - }; +/** + * Return the largest arg length. + * + * @return {Number} + * @api private + */ - /** - * Return program help documentation. - * - * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout - * @return {string} - */ +Command.prototype.largestArgLength = function() { + return this._args.reduce(function(max, arg) { + return Math.max(max, arg.name.length); + }, 0); +}; - helpInformation(contextOptions) { - const helper = this.createHelp(); - if (helper.helpWidth === undefined) { - helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth(); - } - return helper.formatHelp(this, helper); - }; +/** + * Return the pad width. + * + * @return {Number} + * @api private + */ - /** - * @api private - */ +Command.prototype.padWidth = function() { + var width = this.largestOptionLength(); + if (this._argsDescription && this._args.length) { + if (this.largestArgLength() > width) { + width = this.largestArgLength(); + } + } - _getHelpContext(contextOptions) { - contextOptions = contextOptions || {}; - const context = { error: !!contextOptions.error }; - let write; - if (context.error) { - write = (arg) => this._outputConfiguration.writeErr(arg); - } else { - write = (arg) => this._outputConfiguration.writeOut(arg); + if (this.commands && this.commands.length) { + if (this.largestCommandLength() > width) { + width = this.largestCommandLength(); } - context.write = contextOptions.write || write; - context.command = this; - return context; } - /** - * Output help information for this command. - * - * Outputs built-in help, and custom text added using `.addHelpText()`. - * - * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout - */ + return width; +}; - outputHelp(contextOptions) { - let deprecatedCallback; - if (typeof contextOptions === 'function') { - deprecatedCallback = contextOptions; - contextOptions = undefined; - } - const context = this._getHelpContext(contextOptions); +/** + * Return help for options. + * + * @return {String} + * @api private + */ - const groupListeners = []; - let command = this; - while (command) { - groupListeners.push(command); // ordered from current command to root - command = command.parent; - } +Command.prototype.optionHelp = function() { + var width = this.padWidth(); - groupListeners.slice().reverse().forEach(command => command.emit('beforeAllHelp', context)); - this.emit('beforeHelp', context); + var columns = process.stdout.columns || 80; + var descriptionWidth = columns - width - 4; - let helpInformation = this.helpInformation(context); - if (deprecatedCallback) { - helpInformation = deprecatedCallback(helpInformation); - if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) { - throw new Error('outputHelp callback must return a string or a Buffer'); - } - } - context.write(helpInformation); + // Append the help information + return this.options.map(function(option) { + const fullDesc = option.description + + ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : ''); + return pad(option.flags, width) + ' ' + optionalWrap(fullDesc, descriptionWidth, width + 2); + }).concat([pad(this._helpFlags, width) + ' ' + optionalWrap(this._helpDescription, descriptionWidth, width + 2)]) + .join('\n'); +}; - this.emit(this._helpLongFlag); // deprecated - this.emit('afterHelp', context); - groupListeners.forEach(command => command.emit('afterAllHelp', context)); - }; +/** + * Return command help documentation. + * + * @return {String} + * @api private + */ - /** - * 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. - * - * @param {string | boolean} [flags] - * @param {string} [description] - * @return {Command} `this` command for chaining - */ +Command.prototype.commandHelp = function() { + if (!this.commands.length) return ''; - helpOption(flags, description) { - if (typeof flags === 'boolean') { - this._hasHelpOption = flags; - return this; - } - this._helpFlags = flags || this._helpFlags; - this._helpDescription = description || this._helpDescription; + var commands = this.prepareCommands(); + var width = this.padWidth(); - const helpFlags = _parseOptionFlags(this._helpFlags); - this._helpShortFlag = helpFlags.shortFlag; - this._helpLongFlag = helpFlags.longFlag; + var columns = process.stdout.columns || 80; + var descriptionWidth = columns - width - 4; - return this; - }; + return [ + 'Commands:', + commands.map(function(cmd) { + var desc = cmd[1] ? ' ' + cmd[1] : ''; + return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2); + }).join('\n').replace(/^/gm, ' '), + '' + ].join('\n'); +}; - /** - * Output help information and exit. - * - * Outputs built-in help, and custom text added using `.addHelpText()`. - * - * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout - */ +/** + * Return program help documentation. + * + * @return {String} + * @api private + */ - help(contextOptions) { - this.outputHelp(contextOptions); - let exitCode = process.exitCode || 0; - if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) { - exitCode = 1; +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(); + var columns = process.stdout.columns || 80; + var descriptionWidth = columns - width - 5; + desc.push('Arguments:'); + desc.push(''); + this._args.forEach(function(arg) { + desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name], descriptionWidth, width + 4)); + }); + desc.push(''); } - // message: do not have all displayed text available so only passing placeholder. - this._exit(exitCode, 'commander.help', '(outputHelp)'); - }; + } - /** - * 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. - * - * @param {string} position - before or after built-in help - * @param {string | Function} text - string to add, or a function returning a string - * @return {Command} `this` command for chaining - */ - addHelpText(position, text) { - const allowedValues = ['beforeAll', 'before', 'after', 'afterAll']; - if (!allowedValues.includes(position)) { - throw new Error(`Unexpected value for position to addHelpText. -Expecting one of '${allowedValues.join("', '")}'`); - } - const helpEvent = `${position}Help`; - this.on(helpEvent, (context) => { - let helpStr; - if (typeof text === 'function') { - helpStr = text({ error: context.error, command: context.command }); - } else { - helpStr = text; - } - // Ignore falsy value when nothing to output. - if (helpStr) { - context.write(`${helpStr}\n`); - } - }); - return this; + var cmdName = this._name; + if (this._alias) { + cmdName = cmdName + '|' + this._alias; + } + var parentCmdNames = ''; + for (var parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; } + var usage = [ + 'Usage: ' + parentCmdNames + 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'); }; /** - * Expose the root command. + * Output help information for this command. + * + * When listener(s) are available for the helpLongFlag + * those callbacks are invoked. + * + * @api public */ -exports = module.exports = new Command(); -exports.program = exports; // More explicit access to global command. +Command.prototype.outputHelp = function(cb) { + if (!cb) { + cb = function(passthru) { + return passthru; + }; + } + const cbOutput = cb(this.helpInformation()); + if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) { + throw new Error('outputHelp callback must return a string or a Buffer'); + } + process.stdout.write(cbOutput); + this.emit(this._helpLongFlag); +}; /** - * Expose classes + * You can pass in flags and a description to override the help + * flags and help description for your command. + * + * @param {String} [flags] + * @param {String} [description] + * @return {Command} + * @api public */ -exports.Command = Command; -exports.Option = Option; -exports.CommanderError = CommanderError; -exports.InvalidOptionArgumentError = InvalidOptionArgumentError; -exports.Help = Help; +Command.prototype.helpOption = function(flags, description) { + this._helpFlags = flags || this._helpFlags; + this._helpDescription = description || this._helpDescription; + + var splitFlags = this._helpFlags.split(/[ ,|]+/); + + if (splitFlags.length > 1) this._helpShortFlag = splitFlags.shift(); + + this._helpLongFlag = splitFlags.shift(); + + return this; +}; + +/** + * Output help information and exit. + * + * @param {Function} [cb] + * @api public + */ + +Command.prototype.help = function(cb) { + this.outputHelp(cb); + // exitCode: preserving original behaviour which was calling process.exit() + // message: do not have all displayed text available so only passing placeholder. + this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)'); +}; /** * Camel-case the given `flag` * - * @param {string} flag - * @return {string} + * @param {String} flag + * @return {String} * @api private */ function camelcase(flag) { - return flag.split('-').reduce((str, word) => { + 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(' '); +} + +/** + * Wraps the given string with line breaks at the specified width while breaking + * words and indenting every but the first line on the left. + * + * @param {String} str + * @param {Number} width + * @param {Number} indent + * @return {String} + * @api private + */ +function wrap(str, width, indent) { + var regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); + var lines = str.match(regex) || []; + return lines.map(function(line, i) { + if (line.slice(-1) === '\n') { + line = line.slice(0, line.length - 1); + } + return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight(); + }).join('\n'); +} + +/** + * Optionally wrap the given str to a max width of width characters per line + * while indenting with indent spaces. Do not wrap if insufficient width or + * string is manually formatted. + * + * @param {String} str + * @param {Number} width + * @param {Number} indent + * @return {String} + * @api private + */ +function optionalWrap(str, width, indent) { + // Detect manually wrapped and indented strings by searching for line breaks + // followed by multiple spaces/tabs. + if (str.match(/[\n]\s+/)) return str; + // Do not wrap to narrow columns (or can end up with a word per line). + const minWidth = 40; + if (width < minWidth) return str; + + return wrap(str, width, indent); +} + +/** * Output help information if help flags specified * * @param {Command} cmd - command to output help for - * @param {Array} args - array of options to search for help flags + * @param {Array} options - array of options to search for -h or --help * @api private */ -function outputHelpIfRequested(cmd, args) { - const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag); - if (helpOption) { - cmd.outputHelp(); - // (Do not have all displayed text available so only passing placeholder.) - cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); +function outputHelpIfRequested(cmd, options) { + options = options || []; + + for (var i = 0; i < options.length; i++) { + if (options[i] === cmd._helpLongFlag || options[i] === cmd._helpShortFlag) { + cmd.outputHelp(); + // (Do not have all displayed text available so only passing placeholder.) + cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); + } } } @@ -2135,38 +1578,27 @@ function outputHelpIfRequested(cmd, args) { * Takes an argument and returns its human readable equivalent for help usage. * * @param {Object} arg - * @return {string} + * @return {String} * @api private */ function humanReadableArgName(arg) { - const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); + var nameOutput = arg.name + (arg.variadic === true ? '...' : ''); return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']'; } -/** - * Parse the short and long flag out of something like '-m,--mixed <value>' - * - * @api private - */ - -function _parseOptionFlags(flags) { - let shortFlag; - let longFlag; - // Use original very loose parsing to maintain backwards compatibility for now, - // which allowed for example unintended `-sw, --short-word` [sic]. - const flagParts = flags.split(/[ |,]+/); - if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift(); - longFlag = flagParts.shift(); - // Add support for lone short flag without significantly changing parsing! - if (!shortFlag && /^-[^-]$/.test(longFlag)) { - shortFlag = longFlag; - longFlag = undefined; +// 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; } - return { shortFlag, longFlag }; } /** @@ -2183,35 +1615,35 @@ function incrementNodeInspectorPort(args) { // --inspect-brk[=[host:]port] // --inspect-port=[host:]port return args.map((arg) => { - if (!arg.startsWith('--inspect')) { - return arg; - } - let debugOption; - let debugHost = '127.0.0.1'; - let debugPort = '9229'; - let match; - if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { - // e.g. --inspect - debugOption = match[1]; - } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { - debugOption = match[1]; - if (/^\d+$/.test(match[3])) { - // e.g. --inspect=1234 - debugPort = match[3]; - } else { - // e.g. --inspect=localhost + var result = arg; + if (arg.indexOf('--inspect') === 0) { + var debugOption; + var debugHost = '127.0.0.1'; + var debugPort = '9229'; + var match; + if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { + // e.g. --inspect + debugOption = match[1]; + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { + debugOption = match[1]; + if (/^\d+$/.test(match[3])) { + // e.g. --inspect=1234 + debugPort = match[3]; + } else { + // e.g. --inspect=localhost + debugHost = match[3]; + } + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { + // e.g. --inspect=localhost:1234 + debugOption = match[1]; debugHost = match[3]; + debugPort = match[4]; } - } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { - // e.g. --inspect=localhost:1234 - debugOption = match[1]; - debugHost = match[3]; - debugPort = match[4]; - } - if (debugOption && debugPort !== '0') { - return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + if (debugOption && debugPort !== '0') { + result = `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + } } - return arg; + return result; }); } diff --git a/node_modules/commander/package-support.json b/node_modules/commander/package-support.json deleted file mode 100644 index 4eabb970..00000000 --- a/node_modules/commander/package-support.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "versions": [ - { - "version": "*", - "target": { - "node": "supported" - }, - "response": { - "type": "time-permitting" - }, - "backing": { - "npm-funding": true - } - } - ] -} diff --git a/node_modules/commander/package.json b/node_modules/commander/package.json index ca153e59..e4781e5b 100644 --- a/node_modules/commander/package.json +++ b/node_modules/commander/package.json @@ -1,16 +1,12 @@ { "name": "commander", - "version": "7.2.0", + "version": "4.1.1", "description": "the complete solution for node.js command-line programs", "keywords": [ "commander", "command", "option", - "parser", - "cli", - "argument", - "args", - "argv" + "parser" ], "author": "TJ Holowaychuk <tj@vision-media.ca>", "license": "MIT", @@ -19,50 +15,27 @@ "url": "https://github.com/tj/commander.js.git" }, "scripts": { - "lint": "eslint index.js esm.mjs \"tests/**/*.js\"", - "typescript-lint": "eslint typings/*.ts tests/*.ts", + "lint": "eslint index.js \"tests/**/*.js\"", "test": "jest && npm run test-typings", - "test-esm": "node --experimental-modules ./tests/esm-imports-test.mjs", - "test-typings": "tsd", - "typescript-checkJS": "tsc --allowJS --checkJS index.js --noEmit", - "test-all": "npm run test && npm run lint && npm run typescript-lint && npm run typescript-checkJS && npm run test-esm" + "test-typings": "tsc -p tsconfig.json" }, - "main": "./index.js", + "main": "index", "files": [ "index.js", - "esm.mjs", - "typings/index.d.ts", - "package-support.json" + "typings/index.d.ts" ], - "type": "commonjs", "dependencies": {}, "devDependencies": { - "@types/jest": "^26.0.20", - "@types/node": "^14.14.20", - "@typescript-eslint/eslint-plugin": "^4.12.0", - "@typescript-eslint/parser": "^4.12.0", - "eslint": "^7.17.0", - "eslint-config-standard": "^16.0.2", - "eslint-plugin-jest": "^24.1.3", - "jest": "^26.6.3", - "standard": "^16.0.3", - "ts-jest": "^26.5.1", - "tsd": "^0.14.0", - "typescript": "^4.1.2" - }, - "types": "typings/index.d.ts", - "jest": { - "testEnvironment": "node", - "collectCoverage": true, - "transform": { - "^.+\\.tsx?$": "ts-jest" - }, - "testPathIgnorePatterns": [ - "/node_modules/" - ] + "@types/jest": "^24.0.23", + "@types/node": "^12.12.11", + "eslint": "^6.7.0", + "eslint-plugin-jest": "^22.21.0", + "jest": "^24.8.0", + "standard": "^14.3.1", + "typescript": "^3.7.2" }, + "typings": "typings/index.d.ts", "engines": { - "node": ">= 10" - }, - "support": true + "node": ">= 6" + } } diff --git a/node_modules/commander/typings/index.d.ts b/node_modules/commander/typings/index.d.ts index ee40d899..082a3a3c 100644 --- a/node_modules/commander/typings/index.d.ts +++ b/node_modules/commander/typings/index.d.ts @@ -1,9 +1,7 @@ // 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 */ +///<reference types="node" /> declare namespace commander { @@ -13,174 +11,41 @@ declare namespace commander { message: string; nestedError?: string; } - type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError; - - // eslint-disable-next-line @typescript-eslint/no-empty-interface - interface InvalidOptionArgumentError extends CommanderError { - } - type InvalidOptionArgumentErrorConstructor = new (message: string) => InvalidOptionArgumentError; + type CommanderErrorConstructor = { new (exitCode: number, code: string, message: string): CommanderError }; interface 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. - optionFlags: string; + bool: boolean; short?: string; - long?: string; - negate: boolean; - defaultValue?: any; - defaultValueDescription?: string; - parseArg?: <T>(value: string, previous: T) => T; - hidden: boolean; - argChoices?: string[]; - - /** - * Set the default value, and optionally supply the description to be displayed in the help. - */ - default(value: any, description?: 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; - - /** - * Validation of option argument failed. - * Intended for use from custom argument processing functions. - */ - argumentRejected(messsage: string): never; - - /** - * Only allow option value to be one of choices. - */ - choices(values: 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; - } - type OptionConstructor = new (flags: string, description?: string) => Option; - - interface Help { - /** output helpWidth, long lines are wrapped to fit */ - helpWidth?: number; - sortSubcommands: boolean; - sortOptions: boolean; - - /** Get the command term to show in the list of subcommands. */ - subcommandTerm(cmd: Command): string; - /** Get the command description 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 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 arguments which have descriptions. */ - visibleArguments(cmd: Command): Array<{ term: string; description: string}>; - - /** 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 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; - } - type HelpConstructor = new () => Help; - type HelpConfiguration = Partial<Help>; - - interface ParseOptions { - from: 'node' | 'electron' | 'user'; - } - interface HelpContext { // optional parameter for .help() and .outputHelp() - error: boolean; - } - interface AddHelpTextContext { // passed to text function used with .addHelpText() - error: boolean; - command: Command; - } - interface OutputConfiguration { - writeOut?(str: string): void; - writeErr?(str: string): void; - getOutHelpWidth?(): number; - getErrHelpWidth?(): number; - outputError?(str: string, write: (str: string) => void): void; - + long: string; + description: string; } + type OptionConstructor = { new (flags: string, description?: string): Option }; - type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll'; + interface Command extends NodeJS.EventEmitter { + [key: string]: any; // options as properties - interface OptionValues { - [key: string]: any; - } - - interface Command { args: string[]; - commands: Command[]; - parent: Command | null; /** - * Set the program version to `str`. + * 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; + version(str: string, flags?: string, description?: string): Command; /** * 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 @@ -190,104 +55,52 @@ declare namespace commander { * 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']>; + command(nameAndArgs: string, opts?: CommandOptions): Command; /** * 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'); + * .command('stop [service]', 'stop named serice, 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 + * @returns top level command for chaining more command definitions */ - command(nameAndArgs: string, description: string, opts?: commander.ExecutableCommandOptions): this; + command(nameAndArgs: string, description: string, opts?: commander.CommandOptions): Command; /** - * Factory routine to create a new unattached command. + * Define argument syntax for the top-level command. * - * See .command() for creating an attached subcommand, which uses this routine to - * create the command. You can override createCommand to customise subcommands. + * @returns Command for chaining */ - createCommand(name?: string): Command; + arguments(desc: string): Command; /** - * Add a prepared subcommand. - * - * See .command() for creating an attached subcommand which inherits settings from its parent. + * Parse expected `args`. * - * @returns `this` command for chaining - */ - addCommand(cmd: Command, opts?: CommandOptions): this; - - /** - * Define argument syntax for command. + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. * - * @returns `this` command for chaining + * @returns Command for chaining */ - arguments(desc: string): this; - - /** - * Override default decision whether to add implicit help command. - * - * 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; + parseExpectedArgs(args: string[]): Command; /** * Register callback to use as replacement for calling process.exit. */ - exitOverride(callback?: (err: CommanderError) => never|void): this; - - /** - * 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; + exitOverride(callback?: (err: CommanderError) => never|void): Command; /** * Register callback `fn` for the command. @@ -300,15 +113,15 @@ declare namespace commander { * // output help here * }); * - * @returns `this` command for chaining + * @returns Command for chaining */ - action(fn: (...args: any[]) => void | Promise<void>): this; + action(fn: (...args: any[]) => void | Promise<void>): Command; /** * Define option with `flags`, `description` and optional * coercion `fn`. * - * The `flags` string contains the short and/or long flags, + * 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. * @@ -344,155 +157,77 @@ declare namespace commander { * // optional argument * program.option('-c, --cheese [type]', 'add cheese [marble]'); * - * @returns `this` command for chaining + * @returns Command for chaining */ - option(flags: string, description?: string, defaultValue?: string | boolean): 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): this; + option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; + option(flags: string, description?: string, defaultValue?: any): Command; /** * 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. + * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space. */ - requiredOption(flags: string, description?: string, defaultValue?: string | boolean): 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): this; + requiredOption(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; + requiredOption(flags: string, description?: string, defaultValue?: any): Command; - /** - * 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 + * @return Command for chaining */ - storeOptionsAsProperties(): this & OptionValues; - storeOptionsAsProperties(storeAsProperties: true): this & OptionValues; - storeOptionsAsProperties(storeAsProperties?: boolean): this; + storeOptionsAsProperties(value?: boolean): Command; /** - * 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 + * Whether to pass command to action handler, + * or just the options (specify false). + * + * @return Command for chaining */ - combineFlagAndOptionalValue(combine?: boolean): this; + passCommandToAction(value?: boolean): Command; /** * 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 + * @param [arg] if `true` or omitted, no error will be thrown for unknown options. + * @returns 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; + allowUnknownOption(arg?: boolean): Command; /** * 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. - * - * Examples: - * - * 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 + * @returns Command for chaining */ - parse(argv?: string[], options?: ParseOptions): this; + parse(argv: string[]): Command; /** * 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. - * - * Examples: - * - * 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?: string[], options?: ParseOptions): Promise<this>; + parseAsync(argv: string[]): Promise<any>; /** - * Parse options from `argv` removing known options, - * and return argv split into operands and unknown arguments. - * - * @example - * 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], [] + * Parse options from `argv` returning `argv` void of these options. */ parseOptions(argv: string[]): commander.ParseOptionsResult; /** * Return an object containing options as key-value pairs */ - opts(): OptionValues; + opts(): { [key: string]: any }; /** * Set the description. - * - * @returns `this` command for chaining + * + * @returns Command for chaining */ - description(str: string, argsDescription?: {[argName: string]: string}): this; + description(str: string, argsDescription?: {[argName: string]: string}): Command; /** * Get the description. */ @@ -500,36 +235,21 @@ declare namespace commander { /** * 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 + * + * @returns Command for chaining */ - alias(alias: string): this; + alias(alias: string): Command; /** * 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: string[]): this; - /** - * Get aliases for the command. - */ - aliases(): string[]; - - /** * Set the command usage. - * - * @returns `this` command for chaining + * + * @returns Command for chaining */ - usage(str: string): this; + usage(str: string): Command; /** * Get the command usage. */ @@ -537,10 +257,10 @@ declare namespace commander { /** * Set the name of the command. - * - * @returns `this` command for chaining + * + * @returns Command for chaining */ - name(str: string): this; + name(str: string): Command; /** * Get the name of the command. */ @@ -549,79 +269,43 @@ declare namespace commander { /** * Output help information for this command. * - * Outputs built-in help, and custom text added using `.addHelpText()`. - * + * When listener(s) are available for the helpLongFlag + * those callbacks are invoked. */ - 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. + * flags and help description for your command. */ - helpOption(flags?: string | boolean, description?: string): this; + helpOption(flags?: string, description?: string): Command; - /** + /** * 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 | undefined): this; - - /** - * Add a listener (callback) for when events occur. (Implemented using EventEmitter.) - */ - on(event: string | symbol, listener: (...args: any[]) => void): this; } - type CommandConstructor = new (name?: string) => Command; + type CommandConstructor = { new (name?: string): Command }; - interface CommandOptions { - hidden?: boolean; - isDefault?: boolean; - /** @deprecated since v7, replaced by hidden */ - noHelp?: boolean; - } - interface ExecutableCommandOptions extends CommandOptions { - executableFile?: string; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - interface ParseOptionsResult { - operands: string[]; - unknown: string[]; - } + interface CommandOptions { + noHelp?: boolean; + isDefault?: boolean; + executableFile?: string; + } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - interface CommanderStatic extends Command { - program: Command; - Command: CommandConstructor; - Option: OptionConstructor; - CommanderError: CommanderErrorConstructor; - InvalidOptionArgumentError: InvalidOptionArgumentErrorConstructor; - Help: HelpConstructor; - } + interface ParseOptionsResult { + args: string[]; + unknown: string[]; + } + + interface CommanderStatic extends Command { + Command: CommandConstructor; + Option: OptionConstructor; + CommanderError:CommanderErrorConstructor; + } } -// Declaring namespace AND global -// eslint-disable-next-line @typescript-eslint/no-redeclare declare const commander: commander.CommanderStatic; export = commander; |
