Socket
Socket
Sign inDemoInstall

commander

Package Overview
Dependencies
0
Maintainers
6
Versions
114
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 4.0.1 to 4.1.0

171

CHANGELOG.md

@@ -10,2 +10,23 @@ # Changelog

## [4.1.0] (2020-01-06)
### Added
- two routines to change how option values are handled, and eliminate name clashes with command properties ([#933] [#1102])
- see storeOptionsAsProperties and passCommandToAction in README
- `.parseAsync` to use instead of `.parse` if supply async action handlers ([#806] [#1118])
### Fixed
- Remove trailing blanks from wrapped help text ([#1096])
### Changed
- update dependencies
- extend security coverage for Commander 2.x to 2020-02-03
- improvements to README
- improvements to TypeScript definition documentation
- move old versions out of main CHANGELOG
- removed explicit use of `ts-node` in tests
## [4.0.1] (2019-11-12)

@@ -15,3 +36,3 @@

* display help when requested, even if there are missing required options [(#1091)]
* display help when requested, even if there are missing required options ([#1091])

@@ -360,144 +381,7 @@ ## [4.0.0] (2019-11-02)

## 1.3.2 / 2013-07-18
## Older versions
* add support for sub-commands to co-exist with the original command
* [1.x](./changelogs/CHANGELOG-1.md)
* [0.x](./changelogs/CHANGELOG-0.md)
## 1.3.1 / 2013-07-18
* add quick .runningCommand hack so you can opt-out of other logic when running a sub command
## 1.3.0 / 2013-07-09
* add EACCES error handling
* fix sub-command --help
## 1.2.0 / 2013-06-13
* allow "-" hyphen as an option argument
* support for RegExp coercion
## 1.1.1 / 2012-11-20
* add more sub-command padding
* fix .usage() when args are present. Closes #106
## 1.1.0 / 2012-11-16
* add git-style executable subcommand support. Closes #94
## 1.0.5 / 2012-10-09
* fix `--name` clobbering. Closes #92
* fix examples/help. Closes #89
## 1.0.4 / 2012-09-03
* add `outputHelp()` method.
## 1.0.3 / 2012-08-30
* remove invalid .version() defaulting
## 1.0.2 / 2012-08-24
* add `--foo=bar` support [arv]
* fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus]
## 1.0.1 / 2012-08-03
* fix issue #56
* fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode())
## 1.0.0 / 2012-07-05
* add support for optional option descriptions
* add defaulting of `.version()` to package.json's version
## 0.6.1 / 2012-06-01
* Added: append (yes or no) on confirmation
* Added: allow node.js v0.7.x
## 0.6.0 / 2012-04-10
* Added `.prompt(obj, callback)` support. Closes #49
* Added default support to .choose(). Closes #41
* Fixed the choice example
## 0.5.1 / 2011-12-20
* Fixed `password()` for recent nodes. Closes #36
## 0.5.0 / 2011-12-04
* Added sub-command option support [itay]
## 0.4.3 / 2011-12-04
* Fixed custom help ordering. Closes #32
## 0.4.2 / 2011-11-24
* Added travis support
* Fixed: line-buffered input automatically trimmed. Closes #31
## 0.4.1 / 2011-11-18
* Removed listening for "close" on --help
## 0.4.0 / 2011-11-15
* Added support for `--`. Closes #24
## 0.3.3 / 2011-11-14
* Fixed: wait for close event when writing help info [Jerry Hamlet]
## 0.3.2 / 2011-11-01
* Fixed long flag definitions with values [felixge]
## 0.3.1 / 2011-10-31
* Changed `--version` short flag to `-V` from `-v`
* Changed `.version()` so it's configurable [felixge]
## 0.3.0 / 2011-10-31
* Added support for long flags only. Closes #18
## 0.2.1 / 2011-10-24
* "node": ">= 0.4.x < 0.7.0". Closes #20
## 0.2.0 / 2011-09-26
* Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs]
## 0.1.0 / 2011-08-24
* Added support for custom `--help` output
## 0.0.5 / 2011-08-18
* Changed: when the user enters nothing prompt for password again
* Fixed issue with passwords beginning with numbers [NuckChorris]
## 0.0.4 / 2011-08-15
* Fixed `Commander#args`
## 0.0.3 / 2011-08-15
* Added default option value support
## 0.0.2 / 2011-08-15
* Added mask support to `Command#password(str[, mask], fn)`
* Added `Command#password(str, fn)`
## 0.0.1 / 2010-01-03
* Initial release
[#599]: https://github.com/tj/commander.js/issues/599

@@ -507,2 +391,3 @@ [#611]: https://github.com/tj/commander.js/issues/611

[#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

@@ -516,2 +401,3 @@ [#938]: https://github.com/tj/commander.js/issues/938

[#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

@@ -534,2 +420,5 @@ [#1010]: https://github.com/tj/commander.js/pull/1010

[#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

@@ -536,0 +425,0 @@ [Unreleased]: https://github.com/tj/commander.js/compare/master...develop

173

index.js

@@ -118,3 +118,3 @@ /**

*
* @param {String} name
* @param {String} [name]
* @api public

@@ -130,2 +130,6 @@ */

this._name = name || '';
this._optionValues = {};
this._storeOptionsAsProperties = true; // backwards compatible by default
this._passCommandToAction = true; // backwards compatible by default
this._actionResults = [];

@@ -156,3 +160,3 @@ this._helpFlags = '-h, --help';

* .command('start <service>', 'start named service')
* .command('stop [service]', 'stop named serice, or all if no name supplied');
* .command('stop [service]', 'stop named service, or all if no name supplied');
*

@@ -189,2 +193,4 @@ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`

cmd._exitCallback = this._exitCallback;
cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;
cmd._passCommandToAction = this._passCommandToAction;

@@ -330,3 +336,3 @@ cmd._executableFile = opts.executableFile; // Custom name for executable file

// Output help if necessary
outputHelpIfNecessary(self, parsed.unknown);
outputHelpIfRequested(self, parsed.unknown);
self._checkForMissingMandatoryOptions();

@@ -359,3 +365,7 @@

var actionArgs = args.slice(0, expectedArgsCount);
actionArgs[expectedArgsCount] = self;
if (self._passCommandToAction) {
actionArgs[expectedArgsCount] = self;
} else {
actionArgs[expectedArgsCount] = self.opts();
}
// Add the extra arguments so available too.

@@ -366,3 +376,9 @@ if (args.length > expectedArgsCount) {

fn.apply(self, actionArgs);
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);
};

@@ -415,8 +431,8 @@ var parent = this.parent || this;

if (option.negate) {
var opts = self.opts();
defaultValue = Object.prototype.hasOwnProperty.call(opts, name) ? opts[name] : true;
const positiveLongFlag = option.long.replace(/^--no-/, '--');
defaultValue = self.optionFor(positiveLongFlag) ? self._getOptionValue(name) : true;
}
// preassign only if we have a default
if (defaultValue !== undefined) {
self[name] = defaultValue;
self._setOptionValue(name, defaultValue);
option.defaultValue = defaultValue;

@@ -434,18 +450,18 @@ }

if (val !== null && fn) {
val = fn(val, self[name] === undefined ? defaultValue : self[name]);
val = fn(val, self._getOptionValue(name) === undefined ? defaultValue : self._getOptionValue(name));
}
// unassigned or boolean value
if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') {
if (typeof self._getOptionValue(name) === 'boolean' || typeof self._getOptionValue(name) === 'undefined') {
// if no value, negate false, and we have a default, then use it!
if (val == null) {
self[name] = option.negate
self._setOptionValue(name, option.negate
? false
: defaultValue || true;
: defaultValue || true);
} else {
self[name] = val;
self._setOptionValue(name, val);
}
} else if (val !== null) {
// reassign
self[name] = option.negate ? false : val;
self._setOptionValue(name, option.negate ? false : val);
}

@@ -544,4 +560,67 @@ });

/**
* Parse `argv`, settings options and invoking commands when defined.
* 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.
*
* @param {Array} argv

@@ -630,2 +709,16 @@ * @return {Command} for chaining

/**
* 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.

@@ -636,3 +729,3 @@ *

* @param {Array} unknown
* @param {String} specifySubcommand
* @param {String} executableFile
* @api private

@@ -816,3 +909,3 @@ */

} else {
outputHelpIfNecessary(this, unknown);
outputHelpIfRequested(this, unknown);

@@ -859,3 +952,3 @@ // If there were no args and we have unknown options,

cmd.options.forEach((anOption) => {
if (anOption.mandatory && (cmd[anOption.attributeName()] === undefined)) {
if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {
cmd.missingMandatoryOptionValue(anOption);

@@ -872,3 +965,3 @@ }

* @param {Array} argv
* @return {Array}
* @return {{args: Array, unknown: Array}}
* @api public

@@ -954,10 +1047,15 @@ */

Command.prototype.opts = function() {
var result = {},
len = this.options.length;
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];
for (var i = 0; i < len; i++) {
var key = this.options[i].attributeName();
result[key] = key === this._versionOptionName ? this._version : this[key];
}
return result;
}
return result;
return this._optionValues;
};

@@ -981,4 +1079,4 @@

*
* @param {String} option
* @param {String} flag
* @param {Option} option
* @param {String} [flag]
* @api private

@@ -1001,3 +1099,3 @@ */

*
* @param {String} option
* @param {Option} option
* @api private

@@ -1062,5 +1160,6 @@ */

this.options.push(versionOption);
var self = this;
this.on('option:' + this._versionOptionName, function() {
process.stdout.write(str + '\n');
this._exit(0, 'commander.version', str);
self._exit(0, 'commander.version', str);
});

@@ -1074,3 +1173,3 @@ return this;

* @param {String} str
* @param {Object} argsDescription
* @param {Object} [argsDescription]
* @return {String|Command}

@@ -1112,3 +1211,3 @@ * @api public

*
* @param {String} str
* @param {String} [str]
* @return {String|Command}

@@ -1136,3 +1235,3 @@ * @api public

*
* @param {String} str
* @param {String} [str]
* @return {String|Command}

@@ -1454,3 +1553,3 @@ * @api public

}
return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line;
return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight();
}).join('\n');

@@ -1482,10 +1581,10 @@ }

/**
* Output help information if necessary
* Output help information if help flags specified
*
* @param {Command} command to output help for
* @param {Array} array of options to search for -h or --help
* @param {Command} cmd - command to output help for
* @param {Array} options - array of options to search for -h or --help
* @api private
*/
function outputHelpIfNecessary(cmd, options) {
function outputHelpIfRequested(cmd, options) {
options = options || [];

@@ -1492,0 +1591,0 @@

{
"name": "commander",
"version": "4.0.1",
"version": "4.1.0",
"description": "the complete solution for node.js command-line programs",

@@ -29,10 +29,9 @@ "keywords": [

"devDependencies": {
"@types/jest": "^24.0.18",
"@types/node": "^12.7.5",
"eslint": "^6.4.0",
"eslint-plugin-jest": "^22.17.0",
"@types/jest": "^24.0.23",
"@types/node": "^12.12.11",
"eslint": "^6.7.0",
"eslint-plugin-jest": "^22.21.0",
"jest": "^24.8.0",
"standard": "^14.3.1",
"ts-node": "^8.4.1",
"typescript": "^3.6.3"
"typescript": "^3.7.2"
},

@@ -39,0 +38,0 @@ "typings": "typings/index.d.ts",

@@ -14,3 +14,3 @@ # Commander.js

- [Installation](#installation)
- [Declaring _program_ variable](#declaring-program-variable)
- [Declaring program variable](#declaring-program-variable)
- [Options](#options)

@@ -35,4 +35,5 @@ - [Common option types, boolean and value](#common-option-types-boolean-and-value)

- [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 options such as --harmony](#node-options-such-as---harmony)
- [Node debugging](#node-debugging)

@@ -75,2 +76,4 @@ - [Override exit handling](#override-exit-handling)

See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes).
### Common option types, boolean and value

@@ -380,2 +383,15 @@

You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
```js
async function run() { /* code goes here */ }
async function main() {
program
.command('run')
.action(run);
await program.parseAsync(process.argv);
}
```
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.

@@ -557,2 +573,39 @@

### 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 <name>');
program
.command('show')
.option('-a,--action <action>')
.action((options) => {
console.log(options.action);
});
program.parse(process.argv);
const programOptions = program.opts();
console.log(programOptions.name);
```
### TypeScript

@@ -656,3 +709,4 @@

Commander is supported on Node 8 and above. (Commander is likely to still work on older versions of Node, but is not tested below Node 8.)
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.)

@@ -659,0 +713,0 @@ The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.

@@ -1,5 +0,3 @@

// Type definitions for commander 2.11
// Project: https://github.com/visionmedia/commander.js
// Definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Type definitions for commander
// Original definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>

@@ -42,3 +40,2 @@ ///<reference types="node" />

* You can optionally supply the flags and description to override the defaults.
*
*/

@@ -91,4 +88,3 @@ version(str: string, flags?: string, description?: string): Command;

*
* @param {string} desc
* @returns {Command} for chaining
* @returns Command for chaining
*/

@@ -102,4 +98,3 @@ arguments(desc: string): Command;

*
* @param {string[]} args
* @returns {Command} for chaining
* @returns Command for chaining
*/

@@ -124,4 +119,3 @@ parseExpectedArgs(args: string[]): Command;

*
* @param {(...args: any[]) => void} fn
* @returns {Command} for chaining
* @returns Command for chaining
*/

@@ -170,7 +164,3 @@ action(fn: (...args: any[]) => void): Command;

*
* @param {string} flags
* @param {string} [description]
* @param {((arg1: any, arg2: any) => void) | RegExp} [fn] function or default
* @param {*} [defaultValue]
* @returns {Command} for chaining
* @returns Command for chaining
*/

@@ -189,7 +179,24 @@ option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, 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 {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options.
* @returns {Command} for chaining
* @param [arg] if `true` or omitted, no error will be thrown for unknown options.
* @returns Command for chaining
*/

@@ -199,6 +206,5 @@ allowUnknownOption(arg?: boolean): Command;

/**
* Parse `argv`, settings options and invoking commands when defined.
* Parse `argv`, setting options and invoking commands when defined.
*
* @param {string[]} argv
* @returns {Command} for chaining
* @returns Command for chaining
*/

@@ -208,7 +214,13 @@ parse(argv: string[]): Command;

/**
* Parse options from `argv` returning `argv` void of these options.
* 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 {string[]} argv
* @returns {ParseOptionsResult}
* @returns Promise
*/
parseAsync(argv: string[]): Promise<any>;
/**
* Parse options from `argv` returning `argv` void of these options.
*/
parseOptions(argv: string[]): commander.ParseOptionsResult;

@@ -218,4 +230,2 @@

* Return an object containing options as key-value pairs
*
* @returns {{[key: string]: any}}
*/

@@ -225,9 +235,10 @@ opts(): { [key: string]: any };

/**
* Set the description to `str`.
*
* @param {string} str
* @param {{[argName: string]: string}} argsDescription
* @return {(Command | string)}
* Set the description.
*
* @returns Command for chaining
*/
description(str: string, argsDescription?: {[argName: string]: string}): Command;
/**
* Get the description.
*/
description(): string;

@@ -237,16 +248,20 @@

* Set an alias for the command.
*
* @param {string} alias
* @return {(Command | string)}
*
* @returns Command for chaining
*/
alias(alias: string): Command;
/**
* Get alias for the command.
*/
alias(): string;
/**
* Set or get the command usage.
*
* @param {string} str
* @return {(Command | string)}
* Set the command usage.
*
* @returns Command for chaining
*/
usage(str: string): Command;
/**
* Get the command usage.
*/
usage(): string;

@@ -256,12 +271,8 @@

* Set the name of the command.
*
* @param {string} str
* @return {Command}
*
* @returns Command for chaining
*/
name(str: string): Command;
/**
* Get the name of the command.
*
* @return {string}
*/

@@ -275,4 +286,2 @@ name(): string;

* those callbacks are invoked.
*
* @param {(str: string) => string} [cb]
*/

@@ -279,0 +288,0 @@ outputHelp(cb?: (str: string) => string): void;

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc