[Pkg-javascript-commits] [node-argparse] 05/11: Imported Upstream version 1.0.7
Jonathan Horn
jonathanh-guest at moszumanska.debian.org
Sat Mar 19 14:12:41 UTC 2016
This is an automated email from the git hooks/post-receive script.
jonathanh-guest pushed a commit to branch master
in repository node-argparse.
commit 9cb543389f7917dfd335edb5b2f40dd2448ce7ae
Author: Jonathan Ulrich Horn <debian at autoit4you.de>
Date: Sat Mar 19 14:46:01 2016 +0100
Imported Upstream version 1.0.7
---
.jshintignore => .eslintignore | 3 +-
.eslintrc.yml | 135 +++++++++++++++++++++
.jshintrc | 73 ------------
.npmignore | 5 -
.travis.yml | 4 +-
CHANGELOG.md | 99 ++++++++++------
Makefile | 36 +-----
README.md | 20 +++-
examples/.eslintrc.yml | 2 +
examples/arguments.js | 9 ++
examples/choice.js | 6 +-
examples/constants.js | 2 +-
examples/parents.js | 10 +-
examples/prefix_chars.js | 10 +-
examples/sub_commands.js | 11 +-
examples/sum.js | 4 +-
examples/testformatters.js | 58 ++++-----
index.js | 2 +
lib/action.js | 22 ++--
lib/action/append.js | 8 +-
lib/action/append/constant.js | 2 +-
lib/action/help.js | 9 +-
lib/action/store.js | 4 +-
lib/action/store/constant.js | 2 +-
lib/action/store/false.js | 2 +-
lib/action/store/true.js | 2 +-
lib/action/subparsers.js | 27 ++---
lib/action/version.js | 9 +-
lib/action_container.js | 73 ++++++------
lib/argument_parser.js | 259 ++++++++++++++++++++---------------------
lib/const.js | 3 +
lib/help/added_formatters.js | 23 ++--
lib/help/formatter.js | 203 ++++++++++++++++----------------
lib/namespace.js | 13 +--
lib/utils.js | 57 +++++++++
package.json | 12 +-
test/base.js | 204 +++++++++++++++++---------------
test/childgroups.js | 26 ++---
test/choices.js | 20 ++--
test/conflict.js | 46 ++++----
test/constant.js | 28 ++---
test/formatters.js | 44 +++----
test/fromfile.js | 53 ++++-----
test/group.js | 102 ++++++++--------
test/nargs.js | 115 +++++++++---------
test/optionals.js | 58 ++++-----
test/parents.js | 14 +--
test/positionals.js | 6 +-
test/prefix.js | 5 +-
test/sub_commands.js | 27 ++---
test/suppress.js | 8 +-
test/user_defined_type.js | 89 +++++++-------
52 files changed, 1106 insertions(+), 958 deletions(-)
diff --git a/.jshintignore b/.eslintignore
similarity index 57%
rename from .jshintignore
rename to .eslintignore
index 9c80d0b..6c65a9f 100644
--- a/.jshintignore
+++ b/.eslintignore
@@ -1,4 +1,3 @@
-.git/
doc/
node_modules/
-tmp/
+test/fixtures
diff --git a/.eslintrc.yml b/.eslintrc.yml
new file mode 100644
index 0000000..6439b4c
--- /dev/null
+++ b/.eslintrc.yml
@@ -0,0 +1,135 @@
+env:
+ node: true
+
+plugins:
+ - nodeca
+
+rules:
+ accessor-pairs: 2
+ array-bracket-spacing: [ 2, "always", { "singleValue": true, "objectsInArrays": true, "arraysInArrays": true } ]
+ block-scoped-var: 2
+ block-spacing: 2
+ brace-style: [ 2, '1tbs', { "allowSingleLine": true } ]
+ #callback-return: 2
+ comma-dangle: 2
+ comma-spacing: 2
+ comma-style: 2
+ computed-property-spacing: [ 2, never ]
+ #consistent-return: 2
+ consistent-this: [ 2, self ]
+ curly: [ 2, 'multi-line' ]
+ # dot-notation: [ 2, { allowKeywords: true } ]
+ dot-location: [ 2, 'property' ]
+ eol-last: 2
+ eqeqeq: 2
+ func-style: [ 2, declaration ]
+ guard-for-in: 2
+ handle-callback-err: 2
+ # key-spacing: [ 2, { "align": "value" } ]
+ keyword-spacing: 2
+ linebreak-style: 2
+ max-depth: [ 1, 4 ]
+ max-nested-callbacks: [ 1, 7 ]
+ # string can exceed 80 chars, but should not overflow github website :)
+ max-len: [ 2, 120, 1000 ]
+ new-cap: 2
+ new-parens: 2
+ no-alert: 2
+ no-array-constructor: 2
+ no-bitwise: 2
+ no-caller: 2
+ no-case-declarations: 2
+ no-catch-shadow: 2
+ no-cond-assign: 2
+ no-console: 1
+ no-constant-condition: 2
+ no-control-regex: 2
+ no-debugger: 1
+ no-delete-var: 2
+ no-div-regex: 2
+ no-dupe-args: 2
+ no-dupe-keys: 2
+ no-duplicate-case: 2
+ no-else-return: 2
+ # no-empty: 1
+ no-empty-character-class: 2
+ no-empty-pattern: 2
+ no-eq-null: 2
+ no-eval: 2
+ no-ex-assign: 2
+ no-extend-native: 2
+ no-extra-bind: 2
+ no-extra-boolean-cast: 2
+ no-extra-semi: 2
+ no-fallthrough: 2
+ no-floating-decimal: 2
+ no-func-assign: 2
+ no-implied-eval: 2
+ no-inner-declarations: 2
+ no-invalid-regexp: 2
+ no-irregular-whitespace: 2
+ no-iterator: 2
+ no-labels: 2
+ no-label-var: 2
+ no-lone-blocks: 1
+ no-lonely-if: 2
+ no-loop-func: 2
+ no-mixed-requires: [ 1, { "grouping": true } ]
+ no-mixed-spaces-and-tabs: 2
+ no-native-reassign: 2
+ no-negated-in-lhs: 2
+ no-new: 2
+ no-new-func: 2
+ no-new-object: 2
+ no-new-require: 2
+ no-new-wrappers: 2
+ no-obj-calls: 2
+ no-octal: 2
+ no-octal-escape: 2
+ no-path-concat: 2
+ no-proto: 2
+ no-redeclare: 2
+ # no-regex-spaces: 2
+ no-return-assign: 2
+ no-self-compare: 2
+ no-sequences: 2
+ # no-shadow: 2
+ no-shadow-restricted-names: 2
+ no-sparse-arrays: 2
+ no-throw-literal: 2
+ no-trailing-spaces: 2
+ no-undef: 2
+ no-undef-init: 2
+ no-undefined: 2
+ no-unexpected-multiline: 2
+ no-unreachable: 2
+ no-unused-expressions: 2
+ no-unused-vars: 2
+ no-use-before-define: 2
+ no-void: 2
+ no-with: 2
+ object-curly-spacing: [ 2, always, { "objectsInObjects": true, "arraysInObjects": true } ]
+ operator-assignment: 1
+ semi: 2
+ semi-spacing: 2
+ space-before-blocks: 2
+ space-before-function-paren: [ 2, { "anonymous": "always", "named": "never" } ]
+ space-in-parens: [ 2, never ]
+ space-infix-ops: 2
+ space-unary-ops: 2
+ #spaced-comment: [ 1, always, { exceptions: [ '/', '=' ] } ]
+ strict: 2
+ quotes: [ 2, single, avoid-escape ]
+ quote-props: [ 1, 'as-needed' ]
+ radix: 2
+ use-isnan: 2
+ valid-typeof: 2
+ yoda: [ 2, never, { "exceptRange": true } ]
+
+
+
+#
+# Our custom rules from plugin
+#
+ nodeca/indent: [2, spaces, 2]
+ nodeca/no-wire-anonymous: 1
diff --git a/.jshintrc b/.jshintrc
deleted file mode 100644
index 7f1c6ef..0000000
--- a/.jshintrc
+++ /dev/null
@@ -1,73 +0,0 @@
-{
- // Enforcing Options /////////////////////////////////////////////////////////
-
- "bitwise" : true, // Prohibit bitwise operators (&, |, ^, etc.).
- "curly" : true, // Require {} for every new block or scope.
- "eqeqeq" : true, // Require triple equals i.e. `===`.
- "forin" : false, // Tolerate `for in` loops without `hasOwnPrototype`.
- "immed" : true, // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );`
- "latedef" : true, // Prohibit hariable use before definition.
- "newcap" : true, // Require capitalization of all constructor functions e.g. `new F()`.
- "noarg" : true, // Prohibit use of `arguments.caller` and `arguments.callee`.
- "noempty" : true, // Prohibit use of empty blocks.
- "nonew" : true, // Prohibit use of constructors for side-effects.
- "plusplus" : false, // Prohibit use of `++` & `--`.
- "regexp" : false, // Prohibit `.` and `[^...]` in regular expressions.
- "undef" : true, // Require all non-global variables be declared before they are used.
- "unused" : true, // Warns when you define and never use your variables
- "strict" : true, // Require `use strict` pragma in every file.
- "trailing" : true, // Prohibit trailing whitespaces.
-
- // Relaxing Options //////////////////////////////////////////////////////////
-
- "asi" : false, // Tolerate Automatic Semicolon Insertion (no semicolons).
- "boss" : false, // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments.
- "debug" : false, // Allow debugger statements e.g. browser breakpoints.
- "eqnull" : false, // Tolerate use of `== null`.
- //"es5" : true, // Allow ECMAScript 5 syntax.
- "esnext" : false, // Allow ES.next specific features such as const and let
- "evil" : false, // Tolerate use of `eval`.
- "expr" : false, // Tolerate `ExpressionStatement` as Programs.
- "funcscope" : false, // Tolerate declaring variables inside of control structures while accessing them later
- "globalstrict" : true, // Allow global "use strict" (also enables 'strict').
- "iterator" : false, // Allow usage of __iterator__ property.
- "lastsemic" : false, // Tolerate semicolon omited for the last statement.
- "laxbreak" : false, // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons.
- "laxcomma" : true, // This option suppresses warnings about comma-first coding style
- "loopfunc" : false, // Allow functions to be defined within loops.
- "multistr" : false, // Tolerate multi-line strings.
- "onecase" : false, // Tolerate swithes with only one case.
- "proto" : false, // Allow usage of __proto__ property.
- "regexdash" : false, // Tolerate unescaped last dash i.e. `[-...]`.
- "scripturl" : true, // Tolerate script-targeted URLs.
- "smarttabs" : false, // Allow mixed tabs and spaces when the latter are used for alignmnent only.
- "shadow" : false, // Allows re-define variables later in code e.g. `var x=1; x=2;`.
- "sub" : true, // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`.
- "supernew" : true, // Tolerate `new function () { ... };` and `new Object;`.
-
- // Environments //////////////////////////////////////////////////////////////
-
- "browser" : false, // Defines globals exposed by modern browsers
- "couch" : false, // Defines globals exposed by CouchDB
- "devel" : false, // Allow developments statements e.g. `console.log();`.
- "dojo" : false, // Defines globals exposed by the Dojo Toolkit
- "jquery" : false, // Defines globals exposed by the jQuery
- "mootools" : false, // Defines globals exposed by the MooTools
- "node" : true, // Defines globals exposed when running under Node.JS
- "nonstandard" : false, // Defines non-standard but widely adopted globals such as escape and unescape
- "prototypejs" : false, // Defines globals exposed by the Prototype
- "rhino" : false, // Defines globals exposed when running under Rhino
- "wsh" : false, // Defines globals exposed when running under WSH
-
- // Legacy ////////////////////////////////////////////////////////////////////
-
- "nomen" : false, // Prohibit use of initial or trailing underbars in names.
- "onevar" : false, // Allow only one `var` statement per function.
- "passfail" : false, // Stop on first error.
- "white" : false, // Check against strict whitespace and indentation rules.
-
- // Undocumented //////////////////////////////////////////////////////////////
-
- "maxerr" : 100, // Maximum error before stopping.
- "indent" : 2 // Specify indentation spacing
-}
diff --git a/.npmignore b/.npmignore
deleted file mode 100644
index 4d7c43c..0000000
--- a/.npmignore
+++ /dev/null
@@ -1,5 +0,0 @@
-/doc/
-/test/
-/.*
-/Makefile
-
diff --git a/.travis.yml b/.travis.yml
index b0d8340..d949ace 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,6 +2,6 @@ language: node_js
node_js:
- "0.10"
- "0.12"
- - stable
-before_script: "make dev-deps"
+ - "4"
+ - "5"
sudo: false
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f0e950a..61405eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,142 +1,167 @@
+1.0.7 / 2016-03-17
+------------------
+
+- Teach `addArgument` to accept string arg names. #97, @tomxtobin.
+
+
+1.0.6 / 2016-02-06
+------------------
+
+- Maintenance: moved to eslint & updated CS.
+
+
+1.0.5 / 2016-02-05
+------------------
+
+- Removed lodash dependency to significantly reduce install size.
+ Thanks to @mourner.
+
+
+1.0.4 / 2016-01-17
+------------------
+
+- Maintenance: lodash update to 4.0.0.
+
+
1.0.3 / 2015-10-27
------------------
-* Fix parse `=` in args: `--examplepath="C:\myfolder\env=x64"`. #84, @CatWithApple.
+- Fix parse `=` in args: `--examplepath="C:\myfolder\env=x64"`. #84, @CatWithApple.
1.0.2 / 2015-03-22
------------------
-* Relaxed lodash version dependency.
+- Relaxed lodash version dependency.
1.0.1 / 2015-02-20
------------------
-* Changed dependencies to be compatible with ancient nodejs.
+- Changed dependencies to be compatible with ancient nodejs.
1.0.0 / 2015-02-19
------------------
-* Maintenance release.
-* Replaced `underscore` with `lodash`.
-* Bumped version to 1.0.0 to better reflect semver meaning.
-* HISTORY.md -> CHANGELOG.md
+- Maintenance release.
+- Replaced `underscore` with `lodash`.
+- Bumped version to 1.0.0 to better reflect semver meaning.
+- HISTORY.md -> CHANGELOG.md
0.1.16 / 2013-12-01
-------------------
-* Maintenance release. Updated dependencies and docs.
+- Maintenance release. Updated dependencies and docs.
0.1.15 / 2013-05-13
-------------------
-* Fixed #55, @trebor89
+- Fixed #55, @trebor89
0.1.14 / 2013-05-12
-------------------
-* Fixed #62, @maxtaco
+- Fixed #62, @maxtaco
0.1.13 / 2013-04-08
-------------------
-* Added `.npmignore` to reduce package size
+- Added `.npmignore` to reduce package size
0.1.12 / 2013-02-10
-------------------
-* Fixed conflictHandler (#46), @hpaulj
+- Fixed conflictHandler (#46), @hpaulj
0.1.11 / 2013-02-07
-------------------
-* Multiple bugfixes, @hpaulj
-* Added 70+ tests (ported from python), @hpaulj
-* Added conflictHandler, @applepicke
-* Added fromfilePrefixChar, @hpaulj
+- Multiple bugfixes, @hpaulj
+- Added 70+ tests (ported from python), @hpaulj
+- Added conflictHandler, @applepicke
+- Added fromfilePrefixChar, @hpaulj
0.1.10 / 2012-12-30
-------------------
-* Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion)
+- Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion)
support, thanks to @hpaulj
-* Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj
+- Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj
0.1.9 / 2012-12-27
------------------
-* Fixed option dest interferens with other options (issue #23), thanks to @hpaulj
-* Fixed default value behavior with `*` positionals, thanks to @hpaulj
-* Improve `getDefault()` behavior, thanks to @hpaulj
-* Imrove negative argument parsing, thanks to @hpaulj
+- Fixed option dest interferens with other options (issue #23), thanks to @hpaulj
+- Fixed default value behavior with `*` positionals, thanks to @hpaulj
+- Improve `getDefault()` behavior, thanks to @hpaulj
+- Imrove negative argument parsing, thanks to @hpaulj
0.1.8 / 2012-12-01
------------------
-* Fixed parser parents (issue #19), thanks to @hpaulj
-* Fixed negative argument parse (issue #20), thanks to @hpaulj
+- Fixed parser parents (issue #19), thanks to @hpaulj
+- Fixed negative argument parse (issue #20), thanks to @hpaulj
0.1.7 / 2012-10-14
------------------
-* Fixed 'choices' argument parse (issue #16)
-* Fixed stderr output (issue #15)
+- Fixed 'choices' argument parse (issue #16)
+- Fixed stderr output (issue #15)
0.1.6 / 2012-09-09
------------------
-* Fixed check for conflict of options (thanks to @tomxtobin)
+- Fixed check for conflict of options (thanks to @tomxtobin)
0.1.5 / 2012-09-03
------------------
-* Fix parser #setDefaults method (thanks to @tomxtobin)
+- Fix parser #setDefaults method (thanks to @tomxtobin)
0.1.4 / 2012-07-30
------------------
-* Fixed pseudo-argument support (thanks to @CGamesPlay)
-* Fixed addHelp default (should be true), if not set (thanks to @benblank)
+- Fixed pseudo-argument support (thanks to @CGamesPlay)
+- Fixed addHelp default (should be true), if not set (thanks to @benblank)
0.1.3 / 2012-06-27
------------------
-* Fixed formatter api name: Formatter -> HelpFormatter
+- Fixed formatter api name: Formatter -> HelpFormatter
0.1.2 / 2012-05-29
------------------
-* Added basic tests
-* Removed excess whitespace in help
-* Fixed error reporting, when parcer with subcommands
+- Added basic tests
+- Removed excess whitespace in help
+- Fixed error reporting, when parcer with subcommands
called with empty arguments
0.1.1 / 2012-05-23
------------------
-* Fixed line wrapping in help formatter
-* Added better error reporting on invalid arguments
+- Fixed line wrapping in help formatter
+- Added better error reporting on invalid arguments
0.1.0 / 2012-05-16
------------------
-* First release.
+- First release.
diff --git a/Makefile b/Makefile
index 69f36d7..4f18944 100644
--- a/Makefile
+++ b/Makefile
@@ -1,5 +1,3 @@
-PATH := ./node_modules/.bin:${PATH}
-
NPM_PACKAGE := $(shell node -e 'process.stdout.write(require("./package.json").name)')
NPM_VERSION := $(shell node -e 'process.stdout.write(require("./package.json").version)')
@@ -17,48 +15,22 @@ help:
echo "make lint - Lint sources with JSHint"
echo "make test - Lint sources and run all tests"
echo "make doc - Build API docs"
- echo "make dev-deps - Install developer dependencies"
echo "make gh-pages - Build and push API docs into gh-pages branch"
echo "make publish - Set new version tag and publish npm package"
echo "make todo - Find and list all TODOs"
lint:
- if test ! `which jshint` ; then \
- echo "You need 'jshint' installed in order to run lint." >&2 ; \
- echo " $ make dev-deps" >&2 ; \
- exit 128 ; \
- fi
- jshint . --show-non-errors
+ ./node_modules/.bin/eslint .
test: lint
- @if test ! `which mocha` ; then \
- echo "You need 'mocha' installed in order to run tests." >&2 ; \
- echo " $ make dev-deps" >&2 ; \
- exit 128 ; \
- fi
- NODE_ENV=test mocha
+ ./node_modules/.bin/mocha
doc:
- @if test ! `which ndoc` ; then \
- echo "You need 'ndoc' installed in order to generate docs." >&2 ; \
- echo " $ npm install -g ndoc" >&2 ; \
- exit 128 ; \
- fi
rm -rf ./doc
- ndoc --link-format "{package.homepage}/blob/${CURR_HEAD}/{file}#L{line}"
-
-
-dev-deps:
- @if test ! `which npm` ; then \
- echo "You need 'npm' installed." >&2 ; \
- echo " See: http://npmjs.org/" >&2 ; \
- exit 128 ; \
- fi
- npm install -g jshint
- npm install
+ ./node_modules/.bin/ndoc --link-format "{package.homepage}/blob/${CURR_HEAD}/{file}#L{line}"
gh-pages:
@@ -100,5 +72,5 @@ todo:
grep 'TODO' -n -r ./lib 2>/dev/null || test true
-.PHONY: publish lint test doc dev-deps gh-pages todo
+.PHONY: publish lint test doc gh-pages todo
.SILENT: help lint test doc todo
diff --git a/README.md b/README.md
index 72e4261..2d0bcab 100644
--- a/README.md
+++ b/README.md
@@ -42,6 +42,12 @@ parser.addArgument(
help: 'bar foo'
}
);
+parser.addArgument(
+ '--baz',
+ {
+ help: 'baz bar'
+ }
+);
var args = parser.parseArgs();
console.dir(args);
```
@@ -50,7 +56,7 @@ Display help:
```
$ ./test.js -h
-usage: example.js [-h] [-v] [-f FOO] [-b BAR]
+usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ]
Argparse example
@@ -59,13 +65,14 @@ Optional arguments:
-v, --version Show program's version number and exit.
-f FOO, --foo FOO foo bar
-b BAR, --bar BAR bar foo
+ --baz BAZ baz bar
```
Parse arguments:
```
-$ ./test.js -f=3 --bar=4
-{ foo: '3', bar: '4' }
+$ ./test.js -f=3 --bar=4 --baz 5
+{ foo: '3', bar: '4', baz: '5' }
```
More [examples](https://github.com/nodeca/argparse/tree/master/examples).
@@ -105,12 +112,15 @@ addArgument() method
====================
```
-ArgumentParser.addArgument([names or flags], {options})
+ArgumentParser.addArgument(name or flag or [name] or [flags...], {options})
```
Defines how a single command-line argument should be parsed.
-- ```name or flags``` - Either a name or a list of option strings, e.g. foo or -f, --foo.
+- ```name or flag or [name] or [flags...]``` - Either a positional name
+ (e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array
+ of a single positional name (e.g., `['foo']`), or an array of options
+ (e.g., `['-f', '--foo']`).
Options:
diff --git a/examples/.eslintrc.yml b/examples/.eslintrc.yml
new file mode 100644
index 0000000..b1b8596
--- /dev/null
+++ b/examples/.eslintrc.yml
@@ -0,0 +1,2 @@
+rules:
+ no-console: 0
diff --git a/examples/arguments.js b/examples/arguments.js
index 5b090fa..2be03fb 100755
--- a/examples/arguments.js
+++ b/examples/arguments.js
@@ -19,6 +19,12 @@ parser.addArgument(
help: 'bar foo'
}
);
+parser.addArgument(
+ '--baz',
+ {
+ help: 'baz bar'
+ }
+);
parser.printHelp();
@@ -34,3 +40,6 @@ console.log('-----------');
args = parser.parseArgs('--foo 5 --bar 6'.split(' '));
console.dir(args);
console.log('-----------');
+args = parser.parseArgs('--baz 7 -f 8'.split(' '));
+console.dir(args);
+console.log('-----------');
diff --git a/examples/choice.js b/examples/choice.js
index 2616fa4..be5c8e6 100755
--- a/examples/choice.js
+++ b/examples/choice.js
@@ -8,15 +8,15 @@ var parser = new ArgumentParser({
description: 'Argparse examples: choice'
});
-parser.addArgument(['foo'], {choices: 'abc'});
+parser.addArgument([ 'foo' ], { choices: 'abc' });
parser.printHelp();
console.log('-----------');
var args;
-args = parser.parseArgs(['c']);
+args = parser.parseArgs([ 'c' ]);
console.dir(args);
console.log('-----------');
-parser.parseArgs(['X']);
+parser.parseArgs([ 'X' ]);
console.dir(args);
diff --git a/examples/constants.js b/examples/constants.js
index 172a4f3..78486b1 100755
--- a/examples/constants.js
+++ b/examples/constants.js
@@ -9,7 +9,7 @@ var parser = new ArgumentParser({
});
parser.addArgument(
- [ '-a'],
+ [ '-a' ],
{
action: 'storeConst',
dest: 'answer',
diff --git a/examples/parents.js b/examples/parents.js
index dfe8968..adfa9c2 100755
--- a/examples/parents.js
+++ b/examples/parents.js
@@ -7,7 +7,7 @@ var args;
var parent_parser = new ArgumentParser({ addHelp: false });
// note addHelp:false to prevent duplication of the -h option
parent_parser.addArgument(
- ['--parent'],
+ [ '--parent' ],
{ type: 'int', description: 'parent' }
);
@@ -15,14 +15,14 @@ var foo_parser = new ArgumentParser({
parents: [ parent_parser ],
description: 'child1'
});
-foo_parser.addArgument(['foo']);
-args = foo_parser.parseArgs(['--parent', '2', 'XXX']);
+foo_parser.addArgument([ 'foo' ]);
+args = foo_parser.parseArgs([ '--parent', '2', 'XXX' ]);
console.log(args);
var bar_parser = new ArgumentParser({
parents: [ parent_parser ],
description: 'child2'
});
-bar_parser.addArgument(['--bar']);
-args = bar_parser.parseArgs(['--bar', 'YYY']);
+bar_parser.addArgument([ '--bar' ]);
+args = bar_parser.parseArgs([ '--bar', 'YYY' ]);
console.log(args);
diff --git a/examples/prefix_chars.js b/examples/prefix_chars.js
index 430d5e1..f1329a4 100755
--- a/examples/prefix_chars.js
+++ b/examples/prefix_chars.js
@@ -8,16 +8,16 @@ var parser = new ArgumentParser({
description: 'Argparse examples: prefix_chars',
prefixChars: '-+'
});
-parser.addArgument(['+f', '++foo']);
-parser.addArgument(['++bar'], {action: 'storeTrue'});
+parser.addArgument([ '+f', '++foo' ]);
+parser.addArgument([ '++bar' ], { action: 'storeTrue' });
parser.printHelp();
console.log('-----------');
var args;
-args = parser.parseArgs(['+f', '1']);
+args = parser.parseArgs([ '+f', '1' ]);
console.dir(args);
-args = parser.parseArgs(['++bar']);
+args = parser.parseArgs([ '++bar' ]);
console.dir(args);
-args = parser.parseArgs(['++foo', '2', '++bar']);
+args = parser.parseArgs([ '++foo', '2', '++bar' ]);
console.dir(args);
diff --git a/examples/sub_commands.js b/examples/sub_commands.js
index df9c494..77deddd 100755
--- a/examples/sub_commands.js
+++ b/examples/sub_commands.js
@@ -10,10 +10,10 @@ var parser = new ArgumentParser({
var subparsers = parser.addSubparsers({
title: 'subcommands',
- dest: "subcommand_name"
+ dest: 'subcommand_name'
});
-var bar = subparsers.addParser('c1', {addHelp: true, help: 'c1 help'});
+var bar = subparsers.addParser('c1', { addHelp: true, help: 'c1 help' });
bar.addArgument(
[ '-f', '--foo' ],
{
@@ -21,9 +21,10 @@ bar.addArgument(
help: 'foo3 bar3'
}
);
-var bar = subparsers.addParser(
+
+bar = subparsers.addParser(
'c2',
- {aliases: ['co'], addHelp: true, help: 'c2 help'}
+ { aliases: [ 'co' ], addHelp: true, help: 'c2 help' }
);
bar.addArgument(
[ '-b', '--bar' ],
@@ -46,4 +47,4 @@ console.log('-----------');
args = parser.parseArgs('co -b 1'.split(' '));
console.dir(args);
console.log('-----------');
-parser.parseArgs(['c1', '-h']);
+parser.parseArgs([ 'c1', '-h' ]);
diff --git a/examples/sum.js b/examples/sum.js
index 4532800..94e5a0c 100755
--- a/examples/sum.js
+++ b/examples/sum.js
@@ -17,13 +17,13 @@ function max(arr) {
}
-parser.addArgument(['integers'], {
+parser.addArgument([ 'integers' ], {
metavar: 'N',
type: 'int',
nargs: '+',
help: 'an integer for the accumulator'
});
-parser.addArgument(['--sum'], {
+parser.addArgument([ '--sum' ], {
dest: 'accumulate',
action: 'storeConst',
constant: sum,
diff --git a/examples/testformatters.js b/examples/testformatters.js
index 1c03cdc..011d964 100644
--- a/examples/testformatters.js
+++ b/examples/testformatters.js
@@ -5,14 +5,14 @@ var a, group, parser, helptext;
var assert = require('assert');
-var print = function () {
- return console.log.apply(console, arguments);
- };
+function print() {
+ return console.log.apply(console, arguments);
+}
// print = function () {};
var argparse = require('argparse');
-print("TEST argparse.ArgumentDefaultsHelpFormatter");
+print('TEST argparse.ArgumentDefaultsHelpFormatter');
parser = new argparse.ArgumentParser({
debug: true,
@@ -20,20 +20,20 @@ parser = new argparse.ArgumentParser({
description: 'description'
});
-parser.addArgument(['--foo'], {
+parser.addArgument([ '--foo' ], {
help: 'foo help - oh and by the way, %(defaultValue)s'
});
-parser.addArgument(['--bar'], {
+parser.addArgument([ '--bar' ], {
action: 'storeTrue',
help: 'bar help'
});
-parser.addArgument(['spam'], {
+parser.addArgument([ 'spam' ], {
help: 'spam help'
});
-parser.addArgument(['badger'], {
+parser.addArgument([ 'badger' ], {
nargs: '?',
defaultValue: 'wooden',
help: 'badger help'
@@ -44,7 +44,7 @@ group = parser.addArgumentGroup({
description: 'group description'
});
-group.addArgument(['--baz'], {
+group.addArgument([ '--baz' ], {
type: 'int',
defaultValue: 42,
help: 'baz help'
@@ -79,7 +79,7 @@ title:
--baz BAZ baz help (default: 42)
*/
-print("TEST argparse.RawDescriptionHelpFormatter");
+print('TEST argparse.RawDescriptionHelpFormatter');
parser = new argparse.ArgumentParser({
debug: true,
@@ -91,13 +91,13 @@ parser = new argparse.ArgumentParser({
'here\n'
});
-a = parser.addArgument(['--foo'], {
+a = parser.addArgument([ '--foo' ], {
help: ' foo help should not\n' +
' retain this odd formatting'
});
-parser.addArgument(['spam'], {
- 'help': 'spam help'
+parser.addArgument([ 'spam' ], {
+ help: 'spam help'
});
group = parser.addArgumentGroup({
@@ -107,7 +107,7 @@ group = parser.addArgumentGroup({
' exactly like it is here\n'
});
-group.addArgument(['--bar'], {
+group.addArgument([ '--bar' ], {
help: 'bar help'
});
@@ -146,7 +146,7 @@ title:
*/
-print("TEST argparse.RawTextHelpFormatter");
+print('TEST argparse.RawTextHelpFormatter');
parser = new argparse.ArgumentParser({
debug: true,
@@ -158,18 +158,18 @@ parser = new argparse.ArgumentParser({
'here\n'
});
-parser.addArgument(['--baz'], {
+parser.addArgument([ '--baz' ], {
help: ' baz help should also\n' +
'appear as given here'
});
-a = parser.addArgument(['--foo'], {
+a = parser.addArgument([ '--foo' ], {
help: ' foo help should also\n' +
'appear as given here'
});
-parser.addArgument(['spam'], {
- 'help': 'spam help'
+parser.addArgument([ 'spam' ], {
+ help: 'spam help'
});
group = parser.addArgumentGroup({
@@ -179,7 +179,7 @@ group = parser.addArgumentGroup({
' exactly like it is here\n'
});
-group.addArgument(['--bar'], {
+group.addArgument([ '--bar' ], {
help: 'bar help'
});
@@ -217,34 +217,34 @@ title:
*/
-print("TEST metavar as a tuple");
+print('TEST metavar as a tuple');
parser = new argparse.ArgumentParser({
prog: 'PROG'
});
-parser.addArgument(['-w'], {
+parser.addArgument([ '-w' ], {
help: 'w',
nargs: '+',
- metavar: ['W1', 'W2']
+ metavar: [ 'W1', 'W2' ]
});
-parser.addArgument(['-x'], {
+parser.addArgument([ '-x' ], {
help: 'x',
nargs: '*',
- metavar: ['X1', 'X2']
+ metavar: [ 'X1', 'X2' ]
});
-parser.addArgument(['-y'], {
+parser.addArgument([ '-y' ], {
help: 'y',
nargs: 3,
- metavar: ['Y1', 'Y2', 'Y3']
+ metavar: [ 'Y1', 'Y2', 'Y3' ]
});
-parser.addArgument(['-z'], {
+parser.addArgument([ '-z' ], {
help: 'z',
nargs: '?',
- metavar: ['Z1']
+ metavar: [ 'Z1' ]
});
helptext = parser.formatHelp();
diff --git a/index.js b/index.js
index 3b6eea0..3bbc143 100644
--- a/index.js
+++ b/index.js
@@ -1 +1,3 @@
+'use strict';
+
module.exports = require('./lib/argparse');
diff --git a/lib/action.js b/lib/action.js
index 6f7e9a5..ef35989 100644
--- a/lib/action.js
+++ b/lib/action.js
@@ -32,7 +32,7 @@
// Constants
-var $$ = require('./const');
+var c = require('./const');
/**
@@ -74,19 +74,19 @@ var Action = module.exports = function Action(options) {
options = options || {};
this.optionStrings = options.optionStrings || [];
this.dest = options.dest;
- this.nargs = options.nargs !== undefined ? options.nargs : null;
- this.constant = options.constant !== undefined ? options.constant : null;
+ this.nargs = typeof options.nargs !== 'undefined' ? options.nargs : null;
+ this.constant = typeof options.constant !== 'undefined' ? options.constant : null;
this.defaultValue = options.defaultValue;
- this.type = options.type !== undefined ? options.type : null;
- this.choices = options.choices !== undefined ? options.choices : null;
- this.required = options.required !== undefined ? options.required: false;
- this.help = options.help !== undefined ? options.help : null;
- this.metavar = options.metavar !== undefined ? options.metavar : null;
+ this.type = typeof options.type !== 'undefined' ? options.type : null;
+ this.choices = typeof options.choices !== 'undefined' ? options.choices : null;
+ this.required = typeof options.required !== 'undefined' ? options.required : false;
+ this.help = typeof options.help !== 'undefined' ? options.help : null;
+ this.metavar = typeof options.metavar !== 'undefined' ? options.metavar : null;
if (!(this.optionStrings instanceof Array)) {
throw new Error('optionStrings should be an array');
}
- if (this.required !== undefined && typeof(this.required) !== 'boolean') {
+ if (typeof this.required !== 'undefined' && typeof this.required !== 'boolean') {
throw new Error('required should be a boolean');
}
};
@@ -99,9 +99,9 @@ var Action = module.exports = function Action(options) {
Action.prototype.getName = function () {
if (this.optionStrings.length > 0) {
return this.optionStrings.join('/');
- } else if (this.metavar !== null && this.metavar !== $$.SUPPRESS) {
+ } else if (this.metavar !== null && this.metavar !== c.SUPPRESS) {
return this.metavar;
- } else if (this.dest !== undefined && this.dest !== $$.SUPPRESS) {
+ } else if (typeof this.dest !== 'undefined' && this.dest !== c.SUPPRESS) {
return this.dest;
}
return null;
diff --git a/lib/action/append.js b/lib/action/append.js
index 48c6dbe..b5da0de 100644
--- a/lib/action/append.js
+++ b/lib/action/append.js
@@ -14,7 +14,7 @@ var util = require('util');
var Action = require('../action');
// Constants
-var $$ = require('../const');
+var c = require('../const');
/*:nodoc:*
* new ActionAppend(options)
@@ -30,7 +30,7 @@ var ActionAppend = module.exports = function ActionAppend(options) {
'strings are not supplying the value to append, ' +
'the append const action may be more appropriate');
}
- if (!!this.constant && this.nargs !== $$.OPTIONAL) {
+ if (!!this.constant && this.nargs !== c.OPTIONAL) {
throw new Error('nargs must be OPTIONAL to supply const');
}
Action.call(this, options);
@@ -47,9 +47,7 @@ util.inherits(ActionAppend, Action);
* Call the action. Save result in namespace object
**/
ActionAppend.prototype.call = function (parser, namespace, values) {
- var items = [].concat(namespace[this.dest] || []); // or _.clone
+ var items = (namespace[this.dest] || []).slice();
items.push(values);
namespace.set(this.dest, items);
};
-
-
diff --git a/lib/action/append/constant.js b/lib/action/append/constant.js
index 90747ab..313f5d2 100644
--- a/lib/action/append/constant.js
+++ b/lib/action/append/constant.js
@@ -24,7 +24,7 @@ var Action = require('../../action');
var ActionAppendConstant = module.exports = function ActionAppendConstant(options) {
options = options || {};
options.nargs = 0;
- if (options.constant === undefined) {
+ if (typeof options.constant === 'undefined') {
throw new Error('constant option is required for appendAction');
}
Action.call(this, options);
diff --git a/lib/action/help.js b/lib/action/help.js
index 7f7b4e2..b40e05a 100644
--- a/lib/action/help.js
+++ b/lib/action/help.js
@@ -11,7 +11,7 @@ var util = require('util');
var Action = require('../action');
// Constants
-var $$ = require('../const');
+var c = require('../const');
/*:nodoc:*
* new ActionHelp(options)
@@ -22,11 +22,10 @@ var ActionHelp = module.exports = function ActionHelp(options) {
options = options || {};
if (options.defaultValue !== null) {
options.defaultValue = options.defaultValue;
+ } else {
+ options.defaultValue = c.SUPPRESS;
}
- else {
- options.defaultValue = $$.SUPPRESS;
- }
- options.dest = (options.dest !== null ? options.dest: $$.SUPPRESS);
+ options.dest = (options.dest !== null ? options.dest : c.SUPPRESS);
options.nargs = 0;
Action.call(this, options);
diff --git a/lib/action/store.js b/lib/action/store.js
index 8ebc974..283b860 100644
--- a/lib/action/store.js
+++ b/lib/action/store.js
@@ -13,7 +13,7 @@ var util = require('util');
var Action = require('../action');
// Constants
-var $$ = require('../const');
+var c = require('../const');
/*:nodoc:*
@@ -29,7 +29,7 @@ var ActionStore = module.exports = function ActionStore(options) {
'true or store const may be more appropriate');
}
- if (this.constant !== undefined && this.nargs !== $$.OPTIONAL) {
+ if (typeof this.constant !== 'undefined' && this.nargs !== c.OPTIONAL) {
throw new Error('nargs must be OPTIONAL to supply const');
}
Action.call(this, options);
diff --git a/lib/action/store/constant.js b/lib/action/store/constant.js
index 8410fcf..23caa89 100644
--- a/lib/action/store/constant.js
+++ b/lib/action/store/constant.js
@@ -22,7 +22,7 @@ var Action = require('../../action');
var ActionStoreConstant = module.exports = function ActionStoreConstant(options) {
options = options || {};
options.nargs = 0;
- if (options.constant === undefined) {
+ if (typeof options.constant === 'undefined') {
throw new Error('constant option is required for storeAction');
}
Action.call(this, options);
diff --git a/lib/action/store/false.js b/lib/action/store/false.js
index 66417bf..9924f46 100644
--- a/lib/action/store/false.js
+++ b/lib/action/store/false.js
@@ -21,7 +21,7 @@ var ActionStoreConstant = require('./constant');
var ActionStoreFalse = module.exports = function ActionStoreFalse(options) {
options = options || {};
options.constant = false;
- options.defaultValue = options.defaultValue !== null ? options.defaultValue: true;
+ options.defaultValue = options.defaultValue !== null ? options.defaultValue : true;
ActionStoreConstant.call(this, options);
};
util.inherits(ActionStoreFalse, ActionStoreConstant);
diff --git a/lib/action/store/true.js b/lib/action/store/true.js
index 43ec708..9e22f7d 100644
--- a/lib/action/store/true.js
+++ b/lib/action/store/true.js
@@ -20,7 +20,7 @@ var ActionStoreConstant = require('./constant');
var ActionStoreTrue = module.exports = function ActionStoreTrue(options) {
options = options || {};
options.constant = true;
- options.defaultValue = options.defaultValue !== null ? options.defaultValue: false;
+ options.defaultValue = options.defaultValue !== null ? options.defaultValue : false;
ActionStoreConstant.call(this, options);
};
util.inherits(ActionStoreTrue, ActionStoreConstant);
diff --git a/lib/action/subparsers.js b/lib/action/subparsers.js
index 257714d..99dfedd 100644
--- a/lib/action/subparsers.js
+++ b/lib/action/subparsers.js
@@ -9,13 +9,12 @@
var util = require('util');
var format = require('util').format;
-var _ = require('lodash');
var Action = require('../action');
// Constants
-var $$ = require('../const');
+var c = require('../const');
// Errors
var argumentErrorHelper = require('../argument/error');
@@ -27,7 +26,7 @@ var argumentErrorHelper = require('../argument/error');
* Create pseudo action for correct help text
*
**/
-var ChoicesPseudoAction = function (name, help) {
+function ChoicesPseudoAction(name, help) {
var options = {
optionStrings: [],
dest: name,
@@ -35,7 +34,8 @@ var ChoicesPseudoAction = function (name, help) {
};
Action.call(this, options);
-};
+}
+
util.inherits(ChoicesPseudoAction, Action);
/**
@@ -43,10 +43,10 @@ util.inherits(ChoicesPseudoAction, Action);
* - options (object): options hash see [[Action.new]]
*
**/
-var ActionSubparsers = module.exports = function ActionSubparsers(options) {
+function ActionSubparsers(options) {
options = options || {};
- options.dest = options.dest || $$.SUPPRESS;
- options.nargs = $$.PARSER;
+ options.dest = options.dest || c.SUPPRESS;
+ options.nargs = c.PARSER;
this.debug = (options.debug === true);
@@ -57,7 +57,8 @@ var ActionSubparsers = module.exports = function ActionSubparsers(options) {
options.choices = this._nameParserMap;
Action.call(this, options);
-};
+}
+
util.inherits(ActionSubparsers, Action);
/*:nodoc:*
@@ -88,7 +89,7 @@ ActionSubparsers.prototype.addParser = function (name, options) {
var aliases = options.aliases || [];
// create a pseudo-action to hold the choice help
- if (!!options.help || _.isString(options.help)) {
+ if (!!options.help || typeof options.help === 'string') {
var help = options.help;
delete options.help;
@@ -126,18 +127,18 @@ ActionSubparsers.prototype.call = function (parser, namespace, values) {
var argStrings = values.slice(1);
// set the parser name if requested
- if (this.dest !== $$.SUPPRESS) {
+ if (this.dest !== c.SUPPRESS) {
namespace[this.dest] = parserName;
}
// select the parser
- if (!!this._nameParserMap[parserName]) {
+ if (this._nameParserMap[parserName]) {
parser = this._nameParserMap[parserName];
} else {
throw argumentErrorHelper(format(
'Unknown parser "%s" (choices: [%s]).',
parserName,
- _.keys(this._nameParserMap).join(', ')
+ Object.keys(this._nameParserMap).join(', ')
));
}
@@ -145,4 +146,4 @@ ActionSubparsers.prototype.call = function (parser, namespace, values) {
parser.parseArgs(argStrings, namespace);
};
-
+module.exports = ActionSubparsers;
diff --git a/lib/action/version.js b/lib/action/version.js
index a17877c..8053328 100644
--- a/lib/action/version.js
+++ b/lib/action/version.js
@@ -13,7 +13,7 @@ var Action = require('../action');
//
// Constants
//
-var $$ = require('../const');
+var c = require('../const');
/*:nodoc:*
* new ActionVersion(options)
@@ -22,8 +22,8 @@ var $$ = require('../const');
**/
var ActionVersion = module.exports = function ActionVersion(options) {
options = options || {};
- options.defaultValue = (!!options.defaultValue ? options.defaultValue: $$.SUPPRESS);
- options.dest = (options.dest || $$.SUPPRESS);
+ options.defaultValue = (options.defaultValue ? options.defaultValue : c.SUPPRESS);
+ options.dest = (options.dest || c.SUPPRESS);
options.nargs = 0;
this.version = options.version;
Action.call(this, options);
@@ -45,6 +45,3 @@ ActionVersion.prototype.call = function (parser) {
formatter.addText(version);
parser.exit(0, formatter.formatHelp());
};
-
-
-
diff --git a/lib/action_container.js b/lib/action_container.js
index 043ead4..86aa017 100644
--- a/lib/action_container.js
+++ b/lib/action_container.js
@@ -7,10 +7,11 @@
'use strict';
var format = require('util').format;
-var _ = require('lodash');
// Constants
-var $$ = require('./const');
+var c = require('./const');
+
+var $$ = require('./utils');
//Actions
var ActionHelp = require('./action/help');
@@ -27,8 +28,6 @@ var ActionSubparsers = require('./action/subparsers');
// Errors
var argumentErrorHelper = require('./argument/error');
-
-
/**
* new ActionContainer(options)
*
@@ -110,7 +109,7 @@ ActionContainer.prototype.register = function (registryName, value, object) {
};
ActionContainer.prototype._registryGet = function (registryName, value, defaultValue) {
- if (3 > arguments.length) {
+ if (arguments.length < 3) {
defaultValue = null;
}
return this._registries[registryName][value] || defaultValue;
@@ -129,13 +128,15 @@ ActionContainer.prototype._registryGet = function (registryName, value, defaultV
ActionContainer.prototype.setDefaults = function (options) {
options = options || {};
for (var property in options) {
- this._defaults[property] = options[property];
+ if ($$.has(options, property)) {
+ this._defaults[property] = options[property];
+ }
}
// if these defaults match any existing arguments, replace the previous
// default on the object with the new one
this._actions.forEach(function (action) {
- if (action.dest in options) {
+ if ($$.has(options, action.dest)) {
action.defaultValue = options[action.dest];
}
});
@@ -148,10 +149,10 @@ ActionContainer.prototype.setDefaults = function (options) {
* Return action default value
**/
ActionContainer.prototype.getDefault = function (dest) {
- var result = (_.has(this._defaults, dest)) ? this._defaults[dest] : null;
+ var result = $$.has(this._defaults, dest) ? this._defaults[dest] : null;
this._actions.forEach(function (action) {
- if (action.dest === dest && _.has(action, 'defaultValue')) {
+ if (action.dest === dest && $$.has(action, 'defaultValue')) {
result = action.defaultValue;
}
});
@@ -164,21 +165,25 @@ ActionContainer.prototype.getDefault = function (dest) {
/**
* ActionContainer#addArgument(args, options) -> Object
- * - args (Array): array of argument keys
+ * - args (String|Array): argument key, or array of argument keys
* - options (Object): action objects see [[Action.new]]
*
* #### Examples
- * - addArgument([-f, --foo], {action:'store', defaultValue=1, ...})
- * - addArgument(['bar'], action: 'store', nargs:1, ...})
+ * - addArgument([ '-f', '--foo' ], { action: 'store', defaultValue: 1, ... })
+ * - addArgument([ 'bar' ], { action: 'store', nargs: 1, ... })
+ * - addArgument('--baz', { action: 'store', nargs: 1, ... })
**/
ActionContainer.prototype.addArgument = function (args, options) {
args = args;
options = options || {};
- if (!_.isArray(args)) {
- throw new TypeError('addArgument first argument should be an array');
+ if (typeof args === 'string') {
+ args = [ args ];
+ }
+ if (!Array.isArray(args)) {
+ throw new TypeError('addArgument first argument should be a string or an array');
}
- if (!_.isObject(options) || _.isArray(options)) {
+ if (typeof options !== 'object' || Array.isArray(options)) {
throw new TypeError('addArgument second argument should be a hash');
}
@@ -196,25 +201,25 @@ ActionContainer.prototype.addArgument = function (args, options) {
}
// if no default was supplied, use the parser-level default
- if (_.isUndefined(options.defaultValue)) {
+ if (typeof options.defaultValue === 'undefined') {
var dest = options.dest;
- if (_.has(this._defaults, dest)) {
+ if ($$.has(this._defaults, dest)) {
options.defaultValue = this._defaults[dest];
- } else if (!_.isUndefined(this.argumentDefault)) {
+ } else if (typeof this.argumentDefault !== 'undefined') {
options.defaultValue = this.argumentDefault;
}
}
// create the action object, and add it to the parser
var ActionClass = this._popActionClass(options);
- if (! _.isFunction(ActionClass)) {
+ if (typeof ActionClass !== 'function') {
throw new Error(format('Unknown action "%s".', ActionClass));
}
var action = new ActionClass(options);
// throw an error if the action type is not callable
var typeFunction = this._registryGet('type', action.type, action.type);
- if (!_.isFunction(typeFunction)) {
+ if (typeof typeFunction !== 'function') {
throw new Error(format('"%s" is not callable', typeFunction));
}
@@ -263,7 +268,7 @@ ActionContainer.prototype._addAction = function (action) {
// set the flag if any option strings look like negative numbers
action.optionStrings.forEach(function (optionString) {
if (optionString.match(self._regexpNegativeNumber)) {
- if (!_.any(self._hasNegativeNumberOptionals)) {
+ if (!self._hasNegativeNumberOptionals.some(Boolean)) {
self._hasNegativeNumberOptionals.push(true);
}
}
@@ -329,19 +334,17 @@ ActionContainer.prototype._addContainerActions = function (container) {
// add all actions to this container or their group
container._actions.forEach(function (action) {
var key = actionHash(action);
- if (!!groupMap[key]) {
+ if (groupMap[key]) {
groupMap[key]._addAction(action);
- }
- else
- {
+ } else {
this._addAction(action);
}
});
};
ActionContainer.prototype._getPositional = function (dest, options) {
- if (_.isArray(dest)) {
- dest = _.first(dest);
+ if (Array.isArray(dest)) {
+ dest = dest[0];
}
// make sure required is not specified
if (options.required) {
@@ -350,10 +353,10 @@ ActionContainer.prototype._getPositional = function (dest, options) {
// mark positional arguments as required if at least one is
// always required
- if (options.nargs !== $$.OPTIONAL && options.nargs !== $$.ZERO_OR_MORE) {
+ if (options.nargs !== c.OPTIONAL && options.nargs !== c.ZERO_OR_MORE) {
options.required = true;
}
- if (options.nargs === $$.ZERO_OR_MORE && options.defaultValue === undefined) {
+ if (options.nargs === c.ZERO_OR_MORE && typeof options.defaultValue === 'undefined') {
options.required = true;
}
@@ -390,8 +393,8 @@ ActionContainer.prototype._getOptional = function (args, options) {
delete options.dest;
if (!dest) {
- var optionStringDest = optionStringsLong.length ? optionStringsLong[0] :optionStrings[0];
- dest = _.trim(optionStringDest, this.prefixChars);
+ var optionStringDest = optionStringsLong.length ? optionStringsLong[0] : optionStrings[0];
+ dest = $$.trimChars(optionStringDest, this.prefixChars);
if (dest.length === 0) {
throw new Error(
@@ -420,10 +423,10 @@ ActionContainer.prototype._popActionClass = function (options, defaultValue) {
ActionContainer.prototype._getHandler = function () {
var handlerString = this.conflictHandler;
- var handlerFuncName = "_handleConflict" + _.capitalize(handlerString);
+ var handlerFuncName = '_handleConflict' + $$.capitalize(handlerString);
var func = this[handlerFuncName];
if (typeof func === 'undefined') {
- var msg = "invalid conflict resolution value: " + handlerString;
+ var msg = 'invalid conflict resolution value: ' + handlerString;
throw new Error(msg);
} else {
return func;
@@ -439,7 +442,7 @@ ActionContainer.prototype._checkConflict = function (action) {
action.optionStrings.forEach(function (optionString) {
var conflOptional = optionStringActions[optionString];
if (typeof conflOptional !== 'undefined') {
- conflictOptionals.push([optionString, conflOptional]);
+ conflictOptionals.push([ optionString, conflOptional ]);
}
});
@@ -450,7 +453,7 @@ ActionContainer.prototype._checkConflict = function (action) {
};
ActionContainer.prototype._handleConflictError = function (action, conflOptionals) {
- var conflicts = _.map(conflOptionals, function (pair) {return pair[0]; });
+ var conflicts = conflOptionals.map(function (pair) { return pair[0]; });
conflicts = conflicts.join(', ');
throw argumentErrorHelper(
action,
diff --git a/lib/argument_parser.js b/lib/argument_parser.js
index c429ca9..eca1ad6 100644
--- a/lib/argument_parser.js
+++ b/lib/argument_parser.js
@@ -10,12 +10,12 @@
var util = require('util');
var format = require('util').format;
var Path = require('path');
-
-var _ = require('lodash');
var sprintf = require('sprintf-js').sprintf;
// Constants
-var $$ = require('./const');
+var c = require('./const');
+
+var $$ = require('./utils');
var ActionContainer = require('./action_container');
@@ -52,7 +52,7 @@ var Namespace = require('./namespace');
*
* [1]:http://docs.python.org/dev/library/argparse.html#argumentparser-objects
**/
-var ArgumentParser = module.exports = function ArgumentParser(options) {
+function ArgumentParser(options) {
if (!(this instanceof ArgumentParser)) {
return new ArgumentParser(options);
}
@@ -65,8 +65,8 @@ var ArgumentParser = module.exports = function ArgumentParser(options) {
options.conflictHandler = (options.conflictHandler || 'error');
ActionContainer.call(this, options);
- options.addHelp = (options.addHelp === undefined || !!options.addHelp);
- options.parents = (options.parents || []);
+ options.addHelp = typeof options.addHelp === 'undefined' || !!options.addHelp;
+ options.parents = options.parents || [];
// default program name
options.prog = (options.prog || Path.basename(process.argv[1]));
this.prog = options.prog;
@@ -78,14 +78,14 @@ var ArgumentParser = module.exports = function ArgumentParser(options) {
this.formatterClass = (options.formatterClass || HelpFormatter);
this.fromfilePrefixChars = options.fromfilePrefixChars || null;
- this._positionals = this.addArgumentGroup({title: 'Positional arguments'});
- this._optionals = this.addArgumentGroup({title: 'Optional arguments'});
+ this._positionals = this.addArgumentGroup({ title: 'Positional arguments' });
+ this._optionals = this.addArgumentGroup({ title: 'Optional arguments' });
this._subparsers = null;
// register types
- var FUNCTION_IDENTITY = function (o) {
+ function FUNCTION_IDENTITY(o) {
return o;
- };
+ }
this.register('type', 'auto', FUNCTION_IDENTITY);
this.register('type', null, FUNCTION_IDENTITY);
this.register('type', 'int', function (x) {
@@ -110,21 +110,21 @@ var ArgumentParser = module.exports = function ArgumentParser(options) {
var defaultPrefix = (this.prefixChars.indexOf('-') > -1) ? '-' : this.prefixChars[0];
if (options.addHelp) {
this.addArgument(
- [defaultPrefix + 'h', defaultPrefix + defaultPrefix + 'help'],
+ [ defaultPrefix + 'h', defaultPrefix + defaultPrefix + 'help' ],
{
action: 'help',
- defaultValue: $$.SUPPRESS,
+ defaultValue: c.SUPPRESS,
help: 'Show this help message and exit.'
}
);
}
- if (this.version !== undefined) {
+ if (typeof this.version !== 'undefined') {
this.addArgument(
- [defaultPrefix + 'v', defaultPrefix + defaultPrefix + 'version'],
+ [ defaultPrefix + 'v', defaultPrefix + defaultPrefix + 'version' ],
{
action: 'version',
version: this.version,
- defaultValue: $$.SUPPRESS,
+ defaultValue: c.SUPPRESS,
help: "Show program's version number and exit."
}
);
@@ -133,7 +133,7 @@ var ArgumentParser = module.exports = function ArgumentParser(options) {
// add parent arguments and defaults
options.parents.forEach(function (parent) {
self._addContainerActions(parent);
- if (parent._defaults !== undefined) {
+ if (typeof parent._defaults !== 'undefined') {
for (var defaultKey in parent._defaults) {
if (parent._defaults.hasOwnProperty(defaultKey)) {
self._defaults[defaultKey] = parent._defaults[defaultKey];
@@ -141,8 +141,8 @@ var ArgumentParser = module.exports = function ArgumentParser(options) {
}
}
});
+}
-};
util.inherits(ArgumentParser, ActionContainer);
/**
@@ -154,7 +154,7 @@ util.inherits(ArgumentParser, ActionContainer);
* [1]:http://docs.python.org/dev/library/argparse.html#sub-commands
**/
ArgumentParser.prototype.addSubparsers = function (options) {
- if (!!this._subparsers) {
+ if (this._subparsers) {
this.error('Cannot have multiple subparser arguments.');
}
@@ -184,7 +184,7 @@ ArgumentParser.prototype.addSubparsers = function (options) {
var positionals = this._getPositionalActions();
var groups = this._mutuallyExclusiveGroups;
formatter.addUsage(this.usage, positionals, groups, '');
- options.prog = _.trim(formatter.formatHelp());
+ options.prog = formatter.formatHelp().trim();
}
// create the parsers action and add it to the positionals list
@@ -265,11 +265,11 @@ ArgumentParser.prototype.parseKnownArgs = function (args, namespace) {
namespace = namespace || new Namespace();
self._actions.forEach(function (action) {
- if (action.dest !== $$.SUPPRESS) {
- if (!_.has(namespace, action.dest)) {
- if (action.defaultValue !== $$.SUPPRESS) {
+ if (action.dest !== c.SUPPRESS) {
+ if (!$$.has(namespace, action.dest)) {
+ if (action.defaultValue !== c.SUPPRESS) {
var defaultValue = action.defaultValue;
- if (_.isString(action.defaultValue)) {
+ if (typeof action.defaultValue === 'string') {
defaultValue = self._getValue(action, defaultValue);
}
namespace[action.dest] = defaultValue;
@@ -278,7 +278,7 @@ ArgumentParser.prototype.parseKnownArgs = function (args, namespace) {
}
});
- _.keys(self._defaults).forEach(function (dest) {
+ Object.keys(self._defaults).forEach(function (dest) {
namespace[dest] = self._defaults[dest];
});
@@ -288,11 +288,11 @@ ArgumentParser.prototype.parseKnownArgs = function (args, namespace) {
namespace = res[0];
args = res[1];
- if (_.has(namespace, $$._UNRECOGNIZED_ARGS_ATTR)) {
- args = _.union(args, namespace[$$._UNRECOGNIZED_ARGS_ATTR]);
- delete namespace[$$._UNRECOGNIZED_ARGS_ATTR];
+ if ($$.has(namespace, c._UNRECOGNIZED_ARGS_ATTR)) {
+ args = $$.arrayUnion(args, namespace[c._UNRECOGNIZED_ARGS_ATTR]);
+ delete namespace[c._UNRECOGNIZED_ARGS_ATTR];
}
- return [namespace, args];
+ return [ namespace, args ];
} catch (e) {
this.error(e);
}
@@ -326,7 +326,7 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
this._mutuallyExclusiveGroups.forEach(function (mutexGroup) {
mutexGroup._groupActions.forEach(function (mutexAction, i, groupActions) {
key = actionHash(mutexAction);
- if (!_.has(actionConflicts, key)) {
+ if (!$$.has(actionConflicts, key)) {
actionConflicts[key] = [];
}
conflicts = actionConflicts[key];
@@ -349,16 +349,14 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
argStringPatternParts.push('A');
argStringIndex++;
}
- }
- // otherwise, add the arg to the arg strings
- // and note the index if it was an option
- else {
+ } else {
+ // otherwise, add the arg to the arg strings
+ // and note the index if it was an option
var pattern;
var optionTuple = self._parseOptional(argString);
if (!optionTuple) {
pattern = 'A';
- }
- else {
+ } else {
optionStringIndices[argStringIndex] = optionTuple;
pattern = 'O';
}
@@ -380,7 +378,7 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
// value don't really count as "present"
if (argumentValues !== action.defaultValue) {
seenNonDefaultActions.push(action);
- if (!!actionConflicts[actionHash(action)]) {
+ if (actionConflicts[actionHash(action)]) {
actionConflicts[actionHash(action)].forEach(function (actionConflict) {
if (seenNonDefaultActions.indexOf(actionConflict) >= 0) {
throw argumentErrorHelper(
@@ -392,7 +390,7 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
}
}
- if (argumentValues !== $$.SUPPRESS) {
+ if (argumentValues !== c.SUPPRESS) {
action.call(self, namespace, argumentValues, optionString);
}
}
@@ -410,12 +408,12 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
var args, argCount, start, stop;
- while (true) {
+ for (;;) {
if (!action) {
extras.push(argStrings[startIndex]);
return startIndex + 1;
}
- if (!!explicitArg) {
+ if (explicitArg) {
argCount = self._matchArgument(action, 'A');
// if the action is a single-dash option and takes no
@@ -423,39 +421,33 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
// of the tail of the option string
var chars = self.prefixChars;
if (argCount === 0 && chars.indexOf(optionString[1]) < 0) {
- actionTuples.push([action, [], optionString]);
+ actionTuples.push([ action, [], optionString ]);
optionString = optionString[0] + explicitArg[0];
var newExplicitArg = explicitArg.slice(1) || null;
var optionalsMap = self._optionStringActions;
- if (_.keys(optionalsMap).indexOf(optionString) >= 0) {
+ if (Object.keys(optionalsMap).indexOf(optionString) >= 0) {
action = optionalsMap[optionString];
explicitArg = newExplicitArg;
+ } else {
+ throw argumentErrorHelper(action, sprintf('ignored explicit argument %r', explicitArg));
}
- else {
- var msg = 'ignored explicit argument %r';
- throw argumentErrorHelper(action, msg);
- }
- }
- // if the action expect exactly one argument, we've
- // successfully matched the option; exit the loop
- else if (argCount === 1) {
+ } else if (argCount === 1) {
+ // if the action expect exactly one argument, we've
+ // successfully matched the option; exit the loop
stop = startIndex + 1;
- args = [explicitArg];
- actionTuples.push([action, args, optionString]);
+ args = [ explicitArg ];
+ actionTuples.push([ action, args, optionString ]);
break;
+ } else {
+ // error if a double-dash option did not use the
+ // explicit argument
+ throw argumentErrorHelper(action, sprintf('ignored explicit argument %r', explicitArg));
}
- // error if a double-dash option did not use the
- // explicit argument
- else {
- var message = 'ignored explicit argument %r';
- throw argumentErrorHelper(action, sprintf(message, explicitArg));
- }
- }
- // if there is no explicit argument, try to match the
- // optional's string arguments with the following strings
- // if successful, exit the loop
- else {
+ } else {
+ // if there is no explicit argument, try to match the
+ // optional's string arguments with the following strings
+ // if successful, exit the loop
start = startIndex + 1;
var selectedPatterns = argStringsPattern.substr(start);
@@ -466,7 +458,7 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
args = argStrings.slice(start, stop);
- actionTuples.push([action, args, optionString]);
+ actionTuples.push([ action, args, optionString ]);
break;
}
@@ -494,17 +486,17 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
// slice off the appropriate arg strings for each Positional
// and add the Positional and its args to the list
- _.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);
+ for (var i = 0; i < positionals.length; i++) {
+ var action = positionals[i];
+ var argCount = argCounts[i];
+ if (typeof argCount === 'undefined') {
+ continue;
+ }
+ var args = argStrings.slice(startIndex, startIndex + argCount);
- startIndex += argCount;
- takeAction(action, args);
- });
+ startIndex += argCount;
+ takeAction(action, args);
+ }
// slice off the Positionals that we just parsed and return the
// index at which the Positionals' string args stopped
@@ -535,8 +527,7 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
if (position >= startIndex) {
if (nextOptionStringIndex !== null) {
nextOptionStringIndex = Math.min(nextOptionStringIndex, position);
- }
- else {
+ } else {
nextOptionStringIndex = position;
}
}
@@ -549,8 +540,7 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
if (positionalsEndIndex > startIndex) {
startIndex = positionalsEndIndex;
continue;
- }
- else {
+ } else {
startIndex = positionalsEndIndex;
}
}
@@ -581,7 +571,7 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
// make sure all required actions were present
self._actions.forEach(function (action) {
if (action.required) {
- if (_.indexOf(seenActions, action) < 0) {
+ if (seenActions.indexOf(action) < 0) {
self.error(format('Argument "%s" is required', action.getName()));
}
}
@@ -591,15 +581,15 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
var actionUsed = false;
self._mutuallyExclusiveGroups.forEach(function (group) {
if (group.required) {
- actionUsed = _.any(group._groupActions, function (action) {
- return _.contains(seenNonDefaultActions, action);
+ actionUsed = group._groupActions.some(function (action) {
+ return seenNonDefaultActions.indexOf(action) !== -1;
});
// if no actions were used, report the error
if (!actionUsed) {
var names = [];
group._groupActions.forEach(function (action) {
- if (action.help !== $$.SUPPRESS) {
+ if (action.help !== c.SUPPRESS) {
names.push(action.getName());
}
});
@@ -611,16 +601,16 @@ ArgumentParser.prototype._parseKnownArgs = function (argStrings, namespace) {
});
// return the updated namespace and the extra arguments
- return [namespace, extras];
+ return [ namespace, extras ];
};
ArgumentParser.prototype._readArgsFromFiles = function (argStrings) {
// expand arguments referencing files
- var _this = this;
+ var self = this;
var fs = require('fs');
var newArgStrings = [];
argStrings.forEach(function (argString) {
- if (_this.fromfilePrefixChars.indexOf(argString[0]) < 0) {
+ if (self.fromfilePrefixChars.indexOf(argString[0]) < 0) {
// for regular arguments, just add them back into the list
newArgStrings.push(argString);
} else {
@@ -631,14 +621,14 @@ ArgumentParser.prototype._readArgsFromFiles = function (argStrings) {
var content = fs.readFileSync(filename, 'utf8');
content = content.trim().split('\n');
content.forEach(function (argLine) {
- _this.convertArgLineToArgs(argLine).forEach(function (arg) {
+ self.convertArgLineToArgs(argLine).forEach(function (arg) {
argstrs.push(arg);
});
- argstrs = _this._readArgsFromFiles(argstrs);
+ argstrs = self._readArgsFromFiles(argstrs);
});
newArgStrings.push.apply(newArgStrings, argstrs);
} catch (error) {
- return _this.error(error.message);
+ return self.error(error.message);
}
}
});
@@ -646,7 +636,7 @@ ArgumentParser.prototype._readArgsFromFiles = function (argStrings) {
};
ArgumentParser.prototype.convertArgLineToArgs = function (argLine) {
- return [argLine];
+ return [ argLine ];
};
ArgumentParser.prototype._matchArgument = function (action, regexpArgStrings) {
@@ -659,14 +649,15 @@ ArgumentParser.prototype._matchArgument = function (action, regexpArgStrings) {
// throw an exception if we weren't able to find a match
if (!matches) {
switch (action.nargs) {
+ /*eslint-disable no-undefined*/
case undefined:
case null:
message = 'Expected one argument.';
break;
- case $$.OPTIONAL:
+ case c.OPTIONAL:
message = 'Expected at most one argument.';
break;
- case $$.ONE_OR_MORE:
+ case c.ONE_OR_MORE:
message = 'Expected at least one argument.';
break;
default:
@@ -690,9 +681,9 @@ ArgumentParser.prototype._matchArgumentsPartial = function (actions, regexpArgSt
var actionSlice, pattern, matches;
var i, j;
- var getLength = function (string) {
+ function getLength(string) {
return string.length;
- };
+ }
for (i = actions.length; i > 0; i--) {
pattern = '';
@@ -730,8 +721,8 @@ ArgumentParser.prototype._parseOptional = function (argString) {
}
// if the option string is present in the parser, return the action
- if (!!this._optionStringActions[argString]) {
- return [this._optionStringActions[argString], argString, null];
+ if (this._optionStringActions[argString]) {
+ return [ this._optionStringActions[argString], argString, null ];
}
// if it's just a single character, it was meant to be positional
@@ -744,9 +735,9 @@ ArgumentParser.prototype._parseOptional = function (argString) {
optionString = argString.split('=', 1)[0];
argExplicit = argString.slice(optionString.length + 1);
- if (!!this._optionStringActions[optionString]) {
+ if (this._optionStringActions[optionString]) {
action = this._optionStringActions[optionString];
- return [action, optionString, argExplicit];
+ return [ action, optionString, argExplicit ];
}
}
@@ -773,7 +764,7 @@ ArgumentParser.prototype._parseOptional = function (argString) {
// number, it was meant to be positional
// unless there are negative-number-like options
if (argString.match(this._regexpNegativeNumber)) {
- if (!_.any(this._hasNegativeNumberOptionals)) {
+ if (!this._hasNegativeNumberOptionals.some(Boolean)) {
return null;
}
}
@@ -784,7 +775,7 @@ ArgumentParser.prototype._parseOptional = function (argString) {
// it was meant to be an optional but there is no such option
// in this parser (though it might be a valid option in a subparser)
- return [null, argString, null];
+ return [ null, argString, null ];
};
ArgumentParser.prototype._getOptionTuples = function (optionString) {
@@ -811,7 +802,7 @@ ArgumentParser.prototype._getOptionTuples = function (optionString) {
for (actionOptionString in this._optionStringActions) {
if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) {
action = this._optionStringActions[actionOptionString];
- result.push([action, actionOptionString, argExplicit]);
+ result.push([ action, actionOptionString, argExplicit ]);
}
}
@@ -825,11 +816,13 @@ ArgumentParser.prototype._getOptionTuples = function (optionString) {
var argExplicitShort = optionString.substr(2);
for (actionOptionString in this._optionStringActions) {
+ if (!$$.has(this._optionStringActions, actionOptionString)) continue;
+
action = this._optionStringActions[actionOptionString];
if (actionOptionString === optionPrefixShort) {
- result.push([action, actionOptionString, argExplicitShort]);
+ result.push([ action, actionOptionString, argExplicitShort ]);
} else if (actionOptionString.substr(0, optionPrefix.length) === optionPrefix) {
- result.push([action, actionOptionString, argExplicit]);
+ result.push([ action, actionOptionString, argExplicit ]);
}
}
@@ -853,28 +846,28 @@ ArgumentParser.prototype._getNargsPattern = function (action) {
regexpNargs = '(-*A-*)';
break;
// allow zero or more arguments
- case $$.OPTIONAL:
+ case c.OPTIONAL:
regexpNargs = '(-*A?-*)';
break;
// allow zero or more arguments
- case $$.ZERO_OR_MORE:
+ case c.ZERO_OR_MORE:
regexpNargs = '(-*[A-]*)';
break;
// allow one or more arguments
- case $$.ONE_OR_MORE:
+ case c.ONE_OR_MORE:
regexpNargs = '(-*A[A-]*)';
break;
// allow any number of options or arguments
- case $$.REMAINDER:
+ case c.REMAINDER:
regexpNargs = '([-AO]*)';
break;
// allow one argument followed by any number of options or arguments
- case $$.PARSER:
+ case c.PARSER:
regexpNargs = '(-*A[-AO]*)';
break;
// all others should be integers
default:
- regexpNargs = '(-*' + _.repeat('-*A', action.nargs) + '-*)';
+ regexpNargs = '(-*' + $$.repeat('-*A', action.nargs) + '-*)';
}
// if this is an optional action, -- is not allowed
@@ -895,7 +888,7 @@ ArgumentParser.prototype._getValues = function (action, argStrings) {
var self = this;
// for everything but PARSER args, strip out '--'
- if (action.nargs !== $$.PARSER && action.nargs !== $$.REMAINDER) {
+ if (action.nargs !== c.PARSER && action.nargs !== c.REMAINDER) {
argStrings = argStrings.filter(function (arrayElement) {
return arrayElement !== '--';
});
@@ -904,18 +897,18 @@ ArgumentParser.prototype._getValues = function (action, argStrings) {
var value, argString;
// optional argument produces a default when not present
- if (argStrings.length === 0 && action.nargs === $$.OPTIONAL) {
+ if (argStrings.length === 0 && action.nargs === c.OPTIONAL) {
- value = (action.isOptional()) ? action.constant: action.defaultValue;
+ value = (action.isOptional()) ? action.constant : action.defaultValue;
- if (typeof(value) === 'string') {
+ if (typeof (value) === 'string') {
value = this._getValue(action, value);
this._checkValue(action, value);
}
// when nargs='*' on a positional, if there were no command-line
// 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 === c.ZERO_OR_MORE &&
action.optionStrings.length === 0) {
value = (action.defaultValue || argStrings);
@@ -923,20 +916,20 @@ ArgumentParser.prototype._getValues = function (action, argStrings) {
// single argument or optional argument produces a single value
} else if (argStrings.length === 1 &&
- (!action.nargs || action.nargs === $$.OPTIONAL)) {
+ (!action.nargs || action.nargs === c.OPTIONAL)) {
argString = argStrings[0];
value = this._getValue(action, argString);
this._checkValue(action, value);
// REMAINDER arguments convert all values, checking none
- } else if (action.nargs === $$.REMAINDER) {
+ } else if (action.nargs === c.REMAINDER) {
value = argStrings.map(function (v) {
return self._getValue(action, v);
});
// PARSER arguments convert all values, but check only the first
- } else if (action.nargs === $$.PARSER) {
+ } else if (action.nargs === c.PARSER) {
value = argStrings.map(function (v) {
return self._getValue(action, v);
});
@@ -960,7 +953,7 @@ ArgumentParser.prototype._getValue = function (action, argString) {
var result;
var typeFunction = this._registryGet('type', action.type, action.type);
- if (!_.isFunction(typeFunction)) {
+ if (typeof typeFunction !== 'function') {
var message = format('%s is not callable', typeFunction);
throw argumentErrorHelper(action, message);
}
@@ -975,13 +968,13 @@ ArgumentParser.prototype._getValue = function (action, argString) {
// Failing that, include the error message it raised.
} catch (e) {
var name = null;
- if (_.isString(action.type)) {
+ if (typeof action.type === 'string') {
name = action.type;
} else {
name = action.type.name || action.type.displayName || '<function>';
}
var msg = format('Invalid %s value: %s', name, argString);
- if (name === '<function>') {msg += '\n' + e.message; }
+ if (name === '<function>') { msg += '\n' + e.message; }
throw argumentErrorHelper(action, msg);
}
// return the converted value
@@ -991,25 +984,23 @@ ArgumentParser.prototype._getValue = function (action, argString) {
ArgumentParser.prototype._checkValue = function (action, value) {
// converted value must be one of the choices (if specified)
var choices = action.choices;
- if (!!choices) {
+ if (choices) {
// choise for argument can by array or string
- if ((_.isString(choices) || _.isArray(choices)) &&
+ if ((typeof choices === 'string' || Array.isArray(choices)) &&
choices.indexOf(value) !== -1) {
return;
}
// choise for subparsers can by only hash
- if (_.isObject(choices) && !_.isArray(choices) && choices[value]) {
+ if (typeof choices === 'object' && !Array.isArray(choices) && choices[value]) {
return;
}
- if (_.isString(choices)) {
+ if (typeof choices === 'string') {
choices = choices.split('').join(', ');
- }
- else if (_.isArray(choices)) {
+ } else if (Array.isArray(choices)) {
choices = choices.join(', ');
- }
- else {
- choices = _.keys(choices).join(', ');
+ } else {
+ choices = Object.keys(choices).join(', ');
}
var message = format('Invalid choice: %s (choose from [%s])', value, choices);
throw argumentErrorHelper(action, message);
@@ -1070,7 +1061,7 @@ ArgumentParser.prototype.formatHelp = function () {
ArgumentParser.prototype._getFormatter = function () {
var FormatterClass = this.formatterClass;
- var formatter = new FormatterClass({prog: this.prog});
+ var formatter = new FormatterClass({ prog: this.prog });
return formatter;
};
@@ -1125,11 +1116,10 @@ ArgumentParser.prototype._printMessage = function (message, stream) {
* Print message in stderr/stdout and exit program
**/
ArgumentParser.prototype.exit = function (status, message) {
- if (!!message) {
+ if (message) {
if (status === 0) {
this._printMessage(message);
- }
- else {
+ } else {
this._printMessage(message, process.stderr);
}
}
@@ -1154,11 +1144,10 @@ ArgumentParser.prototype.error = function (err) {
throw err;
}
message = err.message;
- }
- else {
+ } else {
message = err;
}
- var msg = format('%s: error: %s', this.prog, message) + $$.EOL;
+ var msg = format('%s: error: %s', this.prog, message) + c.EOL;
if (this.debug === true) {
throw new Error(msg);
@@ -1168,3 +1157,5 @@ ArgumentParser.prototype.error = function (err) {
return this.exit(2, msg);
};
+
+module.exports = ArgumentParser;
diff --git a/lib/const.js b/lib/const.js
index de831ba..b1fd4ce 100644
--- a/lib/const.js
+++ b/lib/const.js
@@ -1,6 +1,9 @@
//
// Constants
//
+
+'use strict';
+
module.exports.EOL = '\n';
module.exports.SUPPRESS = '==SUPPRESS==';
diff --git a/lib/help/added_formatters.js b/lib/help/added_formatters.js
index 3c99c4a..f0fbe5d 100644
--- a/lib/help/added_formatters.js
+++ b/lib/help/added_formatters.js
@@ -1,12 +1,11 @@
'use strict';
var util = require('util');
-var _ = require('lodash');
-
// Constants
-var $$ = require('../const');
+var c = require('../const');
+var $$ = require('../utils');
var HelpFormatter = require('./formatter.js');
/**
@@ -19,17 +18,17 @@ var HelpFormatter = require('./formatter.js');
* provided by the class are considered an implementation detail.
**/
-var ArgumentDefaultsHelpFormatter = function ArgumentDefaultsHelpFormatter(options) {
+function ArgumentDefaultsHelpFormatter(options) {
HelpFormatter.call(this, options);
-};
+}
util.inherits(ArgumentDefaultsHelpFormatter, HelpFormatter);
ArgumentDefaultsHelpFormatter.prototype._getHelpString = function (action) {
var help = action.help;
if (action.help.indexOf('%(defaultValue)s') === -1) {
- if (action.defaultValue !== $$.SUPPRESS) {
- var defaulting_nargs = [$$.OPTIONAL, $$.ZERO_OR_MORE];
+ if (action.defaultValue !== c.SUPPRESS) {
+ var defaulting_nargs = [ c.OPTIONAL, c.ZERO_OR_MORE ];
if (action.isOptional() || (defaulting_nargs.indexOf(action.nargs) >= 0)) {
help += ' (default: %(defaultValue)s)';
}
@@ -50,16 +49,16 @@ module.exports.ArgumentDefaultsHelpFormatter = ArgumentDefaultsHelpFormatter;
* provided by the class are considered an implementation detail.
**/
-var RawDescriptionHelpFormatter = function RawDescriptionHelpFormatter(options) {
+function RawDescriptionHelpFormatter(options) {
HelpFormatter.call(this, options);
-};
+}
util.inherits(RawDescriptionHelpFormatter, HelpFormatter);
RawDescriptionHelpFormatter.prototype._fillText = function (text, width, indent) {
var lines = text.split('\n');
lines = lines.map(function (line) {
- return _.trimRight(indent + line);
+ return $$.trimEnd(indent + line);
});
return lines.join('\n');
};
@@ -75,9 +74,9 @@ module.exports.RawDescriptionHelpFormatter = RawDescriptionHelpFormatter;
* provided by the class are considered an implementation detail.
**/
-var RawTextHelpFormatter = function RawTextHelpFormatter(options) {
+function RawTextHelpFormatter(options) {
RawDescriptionHelpFormatter.call(this, options);
-};
+}
util.inherits(RawTextHelpFormatter, RawDescriptionHelpFormatter);
diff --git a/lib/help/formatter.js b/lib/help/formatter.js
index e050728..61c4f41 100644
--- a/lib/help/formatter.js
+++ b/lib/help/formatter.js
@@ -13,11 +13,12 @@
**/
'use strict';
-var _ = require('lodash');
var sprintf = require('sprintf-js').sprintf;
// Constants
-var $$ = require('../const');
+var c = require('../const');
+
+var $$ = require('../utils');
/*:nodoc:* internal
@@ -53,7 +54,7 @@ Section.prototype.formatHelp = function (formatter) {
var itemHelp, heading;
// format the indented section
- if (!!this._parent) {
+ if (this._parent) {
formatter._indent();
}
@@ -67,7 +68,7 @@ Section.prototype.formatHelp = function (formatter) {
});
itemHelp = formatter._joinParts(itemHelp);
- if (!!this._parent) {
+ if (this._parent) {
formatter._dedent();
}
@@ -78,13 +79,13 @@ Section.prototype.formatHelp = function (formatter) {
// add the heading if the section was non-empty
heading = '';
- if (!!this._heading && this._heading !== $$.SUPPRESS) {
+ if (this._heading && this._heading !== c.SUPPRESS) {
var currentIndent = formatter.currentIndent;
- heading = _.repeat(' ', currentIndent) + this._heading + ':' + $$.EOL;
+ heading = $$.repeat(' ', currentIndent) + this._heading + ':' + c.EOL;
}
// join the section-initialize newline, the heading and the help
- return formatter._joinParts([$$.EOL, heading, itemHelp, $$.EOL]);
+ return formatter._joinParts([ c.EOL, heading, itemHelp, c.EOL ]);
};
/**
@@ -114,7 +115,7 @@ var HelpFormatter = module.exports = function HelpFormatter(options) {
this._currentSection = this._rootSection;
this._whitespaceMatcher = new RegExp('\\s+', 'g');
- this._longBreakMatcher = new RegExp($$.EOL + $$.EOL + $$.EOL + '+', 'g');
+ this._longBreakMatcher = new RegExp(c.EOL + c.EOL + c.EOL + '+', 'g');
};
HelpFormatter.prototype._indent = function () {
@@ -131,7 +132,7 @@ HelpFormatter.prototype._dedent = function () {
};
HelpFormatter.prototype._addItem = function (func, args) {
- this._currentSection.addItem([func, args]);
+ this._currentSection.addItem([ func, args ]);
};
//
@@ -158,7 +159,7 @@ HelpFormatter.prototype.startSection = function (heading) {
this._indent();
var section = new Section(this._currentSection, heading);
var func = section.formatHelp.bind(section);
- this._addItem(func, [this]);
+ this._addItem(func, [ this ]);
this._currentSection = section;
};
@@ -194,8 +195,8 @@ HelpFormatter.prototype.endSection = function () {
*
**/
HelpFormatter.prototype.addText = function (text) {
- if (!!text && text !== $$.SUPPRESS) {
- this._addItem(this._formatText, [text]);
+ if (text && text !== c.SUPPRESS) {
+ this._addItem(this._formatText, [ text ]);
}
};
@@ -215,8 +216,8 @@ HelpFormatter.prototype.addText = function (text) {
*
**/
HelpFormatter.prototype.addUsage = function (usage, actions, groups, prefix) {
- if (usage !== $$.SUPPRESS) {
- this._addItem(this._formatUsage, [usage, actions, groups, prefix]);
+ if (usage !== c.SUPPRESS) {
+ this._addItem(this._formatUsage, [ usage, actions, groups, prefix ]);
}
};
@@ -229,16 +230,16 @@ HelpFormatter.prototype.addUsage = function (usage, actions, groups, prefix) {
* Single variant of [[HelpFormatter#addArguments]]
**/
HelpFormatter.prototype.addArgument = function (action) {
- if (action.help !== $$.SUPPRESS) {
+ if (action.help !== c.SUPPRESS) {
var self = this;
// find all invocations
- var invocations = [this._formatActionInvocation(action)];
+ var invocations = [ this._formatActionInvocation(action) ];
var invocationLength = invocations[0].length;
var actionLength;
- if (!!action._getSubactions) {
+ if (action._getSubactions) {
this._indent();
action._getSubactions().forEach(function (subaction) {
@@ -255,7 +256,7 @@ HelpFormatter.prototype.addArgument = function (action) {
this._actionMaxLength = Math.max(this._actionMaxLength, actionLength);
// add the item to the list
- this._addItem(this._formatAction, [action]);
+ this._addItem(this._formatAction, [ action ]);
}
};
@@ -298,20 +299,20 @@ HelpFormatter.prototype.addArguments = function (actions) {
HelpFormatter.prototype.formatHelp = function () {
var help = this._rootSection.formatHelp(this);
if (help) {
- help = help.replace(this._longBreakMatcher, $$.EOL + $$.EOL);
- help = _.trim(help, $$.EOL) + $$.EOL;
+ help = help.replace(this._longBreakMatcher, c.EOL + c.EOL);
+ help = $$.trimChars(help, c.EOL) + c.EOL;
}
return help;
};
HelpFormatter.prototype._joinParts = function (partStrings) {
return partStrings.filter(function (part) {
- return (!!part && part !== $$.SUPPRESS);
+ return (part && part !== c.SUPPRESS);
}).join('');
};
HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix) {
- if (!prefix && !_.isString(prefix)) {
+ if (!prefix && typeof prefix !== 'string') {
prefix = 'usage: ';
}
@@ -321,7 +322,7 @@ HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix)
// if usage is specified, use that
if (usage) {
- usage = sprintf(usage, {prog: this._prog});
+ usage = sprintf(usage, { prog: this._prog });
// if no optionals or positionals are available, usage is just prog
} else if (!usage && actions.length === 0) {
@@ -346,7 +347,7 @@ HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix)
// build full usage string
actionUsage = this._formatActionsUsage([].concat(optionals, positionals), groups);
- usage = [prog, actionUsage].join(' ');
+ usage = [ prog, actionUsage ].join(' ');
// wrap the usage parts if it's too long
textWidth = this._width - this._currentIndent;
@@ -369,11 +370,12 @@ HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix)
}
// helper for wrapping lines
+ /*eslint-disable func-style*/ // node 0.10 compat
var _getLines = function (parts, indent, prefix) {
var lines = [];
var line = [];
- var lineLength = !!prefix ? prefix.length - 1: indent.length - 1;
+ var lineLength = prefix ? prefix.length - 1 : indent.length - 1;
parts.forEach(function (part) {
if (lineLength + 1 + part.length > textWidth) {
@@ -397,21 +399,21 @@ HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix)
var lines, indent, parts;
// if prog is short, follow it with optionals or positionals
if (prefix.length + prog.length <= 0.75 * textWidth) {
- indent = _.repeat(' ', (prefix.length + prog.length + 1));
+ indent = $$.repeat(' ', (prefix.length + prog.length + 1));
if (optionalParts) {
lines = [].concat(
- _getLines([prog].concat(optionalParts), indent, prefix),
+ _getLines([ prog ].concat(optionalParts), indent, prefix),
_getLines(positionalParts, indent)
);
} else if (positionalParts) {
- lines = _getLines([prog].concat(positionalParts), indent, prefix);
+ lines = _getLines([ prog ].concat(positionalParts), indent, prefix);
} else {
- lines = [prog];
+ lines = [ prog ];
}
// if prog is long, put it on its own line
} else {
- indent = _.repeat(' ', prefix.length);
+ indent = $$.repeat(' ', prefix.length);
parts = optionalParts + positionalParts;
lines = _getLines(parts, indent);
if (lines.length > 1) {
@@ -420,15 +422,15 @@ HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix)
_getLines(positionalParts, indent)
);
}
- lines = [prog] + lines;
+ lines = [ prog ] + lines;
}
// join lines into usage
- usage = lines.join($$.EOL);
+ usage = lines.join(c.EOL);
}
}
// prefix with 'usage:'
- return prefix + usage + $$.EOL + $$.EOL;
+ return prefix + usage + c.EOL + c.EOL;
};
HelpFormatter.prototype._formatActionsUsage = function (actions, groups) {
@@ -446,24 +448,22 @@ HelpFormatter.prototype._formatActionsUsage = function (actions, groups) {
end = start + group._groupActions.length;
//if (actions.slice(start, end) === group._groupActions) {
- if (_.isEqual(actions.slice(start, end), group._groupActions)) {
+ if ($$.arrayEqual(actions.slice(start, end), group._groupActions)) {
group._groupActions.forEach(function (action) {
groupActions.push(action);
});
if (!group.required) {
- if (!!inserts[start]) {
+ if (inserts[start]) {
inserts[start] += ' [';
- }
- else {
+ } else {
inserts[start] = '[';
}
inserts[end] = ']';
} else {
- if (!!inserts[start]) {
+ if (inserts[start]) {
inserts[start] += ' (';
- }
- else {
+ } else {
inserts[start] = '(';
}
inserts[end] = ')';
@@ -486,7 +486,7 @@ HelpFormatter.prototype._formatActionsUsage = function (actions, groups) {
// suppressed arguments are marked with None
// remove | separators for suppressed arguments
- if (action.help === $$.SUPPRESS) {
+ if (action.help === c.SUPPRESS) {
parts.push(null);
if (inserts[actionIndex] === '|') {
inserts.splice(actionIndex, actionIndex);
@@ -549,17 +549,17 @@ HelpFormatter.prototype._formatActionsUsage = function (actions, groups) {
text = text.replace(/\( *\)/g, '');
text = text.replace(/\(([^|]*)\)/g, '$1'); // remove () from single action groups
- text = _.trim(text);
+ text = text.trim();
// return the text
return text;
};
HelpFormatter.prototype._formatText = function (text) {
- text = sprintf(text, {prog: this._prog});
+ text = sprintf(text, { prog: this._prog });
var textWidth = this._width - this._currentIndent;
- var indentIncriment = _.repeat(' ', this._currentIndent);
- return this._fillText(text, textWidth, indentIncriment) + $$.EOL + $$.EOL;
+ var indentIncriment = $$.repeat(' ', this._currentIndent);
+ return this._fillText(text, textWidth, indentIncriment) + c.EOL + c.EOL;
};
HelpFormatter.prototype._formatAction = function (action) {
@@ -578,40 +578,40 @@ HelpFormatter.prototype._formatAction = function (action) {
// no help; start on same line and add a final newline
if (!action.help) {
- actionHeader = _.repeat(' ', this._currentIndent) + actionHeader + $$.EOL;
+ actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL;
// short action name; start on the same line and pad two spaces
} else if (actionHeader.length <= actionWidth) {
- actionHeader = _.repeat(' ', this._currentIndent) +
+ actionHeader = $$.repeat(' ', this._currentIndent) +
actionHeader +
' ' +
- _.repeat(' ', actionWidth - actionHeader.length);
+ $$.repeat(' ', actionWidth - actionHeader.length);
indentFirst = 0;
// long action name; start on the next line
} else {
- actionHeader = _.repeat(' ', this._currentIndent) + actionHeader + $$.EOL;
+ actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL;
indentFirst = helpPosition;
}
// collect the pieces of the action help
- parts = [actionHeader];
+ parts = [ actionHeader ];
// if there was help for the action, add lines of help text
- if (!!action.help) {
+ if (action.help) {
helpText = this._expandHelp(action);
helpLines = this._splitLines(helpText, helpWidth);
- parts.push(_.repeat(' ', indentFirst) + helpLines[0] + $$.EOL);
+ parts.push($$.repeat(' ', indentFirst) + helpLines[0] + c.EOL);
helpLines.slice(1).forEach(function (line) {
- parts.push(_.repeat(' ', helpPosition) + line + $$.EOL);
+ parts.push($$.repeat(' ', helpPosition) + line + c.EOL);
});
// or add a newline if the description doesn't end with one
- } else if (actionHeader.charAt(actionHeader.length - 1) !== $$.EOL) {
- parts.push($$.EOL);
+ } else if (actionHeader.charAt(actionHeader.length - 1) !== c.EOL) {
+ parts.push(c.EOL);
}
// if there are any sub-actions, add their help as well
- if (!!action._getSubactions) {
+ if (action._getSubactions) {
this._indent();
action._getSubactions().forEach(function (subaction) {
parts.push(self._formatAction(subaction));
@@ -627,43 +627,41 @@ HelpFormatter.prototype._formatActionInvocation = function (action) {
var format_func = this._metavarFormatter(action, action.dest);
var metavars = format_func(1);
return metavars[0];
- } else {
- var parts = [];
- var argsDefault;
- var argsString;
+ }
- // if the Optional doesn't take a value, format is: -s, --long
- if (action.nargs === 0) {
- parts = parts.concat(action.optionStrings);
+ var parts = [];
+ var argsDefault;
+ var argsString;
- // if the Optional takes a value, format is: -s ARGS, --long ARGS
- } else {
- argsDefault = action.dest.toUpperCase();
- argsString = this._formatArgs(action, argsDefault);
- action.optionStrings.forEach(function (optionString) {
- parts.push(optionString + ' ' + argsString);
- });
- }
- return parts.join(', ');
+ // if the Optional doesn't take a value, format is: -s, --long
+ if (action.nargs === 0) {
+ parts = parts.concat(action.optionStrings);
+
+ // if the Optional takes a value, format is: -s ARGS, --long ARGS
+ } else {
+ argsDefault = action.dest.toUpperCase();
+ argsString = this._formatArgs(action, argsDefault);
+ action.optionStrings.forEach(function (optionString) {
+ parts.push(optionString + ' ' + argsString);
+ });
}
+ return parts.join(', ');
};
HelpFormatter.prototype._metavarFormatter = function (action, metavarDefault) {
var result;
- if (!!action.metavar || action.metavar === '') {
+ if (action.metavar || action.metavar === '') {
result = action.metavar;
- } else if (!!action.choices) {
+ } else if (action.choices) {
var choices = action.choices;
- if (_.isString(choices)) {
+ if (typeof choices === 'string') {
choices = choices.split('').join(', ');
- } else if (_.isArray(choices)) {
+ } else if (Array.isArray(choices)) {
choices = choices.join(',');
- }
- else
- {
- choices = _.keys(choices).join(',');
+ } else {
+ choices = Object.keys(choices).join(',');
}
result = '{' + choices + '}';
} else {
@@ -673,13 +671,13 @@ HelpFormatter.prototype._metavarFormatter = function (action, metavarDefault) {
return function (size) {
if (Array.isArray(result)) {
return result;
- } else {
- var metavars = [];
- for (var i = 0; i < size; i += 1) {
- metavars.push(result);
- }
- return metavars;
}
+
+ var metavars = [];
+ for (var i = 0; i < size; i += 1) {
+ metavars.push(result);
+ }
+ return metavars;
};
};
@@ -690,27 +688,28 @@ HelpFormatter.prototype._formatArgs = function (action, metavarDefault) {
var buildMetavar = this._metavarFormatter(action, metavarDefault);
switch (action.nargs) {
+ /*eslint-disable no-undefined*/
case undefined:
case null:
metavars = buildMetavar(1);
result = '' + metavars[0];
break;
- case $$.OPTIONAL:
+ case c.OPTIONAL:
metavars = buildMetavar(1);
result = '[' + metavars[0] + ']';
break;
- case $$.ZERO_OR_MORE:
+ case c.ZERO_OR_MORE:
metavars = buildMetavar(2);
result = '[' + metavars[0] + ' [' + metavars[1] + ' ...]]';
break;
- case $$.ONE_OR_MORE:
+ case c.ONE_OR_MORE:
metavars = buildMetavar(2);
result = '' + metavars[0] + ' [' + metavars[1] + ' ...]';
break;
- case $$.REMAINDER:
+ case c.REMAINDER:
result = '...';
break;
- case $$.PARSER:
+ case c.PARSER:
metavars = buildMetavar(1);
result = metavars[0] + ' ...';
break;
@@ -727,20 +726,18 @@ HelpFormatter.prototype._expandHelp = function (action) {
Object.keys(action).forEach(function (actionProperty) {
var actionValue = action[actionProperty];
- if (actionValue !== $$.SUPPRESS) {
+ if (actionValue !== c.SUPPRESS) {
params[actionProperty] = actionValue;
}
});
- if (!!params.choices) {
- if (_.isString(params.choices)) {
+ if (params.choices) {
+ if (typeof params.choices === 'string') {
params.choices = params.choices.split('').join(', ');
- }
- else if (_.isArray(params.choices)) {
+ } else if (Array.isArray(params.choices)) {
params.choices = params.choices.join(', ');
- }
- else {
- params.choices = _.keys(params.choices).join(', ');
+ } else {
+ params.choices = Object.keys(params.choices).join(', ');
}
}
@@ -749,17 +746,17 @@ HelpFormatter.prototype._expandHelp = function (action) {
HelpFormatter.prototype._splitLines = function (text, width) {
var lines = [];
- var delimiters = [" ", ".", ",", "!", "?"];
+ var delimiters = [ ' ', '.', ',', '!', '?' ];
var re = new RegExp('[' + delimiters.join('') + '][^' + delimiters.join('') + ']*$');
text = text.replace(/[\n\|\t]/g, ' ');
- text = _.trim(text);
+ text = text.trim();
text = text.replace(this._whitespaceMatcher, ' ');
// Wraps the single paragraph in text (a string) so every line
// is at most width characters long.
- text.split($$.EOL).forEach(function (line) {
+ text.split(c.EOL).forEach(function (line) {
if (width >= line.length) {
lines.push(line);
return;
@@ -790,7 +787,7 @@ HelpFormatter.prototype._fillText = function (text, width, indent) {
lines = lines.map(function (line) {
return indent + line;
});
- return lines.join($$.EOL);
+ return lines.join(c.EOL);
};
HelpFormatter.prototype._getHelpString = function (action) {
diff --git a/lib/namespace.js b/lib/namespace.js
index 2f1f8f4..a860de9 100644
--- a/lib/namespace.js
+++ b/lib/namespace.js
@@ -10,7 +10,7 @@
**/
'use strict';
-var _ = require('lodash');
+var $$ = require('./utils');
/**
* new Namespace(options)
@@ -18,7 +18,7 @@ var _ = require('lodash');
*
**/
var Namespace = module.exports = function Namespace(options) {
- _.extend(this, options);
+ $$.extend(this, options);
};
/**
@@ -28,7 +28,7 @@ var Namespace = module.exports = function Namespace(options) {
* Tells whenever `namespace` contains given `key` or not.
**/
Namespace.prototype.isset = function (key) {
- return _.has(this, key);
+ return $$.has(this, key);
};
/**
@@ -41,7 +41,7 @@ Namespace.prototype.isset = function (key) {
**/
Namespace.prototype.set = function (key, value) {
if (typeof (key) === 'object') {
- _.extend(this, key);
+ $$.extend(this, key);
} else {
this[key] = value;
}
@@ -56,7 +56,7 @@ Namespace.prototype.set = function (key, value) {
* Return the property key or defaulValue if not set
**/
Namespace.prototype.get = function (key, defaultValue) {
- return !this[key] ? defaultValue: this[key];
+ return !this[key] ? defaultValue : this[key];
};
/**
@@ -71,7 +71,6 @@ Namespace.prototype.unset = function (key, defaultValue) {
if (value !== null) {
delete this[key];
return value;
- } else {
- return defaultValue;
}
+ return defaultValue;
};
diff --git a/lib/utils.js b/lib/utils.js
new file mode 100644
index 0000000..4a9cf3e
--- /dev/null
+++ b/lib/utils.js
@@ -0,0 +1,57 @@
+'use strict';
+
+exports.repeat = function (str, num) {
+ var result = '';
+ for (var i = 0; i < num; i++) { result += str; }
+ return result;
+};
+
+exports.arrayEqual = function (a, b) {
+ if (a.length !== b.length) { return false; }
+ for (var i = 0; i < a.length; i++) {
+ if (a[i] !== b[i]) { return false; }
+ }
+ return true;
+};
+
+exports.trimChars = function (str, chars) {
+ var start = 0;
+ var end = str.length - 1;
+ while (chars.indexOf(str.charAt(start)) >= 0) { start++; }
+ while (chars.indexOf(str.charAt(end)) >= 0) { end--; }
+ return str.slice(start, end + 1);
+};
+
+exports.capitalize = function (str) {
+ return str.charAt(0).toUpperCase() + str.slice(1);
+};
+
+exports.arrayUnion = function () {
+ var result = [];
+ for (var i = 0, values = {}; i < arguments.length; i++) {
+ var arr = arguments[i];
+ for (var j = 0; j < arr.length; j++) {
+ if (!values[arr[j]]) {
+ values[arr[j]] = true;
+ result.push(arr[j]);
+ }
+ }
+ }
+ return result;
+};
+
+function has(obj, key) {
+ return Object.prototype.hasOwnProperty.call(obj, key);
+}
+
+exports.has = has;
+
+exports.extend = function (dest, src) {
+ for (var i in src) {
+ if (has(src, i)) { dest[i] = src[i]; }
+ }
+};
+
+exports.trimEnd = function (str) {
+ return str.replace(/\s+$/g, '');
+};
diff --git a/package.json b/package.json
index 76298e1..651d5d4 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "argparse",
"description": "Very powerful CLI arguments parser. Native port of argparse - python's options parsing library",
- "version": "1.0.3",
+ "version": "1.0.7",
"keywords": [
"cli",
"parser",
@@ -14,16 +14,22 @@
"Eugene Shkuropat",
"Paul Jacobson"
],
+ "files": [
+ "index.js",
+ "lib/"
+ ],
"license": "MIT",
"repository": "nodeca/argparse",
"scripts": {
"test": "make test"
},
"dependencies": {
- "lodash": ">= 3.2.0 < 4.0.0",
"sprintf-js": "~1.0.2"
},
"devDependencies": {
- "mocha": "*"
+ "eslint": "2.0.0-rc.0",
+ "eslint-plugin-nodeca": "~1.0.3",
+ "mocha": "*",
+ "ndoc": "^3.1.0"
}
}
diff --git a/test/base.js b/test/base.js
index 03185db..aed8ebe 100644
--- a/test/base.js
+++ b/test/base.js
@@ -11,9 +11,9 @@ describe('base', function () {
var parser;
var args;
- it("should parse argument in short form", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
+ it('should parse argument in short form', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-f', '--foo' ]);
args = parser.parseArgs('-f 1'.split(' '));
assert.equal(args.foo, 1);
@@ -23,9 +23,9 @@ describe('base', function () {
assert.equal(args.foo, 1);
});
- it("should parse argument in long form", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
+ it('should parse argument in long form', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-f', '--foo' ]);
args = parser.parseArgs('--foo 1'.split(' '));
assert.equal(args.foo, 1);
@@ -33,20 +33,20 @@ describe('base', function () {
assert.equal(args.foo, 1);
});
- it("should parse multiple arguments", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
- parser.addArgument(['--bar']);
+ it('should parse multiple arguments', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-f', '--foo' ]);
+ parser.addArgument([ '--bar' ]);
args = parser.parseArgs('--foo 5 --bar 6'.split(' '));
assert.equal(args.foo, 5);
assert.equal(args.bar, 6);
});
- it("should check argument type", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
- parser.addArgument(['--bar' ], { type: 'int' });
+ it('should check argument type', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-f', '--foo' ]);
+ parser.addArgument([ '--bar' ], { type: 'int' });
assert.throws(function () {
parser.parseArgs('--bar bar'.split(' '));
@@ -56,27 +56,27 @@ describe('base', function () {
});
});
- it("should not drop down with empty args (without positional arguments)", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
+ it('should not drop down with empty args (without positional arguments)', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-f', '--foo' ]);
assert.doesNotThrow(function () { parser.parseArgs([]); });
});
- it("should drop down with empty args (positional arguments)", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
- parser.addArgument([ 'baz']);
+ it('should drop down with empty args (positional arguments)', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-f', '--foo' ]);
+ parser.addArgument([ 'baz' ]);
assert.throws(
- function () {parser.parseArgs([]); },
+ function () { parser.parseArgs([]); },
/too few arguments/
);
});
- it("should support pseudo-argument", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
+ it('should support pseudo-argument', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-f', '--foo' ]);
parser.addArgument([ 'bar' ], { nargs: '+' });
args = parser.parseArgs([ '-f', 'foo', '--', '-f', 'bar' ]);
@@ -84,49 +84,49 @@ describe('base', function () {
assert.equal(args.bar.length, 2);
});
- it("should support #setDefaults", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
- parser.setDefaults({bar: 1});
+ 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']);
+ it('should throw TypeError with conflicting options', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-f', '--foo' ]);
assert.throws(
- function () { parser.addArgument(['-f']); },
+ function () { parser.addArgument([ '-f' ]); },
/Conflicting option string/
);
assert.throws(
- function () { parser.addArgument(['--foo']); },
+ function () { parser.addArgument([ '--foo' ]); },
/Conflicting option string/
);
assert.throws(
- function () { parser.addArgument(['-f', '--flame']); },
+ function () { parser.addArgument([ '-f', '--flame' ]); },
/Conflicting option string/
);
assert.throws(
- function () { parser.addArgument(['-m', '--foo']); },
+ function () { parser.addArgument([ '-m', '--foo' ]); },
/Conflicting option string/
);
});
- it("should parse negative arguments", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--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']);
+ args = parser.parseArgs([ '-1' ]);
assert.equal(args.bar, -1);
});
-
+
it("should parse arguments with '='", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-f', '--foo' ]);
parser.addArgument([ 'bar' ]);
args = parser.parseArgs('-f="foo=nice=path" "bar=nice=path"'.split(' '));
@@ -134,69 +134,69 @@ describe('base', function () {
assert.equal(args.bar, '"bar=nice=path"');
});
- 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: '?'});
+ 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']);
+ 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']);
+ 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: '?'});
+ 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']);
+ 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']);
+ parser.parseArgs([ '-2' ]);
},
/Unrecognized arguments: -2/
);
// negative number options present, so both -1s are options
assert.throws(
function () {
- parser.parseArgs(['-1', '-1']);
+ parser.parseArgs([ '-1', '-1' ]);
},
/argument "-1": Expected one argument/
);
- args = parser.parseArgs(['--', '-f']);
+ 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
+ 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});
+ 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});
+ 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);
@@ -204,32 +204,32 @@ describe('base', function () {
});
- it("getDefault() should get defaults", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
- parser.addArgument(['-g', '--goo'], {defaultValue: 42});
+ 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"});
+ 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 = new ArgumentParser({ debug: true });
parser.addArgument([ 'x' ], { nargs: '?' });
parser.addArgument([ '-y', '--yyy' ], { dest: 'y' });
@@ -257,9 +257,29 @@ describe('base', function () {
it('should support instantiation without new', function () {
assert.doesNotThrow(function () {
- /* jshint -W064 */
- parser = ArgumentParser({debug: true});
- /* jshint +W064 */
+ /*eslint-disable new-cap*/
+ parser = ArgumentParser({ debug: true });
});
});
+
+ it('should accept a string as a positional argument name', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument('foo');
+ args = parser.parseArgs([ 'badger' ]);
+ assert.equal(args.foo, 'badger');
+ });
+
+ it('should accept a string as a short option name', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument('-f');
+ args = parser.parseArgs('-f badger'.split(' '));
+ assert.equal(args.f, 'badger');
+ });
+
+ it('should accept a string as a long option name', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument('--foo');
+ args = parser.parseArgs('--foo badger'.split(' '));
+ assert.equal(args.foo, 'badger');
+ });
});
diff --git a/test/childgroups.js b/test/childgroups.js
index 066bbcd..82dd6a9 100644
--- a/test/childgroups.js
+++ b/test/childgroups.js
@@ -13,17 +13,17 @@ describe('child group', function () {
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 = 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'});
+ 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 () {
@@ -37,14 +37,14 @@ describe('child group', function () {
it('child should throw error if an xclusive group member is missing', function () {
assert.throws(
function () {
- args = childParser.parseArgs(['gbararg']);
+ 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']);
+ args = childParser.parseArgs([ '--xbar', 'gbararg' ]);
assert.equal(args.gbar, 'gbararg');
assert.equal(args.xbar, false);
});
@@ -52,7 +52,7 @@ describe('child group', function () {
it('child throws error if both xclusive options are given', function () {
assert.throws(
function () {
- args = childParser.parseArgs(['--xfoo', '--xbar']);
+ args = childParser.parseArgs([ '--xfoo', '--xbar' ]);
},
/Not allowed with argument/
);
diff --git a/test/choices.js b/test/choices.js
index f596af0..9eb64cb 100644
--- a/test/choices.js
+++ b/test/choices.js
@@ -11,9 +11,9 @@ describe('choices', function () {
var parser;
var args;
- it("should store correct choice(choices defined as string)", function () {
+ it('should store correct choice(choices defined as string)', function () {
parser = new ArgumentParser({ debug: true });
- parser.addArgument(['--foo'], {choices: 'abc'});
+ parser.addArgument([ '--foo' ], { choices: 'abc' });
args = parser.parseArgs('--foo a'.split(' '));
assert.equal(args.foo, 'a');
@@ -21,28 +21,28 @@ describe('choices', function () {
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'});
+ parser.addArgument([ '--foo' ], { choices: 'abc' });
assert.throws(
function () {
args = parser.parseArgs('--foo e'.split(' '));
- console.dir(args);
+ // console.dir(args);
},
/Invalid choice:/
);
assert.throws(
function () {
args = parser.parseArgs('--foo 0'.split(' '));
- console.dir(args);
+ // console.dir(args);
},
/Invalid choice:/
);
});
- it("should store correct choice(choices defined as array)", function () {
+ it('should store correct choice(choices defined as array)', function () {
parser = new ArgumentParser({ debug: true });
- parser.addArgument(['--foo'], {choices: ['a', 'abc', 'd']});
+ parser.addArgument([ '--foo' ], { choices: [ 'a', 'abc', 'd' ] });
args = parser.parseArgs('--foo abc'.split(' '));
assert.equal(args.foo, 'abc');
@@ -50,19 +50,19 @@ describe('choices', function () {
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']});
+ parser.addArgument([ '--foo' ], { choices: [ 'a', 'abc', 'd' ] });
assert.throws(
function () {
args = parser.parseArgs('--foo e'.split(' '));
- console.dir(args);
+ // console.dir(args);
},
/Invalid choice:/
);
assert.throws(
function () {
args = parser.parseArgs('--foo 0'.split(' '));
- console.dir(args);
+ // console.dir(args);
},
/Invalid choice:/
);
diff --git a/test/conflict.js b/test/conflict.js
index 953d0b0..d67ad59 100644
--- a/test/conflict.js
+++ b/test/conflict.js
@@ -10,32 +10,32 @@ describe('Argument conflict handling', function () {
var parser;
var help;
- it("test_bad_type", function () {
+ it('test_bad_type', function () {
assert.throws(function () {
- parser = new ArgumentParser({conflictHandler: 'foo'});
+ parser = new ArgumentParser({ conflictHandler: 'foo' });
},
/invalid conflict resolution value: foo/i
);
});
- it("test_conflict_error", function () {
+ it('test_conflict_error', function () {
parser = new ArgumentParser();
- parser.addArgument(['-x']);
+ parser.addArgument([ '-x' ]);
assert.throws(function () {
- parser.addArgument(['-x']);
+ parser.addArgument([ '-x' ]);
},
/Conflicting option string/i
);
- parser.addArgument(['--spam']);
+ parser.addArgument([ '--spam' ]);
assert.throws(function () {
- parser.addArgument(['--spam']);
+ parser.addArgument([ '--spam' ]);
},
/Conflicting option string/i
);
});
- it("test_resolve_error", function () {
- parser = new ArgumentParser({prog: 'PROG', conflictHandler: 'resolve'});
- parser.addArgument(['-x'], {help: 'OLD X'});
- parser.addArgument(['-x'], {help: 'NEW X'});
+ it('test_resolve_error', function () {
+ parser = new ArgumentParser({ prog: 'PROG', conflictHandler: 'resolve' });
+ parser.addArgument([ '-x' ], { help: 'OLD X' });
+ parser.addArgument([ '-x' ], { help: 'NEW X' });
help = parser.formatHelp();
/* expect
usage: PROG [-h] [-x X]
@@ -47,8 +47,8 @@ describe('Argument conflict handling', function () {
assert(help.match(/usage: PROG \[-h\] \[-x X\]/im));
assert(help.match(/Show this help message and exit/im));
assert(help.match(/-x X\s*NEW X/im));
- parser.addArgument(['--spam'], {metavar: 'OLD_SPAM'});
- parser.addArgument(['--spam'], {metavar: 'NEW_SPAM'});
+ parser.addArgument([ '--spam' ], { metavar: 'OLD_SPAM' });
+ parser.addArgument([ '--spam' ], { metavar: 'NEW_SPAM' });
help = parser.formatHelp();
/* expect
usage: PROG [-h] [-x X] [--spam NEW_SPAM]
@@ -60,19 +60,19 @@ describe('Argument conflict handling', function () {
*/
assert(help.match(/--spam NEW_SPAM/im));
});
- it("TypeError with multiple conflicts", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
- parser.addArgument(['-b', '--bar']);
+ it('TypeError with multiple conflicts', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-f', '--foo' ]);
+ parser.addArgument([ '-b', '--bar' ]);
assert.throws(
- function () { parser.addArgument(['--foo', '--bar', '--foobar']); },
+ function () { parser.addArgument([ '--foo', '--bar', '--foobar' ]); },
/argument "--foo\/--bar\/--foobar": Conflicting option string\(s\): --foo, --bar/
);
});
- it("resolving multiple conflicts", function () {
- parser = new ArgumentParser({debug: true, conflictHandler: 'resolve'});
- parser.addArgument(['-f', '--foo']);
- parser.addArgument(['--bar']);
+ it('resolving multiple conflicts', function () {
+ parser = new ArgumentParser({ debug: true, conflictHandler: 'resolve' });
+ parser.addArgument([ '-f', '--foo' ]);
+ parser.addArgument([ '--bar' ]);
help = parser.formatHelp();
/*
usage: _mocha [-h] [-f FOO] [--bar BAR]
@@ -82,7 +82,7 @@ describe('Argument conflict handling', function () {
--bar BAR
*/
assert(help.match(/-f FOO, --foo FOO/im));
- parser.addArgument(['--foo', '--bar', '--foobar']);
+ parser.addArgument([ '--foo', '--bar', '--foobar' ]);
help = parser.formatHelp();
assert(help.match(/-f FOO$/im));
assert(help.match(/--foo FOO, --bar FOO, --foobar FOO/im));
diff --git a/test/constant.js b/test/constant.js
index c56eb6a..435a0e9 100644
--- a/test/constant.js
+++ b/test/constant.js
@@ -11,21 +11,21 @@ describe('constant actions', function () {
var args;
beforeEach(function () {
- parser = new ArgumentParser({debug: true});
+ 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});
+ 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 () {
+ it('storeConst should give error if constant not given (or misspelled)', function () {
assert.throws(
function () {
parser.addArgument(
- ['-a'],
+ [ '-a' ],
{
action: 'storeConst',
dest: 'answer',
@@ -38,20 +38,20 @@ describe('constant actions', function () {
);
});
- 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'});
+ 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 () {
+ 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});
+ parser.addArgument([ '-a' ], { action: 'appendConst', dest: 'answer',
+ help: 'store constant', const: 42 });
},
/constant option is required for appendAction/
);
diff --git a/test/formatters.js b/test/formatters.js
index 3714367..e479caa 100644
--- a/test/formatters.js
+++ b/test/formatters.js
@@ -17,20 +17,20 @@ describe('formatterClass alternatives', function () {
description: 'description'
});
- parser.addArgument(['--foo'], {
+ parser.addArgument([ '--foo' ], {
help: 'foo help - oh and by the way, %(defaultValue)s'
});
- parser.addArgument(['--bar'], {
+ parser.addArgument([ '--bar' ], {
action: 'storeTrue',
help: 'bar help'
});
- parser.addArgument(['spam'], {
+ parser.addArgument([ 'spam' ], {
help: 'spam help'
});
- parser.addArgument(['badger'], {
+ parser.addArgument([ 'badger' ], {
nargs: '?',
defaultValue: 'wooden',
help: 'badger help'
@@ -41,7 +41,7 @@ describe('formatterClass alternatives', function () {
description: 'group description'
});
- group.addArgument(['--baz'], {
+ group.addArgument([ '--baz' ], {
type: 'int',
defaultValue: 42,
help: 'baz help'
@@ -89,13 +89,13 @@ title:
'here\n'
});
- a = parser.addArgument(['--foo'], {
+ a = parser.addArgument([ '--foo' ], {
help: ' foo help should not\n' +
' retain this odd formatting'
});
- parser.addArgument(['spam'], {
- 'help': 'spam help'
+ parser.addArgument([ 'spam' ], {
+ help: 'spam help'
});
group = parser.addArgumentGroup({
@@ -105,7 +105,7 @@ title:
' exactly like it is here\n'
});
- group.addArgument(['--bar'], {
+ group.addArgument([ '--bar' ], {
help: 'bar help'
});
@@ -153,18 +153,18 @@ title:
'here\n'
});
- parser.addArgument(['--baz'], {
+ parser.addArgument([ '--baz' ], {
help: ' baz help should also\n' +
'appear as given here'
});
- a = parser.addArgument(['--foo'], {
+ a = parser.addArgument([ '--foo' ], {
help: ' foo help should also\n' +
'appear as given here'
});
- parser.addArgument(['spam'], {
- 'help': 'spam help'
+ parser.addArgument([ 'spam' ], {
+ help: 'spam help'
});
group = parser.addArgumentGroup({
@@ -174,7 +174,7 @@ title:
' exactly like it is here\n'
});
- group.addArgument(['--bar'], {
+ group.addArgument([ '--bar' ], {
help: 'bar help'
});
@@ -214,28 +214,28 @@ title:
prog: 'PROG'
});
- parser.addArgument(['-w'], {
+ parser.addArgument([ '-w' ], {
help: 'w',
nargs: '+',
- metavar: ['W1', 'W2']
+ metavar: [ 'W1', 'W2' ]
});
- parser.addArgument(['-x'], {
+ parser.addArgument([ '-x' ], {
help: 'x',
nargs: '*',
- metavar: ['X1', 'X2']
+ metavar: [ 'X1', 'X2' ]
});
- parser.addArgument(['-y'], {
+ parser.addArgument([ '-y' ], {
help: 'y',
nargs: 3,
- metavar: ['Y1', 'Y2', 'Y3']
+ metavar: [ 'Y1', 'Y2', 'Y3' ]
});
- parser.addArgument(['-z'], {
+ parser.addArgument([ '-z' ], {
help: 'z',
nargs: '?',
- metavar: ['Z1']
+ metavar: [ 'Z1' ]
});
helptext = parser.formatHelp();
diff --git a/test/fromfile.js b/test/fromfile.js
index 27bfb8f..13f3141 100644
--- a/test/fromfile.js
+++ b/test/fromfile.js
@@ -3,12 +3,9 @@
'use strict';
var assert = require('assert');
-
-var ArgumentParser = require('../lib/argparse').ArgumentParser;
-
-var assert = require('assert');
var path = require('path');
+var ArgumentParser = require('../lib/argparse').ArgumentParser;
var orig_cwd = process.cwd();
@@ -20,34 +17,34 @@ describe('from file', function () {
process.chdir(path.normalize('./test/fixtures'));
});
beforeEach(function () {
- parser = new ArgumentParser({debug: true, fromfilePrefixChars: '@'});
- parser.addArgument(['-a']);
- parser.addArgument(['x']);
- parser.addArgument(['y'], {nargs: '+'});
+ parser = new ArgumentParser({ debug: true, fromfilePrefixChars: '@' });
+ parser.addArgument([ '-a' ]);
+ parser.addArgument([ 'x' ]);
+ parser.addArgument([ 'y' ], { nargs: '+' });
});
after(function () {
process.chdir(orig_cwd);
});
- it("test reading arguments from a file", function () {
- args = parser.parseArgs(['X', 'Y']);
- assert.deepEqual(args, {a: null, x: 'X', y: ['Y']});
- args = parser.parseArgs(['X', '-a', 'A', 'Y', 'Z']);
- assert.deepEqual(args, { a: 'A', x: 'X', y: ['Y', 'Z']});
- args = parser.parseArgs(['@hello', 'X']);
- assert.deepEqual(args, {a: null, x: 'hello world!', y: ['X']});
- args = parser.parseArgs(['X', '@hello']);
- assert.deepEqual(args, {a: null, x: 'X', y: ['hello world!']});
+ it('test reading arguments from a file', function () {
+ args = parser.parseArgs([ 'X', 'Y' ]);
+ assert.deepEqual(args, { a: null, x: 'X', y: [ 'Y' ] });
+ args = parser.parseArgs([ 'X', '-a', 'A', 'Y', 'Z' ]);
+ assert.deepEqual(args, { a: 'A', x: 'X', y: [ 'Y', 'Z' ] });
+ args = parser.parseArgs([ '@hello', 'X' ]);
+ assert.deepEqual(args, { a: null, x: 'hello world!', y: [ 'X' ] });
+ args = parser.parseArgs([ 'X', '@hello' ]);
+ assert.deepEqual(args, { a: null, x: 'X', y: [ 'hello world!' ] });
});
- it("test recursive reading arguments from files", function () {
- args = parser.parseArgs(['-a', 'B', '@recursive', 'Y', 'Z']);
- assert.deepEqual(args, {a: 'A', x: 'hello world!', y: ['Y', 'Z']});
- args = parser.parseArgs(['X', '@recursive', 'Z', '-a', 'B']);
- assert.deepEqual(args, {a: 'B', x: 'X', y: ['hello world!', 'Z']});
+ it('test recursive reading arguments from files', function () {
+ args = parser.parseArgs([ '-a', 'B', '@recursive', 'Y', 'Z' ]);
+ assert.deepEqual(args, { a: 'A', x: 'hello world!', y: [ 'Y', 'Z' ] });
+ args = parser.parseArgs([ 'X', '@recursive', 'Z', '-a', 'B' ]);
+ assert.deepEqual(args, { a: 'B', x: 'X', y: [ 'hello world!', 'Z' ] });
});
it('test reading arguments from an invalid file', function () {
assert.throws(
function () {
- args = parser.parseArgs(['@invalid']);
+ args = parser.parseArgs([ '@invalid' ]);
},
/ENOENT[:,] no such file or directory/
);
@@ -55,7 +52,7 @@ describe('from file', function () {
it('test reading arguments from an missing file', function () {
assert.throws(
function () {
- args = parser.parseArgs(['@missing']);
+ args = parser.parseArgs([ '@missing' ]);
},
/ENOENT[:,] no such file or directory/
);
@@ -64,12 +61,12 @@ describe('from file', function () {
parser.convertArgLineToArgs = function (argLine) {
// split line into 'words'
args = argLine.split(' ');
- args = args.map(function (arg) {return arg.trim(); });
- args = args.filter(function (arg) {return arg.length > 0; });
+ args = args.map(function (arg) { return arg.trim(); });
+ args = args.filter(function (arg) { return arg.length > 0; });
return args;
};
- args = parser.parseArgs(['X', '@hello']);
- assert.deepEqual(args, {a: null, x: 'X', y: ['hello', 'world!']});
+ args = parser.parseArgs([ 'X', '@hello' ]);
+ assert.deepEqual(args, { a: null, x: 'X', y: [ 'hello', 'world!' ] });
});
});
diff --git a/test/group.js b/test/group.js
index c90c23f..5a556a8 100644
--- a/test/group.js
+++ b/test/group.js
@@ -15,10 +15,10 @@ describe('group', function () {
var group2;
it('group test', function () {
- parser = new ArgumentParser({prog: 'PROG', addHelp: false, debug: true});
- group = parser.addArgumentGroup({title: 'group'});
- group.addArgument(['--foo'], {help: 'foo help'});
- group.addArgument(['bar'], {help: 'bar help'});
+ parser = new ArgumentParser({ prog: 'PROG', addHelp: false, debug: true });
+ group = parser.addArgumentGroup({ title: 'group' });
+ group.addArgument([ '--foo' ], { help: 'foo help' });
+ group.addArgument([ 'bar' ], { help: 'bar help' });
// what to test for in help?
// parser.print_help()
// does group make an difference in parseArgs output?
@@ -26,45 +26,45 @@ describe('group', function () {
});
it('2 groups test', function () {
- parser = new ArgumentParser({prog: 'PROG', addHelp: false, debug: true});
- group1 = parser.addArgumentGroup({title: 'group1', description: 'group1 description'});
- group1.addArgument(['foo'], {help: 'foo help'});
- group2 = parser.addArgumentGroup({title: 'group2', description: 'group2 description'});
- group2.addArgument(['--bar'], {help: 'bar help'});
+ parser = new ArgumentParser({ prog: 'PROG', addHelp: false, debug: true });
+ group1 = parser.addArgumentGroup({ title: 'group1', description: 'group1 description' });
+ group1.addArgument([ 'foo' ], { help: 'foo help' });
+ group2 = parser.addArgumentGroup({ title: 'group2', description: 'group2 description' });
+ group2.addArgument([ '--bar' ], { help: 'bar help' });
//parser.print_help();
assert(group1._groupActions.length, 1);
assert(parser._actionGroups.length, 4); // group1, group2, positionals, optionals
});
it('mutually exclusive group test', function () {
- parser = new ArgumentParser({prog: 'PROG', debug: true});
+ parser = new ArgumentParser({ prog: 'PROG', debug: true });
group = parser.addMutuallyExclusiveGroup();
- group.addArgument(['--foo'], {action: 'storeTrue'});
- group.addArgument(['--bar'], {action: 'storeFalse'});
+ group.addArgument([ '--foo' ], { action: 'storeTrue' });
+ group.addArgument([ '--bar' ], { action: 'storeFalse' });
args = parser.parseArgs([]);
// Python: Namespace(bar=True, foo=False)
assert.equal(args.foo, false);
assert.equal(args.bar, true);
- args = parser.parseArgs(['--foo']);
+ args = parser.parseArgs([ '--foo' ]);
// Python: Namespace(bar=True, foo=True)
assert.equal(args.foo, true);
assert.equal(args.bar, true);
- args = parser.parseArgs(['--bar']);
+ args = parser.parseArgs([ '--bar' ]);
// Python: Namespace(bar=False, foo=False)
assert.equal(args.foo || args.bar, false);
});
it('mutually exclusive group test (2)', function () {
- parser = new ArgumentParser({prog: 'PROG', debug: true});
+ parser = new ArgumentParser({ prog: 'PROG', debug: true });
group = parser.addMutuallyExclusiveGroup();
- group.addArgument(['--foo'], {action: 'storeTrue'});
- group.addArgument(['--bar'], {action: 'storeFalse'});
+ group.addArgument([ '--foo' ], { action: 'storeTrue' });
+ group.addArgument([ '--bar' ], { action: 'storeFalse' });
assert.throws(
function () {
- args = parser.parseArgs(['--foo', '--bar']);
+ args = parser.parseArgs([ '--foo', '--bar' ]);
},
// Python: error: argument --bar: not allowed with argument --foo
// I had problems with the proper pairing of bar and foo
@@ -79,16 +79,16 @@ describe('group', function () {
return m && m[1] !== m[2];
}
},
- "unexpected error"
+ 'unexpected error'
);
});
it('mutually exclusive group test (3)', function () {
- parser = new ArgumentParser({prog: 'PROG', debug: true});
- group = parser.addMutuallyExclusiveGroup({required: true});
+ parser = new ArgumentParser({ prog: 'PROG', debug: true });
+ group = parser.addMutuallyExclusiveGroup({ required: true });
// or should the input be {required: true}?
- group.addArgument(['--foo'], {action: 'storeTrue'});
- group.addArgument(['--bar'], {action: 'storeFalse'});
+ group.addArgument([ '--foo' ], { action: 'storeTrue' });
+ group.addArgument([ '--bar' ], { action: 'storeFalse' });
assert.equal(group.required, true);
assert.equal(group._groupActions.length, 2);
assert.throws(
@@ -103,13 +103,13 @@ describe('group', function () {
it('mutually exclusive group usage', function () {
// adapted from test_argparse.py TestMutuallyExclusiveSimple
var usage;
- parser = new ArgumentParser({prog: 'PROG', debug: true});
- group = parser.addMutuallyExclusiveGroup({required: true});
+ parser = new ArgumentParser({ prog: 'PROG', debug: true });
+ group = parser.addMutuallyExclusiveGroup({ required: true });
// or should the input be {required: true}?
- group.addArgument(['--bar'], {help: 'bar help'});
- group.addArgument(['--baz'], {nargs: '?', constant: 'Z', help: 'baz help'});
- args = parser.parseArgs(['--bar', 'X']);
- assert.deepEqual(args, {bar: 'X', baz: null});
+ group.addArgument([ '--bar' ], { help: 'bar help' });
+ group.addArgument([ '--baz' ], { nargs: '?', constant: 'Z', help: 'baz help' });
+ args = parser.parseArgs([ '--bar', 'X' ]);
+ assert.deepEqual(args, { bar: 'X', baz: null });
assert.throws(
function () {
@@ -128,18 +128,18 @@ describe('group', function () {
it('mutually exclusive optional and positional', function () {
// adapted from test_argparse.py TestMutuallyExclusiveOptionalAndPositional
var usage;
- parser = new ArgumentParser({prog: 'PROG', debug: true});
- group = parser.addMutuallyExclusiveGroup({required: true});
+ parser = new ArgumentParser({ prog: 'PROG', debug: true });
+ group = parser.addMutuallyExclusiveGroup({ required: true });
// or should the input be {required: true}?
- group.addArgument(['--foo'], {action: 'storeTrue', help: 'foo help'});
- group.addArgument(['--spam'], {help: 'spam help'});
- group.addArgument(['badger'], {nargs: '*', defaultValue: 'X', help: 'badger help'});
- args = parser.parseArgs(['--spam', 'S']);
- assert.deepEqual(args, {foo: false, spam: 'S', badger: 'X'});
- args = parser.parseArgs(['X']);
- assert.deepEqual(args, {"foo": false, "spam": null, "badger": ['X']});
- args = parser.parseArgs(['--foo']);
- assert.deepEqual(args, {foo: true, spam: null, badger: 'X'});
+ group.addArgument([ '--foo' ], { action: 'storeTrue', help: 'foo help' });
+ group.addArgument([ '--spam' ], { help: 'spam help' });
+ group.addArgument([ 'badger' ], { nargs: '*', defaultValue: 'X', help: 'badger help' });
+ args = parser.parseArgs([ '--spam', 'S' ]);
+ assert.deepEqual(args, { foo: false, spam: 'S', badger: 'X' });
+ args = parser.parseArgs([ 'X' ]);
+ assert.deepEqual(args, { foo: false, spam: null, badger: [ 'X' ] });
+ args = parser.parseArgs([ '--foo' ]);
+ assert.deepEqual(args, { foo: true, spam: null, badger: 'X' });
assert.throws(
function () {
args = parser.parseArgs('--foo --spam 5'.split(' '));
@@ -156,13 +156,13 @@ describe('group', function () {
it('two mutually exclusive groups', function () {
// adapted from test_argparse.py
var usage, group1, group2;
- parser = new ArgumentParser({prog: 'PROG', debug: true});
- group1 = parser.addMutuallyExclusiveGroup({required: true});
- group1.addArgument(['--foo'], {action: 'storeTrue'});
- group1.addArgument(['--bar'], {action: 'storeFalse'});
- group2 = parser.addMutuallyExclusiveGroup({required: false});
- group2.addArgument(['--soup'], {action: 'storeTrue'});
- group2.addArgument(['--nuts'], {action: 'storeFalse'});
+ parser = new ArgumentParser({ prog: 'PROG', debug: true });
+ group1 = parser.addMutuallyExclusiveGroup({ required: true });
+ group1.addArgument([ '--foo' ], { action: 'storeTrue' });
+ group1.addArgument([ '--bar' ], { action: 'storeFalse' });
+ group2 = parser.addMutuallyExclusiveGroup({ required: false });
+ group2.addArgument([ '--soup' ], { action: 'storeTrue' });
+ group2.addArgument([ '--nuts' ], { action: 'storeFalse' });
usage = parser.formatUsage();
assert.equal(usage, 'usage: PROG [-h] (--foo | --bar) [--soup | --nuts]\n');
});
@@ -170,12 +170,12 @@ describe('group', function () {
it('suppressed and single action groups', function () {
// adapted from test_argparse.py
var usage, group1, group2;
- parser = new ArgumentParser({prog: 'PROG', debug: true});
+ parser = new ArgumentParser({ prog: 'PROG', debug: true });
group1 = parser.addMutuallyExclusiveGroup();
- group1.addArgument(['--sup'], {help: '==SUPPRESS=='});
+ group1.addArgument([ '--sup' ], { help: '==SUPPRESS==' });
// should produce an empty group (), which is removed
- group2 = parser.addMutuallyExclusiveGroup({required: true});
- group2.addArgument(['--xxx'], {});
+ group2 = parser.addMutuallyExclusiveGroup({ required: true });
+ group2.addArgument([ '--xxx' ], {});
// single entry in a required group, remove group ()
usage = parser.formatUsage();
assert.equal(usage, 'usage: PROG [-h] --xxx XXX\n');
diff --git a/test/nargs.js b/test/nargs.js
index 641595d..986ca6a 100644
--- a/test/nargs.js
+++ b/test/nargs.js
@@ -12,7 +12,7 @@ describe('nargs', function () {
var parser;
var args;
it('test specifying the 1 arg for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], { nargs: 1 });
args = parser.parseArgs([]);
@@ -29,7 +29,7 @@ describe('nargs', function () {
});
it('test specifying the 3 args for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], { nargs: 3 });
args = parser.parseArgs([]);
@@ -58,7 +58,7 @@ describe('nargs', function () {
});
it('tests not specifying the number of args for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], {});
args = parser.parseArgs([]);
@@ -75,9 +75,9 @@ describe('nargs', function () {
});
it('test specifying an args for an Optional, that accepts one or more', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], { nargs: '+' });
- parser.addArgument([ '-y' ], { "default": 'spam', nargs: '+', defaultValue: 'spam' });
+ parser.addArgument([ '-y' ], { default: 'spam', nargs: '+', defaultValue: 'spam' });
args = parser.parseArgs([]);
assert.deepEqual(args, { y: 'spam', x: null });
@@ -108,12 +108,12 @@ describe('nargs', function () {
});
it('test specifying an Optional arg for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-w' ], { nargs: '?' });
parser.addArgument([ '-x' ], { const: 42, nargs: '?', constant: 42 });
- parser.addArgument([ '-y' ], { "default": 'spam', nargs: '?', defaultValue: 'spam' });
+ parser.addArgument([ '-y' ], { default: 'spam', nargs: '?', defaultValue: 'spam' });
parser.addArgument([ '-z' ], {
- "default": '84',
+ default: '84',
nargs: '?',
type: 'int',
const: '42',
@@ -146,9 +146,9 @@ describe('nargs', function () {
});
it('test specifying an args for an Optional that accepts zero or more', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], { nargs: '*' });
- parser.addArgument([ '-y' ], { "default": 'spam', nargs: '*', defaultValue: 'spam' });
+ parser.addArgument([ '-y' ], { default: 'spam', nargs: '*', defaultValue: 'spam' });
args = parser.parseArgs([]);
assert.deepEqual(args, { y: 'spam', x: null });
@@ -171,7 +171,7 @@ describe('nargs', function () {
});
it('test a Positional that specifies an nargs of 1', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: 1 });
args = parser.parseArgs([ 'a' ]);
@@ -189,7 +189,7 @@ describe('nargs', function () {
});
it('test a Positional that specifies an nargs of 2', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: 2 });
args = parser.parseArgs([ 'a', 'b' ]);
@@ -210,7 +210,7 @@ describe('nargs', function () {
});
it('test a Positional with 2 nargs followed by one with none', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: 2 });
parser.addArgument([ 'bar' ], {});
@@ -235,7 +235,7 @@ describe('nargs', function () {
});
it('test a Positional with 2 nargs followed by one with one or more', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: 2 });
parser.addArgument([ 'bar' ], { nargs: '+' });
@@ -257,7 +257,7 @@ describe('nargs', function () {
});
it('test a Positional with 2 nargs followed by one optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: 2 });
parser.addArgument([ 'bar' ], { nargs: '?' });
@@ -281,7 +281,7 @@ describe('nargs', function () {
});
it('test a Positional with 2 nargs followed by one with unlimited', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: 2 });
parser.addArgument([ 'bar' ], { nargs: '*' });
@@ -302,7 +302,7 @@ describe('nargs', function () {
});
it('test a Positional that doesn\'t specify nargs', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], {});
args = parser.parseArgs([ 'a' ]);
@@ -320,7 +320,7 @@ describe('nargs', function () {
});
it('test a Positional with no nargs followed by one with 1', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], {});
parser.addArgument([ 'bar' ], { nargs: 1 });
@@ -342,7 +342,7 @@ describe('nargs', function () {
});
it('test two Positionals that don\'t specify nargs', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], {});
parser.addArgument([ 'bar' ], {});
@@ -364,7 +364,7 @@ describe('nargs', function () {
});
it('test a Positional with no nargs followed by one with one or more', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], {});
parser.addArgument([ 'bar' ], { nargs: '+' });
@@ -385,7 +385,7 @@ describe('nargs', function () {
});
it('test three Positionals: no nargs, one or more nargs and 1 nargs', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], {});
parser.addArgument([ 'bar' ], { nargs: '+' });
parser.addArgument([ 'baz' ], { nargs: 1 });
@@ -410,7 +410,7 @@ describe('nargs', function () {
});
it('test a Positional with no nargs followed by one with an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], {});
parser.addArgument([ 'bar' ], { nargs: '?' });
@@ -431,9 +431,9 @@ describe('nargs', function () {
});
it('test three Positionals: no nargs, optional narg and 1 nargs', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], {});
- parser.addArgument([ 'bar' ], { "default": 0.625, nargs: '?', defaultValue: 0.625 });
+ parser.addArgument([ 'bar' ], { default: 0.625, nargs: '?', defaultValue: 0.625 });
parser.addArgument([ 'baz' ], { nargs: 1 });
args = parser.parseArgs([ 'a', 'b' ]);
@@ -453,7 +453,7 @@ describe('nargs', function () {
});
it('test a Positional with no nargs followed by one with unlimited', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], {});
parser.addArgument([ 'bar' ], { nargs: '*' });
@@ -473,7 +473,7 @@ describe('nargs', function () {
});
it('test three Positionals: no nargs, unlimited nargs and 1 nargs', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], {});
parser.addArgument([ 'bar' ], { nargs: '*' });
parser.addArgument([ 'baz' ], { nargs: 1 });
@@ -495,7 +495,7 @@ describe('nargs', function () {
});
it('test a Positional that specifies one or more nargs', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: '+' });
args = parser.parseArgs([ 'a' ]);
@@ -512,7 +512,7 @@ describe('nargs', function () {
});
it('test a Positional with one or more nargs followed by one with 1', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: '+' });
parser.addArgument([ 'bar' ], { nargs: 1 });
@@ -533,7 +533,7 @@ describe('nargs', function () {
});
it('test a Positional with one or more nargs followed by one with none', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: '+' });
parser.addArgument([ 'bar' ], {});
@@ -554,7 +554,7 @@ describe('nargs', function () {
});
it('tests an Optional Positional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: '?' });
args = parser.parseArgs([]);
@@ -571,7 +571,7 @@ describe('nargs', function () {
});
it('test a Positional with an Optional nargs followed by one with 1', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: '?' });
parser.addArgument([ 'bar' ], { nargs: 1 });
@@ -591,9 +591,10 @@ describe('nargs', function () {
});
});
+ /*eslint-disable max-len*/
it('test an Optional Positional with a default value (that needs to be converted to the appropriate type.)', function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument([ 'foo' ], { "default": '42', type: 'int', nargs: '?', defaultValue: '42' });
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ 'foo' ], { default: '42', type: 'int', nargs: '?', defaultValue: '42' });
args = parser.parseArgs([]);
assert.deepEqual(args, { foo: 42 });
@@ -612,8 +613,8 @@ describe('nargs', function () {
});
it('tests an Optional Positional with a default value', function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument([ 'foo' ], { "default": 42, nargs: '?', defaultValue: 42 });
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ 'foo' ], { default: 42, nargs: '?', defaultValue: 42 });
args = parser.parseArgs([]);
assert.deepEqual(args, { foo: 42 });
@@ -629,8 +630,8 @@ describe('nargs', function () {
});
it('test a Positional with an Optional nargs followed by one with none', function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument([ 'foo' ], { "default": 42, nargs: '?', defaultValue: 42 });
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ 'foo' ], { default: 42, nargs: '?', defaultValue: 42 });
parser.addArgument([ 'bar' ], {});
args = parser.parseArgs([ 'a' ]);
@@ -650,7 +651,7 @@ describe('nargs', function () {
});
it('test an Optional narg followed by one or more nargs', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: '?' });
parser.addArgument([ 'bar' ], { nargs: '+' });
@@ -670,9 +671,9 @@ describe('nargs', function () {
});
it('test two optional nargs', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: '?' });
- parser.addArgument([ 'bar' ], { "default": 42, nargs: '?', defaultValue: 42 });
+ parser.addArgument([ 'bar' ], { default: 42, nargs: '?', defaultValue: 42 });
args = parser.parseArgs([]);
assert.deepEqual(args, { foo: null, bar: 42 });
@@ -690,7 +691,7 @@ describe('nargs', function () {
});
it('test an Optional narg followed by unlimited nargs', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: '?' });
parser.addArgument([ 'bar' ], { nargs: '*' });
@@ -709,7 +710,7 @@ describe('nargs', function () {
});
it('test a Positional that specifies unlimited nargs', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: '*' });
args = parser.parseArgs([]);
@@ -726,17 +727,17 @@ describe('nargs', function () {
// Added after bug in ndoc
it('test a `nargs` + `append` combination. Not obvious result - nested array', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { action: 'append', nargs: '+' });
args = parser.parseArgs([ 'a', 'b' ]);
// YES, NESTED array, don't try to 'fix' it.
- assert.deepEqual(args, { foo: [[ 'a', 'b' ]] });
+ assert.deepEqual(args, { foo: [ [ 'a', 'b' ] ] });
});
it('test a Positional with unlimited nargs followed by one with 1', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: '*' });
parser.addArgument([ 'bar' ], { nargs: 1 });
@@ -756,8 +757,8 @@ describe('nargs', function () {
});
it('test a Positional that specifies unlimited nargs and a default', function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument([ 'foo' ], { "default": 'bar', nargs: '*', defaultValue: 'bar' });
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ 'foo' ], { default: 'bar', nargs: '*', defaultValue: 'bar' });
args = parser.parseArgs([]);
assert.deepEqual(args, { foo: 'bar' });
@@ -772,7 +773,7 @@ describe('nargs', function () {
});
it('test a Positional with unlimited nargs followed by one with none', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], { nargs: '*' });
parser.addArgument([ 'bar' ], {});
@@ -793,7 +794,7 @@ describe('nargs', function () {
it('test specifying a positional with nargs=REMAINDER', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'x' ], {});
parser.addArgument([ 'y' ], { nargs: $$.REMAINDER });
parser.addArgument([ '-z' ], {});
@@ -819,7 +820,7 @@ describe('nargs', function () {
});
it('test specifying an args for an Optional that accepts zero or more', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], { nargs: '*' });
parser.addArgument([ 'y' ], { nargs: '*' });
@@ -841,19 +842,19 @@ describe('nargs', function () {
});
it("should accept defaultValue for nargs:'*'", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-f', '--foo']);
- parser.addArgument(['bar'], { nargs: '*', defaultValue: 42});
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-f', '--foo' ]);
+ parser.addArgument([ 'bar' ], { nargs: '*', defaultValue: 42 });
args = parser.parseArgs([]);
assert.equal(args.bar, 42);
});
- it("should accept negative scientific numbers as values", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['--xlim'], {nargs: 2, type: 'float'});
+ it('should accept negative scientific numbers as values', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '--xlim' ], { nargs: 2, type: 'float' });
- args = parser.parseArgs(['--xlim', '-2e-3', '1e4']);
+ args = parser.parseArgs([ '--xlim', '-2e-3', '1e4' ]);
assert.equal(args['xlim'][0], -0.002);
});
diff --git a/test/optionals.js b/test/optionals.js
index 9776d36..1beac50 100644
--- a/test/optionals.js
+++ b/test/optionals.js
@@ -11,7 +11,7 @@ describe('optionals', function () {
var args;
it('test options that may or may not be arguments', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], { type: 'float' });
parser.addArgument([ '-3' ], { dest: 'y', type: 'float' });
parser.addArgument([ 'z' ], { nargs: '*' });
@@ -81,7 +81,7 @@ describe('optionals', function () {
});
it('test the append action for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '--baz' ], { action: 'append' });
args = parser.parseArgs([]);
@@ -106,7 +106,7 @@ describe('optionals', function () {
});
it('test the append_const action for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-b' ], { action: 'appendConst',
const: 'Exception',
constant: 'Exception' });
@@ -137,8 +137,8 @@ describe('optionals', function () {
});
it('test the append_const action for an Optional', function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument([ '-b' ], { "default": [ 'X' ],
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-b' ], { default: [ 'X' ],
action: 'appendConst',
const: 'Exception',
defaultValue: [ 'X' ],
@@ -170,10 +170,10 @@ describe('optionals', function () {
});
it('test the append action for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument(
[ '--baz' ],
- { "default": [ 'X' ], action: 'append', defaultValue: [ 'X' ] }
+ { default: [ 'X' ], action: 'append', defaultValue: [ 'X' ] }
);
args = parser.parseArgs([]);
@@ -198,7 +198,7 @@ describe('optionals', function () {
});
it('test the count action for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], { action: 'count' });
args = parser.parseArgs([]);
@@ -221,7 +221,7 @@ describe('optionals', function () {
});
it('test the store action for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], { action: 'store' });
args = parser.parseArgs([]);
@@ -238,7 +238,7 @@ describe('optionals', function () {
});
it('test the store_const action for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument(
[ '-y' ],
{ action: 'storeConst', const: 'object', constant: 'object' }
@@ -255,7 +255,7 @@ describe('optionals', function () {
});
it('test the store_false action for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-z' ], { action: 'storeFalse' });
args = parser.parseArgs([]);
@@ -275,7 +275,7 @@ describe('optionals', function () {
});
it('test the store_true action for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '--apple' ], { action: 'storeTrue' });
args = parser.parseArgs([]);
@@ -295,7 +295,7 @@ describe('optionals', function () {
});
it('test negative number args when almost numeric options are present', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'x' ], { nargs: '?' });
parser.addArgument([ '-k4' ], { action: 'storeTrue', dest: 'y' });
@@ -317,7 +317,7 @@ describe('optionals', function () {
it('test specifying the choices for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-f' ], { choices: 'abc' });
parser.addArgument([ '-g' ], { type: 'int', choices: [ 0, 1, 2, 3, 4 ] });
@@ -352,9 +352,9 @@ describe('optionals', function () {
});
it('test specifying a default for an Optional', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], {});
- parser.addArgument([ '-y' ], { "default": 42, defaultValue: 42 });
+ parser.addArgument([ '-y' ], { default: 42, defaultValue: 42 });
args = parser.parseArgs([]);
assert.deepEqual(args, { y: 42, x: null });
@@ -369,7 +369,7 @@ describe('optionals', function () {
});
it('test various means of setting destination', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '--foo-bar' ], {});
parser.addArgument([ '--baz' ], { dest: 'zabbaz' });
@@ -388,7 +388,7 @@ describe('optionals', function () {
});
it('test an Optional with a double-dash option string', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '--foo' ], {});
args = parser.parseArgs([]);
@@ -423,7 +423,7 @@ describe('optionals', function () {
});
it('tests partial matching with a double-dash option string', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '--badger' ], { action: 'storeTrue' });
parser.addArgument([ '--bat' ], {});
@@ -463,7 +463,7 @@ describe('optionals', function () {
it('test an Optional with a short opt string', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-1' ], { dest: 'one' });
args = parser.parseArgs([]);
@@ -496,7 +496,7 @@ describe('optionals', function () {
});
it('test negative number args when numeric options are present', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'x' ], { nargs: '?' });
parser.addArgument([ '-4' ], { action: 'storeTrue', dest: 'y' });
@@ -518,7 +518,7 @@ describe('optionals', function () {
});
it('tests the an optional action that is required', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], { required: true, type: 'int' });
args = parser.parseArgs([ '-x', '1' ]);
@@ -535,7 +535,7 @@ describe('optionals', function () {
});
it('test a combination of single- and double-dash option strings', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-v', '--verbose', '-n', '--noisy' ], { action: 'storeTrue' });
args = parser.parseArgs([]);
@@ -564,7 +564,7 @@ describe('optionals', function () {
});
it('test an Optional with a single-dash option string', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], {});
args = parser.parseArgs([]);
@@ -596,7 +596,7 @@ describe('optionals', function () {
});
it('test Optionals that partially match but are not subsets', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-foobar' ], {});
parser.addArgument([ '-foorab' ], {});
@@ -639,7 +639,7 @@ describe('optionals', function () {
});
it('test an Optional with a single-dash option string', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-x' ], { action: 'storeTrue' });
parser.addArgument([ '-yyy' ], { action: 'storeConst', const: 42, constant: 42 });
parser.addArgument([ '-z' ], {});
@@ -705,7 +705,7 @@ describe('optionals', function () {
});
it('test an Optional with a multi-character single-dash option string', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-foo' ], {});
args = parser.parseArgs([]);
@@ -740,7 +740,7 @@ describe('optionals', function () {
});
it('test Optionals where option strings are subsets of each other', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-f' ], {});
parser.addArgument([ '-foobar' ], {});
parser.addArgument([ '-foorab' ], {});
@@ -784,7 +784,7 @@ describe('optionals', function () {
});
it('test an Optional with single- and double-dash option strings', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '-f' ], { action: 'storeTrue' });
parser.addArgument([ '--bar' ], {});
parser.addArgument([ '-baz' ], { action: 'storeConst', const: 42, constant: 42 });
diff --git a/test/parents.js b/test/parents.js
index c46f02b..c45d190 100644
--- a/test/parents.js
+++ b/test/parents.js
@@ -12,15 +12,15 @@ describe('parents', function () {
var args;
beforeEach(function () {
- parent_parser = new ArgumentParser({debug: true, addHelp: false});
- parent_parser.addArgument(['--parent']);
+ parent_parser = new ArgumentParser({ debug: true, addHelp: false });
+ parent_parser.addArgument([ '--parent' ]);
});
- it("should parse args from parents parser", function () {
+ it('should parse args from parents parser', function () {
var parser = new ArgumentParser({
parents: [ parent_parser ]
});
- parser.addArgument(['-f', '--foo']);
+ parser.addArgument([ '-f', '--foo' ]);
args = parser.parseArgs('-f 1 --parent 2'.split(' '));
assert.equal(args.foo, 1);
@@ -31,14 +31,14 @@ describe('parents', function () {
assert.strictEqual(args.parent, null);
});
- it("should throw error if has same args as parent", function () {
+ it('should throw error if has same args as parent', function () {
var parser = new ArgumentParser({
parents: [ parent_parser ]
});
- parser.addArgument(['-f', '--foo']);
+ parser.addArgument([ '-f', '--foo' ]);
assert.throws(function () {
- parent_parser.addArgument(['--parent']);
+ parent_parser.addArgument([ '--parent' ]);
});
});
});
diff --git a/test/positionals.js b/test/positionals.js
index 0ff13fc..643f260 100644
--- a/test/positionals.js
+++ b/test/positionals.js
@@ -11,7 +11,7 @@ describe('positionals', function () {
var args;
it("test the 'append' action", function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'spam' ], { action: 'append' });
parser.addArgument([ 'spam' ], { action: 'append', nargs: 2 });
@@ -36,7 +36,7 @@ describe('positionals', function () {
});
it('test a set of integer choices', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'spam' ], {
type: 'int',
choices: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]
@@ -65,7 +65,7 @@ describe('positionals', function () {
});
it('test a set of single-character choices', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'spam' ], { choices: [ 'a', 'c', 'b', 'e', 'd', 'g', 'f' ] });
args = parser.parseArgs([ 'a' ]);
diff --git a/test/prefix.js b/test/prefix.js
index c337a65..c589094 100644
--- a/test/prefix.js
+++ b/test/prefix.js
@@ -71,6 +71,7 @@ describe('prefix', function () {
});
// http://bugs.python.org/issue9444
+ /*eslint-disable max-len*/
it('when "-" not in prefix_chars, default operators created for help should use the prefix_chars in use rather than - or --', function () {
parser = new ArgumentParser({
addHelp: true,
@@ -154,7 +155,7 @@ describe('prefix', function () {
});
it('test when one double-dash option string is a prefix of another', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ '--badger' ], { action: 'storeTrue' });
parser.addArgument([ '--ba' ], {});
@@ -196,7 +197,7 @@ describe('prefix', function () {
debug: true
});
parser.addArgument([ '-' ], { dest: 'x', const: 'badger', nargs: '?', constant: 'badger' });
- parser.addArgument([ '+' ], { "default": 42, dest: 'y', type: 'int', defaultValue: 42 });
+ parser.addArgument([ '+' ], { default: 42, dest: 'y', type: 'int', defaultValue: 42 });
parser.addArgument([ '-+-' ], { action: 'storeTrue', dest: 'z' });
args = parser.parseArgs([]);
diff --git a/test/sub_commands.js b/test/sub_commands.js
index 261f658..aeb5172 100644
--- a/test/sub_commands.js
+++ b/test/sub_commands.js
@@ -14,37 +14,37 @@ describe('sub-commands', function () {
var c2;
beforeEach(function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
var subparsers = parser.addSubparsers({
title: 'subcommands',
dest: 'subcommand_name'
});
- c1 = subparsers.addParser('c1', {aliases: ['co']});
+ 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 () {
+ 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 () {
+ 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 () {
+ 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 () {
+ it('should have different behavior for different commands', function () {
assert.doesNotThrow(function () {
parser.parseArgs('c1 --foo 5 -b4'.split(' '));
});
@@ -61,25 +61,26 @@ describe('sub-commands', function () {
it('should drop down with "Invalid choice" error if parse unrecognized command', function () {
assert.throws(
- function () {parser.parseArgs('command --baz 1'.split(' ')); },
+ 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([]); },
+ function () { parser.parseArgs([]); },
/too few arguments/
);
});
- it("should support #setDefaults", function () {
- c1.setDefaults({spam: 1});
- c2.setDefaults({eggs: 2});
- args = parser.parseArgs(['c1']);
+ it('should support #setDefaults', function () {
+ /*eslint-disable no-undefined*/
+ 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']);
+ args = parser.parseArgs([ 'c2' ]);
assert.equal(args.eggs, 2);
assert.strictEqual(args.spam, undefined);
});
diff --git a/test/suppress.js b/test/suppress.js
index 1965410..d7ac511 100644
--- a/test/suppress.js
+++ b/test/suppress.js
@@ -11,20 +11,20 @@ describe('suppress defaults', function () {
var parser;
var args;
it('test actions with suppressed defaults', function () {
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.addArgument([ 'foo' ], {
- "default": $$.SUPPRESS,
+ default: $$.SUPPRESS,
nargs: '?',
defaultValue: $$.SUPPRESS
});
parser.addArgument([ 'bar' ], {
- "default": $$.SUPPRESS,
+ default: $$.SUPPRESS,
nargs: '*',
defaultValue: $$.SUPPRESS
});
parser.addArgument([ '--baz' ], {
- "default": $$.SUPPRESS,
+ default: $$.SUPPRESS,
action: 'storeTrue',
defaultValue: $$.SUPPRESS
});
diff --git a/test/user_defined_type.js b/test/user_defined_type.js
index 8b795ac..db85fc5 100644
--- a/test/user_defined_type.js
+++ b/test/user_defined_type.js
@@ -10,61 +10,61 @@ describe('user defined type', function () {
var parser;
var args;
- it("should handle builtin types", function () {
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['--eggs'], {type: 'int'});
- parser.addArgument(['spam'], {type: 'float'});
+ it('should handle builtin types', function () {
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '--eggs' ], { type: 'int' });
+ parser.addArgument([ 'spam' ], { type: 'float' });
- args = parser.parseArgs(['--eggs=42', '42']);
- assert.deepEqual(args, {eggs: 42, spam: 42.0});
- args = parser.parseArgs(['1024.675']);
- assert.deepEqual(args, {eggs: null, spam: 1024.675});
+ args = parser.parseArgs([ '--eggs=42', '42' ]);
+ assert.deepEqual(args, { eggs: 42, spam: 42.0 });
+ args = parser.parseArgs([ '1024.675' ]);
+ assert.deepEqual(args, { eggs: null, spam: 1024.675 });
assert.throws(
- function () { parser.parseArgs(['--eggs', 'a']); },
+ function () { parser.parseArgs([ '--eggs', 'a' ]); },
/Invalid int value: a/i
);
});
- it("should handle user-defined type", function () {
+ it('should handle user-defined type', function () {
function myType(arg) {
return arg;
}
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-x'], {type: myType});
- parser.addArgument(['spam'], {type: myType});
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-x' ], { type: myType });
+ parser.addArgument([ 'spam' ], { type: myType });
- args = parser.parseArgs(['a', '-x', 'b']);
- assert.deepEqual(args, {x: myType('b'), spam: myType('a')});
- args = parser.parseArgs(['-xf', 'g']);
- assert.deepEqual(args, {x: myType('f'), spam: myType('g')});
+ args = parser.parseArgs([ 'a', '-x', 'b' ]);
+ assert.deepEqual(args, { x: myType('b'), spam: myType('a') });
+ args = parser.parseArgs([ '-xf', 'g' ]);
+ assert.deepEqual(args, { x: myType('f'), spam: myType('g') });
});
- it("should give consistent type errors", function () {
+ it('should give consistent type errors', function () {
function dateType(arg) {
var x = new Date(arg);
if (x.toString().match('Invalid')) {
- throw new TypeError("" + arg + " is not a valid date.");
+ throw new TypeError('' + arg + ' is not a valid date.');
}
return x;
}
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-i'], {type: 'int', defaultValue: 0});
- parser.addArgument(['-f'], {type: 'float', defaultValue: 0});
- parser.addArgument(['-d'], {type: dateType, defaultValue: new Date(0)});
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-i' ], { type: 'int', defaultValue: 0 });
+ parser.addArgument([ '-f' ], { type: 'float', defaultValue: 0 });
+ parser.addArgument([ '-d' ], { type: dateType, defaultValue: new Date(0) });
assert.throws(
- function () { parser.parseArgs(['-f', 'abc']); },
+ function () { parser.parseArgs([ '-f', 'abc' ]); },
/Invalid float value: abc/i
);
assert.throws(
- function () { parser.parseArgs(['-i', 'abc']); },
+ function () { parser.parseArgs([ '-i', 'abc' ]); },
/Invalid int value: abc/i
);
args = parser.parseArgs([]);
- assert.deepEqual(args, {i: 0, f: 0, d: new Date(0)});
- args = parser.parseArgs(['-d', '1/1/2012']);
- assert.deepEqual(args, {i: 0, f: 0, d: new Date('1/1/2012')});
+ assert.deepEqual(args, { i: 0, f: 0, d: new Date(0) });
+ args = parser.parseArgs([ '-d', '1/1/2012' ]);
+ assert.deepEqual(args, { i: 0, f: 0, d: new Date('1/1/2012') });
assert.throws(
- function () {parser.parseArgs(['-d', '13/1/2000']); },
+ function () { parser.parseArgs([ '-d', '13/1/2000' ]); },
/Invalid dateType value: (.*)/i
/*
it used to insert the function code rather than its name
@@ -72,45 +72,46 @@ describe('user defined type', function () {
*/
);
assert.throws(
- function () { parser.parseArgs(['-d', 'abc']); },
+ function () { parser.parseArgs([ '-d', 'abc' ]); },
/Invalid dateType value: (.*)/i
);
});
- it("test a user-defined type by registering it", function () {
+ it('test a user-defined type by registering it', function () {
function dateType(arg) {
var x = new Date(arg);
if (x.toString().match('Invalid')) {
- throw new TypeError("" + arg + " is not a valid date.");
+ throw new TypeError('' + arg + ' is not a valid date.');
}
return x;
}
- parser = new ArgumentParser({debug: true});
+ parser = new ArgumentParser({ debug: true });
parser.register('type', 'dateType', dateType);
- parser.addArgument(['-d'], {type: 'dateType'});
- args = parser.parseArgs(['-d', '1/1/2012']);
- assert.deepEqual(args, {d: new Date('1/1/2012')});
+ parser.addArgument([ '-d' ], { type: 'dateType' });
+ args = parser.parseArgs([ '-d', '1/1/2012' ]);
+ assert.deepEqual(args, { d: new Date('1/1/2012') });
assert.throws(
- function () { parser.parseArgs(['-d', '13/1/2000']); },
+ function () { parser.parseArgs([ '-d', '13/1/2000' ]); },
/Invalid dateType value: (.*)/
);
});
- it("test an anonymous user-defined type", function () {
+ it('test an anonymous user-defined type', function () {
+ /*eslint-disable func-style*/
var dateType = function (arg) {
var x = new Date(arg);
if (x.toString().match('Invalid')) {
- throw new TypeError("" + arg + " is not a valid date.");
+ throw new TypeError('' + arg + ' is not a valid date.');
}
return x;
};
//dateType.displayName = 'dateType';
- parser = new ArgumentParser({debug: true});
- parser.addArgument(['-d'], {type: dateType});
- args = parser.parseArgs(['-d', '1/1/2012']);
- assert.deepEqual(args, {d: new Date('1/1/2012')});
+ parser = new ArgumentParser({ debug: true });
+ parser.addArgument([ '-d' ], { type: dateType });
+ args = parser.parseArgs([ '-d', '1/1/2012' ]);
+ assert.deepEqual(args, { d: new Date('1/1/2012') });
assert.throws(
- function () { parser.parseArgs(['-d', 'abc']); },
+ function () { parser.parseArgs([ '-d', 'abc' ]); },
/Invalid <function> value: abc\nabc is not a valid date/im
);
});
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-argparse.git
More information about the Pkg-javascript-commits
mailing list