util: add parseArgs module

Adds util.parseArgs helper for higher level command-line argument
parsing.

PR-URL: https://github.com/nodejs/node/pull/42675
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Ruy Adorno <ruyadorno@github.com>
Reviewed-By: Darshan Sen <raisinten@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Joe Sepi <sepi@joesepi.com>
Reviewed-By: Ian Sutherland <ian@iansutherland.ca>
This commit is contained in:
Benjamin E. Coe authored and Michaël Zasso committed 2022-07-31 15:27:46 +02:00
1 parent a6d4d31da5
commit a1e122be62
9 files changed
+1190 -1

No files matched your search

+35
View File
@@ -2334,6 +2334,40 @@ The `package.json` [`"exports"`][] field does not export the requested subpath.
Because exports are encapsulated, private internal modules that are not exported
cannot be imported through the package resolution, unless using an absolute URL.
<a id="ERR_PARSE_ARGS_INVALID_OPTION_VALUE"></a>
### `ERR_PARSE_ARGS_INVALID_OPTION_VALUE`
<!-- YAML
added: REPLACEME
-->
When `strict` set to `true`, thrown by [`util.parseArgs()`][] if a {boolean}
value is provided for an option of type {string}, or if a {string}
value is provided for an option of type {boolean}.
<a id="ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL"></a>
### `ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL`
<!-- YAML
added: REPLACEME
-->
Thrown by [`util.parseArgs()`][], when a postional argument is provided and
`allowPositionals` is set to `false`.
<a id="ERR_PARSE_ARGS_UNKNOWN_OPTION"></a>
### `ERR_PARSE_ARGS_UNKNOWN_OPTION`
<!-- YAML
added: REPLACEME
-->
When `strict` set to `true`, thrown by [`util.parseArgs()`][] if an argument
is not configured in `options`.
<a id="ERR_PERFORMANCE_INVALID_TIMESTAMP"></a>
### `ERR_PERFORMANCE_INVALID_TIMESTAMP`
@@ -3425,6 +3459,7 @@ The native call from `process.cpuUsage` could not be processed.
[`subprocess.kill()`]: child_process.md#subprocesskillsignal
[`subprocess.send()`]: child_process.md#subprocesssendmessage-sendhandle-options-callback
[`util.getSystemErrorName(error.errno)`]: util.md#utilgetsystemerrornameerr
[`util.parseArgs()`]: util.md#utilparseargsconfig
[`zlib`]: zlib.md
[crypto digest algorithm]: crypto.md#cryptogethashes
[debugger]: debugger.md
+81
View File
@@ -1014,6 +1014,86 @@ Otherwise, returns `false`.
See [`assert.deepStrictEqual()`][] for more information about deep strict
equality.
## `util.parseArgs([config])`
<!-- YAML
added: REPLACEME
-->
> Stability: 1 - Experimental
* `config` {Object} Used to provide arguments for parsing and to configure
the parser. `config` supports the following properties:
* `args` {string\[]} array of argument strings. **Default:** `process.argv`
with `execPath` and `filename` removed.
* `options` {Object} Used to describe arguments known to the parser.
Keys of `options` are the long names of options and values are an
{Object} accepting the following properties:
* `type` {string} Type of argument, which must be either `boolean` or `string`.
* `multiple` {boolean} Whether this option can be provided multiple
times. If `true`, all values will be collected in an array. If
`false`, values for the option are last-wins. **Default:** `false`.
* `short` {string} A single character alias for the option.
* `strict`: {boolean} Should an error be thrown when unknown arguments
are encountered, or when arguments are passed that do not match the
`type` configured in `options`.
**Default:** `true`.
* `allowPositionals`: {boolean} Whether this command accepts positional
arguments.
**Default:** `false` if `strict` is `true`, otherwise `true`.
* Returns: {Object} The parsed command line arguments:
* `values` {Object} A mapping of parsed option names with their {string}
or {boolean} values.
* `positionals` {string\[]} Positional arguments.
Provides a higher level API for command-line argument parsing than interacting
with `process.argv` directly. Takes a specification for the expected arguments
and returns a structured object with the parsed options and positionals.
```mjs
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f'
},
bar: {
type: 'string'
}
};
const {
values,
positionals
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
```
```cjs
const { parseArgs } = require('node:util');
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f'
},
bar: {
type: 'string'
}
};
const {
values,
positionals
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []ss
```
`util.parseArgs` is experimental and behavior may change. Join the
conversation in [pkgjs/parseargs][] to contribute to the design.
## `util.promisify(original)`
<!-- YAML
@@ -2685,5 +2765,6 @@ util.log('Timestamped message.');
[default sort]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
[global symbol registry]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for
[list of deprecated APIS]: deprecations.md#list-of-deprecated-apis
[pkgjs/parseargs]: https://github.com/pkgjs/parseargs
[semantically incompatible]: https://github.com/nodejs/node/issues/4179
[util.inspect.custom]: #utilinspectcustom
+9
View File
@@ -1496,6 +1496,15 @@ E('ERR_PACKAGE_PATH_NOT_EXPORTED', (pkgPath, subpath, base = undefined) => {
return `Package subpath '${subpath}' is not defined by "exports" in ${
pkgPath}package.json${base ? ` imported from ${base}` : ''}`;
}, Error);
E('ERR_PARSE_ARGS_INVALID_OPTION_VALUE', '%s', TypeError);
E('ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL', "Unexpected argument '%s'. This " +
'command does not take positional arguments', TypeError);
E('ERR_PARSE_ARGS_UNKNOWN_OPTION', (option, allowPositionals) => {
const suggestDashDash = allowPositionals ? '. To specify a positional ' +
"argument starting with a '-', place it at the end of the command after " +
`'--', as in '-- ${JSONStringify(option)}` : '';
return `Unknown option '${option}'${suggestDashDash}`;
}, TypeError);
E('ERR_PERFORMANCE_INVALID_TIMESTAMP',
'%d is not a valid timestamp', TypeError);
E('ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS', '%s', TypeError);
+297
View File
@@ -0,0 +1,297 @@
'use strict';
const {
ArrayPrototypeForEach,
ArrayPrototypeIncludes,
ArrayPrototypePushApply,
ArrayPrototypeShift,
ArrayPrototypeSlice,
ArrayPrototypePush,
ArrayPrototypeUnshiftApply,
ObjectPrototypeHasOwnProperty: ObjectHasOwn,
ObjectEntries,
StringPrototypeCharAt,
StringPrototypeIndexOf,
StringPrototypeSlice,
} = primordials;
const {
validateArray,
validateBoolean,
validateObject,
validateString,
validateUnion,
} = require('internal/validators');
const {
findLongOptionForShort,
isLoneLongOption,
isLoneShortOption,
isLongOptionAndValue,
isOptionValue,
isOptionLikeValue,
isShortOptionAndValue,
isShortOptionGroup,
objectGetOwn,
optionsGetOwn,
} = require('internal/util/parse_args/utils');
const {
codes: {
ERR_INVALID_ARG_VALUE,
ERR_PARSE_ARGS_INVALID_OPTION_VALUE,
ERR_PARSE_ARGS_UNKNOWN_OPTION,
ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL,
},
} = require('internal/errors');
function getMainArgs() {
// Work out where to slice process.argv for user supplied arguments.
// Check node options for scenarios where user CLI args follow executable.
const execArgv = process.execArgv;
if (ArrayPrototypeIncludes(execArgv, '-e') ||
ArrayPrototypeIncludes(execArgv, '--eval') ||
ArrayPrototypeIncludes(execArgv, '-p') ||
ArrayPrototypeIncludes(execArgv, '--print')) {
return ArrayPrototypeSlice(process.argv, 1);
}
// Normally first two arguments are executable and script, then CLI arguments
return ArrayPrototypeSlice(process.argv, 2);
}
/**
* In strict mode, throw for possible usage errors like --foo --bar
*
* @param {string} longOption - long option name e.g. 'foo'
* @param {string|undefined} optionValue - value from user args
* @param {string} shortOrLong - option used, with dashes e.g. `-l` or `--long`
* @param {boolean} strict - show errors, from parseArgs({ strict })
*/
function checkOptionLikeValue(longOption, optionValue, shortOrLong, strict) {
if (strict && isOptionLikeValue(optionValue)) {
// Only show short example if user used short option.
const example = (shortOrLong.length === 2) ?
`'--${longOption}=-XYZ' or '${shortOrLong}-XYZ'` :
`'--${longOption}=-XYZ'`;
const errorMessage = `Option '${shortOrLong}' argument is ambiguous.
Did you forget to specify the option argument for '${shortOrLong}'?
To specify an option argument starting with a dash use ${example}.`;
throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(errorMessage);
}
}
/**
* In strict mode, throw for usage errors.
*
* @param {string} longOption - long option name e.g. 'foo'
* @param {string|undefined} optionValue - value from user args
* @param {object} options - option configs, from parseArgs({ options })
* @param {string} shortOrLong - option used, with dashes e.g. `-l` or `--long`
* @param {boolean} strict - show errors, from parseArgs({ strict })
* @param {boolean} allowPositionals - from parseArgs({ allowPositionals })
*/
function checkOptionUsage(longOption, optionValue, options,
shortOrLong, strict, allowPositionals) {
// Strict and options are used from local context.
if (!strict) return;
if (!ObjectHasOwn(options, longOption)) {
throw new ERR_PARSE_ARGS_UNKNOWN_OPTION(shortOrLong, allowPositionals);
}
const short = optionsGetOwn(options, longOption, 'short');
const shortAndLong = short ? `-${short}, --${longOption}` : `--${longOption}`;
const type = optionsGetOwn(options, longOption, 'type');
if (type === 'string' && typeof optionValue !== 'string') {
throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong} <value>' argument missing`);
}
// (Idiomatic test for undefined||null, expecting undefined.)
if (type === 'boolean' && optionValue != null) {
throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong}' does not take an argument`);
}
}
/**
* Store the option value in `values`.
*
* @param {string} longOption - long option name e.g. 'foo'
* @param {string|undefined} optionValue - value from user args
* @param {object} options - option configs, from parseArgs({ options })
* @param {object} values - option values returned in `values` by parseArgs
*/
function storeOption(longOption, optionValue, options, values) {
if (longOption === '__proto__') {
return; // No. Just no.
}
// We store based on the option value rather than option type,
// preserving the users intent for author to deal with.
const newValue = optionValue ?? true;
if (optionsGetOwn(options, longOption, 'multiple')) {
// Always store value in array, including for boolean.
// values[longOption] starts out not present,
// first value is added as new array [newValue],
// subsequent values are pushed to existing array.
// (note: values has null prototype, so simpler usage)
if (values[longOption]) {
ArrayPrototypePush(values[longOption], newValue);
} else {
values[longOption] = [newValue];
}
} else {
values[longOption] = newValue;
}
}
const parseArgs = (config = { __proto__: null }) => {
const args = objectGetOwn(config, 'args') ?? getMainArgs();
const strict = objectGetOwn(config, 'strict') ?? true;
const allowPositionals = objectGetOwn(config, 'allowPositionals') ?? !strict;
const options = objectGetOwn(config, 'options') ?? { __proto__: null };
// Validate input configuration.
validateArray(args, 'args');
validateBoolean(strict, 'strict');
validateBoolean(allowPositionals, 'allowPositionals');
validateObject(options, 'options');
ArrayPrototypeForEach(
ObjectEntries(options),
({ 0: longOption, 1: optionConfig }) => {
validateObject(optionConfig, `options.${longOption}`);
// type is required
validateUnion(objectGetOwn(optionConfig, 'type'), `options.${longOption}.type`, ['string', 'boolean']);
if (ObjectHasOwn(optionConfig, 'short')) {
const shortOption = optionConfig.short;
validateString(shortOption, `options.${longOption}.short`);
if (shortOption.length !== 1) {
throw new ERR_INVALID_ARG_VALUE(
`options.${longOption}.short`,
shortOption,
'must be a single character'
);
}
}
if (ObjectHasOwn(optionConfig, 'multiple')) {
validateBoolean(optionConfig.multiple, `options.${longOption}.multiple`);
}
}
);
const result = {
values: { __proto__: null },
positionals: []
};
const remainingArgs = ArrayPrototypeSlice(args);
while (remainingArgs.length > 0) {
const arg = ArrayPrototypeShift(remainingArgs);
const nextArg = remainingArgs[0];
// Check if `arg` is an options terminator.
// Guideline 10 in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
if (arg === '--') {
if (!allowPositionals && remainingArgs.length > 0) {
throw new ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(nextArg);
}
// Everything after a bare '--' is considered a positional argument.
ArrayPrototypePushApply(
result.positionals,
remainingArgs
);
break; // Finished processing args, leave while loop.
}
if (isLoneShortOption(arg)) {
// e.g. '-f'
const shortOption = StringPrototypeCharAt(arg, 1);
const longOption = findLongOptionForShort(shortOption, options);
let optionValue;
if (optionsGetOwn(options, longOption, 'type') === 'string' &&
isOptionValue(nextArg)) {
// e.g. '-f', 'bar'
optionValue = ArrayPrototypeShift(remainingArgs);
checkOptionLikeValue(longOption, optionValue, arg, strict);
}
checkOptionUsage(longOption, optionValue, options,
arg, strict, allowPositionals);
storeOption(longOption, optionValue, options, result.values);
continue;
}
if (isShortOptionGroup(arg, options)) {
// Expand -fXzy to -f -X -z -y
const expanded = [];
for (let index = 1; index < arg.length; index++) {
const shortOption = StringPrototypeCharAt(arg, index);
const longOption = findLongOptionForShort(shortOption, options);
if (optionsGetOwn(options, longOption, 'type') !== 'string' ||
index === arg.length - 1) {
// Boolean option, or last short in group. Well formed.
ArrayPrototypePush(expanded, `-${shortOption}`);
} else {
// String option in middle. Yuck.
// Expand -abfFILE to -a -b -fFILE
ArrayPrototypePush(expanded, `-${StringPrototypeSlice(arg, index)}`);
break; // finished short group
}
}
ArrayPrototypeUnshiftApply(remainingArgs, expanded);
continue;
}
if (isShortOptionAndValue(arg, options)) {
// e.g. -fFILE
const shortOption = StringPrototypeCharAt(arg, 1);
const longOption = findLongOptionForShort(shortOption, options);
const optionValue = StringPrototypeSlice(arg, 2);
checkOptionUsage(longOption, optionValue, options, `-${shortOption}`, strict, allowPositionals);
storeOption(longOption, optionValue, options, result.values);
continue;
}
if (isLoneLongOption(arg)) {
// e.g. '--foo'
const longOption = StringPrototypeSlice(arg, 2);
let optionValue;
if (optionsGetOwn(options, longOption, 'type') === 'string' &&
isOptionValue(nextArg)) {
// e.g. '--foo', 'bar'
optionValue = ArrayPrototypeShift(remainingArgs);
checkOptionLikeValue(longOption, optionValue, arg, strict);
}
checkOptionUsage(longOption, optionValue, options,
arg, strict, allowPositionals);
storeOption(longOption, optionValue, options, result.values);
continue;
}
if (isLongOptionAndValue(arg)) {
// e.g. --foo=bar
const index = StringPrototypeIndexOf(arg, '=');
const longOption = StringPrototypeSlice(arg, 2, index);
const optionValue = StringPrototypeSlice(arg, index + 1);
checkOptionUsage(longOption, optionValue, options, `--${longOption}`, strict, allowPositionals);
storeOption(longOption, optionValue, options, result.values);
continue;
}
// Anything left is a positional
if (!allowPositionals) {
throw new ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(arg);
}
ArrayPrototypePush(result.positionals, arg);
}
return result;
};
module.exports = {
parseArgs,
};
+184
View File
@@ -0,0 +1,184 @@
'use strict';
const {
ArrayPrototypeFind,
ObjectEntries,
ObjectPrototypeHasOwnProperty: ObjectHasOwn,
StringPrototypeCharAt,
StringPrototypeIncludes,
StringPrototypeStartsWith,
} = primordials;
const {
validateObject,
} = require('internal/validators');
// These are internal utilities to make the parsing logic easier to read, and
// add lots of detail for the curious. They are in a separate file to allow
// unit testing, although that is not essential (this could be rolled into
// main file and just tested implicitly via API).
//
// These routines are for internal use, not for export to client.
/**
* Return the named property, but only if it is an own property.
*/
function objectGetOwn(obj, prop) {
if (ObjectHasOwn(obj, prop))
return obj[prop];
}
/**
* Return the named options property, but only if it is an own property.
*/
function optionsGetOwn(options, longOption, prop) {
if (ObjectHasOwn(options, longOption))
return objectGetOwn(options[longOption], prop);
}
/**
* Determines if the argument may be used as an option value.
* @example
* isOptionValue('V') // returns true
* isOptionValue('-v') // returns true (greedy)
* isOptionValue('--foo') // returns true (greedy)
* isOptionValue(undefined) // returns false
*/
function isOptionValue(value) {
if (value == null) return false;
// Open Group Utility Conventions are that an option-argument
// is the argument after the option, and may start with a dash.
return true; // greedy!
}
/**
* Detect whether there is possible confusion and user may have omitted
* the option argument, like `--port --verbose` when `port` of type:string.
* In strict mode we throw errors if value is option-like.
*/
function isOptionLikeValue(value) {
if (value == null) return false;
return value.length > 1 && StringPrototypeCharAt(value, 0) === '-';
}
/**
* Determines if `arg` is just a short option.
* @example '-f'
*/
function isLoneShortOption(arg) {
return arg.length === 2 &&
StringPrototypeCharAt(arg, 0) === '-' &&
StringPrototypeCharAt(arg, 1) !== '-';
}
/**
* Determines if `arg` is a lone long option.
* @example
* isLoneLongOption('a') // returns false
* isLoneLongOption('-a') // returns false
* isLoneLongOption('--foo') // returns true
* isLoneLongOption('--foo=bar') // returns false
*/
function isLoneLongOption(arg) {
return arg.length > 2 &&
StringPrototypeStartsWith(arg, '--') &&
!StringPrototypeIncludes(arg, '=', 3);
}
/**
* Determines if `arg` is a long option and value in the same argument.
* @example
* isLongOptionAndValue('--foo') // returns false
* isLongOptionAndValue('--foo=bar') // returns true
*/
function isLongOptionAndValue(arg) {
return arg.length > 2 &&
StringPrototypeStartsWith(arg, '--') &&
StringPrototypeIncludes(arg, '=', 3);
}
/**
* Determines if `arg` is a short option group.
*
* See Guideline 5 of the [Open Group Utility Conventions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html).
* One or more options without option-arguments, followed by at most one
* option that takes an option-argument, should be accepted when grouped
* behind one '-' delimiter.
* @example
* isShortOptionGroup('-a', {}) // returns false
* isShortOptionGroup('-ab', {}) // returns true
* // -fb is an option and a value, not a short option group
* isShortOptionGroup('-fb', {
* options: { f: { type: 'string' } }
* }) // returns false
* isShortOptionGroup('-bf', {
* options: { f: { type: 'string' } }
* }) // returns true
* // -bfb is an edge case, return true and caller sorts it out
* isShortOptionGroup('-bfb', {
* options: { f: { type: 'string' } }
* }) // returns true
*/
function isShortOptionGroup(arg, options) {
if (arg.length <= 2) return false;
if (StringPrototypeCharAt(arg, 0) !== '-') return false;
if (StringPrototypeCharAt(arg, 1) === '-') return false;
const firstShort = StringPrototypeCharAt(arg, 1);
const longOption = findLongOptionForShort(firstShort, options);
return optionsGetOwn(options, longOption, 'type') !== 'string';
}
/**
* Determine if arg is a short string option followed by its value.
* @example
* isShortOptionAndValue('-a', {}); // returns false
* isShortOptionAndValue('-ab', {}); // returns false
* isShortOptionAndValue('-fFILE', {
* options: { foo: { short: 'f', type: 'string' }}
* }) // returns true
*/
function isShortOptionAndValue(arg, options) {
validateObject(options, 'options');
if (arg.length <= 2) return false;
if (StringPrototypeCharAt(arg, 0) !== '-') return false;
if (StringPrototypeCharAt(arg, 1) === '-') return false;
const shortOption = StringPrototypeCharAt(arg, 1);
const longOption = findLongOptionForShort(shortOption, options);
return optionsGetOwn(options, longOption, 'type') === 'string';
}
/**
* Find the long option associated with a short option. Looks for a configured
* `short` and returns the short option itself if a long option is not found.
* @example
* findLongOptionForShort('a', {}) // returns 'a'
* findLongOptionForShort('b', {
* options: { bar: { short: 'b' } }
* }) // returns 'bar'
*/
function findLongOptionForShort(shortOption, options) {
validateObject(options, 'options');
const longOptionEntry = ArrayPrototypeFind(
ObjectEntries(options),
({ 1: optionConfig }) => objectGetOwn(optionConfig, 'short') === shortOption
);
return longOptionEntry?.[0] ?? shortOption;
}
module.exports = {
findLongOptionForShort,
isLoneLongOption,
isLoneShortOption,
isLongOptionAndValue,
isOptionValue,
isOptionLikeValue,
isShortOptionAndValue,
isShortOptionGroup,
objectGetOwn,
optionsGetOwn,
};
+8 -1
View File
@@ -248,6 +248,12 @@ const validateUndefined = hideStackFrames((value, name) => {
throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value);
});
function validateUnion(value, name, union) {
if (!ArrayPrototypeIncludes(union, value)) {
throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value);
}
}
module.exports = {
isInt32,
isUint32,
@@ -255,6 +261,7 @@ module.exports = {
validateArray,
validateBoolean,
validateBuffer,
validateCallback,
validateEncoding,
validateFunction,
validateInt32,
@@ -268,6 +275,6 @@ module.exports = {
validateString,
validateUint32,
validateUndefined,
validateCallback,
validateUnion,
validateAbortSignal,
};
+2
View File
@@ -61,6 +61,7 @@ const {
stripVTControlCharacters,
} = require('internal/util/inspect');
const { debuglog } = require('internal/util/debuglog');
const { parseArgs } = require('internal/util/parse_args/parse_args');
const {
validateFunction,
validateNumber,
@@ -370,6 +371,7 @@ module.exports = {
isFunction,
isPrimitive,
log,
parseArgs,
promisify,
stripVTControlCharacters,
toUSVString,
+2
View File
@@ -135,6 +135,8 @@ const expectedModules = new Set([
'NativeModule internal/util/debuglog',
'NativeModule internal/util/inspect',
'NativeModule internal/util/iterable_weak_map',
'NativeModule internal/util/parse_args/utils',
'NativeModule internal/util/parse_args/parse_args',
'NativeModule internal/util/types',
'NativeModule internal/validators',
'NativeModule internal/vm/module',
+572
View File
@@ -0,0 +1,572 @@
import '../common/index.mjs';
import assert from 'node:assert';
import { test } from 'node:test';
import { parseArgs } from 'node:util';
test('when short option used as flag then stored as flag', () => {
const args = ['-f'];
const expected = { values: { __proto__: null, f: true }, positionals: [] };
const result = parseArgs({ strict: false, args });
assert.deepStrictEqual(result, expected);
});
test('when short option used as flag before positional then stored as flag and positional (and not value)', () => {
const args = ['-f', 'bar'];
const expected = { values: { __proto__: null, f: true }, positionals: [ 'bar' ] };
const result = parseArgs({ strict: false, args });
assert.deepStrictEqual(result, expected);
});
test('when short option `type: "string"` used with value then stored as value', () => {
const args = ['-f', 'bar'];
const options = { f: { type: 'string' } };
const expected = { values: { __proto__: null, f: 'bar' }, positionals: [] };
const result = parseArgs({ args, options });
assert.deepStrictEqual(result, expected);
});
test('when short option listed in short used as flag then long option stored as flag', () => {
const args = ['-f'];
const options = { foo: { short: 'f', type: 'boolean' } };
const expected = { values: { __proto__: null, foo: true }, positionals: [] };
const result = parseArgs({ args, options });
assert.deepStrictEqual(result, expected);
});
test('when short option listed in short and long listed in `type: "string"` and ' +
'used with value then long option stored as value', () => {
const args = ['-f', 'bar'];
const options = { foo: { short: 'f', type: 'string' } };
const expected = { values: { __proto__: null, foo: 'bar' }, positionals: [] };
const result = parseArgs({ args, options });
assert.deepStrictEqual(result, expected);
});
test('when short option `type: "string"` used without value then stored as flag', () => {
const args = ['-f'];
const options = { f: { type: 'string' } };
const expected = { values: { __proto__: null, f: true }, positionals: [] };
const result = parseArgs({ strict: false, args, options });
assert.deepStrictEqual(result, expected);
});
test('short option group behaves like multiple short options', () => {
const args = ['-rf'];
const options = { };
const expected = { values: { __proto__: null, r: true, f: true }, positionals: [] };
const result = parseArgs({ strict: false, args, options });
assert.deepStrictEqual(result, expected);
});
test('short option group does not consume subsequent positional', () => {
const args = ['-rf', 'foo'];
const options = { };
const expected = { values: { __proto__: null, r: true, f: true }, positionals: ['foo'] };
const result = parseArgs({ strict: false, args, options });
assert.deepStrictEqual(result, expected);
});
// See: Guideline 5 https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
test('if terminal of short-option group configured `type: "string"`, subsequent positional is stored', () => {
const args = ['-rvf', 'foo'];
const options = { f: { type: 'string' } };
const expected = { values: { __proto__: null, r: true, v: true, f: 'foo' }, positionals: [] };
const result = parseArgs({ strict: false, args, options });
assert.deepStrictEqual(result, expected);
});
test('handles short-option groups in conjunction with long-options', () => {
const args = ['-rf', '--foo', 'foo'];
const options = { foo: { type: 'string' } };
const expected = { values: { __proto__: null, r: true, f: true, foo: 'foo' }, positionals: [] };
const result = parseArgs({ strict: false, args, options });
assert.deepStrictEqual(result, expected);
});
test('handles short-option groups with "short" alias configured', () => {
const args = ['-rf'];
const options = { remove: { short: 'r', type: 'boolean' } };
const expected = { values: { __proto__: null, remove: true, f: true }, positionals: [] };
const result = parseArgs({ strict: false, args, options });
assert.deepStrictEqual(result, expected);
});
test('Everything after a bare `--` is considered a positional argument', () => {
const args = ['--', 'barepositionals', 'mopositionals'];
const expected = { values: { __proto__: null }, positionals: ['barepositionals', 'mopositionals'] };
const result = parseArgs({ allowPositionals: true, args });
assert.deepStrictEqual(result, expected, Error('testing bare positionals'));
});
test('args are true', () => {
const args = ['--foo', '--bar'];
const expected = { values: { __proto__: null, foo: true, bar: true }, positionals: [] };
const result = parseArgs({ strict: false, args });
assert.deepStrictEqual(result, expected, Error('args are true'));
});
test('arg is true and positional is identified', () => {
const args = ['--foo=a', '--foo', 'b'];
const expected = { values: { __proto__: null, foo: true }, positionals: ['b'] };
const result = parseArgs({ strict: false, args });
assert.deepStrictEqual(result, expected, Error('arg is true and positional is identified'));
});
test('args equals are passed `type: "string"`', () => {
const args = ['--so=wat'];
const options = { so: { type: 'string' } };
const expected = { values: { __proto__: null, so: 'wat' }, positionals: [] };
const result = parseArgs({ args, options });
assert.deepStrictEqual(result, expected, Error('arg value is passed'));
});
test('when args include single dash then result stores dash as positional', () => {
const args = ['-'];
const expected = { values: { __proto__: null }, positionals: ['-'] };
const result = parseArgs({ allowPositionals: true, args });
assert.deepStrictEqual(result, expected);
});
test('zero config args equals are parsed as if `type: "string"`', () => {
const args = ['--so=wat'];
const options = { };
const expected = { values: { __proto__: null, so: 'wat' }, positionals: [] };
const result = parseArgs({ strict: false, args, options });
assert.deepStrictEqual(result, expected, Error('arg value is passed'));
});
test('same arg is passed twice `type: "string"` and last value is recorded', () => {
const args = ['--foo=a', '--foo', 'b'];
const options = { foo: { type: 'string' } };
const expected = { values: { __proto__: null, foo: 'b' }, positionals: [] };
const result = parseArgs({ args, options });
assert.deepStrictEqual(result, expected, Error('last arg value is passed'));
});
test('args equals pass string including more equals', () => {
const args = ['--so=wat=bing'];
const options = { so: { type: 'string' } };
const expected = { values: { __proto__: null, so: 'wat=bing' }, positionals: [] };
const result = parseArgs({ args, options });
assert.deepStrictEqual(result, expected, Error('arg value is passed'));
});
test('first arg passed for `type: "string"` and "multiple" is in array', () => {
const args = ['--foo=a'];
const options = { foo: { type: 'string', multiple: true } };
const expected = { values: { __proto__: null, foo: ['a'] }, positionals: [] };
const result = parseArgs({ args, options });
assert.deepStrictEqual(result, expected, Error('first multiple in array'));
});
test('args are passed `type: "string"` and "multiple"', () => {
const args = ['--foo=a', '--foo', 'b'];
const options = {
foo: {
type: 'string',
multiple: true,
},
};
const expected = { values: { __proto__: null, foo: ['a', 'b'] }, positionals: [] };
const result = parseArgs({ args, options });
assert.deepStrictEqual(result, expected, Error('both arg values are passed'));
});
test('when expecting `multiple:true` boolean option and option used multiple times then result includes array of ' +
'booleans matching usage', () => {
const args = ['--foo', '--foo'];
const options = {
foo: {
type: 'boolean',
multiple: true,
},
};
const expected = { values: { __proto__: null, foo: [true, true] }, positionals: [] };
const result = parseArgs({ args, options });
assert.deepStrictEqual(result, expected);
});
test('order of option and positional does not matter (per README)', () => {
const args1 = ['--foo=bar', 'baz'];
const args2 = ['baz', '--foo=bar'];
const options = { foo: { type: 'string' } };
const expected = { values: { __proto__: null, foo: 'bar' }, positionals: ['baz'] };
assert.deepStrictEqual(
parseArgs({ allowPositionals: true, args: args1, options }),
expected,
Error('option then positional')
);
assert.deepStrictEqual(
parseArgs({ allowPositionals: true, args: args2, options }),
expected,
Error('positional then option')
);
});
test('correct default args when use node -p', () => {
const holdArgv = process.argv;
process.argv = [process.argv0, '--foo'];
const holdExecArgv = process.execArgv;
process.execArgv = ['-p', '0'];
const result = parseArgs({ strict: false });
const expected = { values: { __proto__: null, foo: true },
positionals: [] };
assert.deepStrictEqual(result, expected);
process.argv = holdArgv;
process.execArgv = holdExecArgv;
});
test('correct default args when use node --print', () => {
const holdArgv = process.argv;
process.argv = [process.argv0, '--foo'];
const holdExecArgv = process.execArgv;
process.execArgv = ['--print', '0'];
const result = parseArgs({ strict: false });
const expected = { values: { __proto__: null, foo: true },
positionals: [] };
assert.deepStrictEqual(result, expected);
process.argv = holdArgv;
process.execArgv = holdExecArgv;
});
test('correct default args when use node -e', () => {
const holdArgv = process.argv;
process.argv = [process.argv0, '--foo'];
const holdExecArgv = process.execArgv;
process.execArgv = ['-e', '0'];
const result = parseArgs({ strict: false });
const expected = { values: { __proto__: null, foo: true },
positionals: [] };
assert.deepStrictEqual(result, expected);
process.argv = holdArgv;
process.execArgv = holdExecArgv;
});
test('correct default args when use node --eval', () => {
const holdArgv = process.argv;
process.argv = [process.argv0, '--foo'];
const holdExecArgv = process.execArgv;
process.execArgv = ['--eval', '0'];
const result = parseArgs({ strict: false });
const expected = { values: { __proto__: null, foo: true },
positionals: [] };
assert.deepStrictEqual(result, expected);
process.argv = holdArgv;
process.execArgv = holdExecArgv;
});
test('correct default args when normal arguments', () => {
const holdArgv = process.argv;
process.argv = [process.argv0, 'script.js', '--foo'];
const holdExecArgv = process.execArgv;
process.execArgv = [];
const result = parseArgs({ strict: false });
const expected = { values: { __proto__: null, foo: true },
positionals: [] };
assert.deepStrictEqual(result, expected);
process.argv = holdArgv;
process.execArgv = holdExecArgv;
});
test('excess leading dashes on options are retained', () => {
// Enforce a design decision for an edge case.
const args = ['---triple'];
const options = { };
const expected = {
values: { '__proto__': null, '-triple': true },
positionals: []
};
const result = parseArgs({ strict: false, args, options });
assert.deepStrictEqual(result, expected, Error('excess option dashes are retained'));
});
test('positional arguments are allowed by default in strict:false', () => {
const args = ['foo'];
const options = { };
const expected = {
values: { __proto__: null },
positionals: ['foo']
};
const result = parseArgs({ strict: false, args, options });
assert.deepStrictEqual(result, expected);
});
test('positional arguments may be explicitly disallowed in strict:false', () => {
const args = ['foo'];
const options = { };
assert.throws(() => { parseArgs({ strict: false, allowPositionals: false, args, options }); }, {
code: 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL'
});
});
// Test bad inputs
test('invalid argument passed for options', () => {
const args = ['--so=wat'];
const options = 'bad value';
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_INVALID_ARG_TYPE'
});
});
test('type property missing for option then throw', () => {
const knownOptions = { foo: { } };
assert.throws(() => { parseArgs({ options: knownOptions }); }, {
code: 'ERR_INVALID_ARG_TYPE'
});
});
test('boolean passed to "type" option', () => {
const args = ['--so=wat'];
const options = { foo: { type: true } };
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_INVALID_ARG_TYPE'
});
});
test('invalid union value passed to "type" option', () => {
const args = ['--so=wat'];
const options = { foo: { type: 'str' } };
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_INVALID_ARG_TYPE'
});
});
// Test strict mode
test('unknown long option --bar', () => {
const args = ['--foo', '--bar'];
const options = { foo: { type: 'boolean' } };
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_PARSE_ARGS_UNKNOWN_OPTION'
});
});
test('unknown short option -b', () => {
const args = ['--foo', '-b'];
const options = { foo: { type: 'boolean' } };
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_PARSE_ARGS_UNKNOWN_OPTION'
});
});
test('unknown option -r in short option group -bar', () => {
const args = ['-bar'];
const options = { b: { type: 'boolean' }, a: { type: 'boolean' } };
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_PARSE_ARGS_UNKNOWN_OPTION'
});
});
test('unknown option with explicit value', () => {
const args = ['--foo', '--bar=baz'];
const options = { foo: { type: 'boolean' } };
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_PARSE_ARGS_UNKNOWN_OPTION'
});
});
test('unexpected positional', () => {
const args = ['foo'];
const options = { foo: { type: 'boolean' } };
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL'
});
});
test('unexpected positional after --', () => {
const args = ['--', 'foo'];
const options = { foo: { type: 'boolean' } };
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL'
});
});
test('-- by itself is not a positional', () => {
const args = ['--foo', '--'];
const options = { foo: { type: 'boolean' } };
const result = parseArgs({ args, options });
const expected = { values: { __proto__: null, foo: true },
positionals: [] };
assert.deepStrictEqual(result, expected);
});
test('string option used as boolean', () => {
const args = ['--foo'];
const options = { foo: { type: 'string' } };
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'
});
});
test('boolean option used with value', () => {
const args = ['--foo=bar'];
const options = { foo: { type: 'boolean' } };
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'
});
});
test('invalid short option length', () => {
const args = [];
const options = { foo: { short: 'fo', type: 'boolean' } };
assert.throws(() => { parseArgs({ args, options }); }, {
code: 'ERR_INVALID_ARG_VALUE'
});
});
test('null prototype: when no options then values.toString is undefined', () => {
const result = parseArgs({ args: [] });
assert.strictEqual(result.values.toString, undefined);
});
test('null prototype: when --toString then values.toString is true', () => {
const args = ['--toString'];
const options = { toString: { type: 'boolean' } };
const expectedResult = { values: { __proto__: null, toString: true }, positionals: [] };
const result = parseArgs({ args, options });
assert.deepStrictEqual(result, expectedResult);
});
const candidateGreedyOptions = [
'',
'-',
'--',
'abc',
'123',
'-s',
'--foo',
];
candidateGreedyOptions.forEach((value) => {
test(`greedy: when short option with value '${value}' then eaten`, () => {
const args = ['-w', value];
const options = { with: { type: 'string', short: 'w' } };
const expectedResult = { values: { __proto__: null, with: value }, positionals: [] };
const result = parseArgs({ args, options, strict: false });
assert.deepStrictEqual(result, expectedResult);
});
test(`greedy: when long option with value '${value}' then eaten`, () => {
const args = ['--with', value];
const options = { with: { type: 'string', short: 'w' } };
const expectedResult = { values: { __proto__: null, with: value }, positionals: [] };
const result = parseArgs({ args, options, strict: false });
assert.deepStrictEqual(result, expectedResult);
});
});
test('strict: when candidate option value is plain text then does not throw', () => {
const args = ['--with', 'abc'];
const options = { with: { type: 'string' } };
const expectedResult = { values: { __proto__: null, with: 'abc' }, positionals: [] };
const result = parseArgs({ args, options, strict: true });
assert.deepStrictEqual(result, expectedResult);
});
test("strict: when candidate option value is '-' then does not throw", () => {
const args = ['--with', '-'];
const options = { with: { type: 'string' } };
const expectedResult = { values: { __proto__: null, with: '-' }, positionals: [] };
const result = parseArgs({ args, options, strict: true });
assert.deepStrictEqual(result, expectedResult);
});
test("strict: when candidate option value is '--' then throws", () => {
const args = ['--with', '--'];
const options = { with: { type: 'string' } };
assert.throws(() => {
parseArgs({ args, options });
}, {
code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'
});
});
test('strict: when candidate option value is short option then throws', () => {
const args = ['--with', '-a'];
const options = { with: { type: 'string' } };
assert.throws(() => {
parseArgs({ args, options });
}, {
code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'
});
});
test('strict: when candidate option value is short option digit then throws', () => {
const args = ['--with', '-1'];
const options = { with: { type: 'string' } };
assert.throws(() => {
parseArgs({ args, options });
}, {
code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'
});
});
test('strict: when candidate option value is long option then throws', () => {
const args = ['--with', '--foo'];
const options = { with: { type: 'string' } };
assert.throws(() => {
parseArgs({ args, options });
}, {
code: 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE'
});
});
test('strict: when short option and suspect value then throws with short option in error message', () => {
const args = ['-w', '--foo'];
const options = { with: { type: 'string', short: 'w' } };
assert.throws(() => {
parseArgs({ args, options });
}, /for '-w'/
);
});
test('strict: when long option and suspect value then throws with long option in error message', () => {
const args = ['--with', '--foo'];
const options = { with: { type: 'string' } };
assert.throws(() => {
parseArgs({ args, options });
}, /for '--with'/
);
});
test('strict: when short option and suspect value then throws with whole expected message', () => {
const args = ['-w', '--foo'];
const options = { with: { type: 'string', short: 'w' } };
try {
parseArgs({ args, options });
} catch (err) {
console.info(err.message);
}
assert.throws(() => {
parseArgs({ args, options });
}, /To specify an option argument starting with a dash use '--with=-XYZ' or '-w-XYZ'/
);
});
test('strict: when long option and suspect value then throws with whole expected message', () => {
const args = ['--with', '--foo'];
const options = { with: { type: 'string', short: 'w' } };
assert.throws(() => {
parseArgs({ args, options });
}, /To specify an option argument starting with a dash use '--with=-XYZ'/
);
});