util: add tokens to parseArgs

Offer additional meta-data for building
custom and additional behaviour on
top of parseArgs.

PR-URL: https://github.com/nodejs/node/pull/43459
Reviewed-By: Ben Coe <bencoe@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
John Gee authored and Danielle Adams committed 2022-07-25 21:43:41 -04:00
1 parent 8a8de94034
commit acfc33ca8c
3 files changed
+547 -136

No files matched your search

+121 -2
View File
@@ -1024,6 +1024,11 @@ equality.
<!-- YAML
added: v18.3.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/43459
description: add support for returning detailed parse information
using `tokens` in input `config` and returned properties.
-->
> Stability: 1 - Experimental
@@ -1040,18 +1045,24 @@ added: v18.3.0
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
* `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
* `allowPositionals` {boolean} Whether this command accepts positional
arguments.
**Default:** `false` if `strict` is `true`, otherwise `true`.
* `tokens` {boolean} Return the parsed tokens. This is useful for extending
the built-in behavior, from adding additional checks through to reprocessing
the tokens in different ways.
**Default:** `false`.
* 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.
* `tokens` {Object\[] | undefined} See [parseArgs tokens](#parseargs-tokens)
section. Only returned if `config` includes `tokens: true`.
Provides a higher level API for command-line argument parsing than interacting
with `process.argv` directly. Takes a specification for the expected arguments
@@ -1100,6 +1111,114 @@ console.log(values, positionals);
`util.parseArgs` is experimental and behavior may change. Join the
conversation in [pkgjs/parseargs][] to contribute to the design.
### `parseArgs` `tokens`
Detailed parse information is available for adding custom behaviours by
specifying `tokens: true` in the configuration.
The returned tokens have properties describing:
* all tokens
* `kind` {string} One of 'option', 'positional', or 'option-terminator'.
* `index` {number} Index of element in `args` containing token. So the
source argument for a token is `args[token.index]`.
* option tokens
* `name` {string} Long name of option.
* `rawName` {string} How option used in args, like `-f` of `--foo`.
* `value` {string | undefined} Option value specified in args.
Undefined for boolean options.
* `inlineValue` {boolean | undefined} Whether option value specified inline,
like `--foo=bar`.
* positional tokens
* `value` {string} The value of the positional argument in args (i.e. `args[index]`).
* option-terminator token
The returned tokens are in the order encountered in the input args. Options
that appear more than once in args produce a token for each use. Short option
groups like `-xy` expand to a token for each option. So `-xxx` produces
three tokens.
For example to use the returned tokens to add support for a negated option
like `--no-color`, the tokens can be reprocessed to change the value stored
for the negated option.
```mjs
import { parseArgs } from 'node:util';
const options = {
'color': { type: 'boolean' },
'no-color': { type: 'boolean' },
'logfile': { type: 'string' },
'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
// Reprocess the option tokens and overwrite the returned values.
tokens
.filter((token) => token.kind === 'option')
.forEach((token) => {
if (token.name.startsWith('no-')) {
// Store foo:false for --no-foo
const positiveName = token.name.slice(3);
values[positiveName] = false;
delete values[token.name];
} else {
// Resave value so last one wins if both --foo and --no-foo.
values[token.name] = token.value ?? true;
}
});
const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
```
```cjs
const { parseArgs } = require('node:util');
const options = {
'color': { type: 'boolean' },
'no-color': { type: 'boolean' },
'logfile': { type: 'string' },
'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
// Reprocess the option tokens and overwrite the returned values.
tokens
.filter((token) => token.kind === 'option')
.forEach((token) => {
if (token.name.startsWith('no-')) {
// Store foo:false for --no-foo
const positiveName = token.name.slice(3);
values[positiveName] = false;
delete values[token.name];
} else {
// Resave value so last one wins if both --foo and --no-foo.
values[token.name] = token.value ?? true;
}
});
const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
```
Example usage showing negated options, and when an option is used
multiple ways then last one wins.
```console
$ node negate.js
{ logfile: 'default.log', color: undefined }
$ node negate.js --no-logfile --no-color
{ logfile: false, color: false }
$ node negate.js --logfile=test.log --color
{ logfile: 'test.log', color: true }
$ node negate.js --no-logfile --logfile=test.log --color --no-color
{ logfile: 'test.log', color: false }
```
## `util.promisify(original)`
<!-- YAML
+181 -134
View File
@@ -3,16 +3,18 @@
const {
ArrayPrototypeForEach,
ArrayPrototypeIncludes,
ArrayPrototypeMap,
ArrayPrototypePush,
ArrayPrototypePushApply,
ArrayPrototypeShift,
ArrayPrototypeSlice,
ArrayPrototypePush,
ArrayPrototypeUnshiftApply,
ObjectPrototypeHasOwnProperty: ObjectHasOwn,
ObjectEntries,
ObjectPrototypeHasOwnProperty: ObjectHasOwn,
StringPrototypeCharAt,
StringPrototypeIndexOf,
StringPrototypeSlice,
StringPrototypeStartsWith,
} = primordials;
const {
@@ -45,6 +47,11 @@ const {
},
} = require('internal/errors');
const {
kEmptyObject,
} = require('internal/util');
function getMainArgs() {
// Work out where to slice process.argv for user supplied arguments.
@@ -64,19 +71,16 @@ function getMainArgs() {
/**
* 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 })
* @param {object} token - from tokens as available from parseArgs
*/
function checkOptionLikeValue(longOption, optionValue, shortOrLong, strict) {
if (strict && isOptionLikeValue(optionValue)) {
function checkOptionLikeValue(token) {
if (!token.inlineValue && isOptionLikeValue(token.value)) {
// 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}'?
const example = StringPrototypeStartsWith(token.rawName, '--') ?
`'${token.rawName}=-XYZ'` :
`'--${token.name}=-XYZ' or '${token.rawName}-XYZ'`;
const errorMessage = `Option '${token.rawName}' argument is ambiguous.
Did you forget to specify the option argument for '${token.rawName}'?
To specify an option argument starting with a dash use ${example}.`;
throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(errorMessage);
}
@@ -85,34 +89,28 @@ To specify an option argument starting with a dash use ${example}.`;
/**
* 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 })
* @param {object} config - from config passed to parseArgs
* @param {object} token - from tokens as available from parseArgs
*/
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);
function checkOptionUsage(config, token) {
if (!ObjectHasOwn(config.options, token.name)) {
throw new ERR_PARSE_ARGS_UNKNOWN_OPTION(
token.rawName, config.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') {
const short = optionsGetOwn(config.options, token.name, 'short');
const shortAndLong = `${short ? `-${short}, ` : ''}--${token.name}`;
const type = optionsGetOwn(config.options, token.name, 'type');
if (type === 'string' && typeof token.value !== '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) {
if (type === 'boolean' && token.value != null) {
throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong}' does not take an argument`);
}
}
/**
* Store the option value in `values`.
*
@@ -145,16 +143,146 @@ function storeOption(longOption, optionValue, options, values) {
}
}
const parseArgs = (config = { __proto__: null }) => {
/**
* Process args and turn into identified tokens:
* - option (along with value, if any)
* - positional
* - option-terminator
*
* @param {string[]} args - from parseArgs({ args }) or mainArgs
* @param {object} options - option configs, from parseArgs({ options })
*/
function argsToTokens(args, options) {
const tokens = [];
let index = -1;
let groupCount = 0;
const remainingArgs = ArrayPrototypeSlice(args);
while (remainingArgs.length > 0) {
const arg = ArrayPrototypeShift(remainingArgs);
const nextArg = remainingArgs[0];
if (groupCount > 0)
groupCount--;
else
index++;
// Check if `arg` is an options terminator.
// Guideline 10 in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
if (arg === '--') {
// Everything after a bare '--' is considered a positional argument.
ArrayPrototypePush(tokens, { kind: 'option-terminator', index });
ArrayPrototypePushApply(
tokens, ArrayPrototypeMap(remainingArgs, (arg) => {
return { kind: 'positional', index: ++index, value: arg };
})
);
break; // Finished processing args, leave while loop.
}
if (isLoneShortOption(arg)) {
// e.g. '-f'
const shortOption = StringPrototypeCharAt(arg, 1);
const longOption = findLongOptionForShort(shortOption, options);
let value;
let inlineValue;
if (optionsGetOwn(options, longOption, 'type') === 'string' &&
isOptionValue(nextArg)) {
// e.g. '-f', 'bar'
value = ArrayPrototypeShift(remainingArgs);
inlineValue = false;
}
ArrayPrototypePush(
tokens,
{ kind: 'option', name: longOption, rawName: arg,
index, value, inlineValue });
if (value != null) ++index;
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);
groupCount = expanded.length;
continue;
}
if (isShortOptionAndValue(arg, options)) {
// e.g. -fFILE
const shortOption = StringPrototypeCharAt(arg, 1);
const longOption = findLongOptionForShort(shortOption, options);
const value = StringPrototypeSlice(arg, 2);
ArrayPrototypePush(
tokens,
{ kind: 'option', name: longOption, rawName: `-${shortOption}`,
index, value, inlineValue: true });
continue;
}
if (isLoneLongOption(arg)) {
// e.g. '--foo'
const longOption = StringPrototypeSlice(arg, 2);
let value;
let inlineValue;
if (optionsGetOwn(options, longOption, 'type') === 'string' &&
isOptionValue(nextArg)) {
// e.g. '--foo', 'bar'
value = ArrayPrototypeShift(remainingArgs);
inlineValue = false;
}
ArrayPrototypePush(
tokens,
{ kind: 'option', name: longOption, rawName: arg,
index, value, inlineValue });
if (value != null) ++index;
continue;
}
if (isLongOptionAndValue(arg)) {
// e.g. --foo=bar
const equalIndex = StringPrototypeIndexOf(arg, '=');
const longOption = StringPrototypeSlice(arg, 2, equalIndex);
const value = StringPrototypeSlice(arg, equalIndex + 1);
ArrayPrototypePush(
tokens,
{ kind: 'option', name: longOption, rawName: `--${longOption}`,
index, value, inlineValue: true });
continue;
}
ArrayPrototypePush(tokens, { kind: 'positional', index, value: arg });
}
return tokens;
}
const parseArgs = (config = kEmptyObject) => {
const args = objectGetOwn(config, 'args') ?? getMainArgs();
const strict = objectGetOwn(config, 'strict') ?? true;
const allowPositionals = objectGetOwn(config, 'allowPositionals') ?? !strict;
const returnTokens = objectGetOwn(config, 'tokens') ?? false;
const options = objectGetOwn(config, 'options') ?? { __proto__: null };
// Bundle these up for passing to strict-mode checks.
const parseConfig = { args, strict, options, allowPositionals };
// Validate input configuration.
validateArray(args, 'args');
validateBoolean(strict, 'strict');
validateBoolean(allowPositionals, 'allowPositionals');
validateBoolean(returnTokens, 'tokens');
validateObject(options, 'options');
ArrayPrototypeForEach(
ObjectEntries(options),
@@ -182,112 +310,31 @@ const parseArgs = (config = { __proto__: null }) => {
}
);
// Phase 1: identify tokens
const tokens = argsToTokens(args, options);
// Phase 2: process tokens into parsed option values and positionals
const result = {
values: { __proto__: null },
positionals: []
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);
if (returnTokens) {
result.tokens = tokens;
}
ArrayPrototypeForEach(tokens, (token) => {
if (token.kind === 'option') {
if (strict) {
checkOptionUsage(parseConfig, token);
checkOptionLikeValue(token);
}
storeOption(token.name, token.value, options, result.values);
} else if (token.kind === 'positional') {
if (!allowPositionals) {
throw new ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(token.value);
}
ArrayPrototypePush(result.positionals, token.value);
}
});
return result;
};
+245
View File
@@ -578,3 +578,248 @@ test('strict: when long option and suspect value then throws with whole expected
}, /To specify an option argument starting with a dash use '--with=-XYZ'/
);
});
test('tokens: positional', () => {
const args = ['one'];
const expectedTokens = [
{ kind: 'positional', index: 0, value: 'one' },
];
const { tokens } = parseArgs({ strict: false, args, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: -- followed by option-like', () => {
const args = ['--', '--foo'];
const expectedTokens = [
{ kind: 'option-terminator', index: 0 },
{ kind: 'positional', index: 1, value: '--foo' },
];
const { tokens } = parseArgs({ strict: false, args, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:true boolean short', () => {
const args = ['-f'];
const options = {
file: { short: 'f', type: 'boolean' }
};
const expectedTokens = [
{ kind: 'option', name: 'file', rawName: '-f',
index: 0, value: undefined, inlineValue: undefined },
];
const { tokens } = parseArgs({ strict: true, args, options, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:true boolean long', () => {
const args = ['--file'];
const options = {
file: { short: 'f', type: 'boolean' }
};
const expectedTokens = [
{ kind: 'option', name: 'file', rawName: '--file',
index: 0, value: undefined, inlineValue: undefined },
];
const { tokens } = parseArgs({ strict: true, args, options, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:false boolean short', () => {
const args = ['-f'];
const expectedTokens = [
{ kind: 'option', name: 'f', rawName: '-f',
index: 0, value: undefined, inlineValue: undefined },
];
const { tokens } = parseArgs({ strict: false, args, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:false boolean long', () => {
const args = ['--file'];
const expectedTokens = [
{ kind: 'option', name: 'file', rawName: '--file',
index: 0, value: undefined, inlineValue: undefined },
];
const { tokens } = parseArgs({ strict: false, args, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:false boolean option group', () => {
const args = ['-ab'];
const expectedTokens = [
{ kind: 'option', name: 'a', rawName: '-a',
index: 0, value: undefined, inlineValue: undefined },
{ kind: 'option', name: 'b', rawName: '-b',
index: 0, value: undefined, inlineValue: undefined },
];
const { tokens } = parseArgs({ strict: false, args, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:false boolean option group with repeated option', () => {
// Also positional to check index correct after grouop
const args = ['-aa', 'pos'];
const expectedTokens = [
{ kind: 'option', name: 'a', rawName: '-a',
index: 0, value: undefined, inlineValue: undefined },
{ kind: 'option', name: 'a', rawName: '-a',
index: 0, value: undefined, inlineValue: undefined },
{ kind: 'positional', index: 1, value: 'pos' },
];
const { tokens } = parseArgs({ strict: false, allowPositionals: true, args, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:true string short with value after space', () => {
// Also positional to check index correct after out-of-line.
const args = ['-f', 'bar', 'ppp'];
const options = {
file: { short: 'f', type: 'string' }
};
const expectedTokens = [
{ kind: 'option', name: 'file', rawName: '-f',
index: 0, value: 'bar', inlineValue: false },
{ kind: 'positional', index: 2, value: 'ppp' },
];
const { tokens } = parseArgs({ strict: true, allowPositionals: true, args, options, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:true string short with value inline', () => {
const args = ['-fBAR'];
const options = {
file: { short: 'f', type: 'string' }
};
const expectedTokens = [
{ kind: 'option', name: 'file', rawName: '-f',
index: 0, value: 'BAR', inlineValue: true },
];
const { tokens } = parseArgs({ strict: true, args, options, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:false string short missing value', () => {
const args = ['-f'];
const options = {
file: { short: 'f', type: 'string' }
};
const expectedTokens = [
{ kind: 'option', name: 'file', rawName: '-f',
index: 0, value: undefined, inlineValue: undefined },
];
const { tokens } = parseArgs({ strict: false, args, options, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:true string long with value after space', () => {
// Also positional to check index correct after out-of-line.
const args = ['--file', 'bar', 'ppp'];
const options = {
file: { short: 'f', type: 'string' }
};
const expectedTokens = [
{ kind: 'option', name: 'file', rawName: '--file',
index: 0, value: 'bar', inlineValue: false },
{ kind: 'positional', index: 2, value: 'ppp' },
];
const { tokens } = parseArgs({ strict: true, allowPositionals: true, args, options, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:true string long with value inline', () => {
// Also positional to check index correct after out-of-line.
const args = ['--file=bar', 'pos'];
const options = {
file: { short: 'f', type: 'string' }
};
const expectedTokens = [
{ kind: 'option', name: 'file', rawName: '--file',
index: 0, value: 'bar', inlineValue: true },
{ kind: 'positional', index: 1, value: 'pos' },
];
const { tokens } = parseArgs({ strict: true, allowPositionals: true, args, options, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:false string long with value inline', () => {
const args = ['--file=bar'];
const expectedTokens = [
{ kind: 'option', name: 'file', rawName: '--file',
index: 0, value: 'bar', inlineValue: true },
];
const { tokens } = parseArgs({ strict: false, args, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:false string long missing value', () => {
const args = ['--file'];
const options = {
file: { short: 'f', type: 'string' }
};
const expectedTokens = [
{ kind: 'option', name: 'file', rawName: '--file',
index: 0, value: undefined, inlineValue: undefined },
];
const { tokens } = parseArgs({ strict: false, args, options, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:true complex option group with value after space', () => {
// Also positional to check index correct afterwards.
const args = ['-ab', 'c', 'pos'];
const options = {
alpha: { short: 'a', type: 'boolean' },
beta: { short: 'b', type: 'string' },
};
const expectedTokens = [
{ kind: 'option', name: 'alpha', rawName: '-a',
index: 0, value: undefined, inlineValue: undefined },
{ kind: 'option', name: 'beta', rawName: '-b',
index: 0, value: 'c', inlineValue: false },
{ kind: 'positional', index: 2, value: 'pos' },
];
const { tokens } = parseArgs({ strict: true, allowPositionals: true, args, options, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:true complex option group with inline value', () => {
// Also positional to check index correct afterwards.
const args = ['-abc', 'pos'];
const options = {
alpha: { short: 'a', type: 'boolean' },
beta: { short: 'b', type: 'string' },
};
const expectedTokens = [
{ kind: 'option', name: 'alpha', rawName: '-a',
index: 0, value: undefined, inlineValue: undefined },
{ kind: 'option', name: 'beta', rawName: '-b',
index: 0, value: 'c', inlineValue: true },
{ kind: 'positional', index: 1, value: 'pos' },
];
const { tokens } = parseArgs({ strict: true, allowPositionals: true, args, options, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:false with single dashes', () => {
const args = ['--file', '-', '-'];
const options = {
file: { short: 'f', type: 'string' },
};
const expectedTokens = [
{ kind: 'option', name: 'file', rawName: '--file',
index: 0, value: '-', inlineValue: false },
{ kind: 'positional', index: 2, value: '-' },
];
const { tokens } = parseArgs({ strict: false, args, options, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});
test('tokens: strict:false with -- --', () => {
const args = ['--', '--'];
const expectedTokens = [
{ kind: 'option-terminator', index: 0 },
{ kind: 'positional', index: 1, value: '--' },
];
const { tokens } = parseArgs({ strict: false, args, tokens: true });
assert.deepStrictEqual(tokens, expectedTokens);
});