From 1c0387549700d9ce64918fb5536e37350757c7dd Mon Sep 17 00:00:00 2001 From: littleblack111 Date: Wed, 27 Mar 2024 15:44:30 +0800 Subject: updates --- node_modules/commander/CHANGELOG.md | 701 ++++++++++++------------- node_modules/commander/Readme.md | 599 ++++++--------------- node_modules/commander/index.js | 847 ++++++++---------------------- node_modules/commander/package.json | 23 +- node_modules/commander/typings/index.d.ts | 293 +++++------ 5 files changed, 866 insertions(+), 1597 deletions(-) (limited to 'node_modules/commander') diff --git a/node_modules/commander/CHANGELOG.md b/node_modules/commander/CHANGELOG.md index f00cb2b5..7dce779d 100644 --- a/node_modules/commander/CHANGELOG.md +++ b/node_modules/commander/CHANGELOG.md @@ -1,436 +1,419 @@ -# Changelog +2.20.3 / 2019-10-11 +================== -All notable changes to this project will be documented in this file. + * Support Node.js 0.10 (Revert #1059) + * Ran "npm unpublish commander@2.20.2". There is no 2.20.2. -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.) +2.20.1 / 2019-09-29 +================== - + * Improve executable subcommand tracking + * Update dev dependencies -## [4.1.1] (2020-02-02) +2.20.0 / 2019-04-02 +================== -### Fixed + * fix: resolve symbolic links completely when hunting for subcommands (#935) + * Update index.d.ts (#930) + * Update Readme.md (#924) + * Remove --save option as it isn't required anymore (#918) + * Add link to the license file (#900) + * Added example of receiving args from options (#858) + * Added missing semicolon (#882) + * Add extension to .eslintrc (#876) + +2.19.0 / 2018-10-02 +================== -* TypeScript definition for `.action()` should include Promise for async ([#1157]) + * Removed newline after Options and Commands headers (#864) + * Bugfix - Error output (#862) + * Fix to change default value to string (#856) + +2.18.0 / 2018-09-07 +================== + + * Standardize help output (#853) + * chmod 644 travis.yml (#851) + * add support for execute typescript subcommand via ts-node (#849) + +2.17.1 / 2018-08-07 +================== + + * Fix bug in command emit (#844) + +2.17.0 / 2018-08-03 +================== + + * fixed newline output after help information (#833) + * Fix to emit the action even without command (#778) + * npm update (#823) + +2.16.0 / 2018-06-29 +================== + + * Remove Makefile and `test/run` (#821) + * Make 'npm test' run on Windows (#820) + * Add badge to display install size (#807) + * chore: cache node_modules (#814) + * chore: remove Node.js 4 (EOL), add Node.js 10 (#813) + * fixed typo in readme (#812) + * Fix types (#804) + * Update eslint to resolve vulnerabilities in lodash (#799) + * updated readme with custom event listeners. (#791) + * fix tests (#794) + +2.15.0 / 2018-03-07 +================== + + * Update downloads badge to point to graph of downloads over time instead of duplicating link to npm + * Arguments description + +2.14.1 / 2018-02-07 +================== + + * Fix typing of help function + +2.14.0 / 2018-02-05 +================== + + * only register the option:version event once + * Fixes issue #727: Passing empty string for option on command is set to undefined + * enable eqeqeq rule + * resolves #754 add linter configuration to project + * resolves #560 respect custom name for version option + * document how to override the version flag + * document using options per command + +2.13.0 / 2018-01-09 +================== + + * Do not print default for --no- + * remove trailing spaces in command help + * Update CI's Node.js to LTS and latest version + * typedefs: Command and Option types added to commander namespace + +2.12.2 / 2017-11-28 +================== + + * fix: typings are not shipped + +2.12.1 / 2017-11-23 +================== + + * Move @types/node to dev dependency + +2.12.0 / 2017-11-22 +================== + + * add attributeName() method to Option objects + * Documentation updated for options with --no prefix + * typings: `outputHelp` takes a string as the first parameter + * typings: use overloads + * feat(typings): update to match js api + * Print default value in option help + * Fix translation error + * Fail when using same command and alias (#491) + * feat(typings): add help callback + * fix bug when description is add after command with options (#662) + * Format js code + * Rename History.md to CHANGELOG.md (#668) + * feat(typings): add typings to support TypeScript (#646) + * use current node + +2.11.0 / 2017-07-03 +================== + + * Fix help section order and padding (#652) + * feature: support for signals to subcommands (#632) + * Fixed #37, --help should not display first (#447) + * Fix translation errors. (#570) + * Add package-lock.json + * Remove engines + * Upgrade package version + * Prefix events to prevent conflicts between commands and options (#494) + * Removing dependency on graceful-readlink + * Support setting name in #name function and make it chainable + * Add .vscode directory to .gitignore (Visual Studio Code metadata) + * Updated link to ruby commander in readme files + +2.10.0 / 2017-06-19 +================== + + * Update .travis.yml. drop support for older node.js versions. + * Fix require arguments in README.md + * On SemVer you do not start from 0.0.1 + * Add missing semi colon in readme + * Add save param to npm install + * node v6 travis test + * Update Readme_zh-CN.md + * Allow literal '--' to be passed-through as an argument + * Test subcommand alias help + * link build badge to master branch + * Support the alias of Git style sub-command + * added keyword commander for better search result on npm + * Fix Sub-Subcommands + * test node.js stable + * Fixes TypeError when a command has an option called `--description` + * Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets. + * Add chinese Readme file -## [4.1.0] (2020-01-06) +2.9.0 / 2015-10-13 +================== -### Added + * 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 -* 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]) +2.8.1 / 2015-04-22 +================== -### Fixed + * Back out `support multiline description` Close #396 #397 -* Remove trailing blanks from wrapped help text ([#1096]) +2.8.0 / 2015-04-07 +================== -### Changed + * 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 -* 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 +2.7.1 / 2015-03-11 +================== -## [4.0.1] (2019-11-12) + * Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367. -### Fixed +2.7.0 / 2015-03-09 +================== -* display help when requested, even if there are missing required options ([#1091]) + * 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 -## [4.0.0] (2019-11-02) +2.6.0 / 2014-12-30 +================== -### Added + * added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee + * Add application description to the help msg. Close #112 @dalssoft -* 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 +2.5.1 / 2014-12-15 +================== -### Changed + * fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee -* 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]) +2.5.0 / 2014-10-24 +================== -### Fixed + * add support for variadic arguments. Closes #277 @whitlockjc -* *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]) +2.4.0 / 2014-10-17 +================== -### Migration Tips + * 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 -#### Testing for no arguments +2.3.0 / 2014-07-16 +================== -If you were previously using code like: + * add command alias'. Closes PR #210 + * fix: Typos. Closes #99 + * fix: Unused fs module. Closes #217 -```js -if (!program.args.length) ... -``` +2.2.0 / 2014-03-29 +================== -a partial replacement is: + * 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. -```js -if (program.rawArgs.length < 3) ... -``` +2.1.0 / 2013-11-21 +================== -## [4.0.0-1] Prerelease (2019-10-08) + * add: allow cflag style option params, unit test, fixes #174 -(Released in 4.0.0) +2.0.0 / 2013-07-18 +================== -## [4.0.0-0] Prerelease (2019-10-01) + * remove input methods (.prompt, .confirm, etc) -(Released in 4.0.0) +1.3.2 / 2013-07-18 +================== -## [2.20.1] (2019-09-29) + * add support for sub-commands to co-exist with the original command -### Fixed +1.3.1 / 2013-07-18 +================== -* Improve tracking of executable subcommands. + * add quick .runningCommand hack so you can opt-out of other logic when running a sub command -### Changed +1.3.0 / 2013-07-09 +================== -* update development dependencies + * add EACCES error handling + * fix sub-command --help -## [3.0.2] (2019-09-27) +1.2.0 / 2013-06-13 +================== -### Fixed + * allow "-" hyphen as an option argument + * support for RegExp coercion -* Improve tracking of executable subcommands. +1.1.1 / 2012-11-20 +================== -### Changed + * add more sub-command padding + * fix .usage() when args are present. Closes #106 -* update development dependencies +1.1.0 / 2012-11-16 +================== -## [3.0.1] (2019-08-30) + * add git-style executable subcommand support. Closes #94 -### Added +1.0.5 / 2012-10-09 +================== -* .name and .usage to README ([#1010]) -* Table of Contents to README ([#1010]) -* TypeScript definition for `executableFile` in CommandOptions ([#1028]) + * fix `--name` clobbering. Closes #92 + * fix examples/help. Closes #89 -### Changed +1.0.4 / 2012-09-03 +================== -* consistently use `const` rather than `var` in README ([#1026]) + * add `outputHelp()` method. -### Fixed +1.0.3 / 2012-08-30 +================== -* help for sub commands with custom executableFile ([#1018]) + * remove invalid .version() defaulting -## [3.0.0] / 2019-08-08 +1.0.2 / 2012-08-24 +================== -* 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` + * add `--foo=bar` support [arv] + * fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus] -### Migration Tips +1.0.1 / 2012-08-03 +================== -The custom event for a negated option like `--no-foo` is `option:no-foo` (previously `option:foo`). + * fix issue #56 + * fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode()) -```js -program - .option('--no-foo') - .on('option:no-foo', () => { - console.log('removing foo'); - }); -``` +1.0.0 / 2012-07-05 +================== -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). + * add support for optional option descriptions + * add defaulting of `.version()` to package.json's version -```js -program - .command('action1', undefined, { noHelp: true }) // No longer valid - .command('action2', { noHelp: true }) // Correct -``` +0.6.1 / 2012-06-01 +================== -## 3.0.0-0 Prerelease / 2019-07-28 + * Added: append (yes or no) on confirmation + * Added: allow node.js v0.7.x -(Released as 3.0.0) +0.6.0 / 2012-04-10 +================== -## 2.20.0 / 2019-04-02 + * Added `.prompt(obj, callback)` support. Closes #49 + * Added default support to .choose(). Closes #41 + * Fixed the choice example -* 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) +0.5.1 / 2011-12-20 +================== -## 2.19.0 / 2018-10-02 + * Fixed `password()` for recent nodes. Closes #36 -* Removed newline after Options and Commands headers (#864) -* Bugfix - Error output (#862) -* Fix to change default value to string (#856) +0.5.0 / 2011-12-04 +================== -## 2.18.0 / 2018-09-07 + * Added sub-command option support [itay] -* Standardize help output (#853) -* chmod 644 travis.yml (#851) -* add support for execute typescript subcommand via ts-node (#849) +0.4.3 / 2011-12-04 +================== -## 2.17.1 / 2018-08-07 + * Fixed custom help ordering. Closes #32 -* Fix bug in command emit (#844) - -## 2.17.0 / 2018-08-03 - -* fixed newline output after help information (#833) -* Fix to emit the action even without command (#778) -* npm update (#823) - -## 2.16.0 / 2018-06-29 - -* Remove Makefile and `test/run` (#821) -* Make 'npm test' run on Windows (#820) -* Add badge to display install size (#807) -* chore: cache node_modules (#814) -* chore: remove Node.js 4 (EOL), add Node.js 10 (#813) -* fixed typo in readme (#812) -* Fix types (#804) -* Update eslint to resolve vulnerabilities in lodash (#799) -* updated readme with custom event listeners. (#791) -* fix tests (#794) - -## 2.15.0 / 2018-03-07 - -* Update downloads badge to point to graph of downloads over time instead of duplicating link to npm -* Arguments description - -## 2.14.1 / 2018-02-07 - -* Fix typing of help function - -## 2.14.0 / 2018-02-05 - -* only register the option:version event once -* Fixes issue #727: Passing empty string for option on command is set to undefined -* enable eqeqeq rule -* resolves #754 add linter configuration to project -* resolves #560 respect custom name for version option -* document how to override the version flag -* document using options per command - -## 2.13.0 / 2018-01-09 - -* Do not print default for --no- -* remove trailing spaces in command help -* Update CI's Node.js to LTS and latest version -* typedefs: Command and Option types added to commander namespace +0.4.2 / 2011-11-24 +================== -## 2.12.2 / 2017-11-28 + * Added travis support + * Fixed: line-buffered input automatically trimmed. Closes #31 -* fix: typings are not shipped +0.4.1 / 2011-11-18 +================== -## 2.12.1 / 2017-11-23 + * Removed listening for "close" on --help -* Move @types/node to dev dependency +0.4.0 / 2011-11-15 +================== -## 2.12.0 / 2017-11-22 + * Added support for `--`. Closes #24 -* 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 +0.3.3 / 2011-11-14 +================== -## 2.11.0 / 2017-07-03 + * Fixed: wait for close event when writing help info [Jerry Hamlet] -* 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 +0.3.2 / 2011-11-01 +================== -## 2.10.0 / 2017-06-19 + * Fixed long flag definitions with values [felixge] -* Update .travis.yml. drop support for older node.js versions. -* Fix require arguments in README.md -* On SemVer you do not start from 0.0.1 -* Add missing semi colon in readme -* Add save param to npm install -* node v6 travis test -* Update Readme_zh-CN.md -* Allow literal '--' to be passed-through as an argument -* Test subcommand alias help -* link build badge to master branch -* Support the alias of Git style sub-command -* added keyword commander for better search result on npm -* Fix Sub-Subcommands -* test node.js stable -* Fixes TypeError when a command has an option called `--description` -* Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets. -* Add chinese Readme file - -## 2.9.0 / 2015-10-13 - -* Add option `isDefault` to set default subcommand #415 @Qix- -* Add callback to allow filtering or post-processing of help text #434 @djulien -* Fix `undefined` text in help information close #414 #416 @zhiyelee - -## 2.8.1 / 2015-04-22 - -* Back out `support multiline description` Close #396 #397 - -## 2.8.0 / 2015-04-07 - -* Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee -* Fix bug in Git-style sub-commands #372 @zhiyelee -* Allow commands to be hidden from help #383 @tonylukasavage -* When git-style sub-commands are in use, yet none are called, display help #382 @claylo -* Add ability to specify arguments syntax for top-level command #258 @rrthomas -* Support multiline descriptions #208 @zxqfox - -## 2.7.1 / 2015-03-11 - -* Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367. - -## 2.7.0 / 2015-03-09 - -* Fix git-style bug when installed globally. Close #335 #349 @zhiyelee -* Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage -* Add support for camelCase on `opts()`. Close #353 @nkzawa -* Add node.js 0.12 and io.js to travis.yml -* Allow RegEx options. #337 @palanik -* Fixes exit code when sub-command failing. Close #260 #332 @pirelenito -* git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee - -## 2.6.0 / 2014-12-30 - -* added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee -* Add application description to the help msg. Close #112 @dalssoft - -## 2.5.1 / 2014-12-15 - -* fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee - -## 2.5.0 / 2014-10-24 - -* add support for variadic arguments. Closes #277 @whitlockjc - -## 2.4.0 / 2014-10-17 - -* fixed a bug on executing the coercion function of subcommands option. Closes #270 -* added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage -* added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage -* fixed a bug on subcommand name. Closes #248 @jonathandelgado -* fixed function normalize doesn’t honor option terminator. Closes #216 @abbr - -## 2.3.0 / 2014-07-16 - -* add command alias'. Closes PR #210 -* fix: Typos. Closes #99 -* fix: Unused fs module. Closes #217 - -## 2.2.0 / 2014-03-29 - -* add passing of previous option value -* fix: support subcommands on windows. Closes #142 -* Now the defaultValue passed as the second argument of the coercion function. - -## 2.1.0 / 2013-11-21 - -* add: allow cflag style option params, unit test, fixes #174 - -## 2.0.0 / 2013-07-18 - -* remove input methods (.prompt, .confirm, etc) - -## Older versions - -* [1.x](./changelogs/CHANGELOG-1.md) -* [0.x](./changelogs/CHANGELOG-0.md) - -[#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 -[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 +0.3.1 / 2011-10-31 +================== + + * Changed `--version` short flag to `-V` from `-v` + * Changed `.version()` so it's configurable [felixge] + +0.3.0 / 2011-10-31 +================== + + * Added support for long flags only. Closes #18 + +0.2.1 / 2011-10-24 +================== + + * "node": ">= 0.4.x < 0.7.0". Closes #20 + +0.2.0 / 2011-09-26 +================== + + * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs] + +0.1.0 / 2011-08-24 +================== + + * Added support for custom `--help` output + +0.0.5 / 2011-08-18 +================== + + * Changed: when the user enters nothing prompt for password again + * Fixed issue with passwords beginning with numbers [NuckChorris] + +0.0.4 / 2011-08-15 +================== + + * Fixed `Commander#args` + +0.0.3 / 2011-08-15 +================== + + * Added default option value support + +0.0.2 / 2011-08-15 +================== + + * Added mask support to `Command#password(str[, mask], fn)` + * Added `Command#password(str, fn)` + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/commander/Readme.md b/node_modules/commander/Readme.md index aa4f42b5..c846e7a2 100644 --- a/node_modules/commander/Readme.md +++ b/node_modules/commander/Readme.md @@ -1,345 +1,187 @@ # Commander.js + [![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js) [![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander) [![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true) [![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander) +[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + + The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander). + [API documentation](http://tj.github.com/commander.js/) -The complete solution for [node.js](http://nodejs.org) command-line interfaces, 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) - - [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 flag|value](#other-option-types-negatable-boolean-and-flagvalue) - - [Custom option processing](#custom-option-processing) - - [Required option](#required-option) - - [Version option](#version-option) - - [Commands](#commands) - - [Specify the argument syntax](#specify-the-argument-syntax) - - [Action handler (sub)commands](#action-handler-subcommands) - - [Git-style executable (sub)commands](#git-style-executable-subcommands) - - [Automated --help](#automated---help) - - [Custom help](#custom-help) - - [.usage and .name](#usage-and-name) - - [.outputHelp(cb)](#outputhelpcb) - - [.helpOption(flags, description)](#helpoptionflags-description) - - [.help(cb)](#helpcb) - - [Custom event listeners](#custom-event-listeners) - - [Bits and pieces](#bits-and-pieces) - - [Avoiding option name clashes](#avoiding-option-name-clashes) - - [TypeScript](#typescript) - - [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) ## Installation -```bash -npm install commander -``` + $ npm install commander -## Declaring _program_ variable +## Option parsing -Commander exports a global object which is convenient for quick programs. -This is used in the examples in this README for brevity. +Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. ```js -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 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. - -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`. - -See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes). - -### Common option types, boolean and value +#!/usr/bin/env node -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. +/** + * Module dependencies. + */ -```js -const program = require('commander'); +var program = require('commander'); program - .option('-d, --debug', 'output extra debugging') - .option('-s, --small', 'small pizza size') - .option('-p, --pizza-type ', 'flavour of pizza'); - -program.parse(process.argv); - -if (program.debug) console.log(program.opts()); -console.log('pizza details:'); -if (program.small) console.log('- small pizza size'); -if (program.pizzaType) console.log(`- ${program.pizzaType}`); -``` + .version('0.1.0') + .option('-p, --peppers', 'Add peppers') + .option('-P, --pineapple', 'Add pineapple') + .option('-b, --bbq-sauce', 'Add bbq sauce') + .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') + .parse(process.argv); -```bash -$ pizza-options -d -{ debug: true, small: undefined, pizzaType: undefined } -pizza details: -$ pizza-options -p -error: option '-p, --pizza-type ' argument missing -$ pizza-options -ds -p vegetarian -{ debug: true, small: true, pizzaType: 'vegetarian' } -pizza details: -- small pizza size -- vegetarian -$ pizza-options --pizza-type=cheese -pizza details: -- cheese +console.log('you ordered a pizza with:'); +if (program.peppers) console.log(' - peppers'); +if (program.pineapple) console.log(' - pineapple'); +if (program.bbqSauce) console.log(' - bbq'); +console.log(' - %s cheese', program.cheese); ``` -`program.parse(arguments)` processes the arguments, leaving any args not consumed by the options as the `program.args` array. - -### Default option value +Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. -You can specify a default value for an option which takes a value. +Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false. ```js -const program = require('commander'); - -program - .option('-c, --cheese ', 'add the specified type of cheese', 'blue'); - -program.parse(process.argv); - -console.log(`cheese: ${program.cheese}`); -``` - -```bash -$ pizza-options -cheese: blue -$ pizza-options --cheese stilton -cheese: stilton -``` - -### Other option types, negatable boolean and flag|value - -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. +#!/usr/bin/env node -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 flag and it can be overridden on command line. +/** + * Module dependencies. + */ -```js -const program = require('commander'); +var program = require('commander'); program .option('--no-sauce', 'Remove sauce') - .option('--cheese ', 'cheese flavour', 'mozzarella') - .option('--no-cheese', 'plain with no cheese') .parse(process.argv); -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}`); +console.log('you ordered a pizza'); +if (program.sauce) console.log(' with sauce'); +else console.log(' without sauce'); ``` -```bash -$ pizza-options -You ordered a pizza with sauce and mozzarella cheese -$ pizza-options --sauce -error: unknown option '--sauce' -$ pizza-options --cheese=blue -You ordered a pizza with sauce and blue cheese -$ pizza-options --no-sauce --no-cheese -You ordered a pizza with no sauce and no cheese -``` +To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs. -You can specify an option which functions as a flag but may also take a value (declared using square brackets). +e.g. ```.option('-m --myarg [myVar]', 'my super cool description')``` -```js -const program = require('commander'); +Then to access the input if it was passed in. -program - .option('-c, --cheese [type]', 'Add cheese with optional type'); +e.g. ```var myInput = program.myarg``` -program.parse(process.argv); +**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in. -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 -$ pizza-options -no cheese -$ pizza-options --cheese -add cheese -$ pizza-options --cheese mozzarella -add cheese type mozzarella -``` -### Custom option processing +## Version option -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. +Calling the `version` implicitly adds the `-V` and `--version` options to the command. +When either of these options is present, the command prints the version number and exits. -This allows you to coerce the option value to the desired type, or accumulate values, or do entirely custom processing. + $ ./examples/pizza -V + 0.0.1 -You can optionally specify the default/starting value for the option after the function. +If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method. ```js -const program = require('commander'); - -function myParseInt(value, dummyPrevious) { - // parseInt takes a string and an optional radix - return parseInt(value); -} - -function increaseVerbosity(dummyValue, previous) { - return previous + 1; -} - -function collect(value, previous) { - return previous.concat([value]); -} - -function commaSeparatedList(value, dummyPrevious) { - return value.split(','); -} - program - .option('-f, --float ', 'float argument', parseFloat) - .option('-i, --integer ', 'integer argument', myParseInt) - .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0) - .option('-c, --collect ', 'repeatable value', collect, []) - .option('-l, --list ', 'comma separated list', commaSeparatedList) -; - -program.parse(process.argv); - -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); + .version('0.0.1', '-v, --version') ``` -```bash -$ custom -f 1e2 -float: 100 -$ custom --integer 2 -integer: 2 -$ custom -v -v -v -verbose: 3 -$ custom -c a -c b -c c -[ 'a', 'b', 'c' ] -$ custom --list x,y,z -[ 'x', 'y', 'z' ] -``` +The version flags can be named anything, but the long option is required. -### Required option +## Command-specific options -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. +You can attach options to a command. ```js -const program = require('commander'); - -program - .requiredOption('-c, --cheese ', 'pizza must have cheese'); - -program.parse(process.argv); -``` - -``` -$ pizza -error: required option '-c, --cheese ' not specified -``` +#!/usr/bin/env node -### Version option +var program = require('commander'); -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. +program + .command('rm ') + .option('-r, --recursive', 'Remove recursively') + .action(function (dir, cmd) { + console.log('remove ' + dir + (cmd.recursive ? ' recursively' : '')) + }) -```js -program.version('0.0.1'); +program.parse(process.argv) ``` -```bash -$ ./examples/pizza -V -0.0.1 -``` +A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated. -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. +## Coercion ```js -program.version('0.0.1', '-v, --vers', 'output the current version'); -``` +function range(val) { + return val.split('..').map(Number); +} -## Commands +function list(val) { + return val.split(','); +} -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 `` or `[optional]`, and the last argument may also be `variadic...`. +function collect(val, memo) { + memo.push(val); + return memo; +} -For example: +function increaseVerbosity(v, total) { + return total + 1; +} -```js -// Command implemented using action handler (description is supplied separately to `.command`) -// Returns new command for configuring. program - .command('clone [destination]') - .description('clone a repository into a newly created directory') - .action((source, destination) => { - console.log('clone command called'); - }); + .version('0.1.0') + .usage('[options] ') + .option('-i, --integer ', 'An integer argument', parseInt) + .option('-f, --float ', 'A float argument', parseFloat) + .option('-r, --range ..', 'A range', range) + .option('-l, --list ', 'A list', list) + .option('-o, --optional [value]', 'An optional value') + .option('-c, --collect [value]', 'A repeatable value', collect, []) + .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0) + .parse(process.argv); -// Command implemented using separate executable file (description is second parameter to `.command`) -// Returns top-level command for adding more commands. -program - .command('start ', 'start named service') - .command('stop [service]', 'stop named service, or all if no name supplied'); +console.log(' int: %j', program.integer); +console.log(' float: %j', program.float); +console.log(' optional: %j', program.optional); +program.range = program.range || []; +console.log(' range: %j..%j', program.range[0], program.range[1]); +console.log(' list: %j', program.list); +console.log(' collect: %j', program.collect); +console.log(' verbosity: %j', program.verbose); +console.log(' args: %j', program.args); ``` -### Specify the argument syntax - -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. ``) indicate required input. Square brackets (e.g. `[optional]`) indicate optional input. - +## Regular Expression ```js -const program = require('commander'); - program .version('0.1.0') - .arguments(' [env]') - .action(function (cmd, env) { - cmdValue = cmd; - envValue = env; - }); - -program.parse(process.argv); + .option('-s --size ', 'Pizza size', /^(large|medium|small)$/i, 'medium') + .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i) + .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"); +console.log(' size: %j', program.size); +console.log(' drink: %j', program.drink); ``` - 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: +## Variadic arguments + + The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to + append `...` to the argument name. Here is an example: ```js -const program = require('commander'); +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var program = require('commander'); program .version('0.1.0') @@ -356,91 +198,83 @@ program program.parse(process.argv); ``` -The variadic argument is passed to the action handler as an array. (And this also applies to `program.args`.) - -### Action handler (sub)commands + An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed + to your action as demonstrated above. -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. +## Specify the argument syntax ```js -const program = require('commander'); - -program - .command('rm ') - .option('-r, --recursive', 'Remove recursively') - .action(function (dir, cmdObj) { - console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : '')) - }) +#!/usr/bin/env node -program.parse(process.argv) -``` +var program = require('commander'); -You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`. +program + .version('0.1.0') + .arguments(' [env]') + .action(function (cmd, env) { + cmdValue = cmd; + envValue = env; + }); -```js -async function run() { /* code goes here */ } +program.parse(process.argv); -async function main() { - program - .command('run') - .action(run); - await program.parseAsync(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"); ``` +Angled brackets (e.g. ``) indicate required input. Square brackets (e.g. `[env]`) indicate optional input. -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. - -Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. - -### 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. +## Git-style sub-commands ```js // file: ./examples/pm -const program = require('commander'); +var 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}) .parse(process.argv); ``` -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. +When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools. +The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`. + +Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the subcommand from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified. If the program is designed to be installed globally, make sure the executables have proper modes, like `755`. +### `--harmony` + +You can enable `--harmony` option in two ways: +* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern. +* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process. + ## Automated --help 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 +``` $ ./examples/pizza --help Usage: pizza [options] An application for pizzas ordering Options: + -h, --help output usage information -V, --version output the version number -p, --peppers Add peppers -P, --pineapple Add pineapple -b, --bbq Add bbq sauce - -c, --cheese Add the specified type of cheese (default: "marble") + -c, --cheese Add the specified type of cheese [marble] -C, --no-cheese You do not want any cheese - -h, --help output usage information ``` -### Custom help +## Custom help You can display arbitrary `-h, --help` information by listening for "--help". Commander will automatically @@ -452,7 +286,11 @@ Options: ```js #!/usr/bin/env node -const program = require('commander'); +/** + * Module dependencies. + */ + +var program = require('commander'); program .version('0.1.0') @@ -477,7 +315,7 @@ console.log('stuff'); 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: @@ -492,24 +330,7 @@ Examples: $ custom-help -h ``` -### .usage and .name - -These allow you to customise the usage description in the first line of the help. The name is otherwise -deduced from the (full) program arguments. Given: - -```js -program - .name("my-command") - .usage("[global options] command") -``` - -The help will start with: - -```Text -Usage: my-command [global options] command -``` - -### .outputHelp(cb) +## .outputHelp(cb) Output help information without exiting. Optional callback cb allows post-processing of help text before it is displayed. @@ -517,8 +338,8 @@ Optional callback cb allows post-processing of help text before it is displayed. If you want to display help by default (e.g. if no command was provided), you can use something like: ```js -const program = require('commander'); -const colors = require('colors'); +var program = require('commander'); +var colors = require('colors'); program .version('0.1.0') @@ -534,22 +355,13 @@ function make_red(txt) { } ``` -### .helpOption(flags, description) - - Override the default help flags and description. - -```js -program - .helpOption('-e, --HELP', 'read more information'); -``` - -### .help(cb) +## .help(cb) Output help information and exit immediately. Optional callback cb allows post-processing of help text before it is displayed. -## Custom event listeners +## Custom event listeners You can execute custom actions by listening to command and option events. ```js @@ -564,94 +376,10 @@ program.on('command:*', function () { }); ``` -## Bits and pieces - -### Avoiding option name clashes - -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. - -There are two new routines to change the behaviour, and the default behaviour may change in the future: - -- `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 -// file: ./examples/storeOptionsAsProperties.action.js -program - .storeOptionsAsProperties(false) - .passCommandToAction(false); - -program - .name('my-program-name') - .option('-n,--name '); - -program - .command('show') - .option('-a,--action ') - .action((options) => { - console.log(options.action); - }); - -program.parse(process.argv); - -const programOptions = program.opts(); -console.log(programOptions.name); -``` - -### TypeScript - -The Commander package includes its TypeScript Definition file, but also requires the node types which you need to install yourself. e.g. - -```bash -npm install commander -npm install --save-dev @types/node -``` - -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. - -```bash -node -r ts-node/register pm.ts -``` - -### Node options such as `--harmony` - -You can enable `--harmony` option in two ways: - -- 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. - -### Node debugging - -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. - -### 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`. - -The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help -is not affected by the override which is called after the display. - -``` js -program.exitOverride(); - -try { - program.parse(process.argv); -} catch (err) { - // custom processing... -} -``` - ## Examples ```js -const program = require('commander'); +var program = require('commander'); program .version('0.1.0') @@ -664,7 +392,7 @@ program .description('run setup commands for all envs') .option("-s, --setup_mode [mode]", "Which setup mode to use") .action(function(env, options){ - const mode = options.setup_mode || "normal"; + var mode = options.setup_mode || "normal"; env = env || 'all'; console.log('setup for %s env(s) with %s mode', env, mode); }); @@ -698,16 +426,3 @@ More Demos can be found in the [examples](https://github.com/tj/commander.js/tre ## License [MIT](https://github.com/tj/commander.js/blob/master/LICENSE) - -## 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. - -### Commander for enterprise - -Available as part of the Tidelift Subscription - -The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/commander/index.js b/node_modules/commander/index.js index 37d20cc5..ec1d61d5 100644 --- a/node_modules/commander/index.js +++ b/node_modules/commander/index.js @@ -43,10 +43,9 @@ exports.Option = Option; 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; + this.required = flags.indexOf('<') >= 0; + this.optional = flags.indexOf('[') >= 0; + this.bool = flags.indexOf('-no-') === -1; flags = flags.split(/[ ,|]+/); if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); this.long = flags.shift(); @@ -61,7 +60,9 @@ function Option(flags, description) { */ Option.prototype.name = function() { - return this.long.replace(/^--/, ''); + return this.long + .replace('--', '') + .replace('no-', ''); }; /** @@ -73,7 +74,7 @@ Option.prototype.name = function() { */ Option.prototype.attributeName = function() { - return camelcase(this.name().replace(/^no-/, '')); + return camelcase(this.name()); }; /** @@ -88,109 +89,99 @@ Option.prototype.is = function(arg) { return this.short === arg || this.long === arg; }; -/** - * CommanderError class - * @class - */ -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 - * @constructor - */ - constructor(exitCode, code, message) { - super(message); - // properly capture stack trace in Node.js - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - this.code = code; - this.exitCode = exitCode; - } -} - -exports.CommanderError = CommanderError; - /** * Initialize a new `Command`. * - * @param {String} [name] + * @param {String} name * @api public */ function Command(name) { this.commands = []; this.options = []; - this._execs = new Set(); + this._execs = {}; 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'; } /** - * Define a command. + * Add command `name`. + * + * The `.action()` callback is invoked when the + * command `name` is specified via __ARGV__, + * and the remaining arguments are applied to the + * function for access. * - * There are two styles of command: pay attention to where to put the description. + * When the `name` is "*" an un-matched command + * will be passed as the first arg, followed by + * the rest of __ARGV__ remaining. * * Examples: * - * // Command implemented using action handler (description is supplied separately to `.command`) * program - * .command('clone [destination]') - * .description('clone a repository into a newly created directory') - * .action((source, destination) => { - * console.log('clone command called'); + * .version('0.0.1') + * .option('-C, --chdir ', 'change the working directory') + * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + * .option('-T, --no-tests', 'ignore test hook') + * + * program + * .command('setup') + * .description('run remote setup commands') + * .action(function() { + * console.log('setup'); * }); * - * // Command implemented using separate executable file (description is second parameter to `.command`) * program - * .command('start ', 'start named service') - * .command('stop [service]', 'stop named service, or all if no name supplied'); + * .command('exec ') + * .description('run the given remote command') + * .action(function(cmd) { + * console.log('exec "%s"', cmd); + * }); + * + * program + * .command('teardown [otherDirs...]') + * .description('run teardown commands') + * .action(function(dir, otherDirs) { + * console.log('dir "%s"', dir); + * if (otherDirs) { + * otherDirs.forEach(function (oDir) { + * console.log('dir "%s"', oDir); + * }); + * } + * }); * - * @param {string} nameAndArgs - command name and arguments, args are `` 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 + * program + * .command('*') + * .description('deploy the given env') + * .action(function(env) { + * console.log('deploying "%s"', env); + * }); + * + * program.parse(process.argv); + * + * @param {String} name + * @param {String} [desc] for git-style sub-commands + * @return {Command} the new command * @api public */ -Command.prototype.command = function(nameAndArgs, actionOptsOrExecDesc, execOpts) { - var desc = actionOptsOrExecDesc; - var opts = execOpts; +Command.prototype.command = function(name, desc, opts) { if (typeof desc === 'object' && desc !== null) { opts = desc; desc = null; } opts = opts || {}; - var args = nameAndArgs.split(/ +/); + var args = name.split(/ +/); var cmd = new Command(args.shift()); if (desc) { cmd.description(desc); this.executables = true; - this._execs.add(cmd._name); + this._execs[cmd._name] = true; 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; @@ -261,47 +252,6 @@ Command.prototype.parseExpectedArgs = function(args) { 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} for chaining - * @api public - */ - -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; -}; - -/** - * 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 - */ - -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); -}; - /** * Register callback `fn` for the command. * @@ -329,8 +279,7 @@ Command.prototype.action = function(fn) { var parsed = self.parseOptions(unknown); // Output help if necessary - outputHelpIfRequested(self, parsed.unknown); - self._checkForMissingMandatoryOptions(); + outputHelpIfNecessary(self, parsed.unknown); // If there are still any unknown options, then we simply // die, unless someone asked for help, in which case we give it @@ -354,26 +303,16 @@ Command.prototype.action = function(fn) { } }); - // 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; + // Always append ourselves to the end of the arguments, + // to make sure we match the number of arguments the user + // expects + if (self._args.length) { + args[self._args.length] = self; } else { - actionArgs[expectedArgsCount] = self.opts(); - } - // Add the extra arguments so available too. - if (args.length > expectedArgsCount) { - actionArgs.push(args.slice(expectedArgsCount)); + args.push(self); } - 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; - } - rootCommand._actionResults.push(actionResult); + fn.apply(self, args); }; var parent = this.parent || this; var name = parent === this ? '*' : this._name; @@ -383,29 +322,63 @@ Command.prototype.action = function(fn) { }; /** - * Internal implementation shared by .option() and .requiredOption() + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to false + * program.option('-p, --pepper', 'add pepper'); + * + * --pepper + * program.pepper + * // => Boolean + * + * // simple boolean defaulting to true + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); * - * @param {Object} config * @param {String} flags * @param {String} description - * @param {Function|*} [fn] - custom option processing function or default vaue + * @param {Function|*} [fn] or default * @param {*} [defaultValue] * @return {Command} for chaining - * @api private + * @api public */ -Command.prototype._optionEx = function(config, flags, description, fn, defaultValue) { +Command.prototype.option = function(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); @@ -417,16 +390,13 @@ Command.prototype._optionEx = function(config, flags, description, fn, defaultVa } } - // preassign default value for --no-*, [optional], , 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; - } + // preassign default value only for --no-*, [optional], or + if (!option.bool || option.optional || option.required) { + // when --no-* we make sure default is true + if (!option.bool) defaultValue = true; // preassign only if we have a default if (defaultValue !== undefined) { - self._setOptionValue(name, defaultValue); + self[name] = defaultValue; option.defaultValue = defaultValue; } } @@ -439,102 +409,28 @@ Command.prototype._optionEx = function(config, flags, description, fn, defaultVa this.on('option:' + oname, function(val) { // coercion if (val !== null && fn) { - val = fn(val, self._getOptionValue(name) === undefined ? defaultValue : self._getOptionValue(name)); + val = fn(val, self[name] === undefined ? defaultValue : self[name]); } - // 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! + // unassigned or bool + if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') { + // if no value, bool true, and we have a default, then use it! if (val == null) { - self._setOptionValue(name, option.negate - ? false - : defaultValue || true); + self[name] = option.bool + ? defaultValue || true + : false; } else { - self._setOptionValue(name, val); + self[name] = val; } } else if (val !== null) { // reassign - self._setOptionValue(name, option.negate ? false : val); + self[name] = val; } }); return this; }; -/** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * Examples: - * - * // simple boolean defaulting to 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 ', '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 - */ - -Command.prototype.option = function(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 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 - */ - -Command.prototype.requiredOption = function(flags, description, fn, defaultValue) { - return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); -}; - /** * Allow unknown options on the command line. * @@ -548,70 +444,7 @@ Command.prototype.allowUnknownOption = function(arg) { }; /** - * 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 - */ - -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; -}; - -/** - * Whether to pass command to action handler, - * or just the options (specify false). - * - * @param {boolean} value - * @return {Command} Command for chaining - * @api public - */ - -Command.prototype.passCommandToAction = function(value) { - this._passCommandToAction = (value === undefined) || value; - return this; -}; - -/** - * Store option value - * - * @param {String} key - * @param {Object} value - * @api private - */ - -Command.prototype._setOptionValue = function(key, value) { - if (this._storeOptionsAsProperties) { - this[key] = value; - } else { - this._optionValues[key] = value; - } -}; - -/** - * Retrieve option value - * - * @param {String} key - * @return {Object} value - * @api private - */ - -Command.prototype._getOptionValue = function(key) { - if (this._storeOptionsAsProperties) { - return this[key]; - } - return this._optionValues[key]; -}; - -/** - * Parse `argv`, setting options and invoking commands when defined. + * Parse `argv`, settings options and invoking commands when defined. * * @param {Array} argv * @return {Command} for chaining @@ -631,117 +464,72 @@ Command.prototype.parse = function(argv) { // github-style sub-commands with no sub-command if (this.executables && argv.length < 3 && !this.defaultExecutable) { // this user needs help - argv.push(this._helpLongFlag); + argv.push('--help'); } // process argv - var normalized = this.normalize(argv.slice(2)); - var parsed = this.parseOptions(normalized); + var parsed = this.parseOptions(this.normalize(argv.slice(2))); var args = this.args = parsed.args; var result = this.parseArgs(this.args, parsed.unknown); - if (args[0] === 'help' && args.length === 1) this.help(); - - // Note for future: we could return early if we found an action handler in parseArgs, as none of following code needed? - - // --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(); - } - // 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; - // Look for subcommand + var aliasCommand = null; + // check alias of sub commands if (name) { - subCommand = this.commands.find(function(command) { - return command._name === name; - }); - } - - // Look for alias - if (!subCommand && name) { - subCommand = this.commands.find(function(command) { + aliasCommand = this.commands.filter(function(command) { return command.alias() === name; - }); - if (subCommand) { - name = subCommand._name; - args[0] = name; - } - } - - // Look for default subcommand - if (!subCommand && this.defaultExecutable) { - name = this.defaultExecutable; - args.unshift(name); - subCommand = this.commands.find(function(command) { - return command._name === name; - }); + })[0]; } - if (this._execs.has(name)) { - return this.executeSubCommand(argv, args, parsed.unknown, subCommand ? subCommand._executableFile : undefined); + if (this._execs[name] === true) { + return this.executeSubCommand(argv, args, parsed.unknown); + } else if (aliasCommand) { + // is alias of a subCommand + args[0] = aliasCommand._name; + return this.executeSubCommand(argv, args, parsed.unknown); + } else if (this.defaultExecutable) { + // use the default subcommand + args.unshift(this.defaultExecutable); + return this.executeSubCommand(argv, args, parsed.unknown); } return result; }; -/** - * 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); -}; - /** * Execute a sub-command executable. * * @param {Array} argv * @param {Array} args * @param {Array} unknown - * @param {String} executableFile * @api private */ -Command.prototype.executeSubCommand = function(argv, args, unknown, executableFile) { +Command.prototype.executeSubCommand = function(argv, args, unknown) { args = args.concat(unknown); if (!args.length) this.help(); + if (args[0] === 'help' && args.length === 1) this.help(); - var isExplicitJS = false; // Whether to use node to launch "executable" + // --help + if (args[0] === 'help') { + args[0] = args[1]; + args[1] = '--help'; + } // 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'; - } + var f = argv[1]; + // name of the subcommand, link `pm-install` + var bin = basename(f, path.extname(f)) + '-' + args[0]; // In case of globally installed, get the base dir where executable // subcommand file should be located at var baseDir; - var resolvedLink = fs.realpathSync(pm); + var resolvedLink = fs.realpathSync(f); baseDir = dirname(resolvedLink); @@ -749,15 +537,13 @@ Command.prototype.executeSubCommand = function(argv, args, unknown, executableFi var localBin = path.join(baseDir, bin); // whether bin file is a js script with explicit `.js` or `.ts` extension + var isExplicitJS = false; if (exists(localBin + '.js')) { bin = localBin + '.js'; isExplicitJS = true; } else if (exists(localBin + '.ts')) { bin = localBin + '.ts'; isExplicitJS = true; - } else if (exists(localBin + '.mjs')) { - bin = localBin + '.mjs'; - isExplicitJS = true; } else if (exists(localBin)) { bin = localBin; } @@ -769,16 +555,14 @@ Command.prototype.executeSubCommand = function(argv, args, unknown, executableFi if (isExplicitJS) { args.unshift(bin); // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); + args = (process.execArgv || []).concat(args); - proc = spawn(process.argv[0], args, { stdio: 'inherit' }); + proc = spawn(process.argv[0], args, { stdio: 'inherit', customFds: [0, 1, 2] }); } else { - proc = spawn(bin, args, { stdio: 'inherit' }); + proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] }); } } else { args.unshift(bin); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); proc = spawn(process.execPath, args, { stdio: 'inherit' }); } @@ -790,30 +574,14 @@ Command.prototype.executeSubCommand = function(argv, args, unknown, executableFi } }); }); - - // 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('close', process.exit.bind(process)); proc.on('error', function(err) { if (err.code === 'ENOENT') { console.error('error: %s(1) does not exist, try --help', bin); } else if (err.code === 'EACCES') { console.error('error: %s(1) not executable. try chmod or run with root', bin); } - if (!exitCallback) { - process.exit(1); - } else { - const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); - wrappedError.nestedError = err; - exitCallback(wrappedError); - } + process.exit(1); }); // Store the reference to the child process @@ -834,9 +602,7 @@ Command.prototype.normalize = function(args) { var ret = [], arg, lastOpt, - index, - short, - opt; + index; for (var i = 0, len = args.length; i < len; ++i) { arg = args[i]; @@ -850,17 +616,10 @@ Command.prototype.normalize = function(args) { 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 { - arg.slice(1).split('').forEach(function(c) { - ret.push('-' + c); - }); - } + } else if (arg.length > 1 && arg[0] === '-' && arg[1] !== '-') { + arg.slice(1).split('').forEach(function(c) { + ret.push('-' + c); + }); } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { ret.push(arg.slice(0, index), arg.slice(index + 1)); } else { @@ -891,14 +650,14 @@ Command.prototype.parseArgs = function(args, unknown) { if (this.listeners('command:' + name).length) { this.emit('command:' + args.shift(), args, unknown); } else { - this.emit('command:*', args, unknown); + this.emit('command:*', args); } } else { - outputHelpIfRequested(this, unknown); + outputHelpIfNecessary(this, unknown); // If there were no args and we have unknown options, // then they are extraneous and we need to error. - if (unknown.length > 0 && !this.defaultExecutable) { + if (unknown.length > 0) { this.unknownOption(unknown[0]); } if (this.commands.length === 0 && @@ -926,29 +685,12 @@ Command.prototype.optionFor = function(arg) { } }; -/** - * Display an error message if a mandatory option does not have a value. - * - * @api private - */ - -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); - } - }); - } -}; - /** * Parse options from `argv` returning `argv` * void of these options. * * @param {Array} argv - * @return {{args: Array, unknown: Array}} + * @return {Array} * @api public */ @@ -995,7 +737,7 @@ Command.prototype.parseOptions = function(argv) { ++i; } this.emit('option:' + option.name(), arg); - // flag + // bool } else { this.emit('option:' + option.name()); } @@ -1009,7 +751,7 @@ Command.prototype.parseOptions = function(argv) { // 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] === '-')) { + if ((i + 1) < argv.length && argv[i + 1][0] !== '-') { unknownOptions.push(argv[++i]); } continue; @@ -1029,19 +771,14 @@ Command.prototype.parseOptions = function(argv) { * @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; - } + var result = {}, + len = this.options.length; - return this._optionValues; + for (var i = 0; i < len; i++) { + var key = this.options[i].attributeName(); + result[key] = key === this._versionOptionName ? this._version : this[key]; + } + return result; }; /** @@ -1052,41 +789,25 @@ Command.prototype.opts = function() { */ Command.prototype.missingArgument = function(name) { - const message = `error: missing required argument '${name}'`; - console.error(message); - this._exit(1, 'commander.missingArgument', message); + console.error("error: missing required argument `%s'", name); + process.exit(1); }; /** * `Option` is missing an argument, but received `flag` or nothing. * - * @param {Option} option - * @param {String} [flag] + * @param {String} 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}'`; + console.error("error: option `%s' argument missing, got `%s'", option.flags, flag); } else { - message = `error: option '${option.flags}' argument missing`; + console.error("error: option `%s' argument missing", option.flags); } - console.error(message); - this._exit(1, 'commander.optionMissingArgument', message); -}; - -/** - * `Option` does not have a value, and is a mandatory option. - * - * @param {Option} option - * @api private - */ - -Command.prototype.missingMandatoryOptionValue = function(option) { - const message = `error: required option '${option.flags}' not specified`; - console.error(message); - this._exit(1, 'commander.missingMandatoryOptionValue', message); + process.exit(1); }; /** @@ -1098,9 +819,8 @@ Command.prototype.missingMandatoryOptionValue = function(option) { Command.prototype.unknownOption = function(flag) { if (this._allowUnknownOption) return; - const message = `error: unknown option '${flag}'`; - console.error(message); - this._exit(1, 'commander.unknownOption', message); + console.error("error: unknown option `%s'", flag); + process.exit(1); }; /** @@ -1111,9 +831,8 @@ Command.prototype.unknownOption = function(flag) { */ Command.prototype.variadicArgNotLast = function(name) { - const message = `error: variadic arguments must be last '${name}'`; - console.error(message); - this._exit(1, 'commander.variadicArgNotLast', message); + console.error("error: variadic arguments must be last `%s'", name); + process.exit(1); }; /** @@ -1122,27 +841,22 @@ Command.prototype.variadicArgNotLast = function(name) { * 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 */ -Command.prototype.version = function(str, flags, description) { +Command.prototype.version = function(str, flags) { 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); + var versionOption = new Option(flags, 'output the version number'); 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); + process.exit(0); }); return this; }; @@ -1151,7 +865,7 @@ Command.prototype.version = function(str, flags, description) { * Set the description to `str`. * * @param {String} str - * @param {Object} [argsDescription] + * @param {Object} argsDescription * @return {String|Command} * @api public */ @@ -1188,7 +902,7 @@ Command.prototype.alias = function(alias) { /** * Set / get the command usage `str`. * - * @param {String} [str] + * @param {String} str * @return {String|Command} * @api public */ @@ -1211,7 +925,7 @@ Command.prototype.usage = function(str) { /** * Get or set the name of the command * - * @param {String} [str] + * @param {String} str * @return {String|Command} * @api public */ @@ -1271,9 +985,8 @@ Command.prototype.largestCommandLength = function() { Command.prototype.largestOptionLength = function() { var options = [].slice.call(this.options); options.push({ - flags: this._helpFlags + flags: '-h, --help' }); - return options.reduce(function(max, option) { return Math.max(max, option.flags.length); }, 0); @@ -1326,15 +1039,11 @@ Command.prototype.padWidth = function() { Command.prototype.optionHelp = function() { var width = this.padWidth(); - var columns = process.stdout.columns || 80; - var descriptionWidth = columns - width - 4; - // 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)]) + return pad(option.flags, width) + ' ' + option.description + + ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : ''); + }).concat([pad('-h, --help', width) + ' ' + 'output usage information']) .join('\n'); }; @@ -1351,14 +1060,11 @@ Command.prototype.commandHelp = function() { var commands = this.prepareCommands(); var width = this.padWidth(); - var columns = process.stdout.columns || 80; - var descriptionWidth = columns - width - 4; - 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); + return (desc ? pad(cmd[0], width) : cmd[0]) + desc; }).join('\n').replace(/^/gm, ' '), '' ].join('\n'); @@ -1382,12 +1088,10 @@ Command.prototype.helpInformation = function() { 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(' ' + pad(arg.name, width) + ' ' + argsDescription[arg.name]); }); desc.push(''); } @@ -1397,12 +1101,8 @@ Command.prototype.helpInformation = function() { 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(), + 'Usage: ' + cmdName + ' ' + this.usage(), '' ]; @@ -1424,10 +1124,7 @@ Command.prototype.helpInformation = function() { }; /** - * Output help information for this command. - * - * When listener(s) are available for the helpLongFlag - * those callbacks are invoked. + * Output help information for this command * * @api public */ @@ -1438,49 +1135,19 @@ Command.prototype.outputHelp = function(cb) { 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); -}; - -/** - * 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 - */ - -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; + process.stdout.write(cb(this.helpInformation())); + this.emit('--help'); }; /** * 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)'); + process.exit(); }; /** @@ -1512,70 +1179,25 @@ function pad(str, width) { } /** - * Wraps the given string with line breaks at the specified width while breaking - * words and indenting every but the first line on the left. + * Output help information if necessary * - * @param {String} str - * @param {Number} width - * @param {Number} indent - * @return {String} + * @param {Command} command to output help for + * @param {Array} array of options to search for -h or --help * @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} options - array of options to search for -h or --help - * @api private - */ - -function outputHelpIfRequested(cmd, options) { +function outputHelpIfNecessary(cmd, options) { options = options || []; - for (var i = 0; i < options.length; i++) { - if (options[i] === cmd._helpLongFlag || options[i] === cmd._helpShortFlag) { + if (options[i] === '--help' || options[i] === '-h') { cmd.outputHelp(); - // (Do not have all displayed text available so only passing placeholder.) - cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); + process.exit(0); } } } /** - * Takes an argument and returns its human readable equivalent for help usage. + * Takes an argument an returns its human readable equivalent for help usage. * * @param {Object} arg * @return {String} @@ -1600,50 +1222,3 @@ function exists(file) { return false; } } - -/** - * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). - * - * @param {string[]} args - array of arguments from node.execArgv - * @returns {string[]} - * @api private - */ - -function incrementNodeInspectorPort(args) { - // Testing for these options: - // --inspect[=[host:]port] - // --inspect-brk[=[host:]port] - // --inspect-port=[host:]port - return args.map((arg) => { - 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]; - } - - if (debugOption && debugPort !== '0') { - result = `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; - } - } - return result; - }); -} diff --git a/node_modules/commander/package.json b/node_modules/commander/package.json index e4781e5b..0023c5cd 100644 --- a/node_modules/commander/package.json +++ b/node_modules/commander/package.json @@ -1,6 +1,6 @@ { "name": "commander", - "version": "4.1.1", + "version": "2.20.3", "description": "the complete solution for node.js command-line programs", "keywords": [ "commander", @@ -15,8 +15,8 @@ "url": "https://github.com/tj/commander.js.git" }, "scripts": { - "lint": "eslint index.js \"tests/**/*.js\"", - "test": "jest && npm run test-typings", + "lint": "eslint index.js", + "test": "node test/run.js && npm run test-typings", "test-typings": "tsc -p tsconfig.json" }, "main": "index", @@ -26,16 +26,13 @@ ], "dependencies": {}, "devDependencies": { - "@types/jest": "^24.0.23", - "@types/node": "^12.12.11", - "eslint": "^6.7.0", - "eslint-plugin-jest": "^22.21.0", - "jest": "^24.8.0", + "@types/node": "^12.7.8", + "eslint": "^6.4.0", + "should": "^13.2.3", + "sinon": "^7.5.0", "standard": "^14.3.1", - "typescript": "^3.7.2" + "ts-node": "^8.4.1", + "typescript": "^3.6.3" }, - "typings": "typings/index.d.ts", - "engines": { - "node": ">= 6" - } + "typings": "typings/index.d.ts" } diff --git a/node_modules/commander/typings/index.d.ts b/node_modules/commander/typings/index.d.ts index 082a3a3c..bcda2771 100644 --- a/node_modules/commander/typings/index.d.ts +++ b/node_modules/commander/typings/index.d.ts @@ -1,106 +1,130 @@ -// Type definitions for commander -// Original definitions by: Alan Agius , Marcelo Dezem , vvakame , Jules Randolph +// Type definitions for commander 2.11 +// Project: https://github.com/visionmedia/commander.js +// Definitions by: Alan Agius , Marcelo Dezem , vvakame , Jules Randolph +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +declare namespace local { -declare namespace commander { - - interface CommanderError extends Error { - code: string; - exitCode: number; - message: string; - nestedError?: string; - } - type CommanderErrorConstructor = { new (exitCode: number, code: string, message: string): CommanderError }; - - interface Option { + class Option { flags: string; - required: boolean; // A value must be supplied when the option is specified. - optional: boolean; // A value is optional when the option is specified. - mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line. + required: boolean; + optional: boolean; bool: boolean; short?: string; long: string; description: string; + + /** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {string} flags + * @param {string} [description] + */ + constructor(flags: string, description?: string); } - type OptionConstructor = { new (flags: string, description?: string): Option }; - interface Command extends NodeJS.EventEmitter { - [key: string]: any; // options as properties + class Command extends NodeJS.EventEmitter { + [key: string]: any; args: string[]; /** - * Set the program version to `str`. + * Initialize a new `Command`. * - * 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} [name] */ - version(str: string, flags?: string, description?: string): Command; + constructor(name?: string); /** - * Define a command, implemented using an action handler. - * - * @remarks - * The command description is supplied using `.description`, not as a parameter to `.command`. - * - * @example - * ```ts - * program - * .command('clone [destination]') - * .description('clone a repository into a newly created directory') - * .action((source, destination) => { - * console.log('clone command called'); - * }); - * ``` - * - * @param nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` - * @param opts - configuration options - * @returns new command + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * @param {string} str + * @param {string} [flags] + * @returns {Command} for chaining */ - command(nameAndArgs: string, opts?: CommandOptions): Command; + version(str: string, flags?: string): Command; + /** - * Define a command, implemented in a separate executable file. - * - * @remarks - * The command description is supplied as the second parameter to `.command`. - * + * Add command `name`. + * + * The `.action()` callback is invoked when the + * command `name` is specified via __ARGV__, + * and the remaining arguments are applied to the + * function for access. + * + * When the `name` is "*" an un-matched command + * will be passed as the first arg, followed by + * the rest of __ARGV__ remaining. + * * @example - * ```ts - * program - * .command('start ', 'start named service') - * .command('stop [service]', 'stop named serice, or all if no name supplied'); - * ``` - * - * @param nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` - * @param description - description of executable command - * @param opts - configuration options - * @returns top level command for chaining more command definitions + * program + * .version('0.0.1') + * .option('-C, --chdir ', 'change the working directory') + * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') + * .option('-T, --no-tests', 'ignore test hook') + * + * program + * .command('setup') + * .description('run remote setup commands') + * .action(function() { + * console.log('setup'); + * }); + * + * program + * .command('exec ') + * .description('run the given remote command') + * .action(function(cmd) { + * console.log('exec "%s"', cmd); + * }); + * + * program + * .command('teardown [otherDirs...]') + * .description('run teardown commands') + * .action(function(dir, otherDirs) { + * console.log('dir "%s"', dir); + * if (otherDirs) { + * otherDirs.forEach(function (oDir) { + * console.log('dir "%s"', oDir); + * }); + * } + * }); + * + * program + * .command('*') + * .description('deploy the given env') + * .action(function(env) { + * console.log('deploying "%s"', env); + * }); + * + * program.parse(process.argv); + * + * @param {string} name + * @param {string} [desc] for git-style sub-commands + * @param {CommandOptions} [opts] command options + * @returns {Command} the new command */ - command(nameAndArgs: string, description: string, opts?: commander.CommandOptions): Command; + command(name: string, desc?: string, opts?: commander.CommandOptions): Command; /** * Define argument syntax for the top-level command. * - * @returns Command for chaining + * @param {string} desc + * @returns {Command} for chaining */ arguments(desc: string): Command; /** - * Parse expected `args`. + * Parse expected `args`. * * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. * - * @returns Command for chaining + * @param {string[]} args + * @returns {Command} for chaining */ - parseExpectedArgs(args: string[]): Command; - - /** - * Register callback to use as replacement for calling process.exit. - */ - exitOverride(callback?: (err: CommanderError) => never|void): Command; + parseExpectedArgs(args: string[]): Command; /** * Register callback `fn` for the command. @@ -113,9 +137,10 @@ declare namespace commander { * // output help here * }); * - * @returns Command for chaining + * @param {(...args: any[]) => void} fn + * @returns {Command} for chaining */ - action(fn: (...args: any[]) => void | Promise): Command; + action(fn: (...args: any[]) => void): Command; /** * Define option with `flags`, `description` and optional @@ -157,141 +182,114 @@ declare namespace commander { * // optional argument * program.option('-c, --cheese [type]', 'add cheese [marble]'); * - * @returns Command for chaining + * @param {string} flags + * @param {string} [description] + * @param {((arg1: any, arg2: any) => void) | RegExp} [fn] function or default + * @param {*} [defaultValue] + * @returns {Command} for chaining */ option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; option(flags: string, description?: string, defaultValue?: any): Command; - /** - * 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 should contain both the short and long flags, separated by comma, a pipe or space. - */ - requiredOption(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command; - requiredOption(flags: string, description?: string, defaultValue?: any): Command; - - - /** - * 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(). - * - * @return Command for chaining - */ - storeOptionsAsProperties(value?: boolean): Command; - - /** - * Whether to pass command to action handler, - * or just the options (specify false). - * - * @return Command for chaining - */ - passCommandToAction(value?: boolean): Command; - /** * Allow unknown options on the command line. * - * @param [arg] if `true` or omitted, no error will be thrown for unknown options. - * @returns Command for chaining + * @param {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options. + * @returns {Command} for chaining */ allowUnknownOption(arg?: boolean): Command; /** - * Parse `argv`, setting options and invoking commands when defined. + * Parse `argv`, settings options and invoking commands when defined. * - * @returns Command for chaining + * @param {string[]} argv + * @returns {Command} for chaining */ 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. - * - * @returns Promise - */ - parseAsync(argv: string[]): Promise; - /** * Parse options from `argv` returning `argv` void of these options. + * + * @param {string[]} argv + * @returns {ParseOptionsResult} */ parseOptions(argv: string[]): commander.ParseOptionsResult; /** * Return an object containing options as key-value pairs + * + * @returns {{[key: string]: any}} */ opts(): { [key: string]: any }; /** - * Set the description. - * - * @returns Command for chaining + * Set the description to `str`. + * + * @param {string} str + * @param {{[argName: string]: string}} argsDescription + * @return {(Command | string)} */ description(str: string, argsDescription?: {[argName: string]: string}): Command; - /** - * Get the description. - */ description(): string; /** * Set an alias for the command. - * - * @returns Command for chaining + * + * @param {string} alias + * @return {(Command | string)} */ alias(alias: string): Command; - /** - * Get alias for the command. - */ alias(): string; /** - * Set the command usage. - * - * @returns Command for chaining + * Set or get the command usage. + * + * @param {string} str + * @return {(Command | string)} */ usage(str: string): Command; - /** - * Get the command usage. - */ usage(): string; /** * Set the name of the command. - * - * @returns Command for chaining + * + * @param {string} str + * @return {Command} */ name(str: string): Command; + /** * Get the name of the command. + * + * @return {string} */ name(): string; /** * Output help information for this command. * - * When listener(s) are available for the helpLongFlag - * those callbacks are invoked. + * @param {(str: string) => string} [cb] */ outputHelp(cb?: (str: string) => string): void; - /** - * You can pass in flags and a description to override the help - * flags and help description for your command. - */ - helpOption(flags?: string, description?: string): Command; - - /** - * Output help information and exit. + /** Output help information and exit. + * + * @param {(str: string) => string} [cb] */ help(cb?: (str: string) => string): never; } - type CommandConstructor = { new (name?: string): Command }; +} + +declare namespace commander { + + type Command = local.Command + + type Option = local.Option interface CommandOptions { noHelp?: boolean; isDefault?: boolean; - executableFile?: string; } interface ParseOptionsResult { @@ -300,10 +298,11 @@ declare namespace commander { } interface CommanderStatic extends Command { - Command: CommandConstructor; - Option: OptionConstructor; - CommanderError:CommanderErrorConstructor; - } + Command: typeof local.Command; + Option: typeof local.Option; + CommandOptions: CommandOptions; + ParseOptionsResult: ParseOptionsResult; + } } -- cgit v1.2.3