Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

argparse

Package Overview
Dependencies
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

argparse - npm Package Compare versions

Comparing version 0.1.10 to 0.1.11

test/fromfile.js

8

HISTORY.md

@@ -0,1 +1,9 @@

0.1.11 / 2013-02-07
* Multiple bugfixes, @hpaulj
* Added 70+ tests (ported from python), @hpaulj
* Added conflictHandler, @applepicke
* Added fromfilePrefixChar, @hpaulj
0.1.10 / 2012-12-30

@@ -2,0 +10,0 @@ -------------------

19

lib/action_container.js

@@ -42,2 +42,3 @@ /** internal

* - `argumentDefault` -- The default value for all arguments
* - `conflictHandler` -- The conflict handler to use for duplicate arguments
**/

@@ -50,5 +51,4 @@ var ActionContainer = module.exports = function ActionContainer(options) {

this.prefixChars = options.prefixChars || '';
this.conflictHandler = options.conflictHandler;
// ToDo conflict handler
// set up registries

@@ -240,2 +240,8 @@ this._registries = {};

/**
* ActionContainer#addMutuallyExclusiveGroup(options) -> ArgumentGroup
* - options (Object): {required: false}
*
* Create new mutual exclusive groups
**/
ActionContainer.prototype.addMutuallyExclusiveGroup = function (options) {

@@ -422,2 +428,3 @@ var group = new MutuallyExclusiveGroup(this, options);

ActionContainer.prototype._checkConflict = function (action) {
var conflictHandler = this._container.conflictHandler;
var optionStringActions = this._optionStringActions;

@@ -429,3 +436,3 @@ var conflictOptionals = [];

if (!!optionStringActions[optionString]) {
conflictOptionals.push([optionString]);
conflictOptionals.push(optionString);
}

@@ -435,2 +442,8 @@ });

if (conflictOptionals.length > 0) {
if (conflictHandler === 'resolve') {
this._removeAction(optionStringActions['--glop']);
return;
}
throw argumentErrorHelper(

@@ -437,0 +450,0 @@ action,

3

lib/action/append.js

@@ -50,3 +50,4 @@ /*:nodoc:*

ActionAppend.prototype.call = function (parser, namespace, values) {
var items = [].concat(namespace[this.dest] || [], values);
var items = [].concat(namespace[this.dest] || []); // or _.clone
items.push(values);
namespace.set(this.dest, items);

@@ -53,0 +54,0 @@ };

@@ -42,4 +42,6 @@ /**

* - `prefixChars` Characters that prefix optional arguments
* - `fromfilePrefixChars` Characters that prefix files containing additional arguments
* - `argumentDefault` The default value for all arguments
* - `addHelp` Add a -h/-help option
* - `conflictHandler` Specifies how to handle conflicting argument names
* - `debug` Enable debug mode. Argument errors throw exception in

@@ -72,5 +74,6 @@ * debug mode and process.exit in normal. Used for development and

this.debug = (options.debug === true);
this.conflictHandler = options.conflictHandler;
this.formatterClass = (options.formatterClass || HelpFormatter);
this.fromfilePrefixChars = options.fromfilePrefixChars || null;
this._positionals = this.addArgumentGroup({title: 'Positional arguments'});

@@ -105,7 +108,9 @@ this._optionals = this.addArgumentGroup({title: 'Optional arguments'});

// add help and version arguments if necessary
var defaultPrefix = (this.prefixChars.indexOf('-') > -1) ? '-' : this.prefixChars[0];
if (options.addHelp) {
this.addArgument(
['-h', '--help'],
[defaultPrefix + 'h', defaultPrefix + defaultPrefix + 'help'],
{
action: 'help',
defaultValue: $$.SUPPRESS,
help: 'Show this help message and exit.'

@@ -117,6 +122,7 @@ }

this.addArgument(
['-v', '--version'],
[defaultPrefix + 'v', defaultPrefix + defaultPrefix + 'version'],
{
action: 'version',
version: this.version,
defaultValue: $$.SUPPRESS,
help: "Show program's version number and exit."

@@ -265,3 +271,3 @@ }

if (action.dest !== $$.SUPPRESS) {
if (_.indexOf(namespace, action.dest) === -1) {
if (!_.has(namespace, action.dest)) {
if (action.defaultValue !== $$.SUPPRESS) {

@@ -288,3 +294,3 @@ var defaultValue = action.defaultValue;

args = res[1];
if (_.indexOf(Namespace, $$._UNRECOGNIZED_ARGS_ATTR) !== -1) {
if (_.has(namespace, $$._UNRECOGNIZED_ARGS_ATTR)) {
args = _.union(args, namespace[$$._UNRECOGNIZED_ARGS_ATTR]);

@@ -305,4 +311,5 @@ delete namespace[$$._UNRECOGNIZED_ARGS_ATTR];

// replace arg strings that are file references
// ToDo read args from files
if (this.fromfilePrefixChars !== null) {
argStrings = this._readArgsFromFiles(argStrings);
}
// map all mutually exclusive arguments to the other arguments

@@ -377,3 +384,3 @@ // they can't occur with

// value don't really count as "present"
if (argumentValues !== action.default) {
if (argumentValues !== action.defaultValue) {
seenNonDefaultActions.push(action);

@@ -497,6 +504,8 @@ if (!!actionConflicts[actionHash(action)]) {

// and add the Positional and its args to the list
if (argCounts.length > 0) {
_.zip(positionals, argCounts).forEach(function (item) {
_.zip(positionals, argCounts).forEach(function (item) {
var action = item[0];
var argCount = item[1];
if (argCount === undefined) {
return;
}
var args = argStrings.slice(startIndex, startIndex + argCount);

@@ -507,4 +516,3 @@

});
}
// slice off the Positionals that we just parsed and return the

@@ -617,6 +625,41 @@ // index at which the Positionals' string args stopped

ArgumentParser.prototype._readArgsFromFiles = function (argStrings) {
// expand arguments referencing files
var _this = this;
var fs = require('fs');
var newArgStrings = [];
argStrings.forEach(function (argString) {
if (_this.fromfilePrefixChars.indexOf(argString[0]) < 0) {
// for regular arguments, just add them back into the list
newArgStrings.push(argString);
} else {
// replace arguments referencing files with the file content
try {
var argstrs = [];
var filename = argString.slice(1);
var content = fs.readFileSync(filename, 'utf8');
content = content.trim().split('\n');
content.forEach(function (argLine) {
_this.convertArgLineToArgs(argLine).forEach(function (arg) {
argstrs.push(arg);
});
argstrs = _this._readArgsFromFiles(argstrs);
});
newArgStrings.push.apply(newArgStrings, argstrs);
} catch (error) {
return _this.error(error.message);
}
}
});
return newArgStrings;
};
ArgumentParser.prototype.convertArgLineToArgs = function (argLine) {
return [argLine];
};
ArgumentParser.prototype._matchArgument = function (action, regexpArgStrings) {
// match the pattern for this action to the arg strings
var regexpNargs = new RegExp(this._getNargsPattern(action));
var regexpNargs = new RegExp('^' + this._getNargsPattern(action));
var matches = regexpArgStrings.match(regexpNargs);

@@ -670,3 +713,3 @@ var message;

pattern = new RegExp(pattern);
pattern = new RegExp('^' + pattern);
matches = regexpArgStrings.match(pattern);

@@ -889,3 +932,4 @@

// args, use the default if it is anything other than None
} else if (argStrings.length === 0 && action.nargs === $$.ZERO_OR_MORE) {
} else if (argStrings.length === 0 && action.nargs === $$.ZERO_OR_MORE &&
action.optionStrings.length === 0) {

@@ -947,11 +991,18 @@ value = (action.defaultValue || argStrings);

// ArgumentTypeErrors indicate errors
// If action.type is not a registered string, it is a function
// Try to deduce its name for inclusion in the error message
// Failing that, include the error message it raised.
} catch (e) {
throw argumentErrorHelper(
action,
_.str.sprintf('Invalid %(type)s value: %(value)s', {
type: action.type,
value: argString
})
);
var name = null;
if (_.isString(action.type)) {
name = action.type;
} else {
name = action.type.name || action.type.displayName || '<function>';
}
var msg = _.str.sprintf('Invalid %(type)s value: %(value)s', {
type: name,
value: argString
});
if (name === '<function>') {msg += '\n' + e.message; }
throw argumentErrorHelper(action, msg);
}

@@ -958,0 +1009,0 @@ // return the converted value

/** internal
* class ArgumentGroup
* class MutuallyExclusiveGroup
*

@@ -20,6 +20,7 @@ * Group arguments.

/**
* new MutuallyExclusiveGroup(container, required)
* new MutuallyExclusiveGroup(container, options)
* - container (object): main container
* - options.required: true/false
* (required could be an argument itself, but making it a property of
* - options (object): options.required -> true/false
*
* `required` could be an argument itself, but making it a property of
* the options argument is more consistent with the JS adaptation of the Python)

@@ -26,0 +27,0 @@ **/

@@ -69,4 +69,4 @@ /** internal

ActionContainer.prototype._removeAction.call(this, action);
this._groupActions.remove(action);
this._groupActions.splice(action);
};

@@ -448,3 +448,4 @@ /**

if (actions.slice(start, end) === group._groupActions) {
//if (actions.slice(start, end) === group._groupActions) {
if (_.isEqual(actions.slice(start, end), group._groupActions)) {
group._groupActions.forEach(function (action) {

@@ -534,8 +535,7 @@ groupActions.push(action);

// insert things at the necessary indices
inserts.reverse().forEach(function (insert, insertIndex) {
parts = parts.slice(0, insertIndex).concat(
[insert],
parts.slice(insertIndex + 1, parts.length - 1)
);
});
for (var i = inserts.length - 1; i >= 0; --i) {
if (inserts[i] !== null) {
parts.splice(i, 0, inserts[i]);
}
}

@@ -548,8 +548,8 @@ // join all the action items with spaces

// clean up separators for mutually exclusive groups
var regexpOpen = '[\\[(]';
var regexpClose = '[\\])]';
text = text.replace('(' + regexpOpen + ') ', '\\1');
text = text.replace(' (' + regexpClose + ')', '\\1');
text = text.replace(regexpOpen + ' *' + regexpClose, '');
text = text.replace('\\(([^|]*)\\)', '\\1');
text = text.replace(/([\[(]) /g, '$1'); // remove spaces
text = text.replace(/ ([\])])/g, '$1');
text = text.replace(/\[ *\]/g, ''); // remove empty groups
text = text.replace(/\( *\)/g, '');
text = text.replace(/\(([^|]*)\)/g, '$1'); // remove () from single action groups
text = _.str.strip(text);

@@ -707,7 +707,7 @@

metavars = buildMetavar(2);
result = '[' + metavars[0] + '[' + metavars[1] + ' ...]]';
result = '[' + metavars[0] + ' [' + metavars[1] + ' ...]]';
break;
case $$.ONE_OR_MORE:
metavars = buildMetavar(2);
result = '' + metavars[0] + '[' + metavars[1] + ' ...]';
result = '' + metavars[0] + ' [' + metavars[1] + ' ...]';
break;

@@ -714,0 +714,0 @@ case $$.REMAINDER:

@@ -31,3 +31,3 @@ /**

Namespace.prototype.isset = function (key) {
return !!this[key];
return _.has(this, key);
};

@@ -47,7 +47,3 @@

} else {
if (value !== null) {
this[key] = value;
} else {
delete this[key];
}
this[key] = value;
}

@@ -54,0 +50,0 @@ return this;

{
"name" : "argparse",
"description" : "Very powerful CLI arguments parser. Native port of argparse - python's options parsing library",
"version" : "0.1.10",
"version" : "0.1.11",
"keywords" : ["cli", "parser", "argparse", "option", "args"],
"homepage" : "https://github.com/nodeca/argparse",
"author" : "Eugene Shkuropat <e.shkuropat@gmail.com>",
"contributors" : ["Eugene Shkuropat", "Paul Jacobson"],

@@ -21,7 +21,7 @@ "bugs" : { "url": "https://github.com/nodeca/argparse/issues" },

"dependencies" : {
"underscore" : "~1.3.3",
"underscore.string" : "~2.1.1"
"underscore" : "~1.4.3",
"underscore.string" : "~2.3.1"
},
"devDependencies" : { "mocha": "~1.2.1" },
"devDependencies" : { "mocha": "~1.8.1" },
"engines" : { "node": ">= 0.6.0" }
}

@@ -90,2 +90,3 @@ argparse

- ```usage``` - The string describing the program usage (default: generated)
- ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals.

@@ -95,4 +96,4 @@ **Not supportied yet**

- ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read.
- ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals.
Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects)

@@ -225,7 +226,9 @@

Author
======
Contributors
============
[Eugene Shkuropat](https://github.com/shkuropat)
- [Eugene Shkuropat](https://github.com/shkuropat)
- [Paul Jacobson](https://github.com/hpaulj)
[others](https://github.com/nodeca/argparse/graphs/contributors)

@@ -232,0 +235,0 @@ License

@@ -1,2 +0,2 @@

/*global describe, it, beforeEach*/
/*global describe, it*/

@@ -9,138 +9,251 @@

var ArgumentParser = require('../lib/argparse').ArgumentParser;
describe('ArgumentParser', function () {
describe('base', function () {
var parser;
var args;
beforeEach(function () {
parser = new ArgumentParser({debug: true});
parser.addArgument([ '-f', '--foo' ]);
});
it("should parse argument in short form", function () {
args = parser.parseArgs('-f 1'.split(' '));
assert.equal(args.foo, 1);
args = parser.parseArgs('-f=1'.split(' '));
assert.equal(args.foo, 1);
args = parser.parseArgs('-f1'.split(' '));
assert.equal(args.foo, 1);
});
describe('base', function () {
var parser;
var args;
it("should parse argument in long form", function () {
args = parser.parseArgs('--foo 1'.split(' '));
assert.equal(args.foo, 1);
args = parser.parseArgs('--foo=1'.split(' '));
assert.equal(args.foo, 1);
});
it("should parse argument in short form", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
it("should parse multiple arguments", function () {
parser.addArgument(['--bar' ]);
args = parser.parseArgs('--foo 5 --bar 6'.split(' '));
assert.equal(args.foo, 5);
assert.equal(args.bar, 6);
});
args = parser.parseArgs('-f 1'.split(' '));
assert.equal(args.foo, 1);
args = parser.parseArgs('-f=1'.split(' '));
assert.equal(args.foo, 1);
args = parser.parseArgs('-f1'.split(' '));
assert.equal(args.foo, 1);
});
it("should check argument type", function () {
parser.addArgument(['--bar' ], { type: 'int' });
assert.throws(function () {
parser.parseArgs('--bar bar'.split(' '));
});
assert.doesNotThrow(function () {
parser.parseArgs('--bar 1'.split(' '));
});
});
it("should parse argument in long form", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
it("should not drop down with empty args (without positional arguments)", function () {
assert.doesNotThrow(function () {
parser.parseArgs([]);
});
});
args = parser.parseArgs('--foo 1'.split(' '));
assert.equal(args.foo, 1);
args = parser.parseArgs('--foo=1'.split(' '));
assert.equal(args.foo, 1);
});
it("should drop down with empty args (positional arguments)", function () {
parser.addArgument([ 'baz']);
assert.throws(
function () {parser.parseArgs([]); },
/too few arguments/
);
});
it("should parse multiple arguments", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
parser.addArgument(['--bar']);
it("should support pseudo-argument", function () {
parser.addArgument([ 'bar' ], { nargs: '+' });
args = parser.parseArgs([ '-f', 'foo', '--', '-f', 'bar' ]);
assert.equal(args.foo, 'foo');
assert.equal(args.bar.length, 2);
});
args = parser.parseArgs('--foo 5 --bar 6'.split(' '));
assert.equal(args.foo, 5);
assert.equal(args.bar, 6);
});
it("should support #setDefaults", function () {
parser.setDefaults({bar: 1});
args = parser.parseArgs([]);
assert.equal(args.bar, 1);
});
it("should check argument type", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
parser.addArgument(['--bar' ], { type: 'int' });
it("should throw TypeError with conflicting options", function () {
assert.throws(
function () {
parser.addArgument(['-f']);
},
/Conflicting option string/
);
assert.throws(
function () {
parser.addArgument(['--foo']);
},
/Conflicting option string/
);
assert.throws(
function () {
parser.addArgument(['-f', '--flame']);
},
/Conflicting option string/
);
assert.throws(
function () {
parser.addArgument(['-m', '--foo']);
},
/Conflicting option string/
);
assert.throws(function () {
parser.parseArgs('--bar bar'.split(' '));
});
assert.doesNotThrow(function () {
parser.parseArgs('--bar 1'.split(' '));
});
});
it("should parse negative arguments", function () {
parser.addArgument([ 'bar' ], { type: 'int', });
args = parser.parseArgs(['-1']);
it("should not drop down with empty args (without positional arguments)", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
assert.equal(args.bar, -1);
});
assert.doesNotThrow(function () { parser.parseArgs([]); });
});
it("should infer option destination from long and short options", function () {
//parser.addArgument(['-f', '--foo']); // from long option
parser.addArgument(['-g']); // from short option
parser.addArgument(['-x'], { dest: 'xxx' });// from dest keyword
it("should drop down with empty args (positional arguments)", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
parser.addArgument([ 'baz']);
args = parser.parseArgs(['-f', '1']);
assert.deepEqual(args, { foo: '1', g: null, xxx: null});
args = parser.parseArgs(['-g', '2']);
assert.deepEqual(args, { foo: null, g: '2', xxx: null});
args = parser.parseArgs(['-f', 1, '-g', 2, '-x', 3]);
assert.deepEqual(args, { foo: 1, g: 2, xxx: 3});
});
assert.throws(
function () {parser.parseArgs([]); },
/too few arguments/
);
});
it("should accept 0 defaultValue", function () {
parser.addArgument(['bar'], { nargs: '?', defaultValue: 0});
args = parser.parseArgs([]);
assert.equal(args.bar, 0);
// could also test for '', and false
});
it("should support pseudo-argument", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
parser.addArgument([ 'bar' ], { nargs: '+' });
it("should accept defaultValue for nargs:'*'", function () {
parser.addArgument(['bar'], { nargs: '*', defaultValue: 42});
args = parser.parseArgs([]);
assert.equal(args.bar, 42);
});
args = parser.parseArgs([ '-f', 'foo', '--', '-f', 'bar' ]);
assert.equal(args.foo, 'foo');
assert.equal(args.bar.length, 2);
});
it("getDefault() should get defaults", function () {
parser.addArgument(['-g', '--goo'], {defaultValue: 42});
assert.equal(parser.getDefault('goo'), 42);
assert.equal(parser.getDefault('help'), require('../lib/const').SUPPRESS);
it("should support #setDefaults", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
parser.setDefaults({bar: 1});
args = parser.parseArgs([]);
assert.equal(args.bar, 1);
});
it("should throw TypeError with conflicting options", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
assert.throws(
function () { parser.addArgument(['-f']); },
/Conflicting option string/
);
assert.throws(
function () { parser.addArgument(['--foo']); },
/Conflicting option string/
);
assert.throws(
function () { parser.addArgument(['-f', '--flame']); },
/Conflicting option string/
);
assert.throws(
function () { parser.addArgument(['-m', '--foo']); },
/Conflicting option string/
);
});
it("should overwrite arguments when given the 'resolve' conflictHandler", function () {
parser = new ArgumentParser({conflictHandler: 'resolve'});
parser.addArgument(['--foo'], {help: 'old foo'});
parser.addArgument(['--foo'], {help: 'new foo'});
var help = parser._optionStringActions['--foo'].help;
assert.equal(help, 'new foo');
});
it("should parse negative arguments", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
parser.addArgument([ 'bar' ], { type: 'int', });
args = parser.parseArgs(['-1']);
assert.equal(args.bar, -1);
});
it("No negative number options; neg number is positional argument", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-x'], {dest: 'x'});
parser.addArgument(['foo'], {nargs: '?'});
// no negative number options, so -1 is a positional argument
args = parser.parseArgs(['-x', '-1']);
// Namespace(foo=None, x='-1')
assert.equal(args.x, '-1');
// no negative number options, so -1 and -5 are positional arguments
args = parser.parseArgs(['-x', '-1', '-5']);
// Namespace(foo='-5', x='-1') order not determined
assert.equal(args.x, '-1');
assert.equal(args.foo, '-5');
});
it("negative number options present, so any neg number is an option", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-1'], {dest: 'one'});
parser.addArgument(['foo'], {nargs: '?'});
// negative number options present, so -1 is an option
args = parser.parseArgs(['-1', 'X']);
// Namespace(foo=None, one='X')
assert.equal(args.one, 'X');
// negative number options present, so -2 is an option
assert.throws(
function () {
parser.parseArgs(['-2']);
},
/Unrecognized arguments: -2/
);
// negative number options present, so both -1s are options
assert.throws(
function () {
parser.parseArgs(['-1', '-1']);
},
/argument "-1": Expected one argument/
);
args = parser.parseArgs(['--', '-f']);
// Namespace(foo='-f', one=None)
assert.equal(args.foo, '-f');
});
it("should infer option destination from long and short options", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']); // from long option
parser.addArgument(['-g']); // from short option
parser.addArgument(['-x'], { dest: 'xxx' });// from dest keyword
args = parser.parseArgs(['-f', '1']);
assert.deepEqual(args, { foo: '1', g: null, xxx: null});
args = parser.parseArgs(['-g', '2']);
assert.deepEqual(args, { foo: null, g: '2', xxx: null});
args = parser.parseArgs(['-f', 1, '-g', 2, '-x', 3]);
assert.deepEqual(args, { foo: 1, g: 2, xxx: 3});
});
it("should accept 0 defaultValue", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
parser.addArgument(['bar'], { nargs: '?', defaultValue: 0});
args = parser.parseArgs([]);
assert.equal(args.bar, 0);
// could also test for '', and false
});
it("getDefault() should get defaults", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
parser.addArgument(['-g', '--goo'], {defaultValue: 42});
assert.equal(parser.getDefault('goo'), 42);
assert.equal(parser.getDefault('help'), require('../lib/const').SUPPRESS);
});
it("should handle mixed positional and optional args", function () {
parser = new ArgumentParser({debug: true});
parser.addArgument(['-f', '--foo']);
parser.addArgument(['x']);
parser.addArgument(['y']);
args = parser.parseArgs(['X', 'Y']);
assert.deepEqual(args, {"foo": null, "x": "X", "y": "Y"});
args = parser.parseArgs(['-f', 'A', 'X', 'Y']);
assert.deepEqual(args, {"foo": "A", "x": "X", "y": "Y"});
args = parser.parseArgs(['X', '-f', 'A', 'Y']);
assert.deepEqual(args, {"foo": "A", "x": "X", "y": "Y"});
// was giving: Error: _mocha: error: Unrecognized arguments: X.
});
it('test empty and space containing arguments', function () {
parser = new ArgumentParser({debug: true});
parser.addArgument([ 'x' ], { nargs: '?' });
parser.addArgument([ '-y', '--yyy' ], { dest: 'y' });
args = parser.parseArgs([ '' ]);
assert.deepEqual(args, { y: null, x: '' });
args = parser.parseArgs([ 'a badger' ]);
assert.deepEqual(args, { y: null, x: 'a badger' });
args = parser.parseArgs([ '-a badger' ]);
assert.deepEqual(args, { y: null, x: '-a badger' });
args = parser.parseArgs([ '-y', '' ]);
assert.deepEqual(args, { y: '', x: null });
args = parser.parseArgs([ '-y', 'a badger' ]);
assert.deepEqual(args, { y: 'a badger', x: null });
args = parser.parseArgs([ '-y', '-a badger' ]);
assert.deepEqual(args, { y: '-a badger', x: null });
args = parser.parseArgs([ '--yyy=a badger' ]);
assert.deepEqual(args, { y: 'a badger', x: null });
args = parser.parseArgs([ '--yyy=-a badger' ]);
assert.deepEqual(args, { y: '-a badger', x: null });
assert.throws(function () {
args = parser.parseArgs([ '-y' ]);
});
});
});

@@ -9,54 +9,53 @@ /*global describe, it, beforeEach*/

var ArgumentParser = require('../lib/argparse').ArgumentParser;
describe('ArgumentParser', function () {
describe('group', function () {
var args;
var parentParser, group, xgroup, childParser;
beforeEach(function () {
// parent has name group and exclusive group that should be passed to child
parentParser = new ArgumentParser({prog: 'PROG', debug: true, addHelp: false});
parentParser.addArgument(['--foo'], {help: 'parent foo'});
// parentParser.addArgument(['pbar'], {help: 'parent positional'});
group = parentParser.addArgumentGroup({title: 'parent group'});
group.addArgument(['--gfoo'], {help: 'group foo help'});
group.addArgument(['gbar'], {help: 'group bar help'});
xgroup = parentParser.addMutuallyExclusiveGroup({required: true});
xgroup.addArgument(['--xfoo'], {action: 'storeTrue', help: 'xfoo or xbar, set true'});
xgroup.addArgument(['--xbar'], {action: 'storeFalse', help: 'xfoo or xbar, set false'});
childParser = new ArgumentParser({parents: [parentParser], description: 'child parser', debug: true});
childParser.addArgument(['--cbar'], {help: 'child bar opt arg'});
});
it('compare help parent and child', function () {
// format helps and compare selected passages
var phelp = parentParser.formatHelp();
var chelp = childParser.formatHelp();
assert(phelp.match(/parent group:/));
assert(chelp.match(/parent group:/));
});
it('child should throw error if an xclusive group member is missing', function () {
assert.throws(
function () {
args = childParser.parseArgs(['gbararg']);
},
/one of the arguments (.*) is required/i
);
});
it('child accepts an xgroup item and positional arg from parent', function () {
args = childParser.parseArgs(['--xbar', 'gbararg']);
assert.equal(args.gbar, 'gbararg');
assert.equal(args.xbar, false);
});
it('', function () {
args = childParser.parseArgs(['--foo', 'fooarg', 'gbararg', '--xfoo']);
assert.equal(args.foo, 'fooarg');
});
it('child throws error if both xclusive options are given', function () {
assert.throws(
function () {
args = childParser.parseArgs(['--xfoo', '--xbar']);
},
/Not allowed with argument/i
);
});
describe('child group', function () {
var args;
var parentParser, group, xgroup, childParser;
beforeEach(function () {
// parent has name group and exclusive group that should be passed to child
parentParser = new ArgumentParser({prog: 'PROG', debug: true, addHelp: false});
parentParser.addArgument(['--foo'], {help: 'parent foo'});
// parentParser.addArgument(['pbar'], {help: 'parent positional'});
group = parentParser.addArgumentGroup({title: 'parent group'});
group.addArgument(['--gfoo'], {help: 'group foo help'});
group.addArgument(['gbar'], {help: 'group bar help'});
xgroup = parentParser.addMutuallyExclusiveGroup({required: true});
xgroup.addArgument(['--xfoo'], {action: 'storeTrue', help: 'xfoo or xbar, set true'});
xgroup.addArgument(['--xbar'], {action: 'storeFalse', help: 'xfoo or xbar, set false'});
childParser = new ArgumentParser({parents: [parentParser], description: 'child parser', debug: true});
childParser.addArgument(['--cbar'], {help: 'child bar opt arg'});
});
it('compare help parent and child', function () {
// format helps and compare selected passages
var phelp = parentParser.formatHelp();
var chelp = childParser.formatHelp();
assert(phelp.match(/parent group:/));
assert(chelp.match(/parent group:/));
});
it('child should throw error if an xclusive group member is missing', function () {
assert.throws(
function () {
args = childParser.parseArgs(['gbararg']);
},
/one of the arguments (.*) is required/
);
});
it('child accepts an xgroup item and positional arg from parent', function () {
args = childParser.parseArgs(['--xbar', 'gbararg']);
assert.equal(args.gbar, 'gbararg');
assert.equal(args.xbar, false);
});
it('child throws error if both xclusive options are given', function () {
assert.throws(
function () {
args = childParser.parseArgs(['--xfoo', '--xbar']);
},
/Not allowed with argument/
);
});
});

@@ -1,2 +0,2 @@

/*global describe, it, beforeEach*/
/*global describe, it*/

@@ -10,60 +10,62 @@

describe('ArgumentParser', function () {
describe('sub-commands', function () {
var parser;
var args;
describe('choices', function () {
var parser;
var args;
beforeEach(function () {
parser = new ArgumentParser({debug: true});
});
it("should store correct choice(choices defined as string)", function () {
parser = new ArgumentParser({ debug: true });
parser.addArgument(['--foo'], {choices: 'abc'});
it("should store correct choice(choices defined as string)", function () {
parser.addArgument(['--foo'], {choices: 'abc'});
args = parser.parseArgs('--foo a'.split(' '));
assert.equal(args.foo, 'a');
});
args = parser.parseArgs('--foo a'.split(' '));
assert.equal(args.foo, 'a');
});
it("should drop down with 'Invalid choice' error for incorrect choices(choices defined as string)", function () {
parser.addArgument(['--foo'], {choices: 'abc'});
assert.throws(
function () {
args = parser.parseArgs('--foo e'.split(' '));
console.dir(args);
},
/Invalid choice:/
);
assert.throws(
function () {
args = parser.parseArgs('--foo 0'.split(' '));
console.dir(args);
},
/Invalid choice:/
);
});
it("should drop down with 'Invalid choice' error for incorrect choices(choices defined as string)", function () {
parser = new ArgumentParser({ debug: true });
parser.addArgument(['--foo'], {choices: 'abc'});
assert.throws(
function () {
args = parser.parseArgs('--foo e'.split(' '));
console.dir(args);
},
/Invalid choice:/
);
assert.throws(
function () {
args = parser.parseArgs('--foo 0'.split(' '));
console.dir(args);
},
/Invalid choice:/
);
});
it("should store correct choice(choices defined as array)", function () {
parser.addArgument(['--foo'], {choices: ['a', 'abc', 'd']});
args = parser.parseArgs('--foo abc'.split(' '));
assert.equal(args.foo, 'abc');
});
it("should drop down with 'Invalid choice' error for incorrect choices(choices defined as array)", function () {
parser.addArgument(['--foo'], {choices: ['a', 'abc', 'd']});
assert.throws(
function () {
args = parser.parseArgs('--foo e'.split(' '));
console.dir(args);
},
/Invalid choice:/
);
assert.throws(
function () {
args = parser.parseArgs('--foo 0'.split(' '));
console.dir(args);
},
/Invalid choice:/
);
});
it("should store correct choice(choices defined as array)", function () {
parser = new ArgumentParser({ debug: true });
parser.addArgument(['--foo'], {choices: ['a', 'abc', 'd']});
args = parser.parseArgs('--foo abc'.split(' '));
assert.equal(args.foo, 'abc');
});
it("should drop down with 'Invalid choice' error for incorrect choices(choices defined as array)", function () {
parser = new ArgumentParser({ debug: true });
parser.addArgument(['--foo'], {choices: ['a', 'abc', 'd']});
assert.throws(
function () {
args = parser.parseArgs('--foo e'.split(' '));
console.dir(args);
},
/Invalid choice:/
);
assert.throws(
function () {
args = parser.parseArgs('--foo 0'.split(' '));
console.dir(args);
},
/Invalid choice:/
);
});
});

@@ -9,47 +9,52 @@ /*global describe, it, beforeEach*/

describe('ArgumentParser', function () {
describe('constant actions', function () {
var parser;
var args;
describe('constant actions', function () {
var parser;
var args;
beforeEach(function () {
parser = new ArgumentParser({debug: true});
});
beforeEach(function () {
parser = new ArgumentParser({debug: true});
});
it("storeConst should store constant as given", function () {
parser.addArgument(['-a'], {action: 'storeConst', dest: 'answer',
help: 'store constant', constant: 42});
args = parser.parseArgs('-a'.split(' '));
assert.equal(args.answer, '42');
});
it("storeConst should store constant as given", function () {
parser.addArgument(['-a'], {action: 'storeConst', dest: 'answer',
help: 'store constant', constant: 42});
args = parser.parseArgs('-a'.split(' '));
assert.equal(args.answer, '42');
});
it("storeConst should give error if constant not given (or misspelled)", function () {
assert.throws(
function () {
parser.addArgument(['-a'], {action: 'storeConst', dest: 'answer',
help: 'store constant', const: 42});
},
it("storeConst should give error if constant not given (or misspelled)", function () {
assert.throws(
function () {
parser.addArgument(
['-a'],
{
action: 'storeConst',
dest: 'answer',
help: 'store constant',
const: 42
}
);
},
/constant option is required for storeAction/
);
});
it("appendConst should append constant as given", function () {
parser.addArgument([ '--str' ], {action: 'appendConst', dest: 'types',
help: 'append constant "str" to types', constant: 'str'});
parser.addArgument([ '--int' ], {action: 'appendConst', dest: 'types',
help: 'append constant "int" to types', constant: 'int'});
args = parser.parseArgs('--str --int'.split(' '));
assert.deepEqual(args.types, [ 'str', 'int' ]);
});
it("appendConst should give error if constant not given (or misspelled)", function () {
assert.throws(
function () {
parser.addArgument(['-a'], {action: 'appendConst', dest: 'answer',
help: 'store constant', const: 42});
},
/constant option is required for appendAction/
);
});
});
it("appendConst should append constant as given", function () {
parser.addArgument([ '--str' ], {action: 'appendConst', dest: 'types',
help: 'append constant "str" to types', constant: 'str'});
parser.addArgument([ '--int' ], {action: 'appendConst', dest: 'types',
help: 'append constant "int" to types', constant: 'int'});
args = parser.parseArgs('--str --int'.split(' '));
assert.deepEqual(args.types, [ 'str', 'int' ]);
});
it("appendConst should give error if constant not given (or misspelled)", function () {
assert.throws(
function () {
parser.addArgument(['-a'], {action: 'appendConst', dest: 'answer',
help: 'store constant', const: 42});
},
/constant option is required for appendAction/
);
});
});

@@ -10,38 +10,36 @@ /*global describe, it, beforeEach*/

describe('ArgumentParser', function () {
describe('sub-commands', function () {
var parent_parser;
var args;
describe('parents', function () {
var parent_parser;
var args;
beforeEach(function () {
parent_parser = new ArgumentParser({debug: true, addHelp: false});
parent_parser.addArgument(['--parent']);
beforeEach(function () {
parent_parser = new ArgumentParser({debug: true, addHelp: false});
parent_parser.addArgument(['--parent']);
});
it("should parse args from parents parser", function () {
var parser = new ArgumentParser({
parents: [ parent_parser ],
});
parser.addArgument(['-f', '--foo']);
it("should parse args from parents parser", function () {
var parser = new ArgumentParser({
parents: [ parent_parser ],
});
parser.addArgument(['-f', '--foo']);
args = parser.parseArgs('-f 1 --parent 2'.split(' '));
assert.equal(args.foo, 1);
assert.equal(args.parent, 2);
args = parser.parseArgs('-f 1 --parent 2'.split(' '));
assert.equal(args.foo, 1);
assert.equal(args.parent, 2);
args = parser.parseArgs('-f 1'.split(' '));
assert.equal(args.foo, 1);
assert.strictEqual(args.parent, null);
});
args = parser.parseArgs('-f 1'.split(' '));
assert.equal(args.foo, 1);
assert.strictEqual(args.parent, null);
it("should throw error if has same args as parent", function () {
var parser = new ArgumentParser({
parents: [ parent_parser ],
});
parser.addArgument(['-f', '--foo']);
it("should throw error if has same args as parent", function () {
var parser = new ArgumentParser({
parents: [ parent_parser ],
});
parser.addArgument(['-f', '--foo']);
assert.throws(function () {
parent_parser.addArgument(['--parent']);
});
assert.throws(function () {
parent_parser.addArgument(['--parent']);
});
});
});

@@ -10,80 +10,78 @@ /*global describe, it, beforeEach*/

describe('ArgumentParser', function () {
describe('sub-commands', function () {
var parser;
var args;
var c1;
var c2;
describe('sub-commands', function () {
var parser;
var args;
var c1;
var c2;
beforeEach(function () {
parser = new ArgumentParser({debug: true});
var subparsers = parser.addSubparsers({
title: 'subcommands',
dest: 'subcommand_name'
});
c1 = subparsers.addParser('c1', {aliases: ['co']});
c1.addArgument([ '-f', '--foo' ], {});
c1.addArgument([ '-b', '--bar' ], {});
c2 = subparsers.addParser('c2', {});
c2.addArgument([ '--baz' ], {});
beforeEach(function () {
parser = new ArgumentParser({debug: true});
var subparsers = parser.addSubparsers({
title: 'subcommands',
dest: 'subcommand_name'
});
c1 = subparsers.addParser('c1', {aliases: ['co']});
c1.addArgument([ '-f', '--foo' ], {});
c1.addArgument([ '-b', '--bar' ], {});
c2 = subparsers.addParser('c2', {});
c2.addArgument([ '--baz' ], {});
});
it("should store command name", function () {
args = parser.parseArgs('c1 --foo 5'.split(' '));
assert.equal(args.subcommand_name, 'c1');
});
it("should store command name", function () {
args = parser.parseArgs('c1 --foo 5'.split(' '));
assert.equal(args.subcommand_name, 'c1');
});
it("should store command arguments", function () {
args = parser.parseArgs('c1 --foo 5 -b4'.split(' '));
assert.equal(args.foo, 5);
assert.equal(args.bar, 4);
});
it("should store command arguments", function () {
args = parser.parseArgs('c1 --foo 5 -b4'.split(' '));
assert.equal(args.foo, 5);
assert.equal(args.bar, 4);
});
it("should have same behavior for alias and original command", function () {
args = parser.parseArgs('c1 --foo 5 -b4'.split(' '));
var aliasArgs = parser.parseArgs('co --foo 5 -b4'.split(' '));
assert.equal(args.foo, aliasArgs.foo);
assert.equal(args.bar, aliasArgs.bar);
});
it("should have same behavior for alias and original command", function () {
args = parser.parseArgs('c1 --foo 5 -b4'.split(' '));
var aliasArgs = parser.parseArgs('co --foo 5 -b4'.split(' '));
assert.equal(args.foo, aliasArgs.foo);
assert.equal(args.bar, aliasArgs.bar);
});
it("should have different behavior for different commands", function () {
assert.doesNotThrow(function () {
parser.parseArgs('c1 --foo 5 -b4'.split(' '));
});
assert.throws(function () {
parser.parseArgs('c2 --foo 5 -b4'.split(' '));
});
assert.doesNotThrow(function () {
parser.parseArgs('c2 --baz 1'.split(' '));
});
assert.throws(function () {
parser.parseArgs('c1 --baz 1'.split(' '));
});
it("should have different behavior for different commands", function () {
assert.doesNotThrow(function () {
parser.parseArgs('c1 --foo 5 -b4'.split(' '));
});
it("should drop down with 'Invalid choice' error if parse unrecognized command", function () {
assert.throws(
function () {parser.parseArgs('command --baz 1'.split(' ')); },
/Invalid choice:/
);
assert.throws(function () {
parser.parseArgs('c2 --foo 5 -b4'.split(' '));
});
it("should drop down with empty args ('too few arguments' error)", function () {
assert.throws(
function () {parser.parseArgs([]); },
/too few arguments/
);
assert.doesNotThrow(function () {
parser.parseArgs('c2 --baz 1'.split(' '));
});
it("should support #setDefaults", function () {
c1.setDefaults({spam: 1});
c2.setDefaults({eggs: 2});
args = parser.parseArgs(['c1']);
assert.equal(args.spam, 1);
assert.strictEqual(args.eggs, undefined);
args = parser.parseArgs(['c2']);
assert.equal(args.eggs, 2);
assert.strictEqual(args.spam, undefined);
assert.throws(function () {
parser.parseArgs('c1 --baz 1'.split(' '));
});
});
it('should drop down with "Invalid choice" error if parse unrecognized command', function () {
assert.throws(
function () {parser.parseArgs('command --baz 1'.split(' ')); },
/Invalid choice:/
);
});
it("should drop down with empty args ('too few arguments' error)", function () {
assert.throws(
function () {parser.parseArgs([]); },
/too few arguments/
);
});
it("should support #setDefaults", function () {
c1.setDefaults({spam: 1});
c2.setDefaults({eggs: 2});
args = parser.parseArgs(['c1']);
assert.equal(args.spam, 1);
assert.strictEqual(args.eggs, undefined);
args = parser.parseArgs(['c2']);
assert.equal(args.eggs, 2);
assert.strictEqual(args.spam, undefined);
});
});
SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc