Skip to content

Commit

Permalink
util: support --no- for argument with boolean type for parseArgs
Browse files Browse the repository at this point in the history
  • Loading branch information
kylo5aby committed May 24, 2024
1 parent 1b96527 commit 0c957ea
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 9 deletions.
6 changes: 6 additions & 0 deletions doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -1429,6 +1429,8 @@ changes:
* `allowPositionals` {boolean} Whether this command accepts positional
arguments.
**Default:** `false` if `strict` is `true`, otherwise `true`.
* `allowNegative` {boolean} Whether allow negative options.
**Default:** `false`.
* `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.
Expand All @@ -1445,6 +1447,10 @@ 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.

for an argument with type `boolean`, If the argument is passed with
the `--no-` prefix, the value of the argument will be set to the opposite
of its default value.

```mjs
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
Expand Down
40 changes: 31 additions & 9 deletions lib/internal/util/parse_args/parse_args.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,24 @@ To specify an option argument starting with a dash use ${example}.`;
* @param {object} token - from tokens as available from parseArgs
*/
function checkOptionUsage(config, token) {
if (!ObjectHasOwn(config.options, token.name)) {
throw new ERR_PARSE_ARGS_UNKNOWN_OPTION(
token.rawName, config.allowPositionals);
let tokenName = token.name;
if (!ObjectHasOwn(config.options, tokenName)) {
// Check for negated boolean option.
if (config.allowNegative && StringPrototypeStartsWith(tokenName, 'no-')) {
tokenName = StringPrototypeSlice(tokenName, 3);
if (!ObjectHasOwn(config.options, tokenName) || optionsGetOwn(config.options, tokenName, 'type') !== 'boolean') {
throw new ERR_PARSE_ARGS_UNKNOWN_OPTION(
token.rawName, config.allowPositionals);
}
} else {
throw new ERR_PARSE_ARGS_UNKNOWN_OPTION(
token.rawName, config.allowPositionals);
}
}

const short = optionsGetOwn(config.options, token.name, 'short');
const shortAndLong = `${short ? `-${short}, ` : ''}--${token.name}`;
const type = optionsGetOwn(config.options, token.name, 'type');
const short = optionsGetOwn(config.options, tokenName, 'short');
const shortAndLong = `${short ? `-${short}, ` : ''}--${tokenName}`;
const type = optionsGetOwn(config.options, tokenName, 'type');
if (type === 'string' && typeof token.value !== 'string') {
throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong} <value>' argument missing`);
}
Expand All @@ -118,12 +128,22 @@ function checkOptionUsage(config, token) {
* @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
* @param {boolean} allowNegative - allow negative optinons if true
*/
function storeOption(longOption, optionValue, options, values) {
function storeOption(longOption, optionValue, options, values, allowNegative) {
if (longOption === '__proto__') {
return; // No. Just no.
}

if (allowNegative && StringPrototypeStartsWith(longOption, 'no-')) {
// Boolean option negation: --no-foo
const longOptionWithoutPrefixNo = StringPrototypeSlice(longOption, 3);
if (optionsGetOwn(options, longOptionWithoutPrefixNo, 'type') !== 'string') {
longOption = StringPrototypeSlice(longOption, 3);
optionValue = false;
}
}

// We store based on the option value rather than option type,
// preserving the users intent for author to deal with.
const newValue = optionValue ?? true;
Expand Down Expand Up @@ -290,15 +310,17 @@ const parseArgs = (config = kEmptyObject) => {
const strict = objectGetOwn(config, 'strict') ?? true;
const allowPositionals = objectGetOwn(config, 'allowPositionals') ?? !strict;
const returnTokens = objectGetOwn(config, 'tokens') ?? false;
const allowNegative = objectGetOwn(config, 'allowNegative') ?? false;
const options = objectGetOwn(config, 'options') ?? { __proto__: null };
// Bundle these up for passing to strict-mode checks.
const parseConfig = { args, strict, options, allowPositionals };
const parseConfig = { args, strict, options, allowPositionals, allowNegative };

// Validate input configuration.
validateArray(args, 'args');
validateBoolean(strict, 'strict');
validateBoolean(allowPositionals, 'allowPositionals');
validateBoolean(returnTokens, 'tokens');
validateBoolean(allowNegative, 'allowNegative');
validateObject(options, 'options');
ArrayPrototypeForEach(
ObjectEntries(options),
Expand Down Expand Up @@ -360,7 +382,7 @@ const parseArgs = (config = kEmptyObject) => {
checkOptionUsage(parseConfig, token);
checkOptionLikeValue(token);
}
storeOption(token.name, token.value, options, result.values);
storeOption(token.name, token.value, options, result.values, parseConfig.allowNegative);
} else if (token.kind === 'positional') {
if (!allowPositionals) {
throw new ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(token.value);
Expand Down
70 changes: 70 additions & 0 deletions test/parallel/test-parse-args.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -992,3 +992,73 @@ test('multiple as false should expect a String', () => {
}, /"options\.alpha\.default" property must be of type string/
);
});

// Test negative options
test('disable negative options and args are started with "--no-" prefix', () => {
const args = ['--no-alpha'];
const options = { alpha: { type: 'boolean' } };
assert.throws(() => {
parseArgs({ args, options });
}, {
code: 'ERR_PARSE_ARGS_UNKNOWN_OPTION'
});
});

test('args are passed `type: "string"` and allow negative options', () => {
const args = ['--no-alpha', 'value'];
const options = { alpha: { type: 'string' } };
assert.throws(() => {
parseArgs({ args, options, allowNegative: true });
}, {
code: 'ERR_PARSE_ARGS_UNKNOWN_OPTION'
});
});

test('args are passed `type: "boolean"` and allow negative options', () => {
const args = ['--no-alpha'];
const options = { alpha: { type: 'boolean' } };
const expected = { values: { __proto__: null, alpha: false }, positionals: [] };
assert.deepStrictEqual(parseArgs({ args, options, allowNegative: true }), expected);
});

test('args are passed `default: "true"` and allow negative options', () => {
const args = ['--no-alpha'];
const options = { alpha: { type: 'boolean', default: true } };
const expected = { values: { __proto__: null, alpha: false }, positionals: [] };
assert.deepStrictEqual(parseArgs({ args, options, allowNegative: true }), expected);
});

test('args are passed `default: "false" and allow negative options', () => {
const args = ['--no-alpha'];
const options = { alpha: { type: 'boolean', default: false } };
const expected = { values: { __proto__: null, alpha: false }, positionals: [] };
assert.deepStrictEqual(parseArgs({ args, options, allowNegative: true }), expected);
});

test('allow negative options and multiple as true', () => {
const args = ['--no-alpha', '--alpha', '--no-alpha'];
const options = { alpha: { type: 'boolean', multiple: true } };
const expected = { values: { __proto__: null, alpha: [false, true, false] }, positionals: [] };
assert.deepStrictEqual(parseArgs({ args, options, allowNegative: true }), expected);
});

test('allow negative options and passed multiple arguments', () => {
const args = ['--alpha', '--no-alpha', '--alpha'];
const options = { alpha: { type: 'boolean' } };
const expected = { values: { __proto__: null, alpha: true }, positionals: [] };
assert.deepStrictEqual(parseArgs({ args, options, allowNegative: true }), expected);
});

test('allow negative options when normal arguments', () => {
const holdArgv = process.argv;
process.argv = [process.argv0, 'script.js', '--no-foo'];
const holdExecArgv = process.execArgv;
process.execArgv = [];
const result = parseArgs({ strict: false, allowNegative: true });

const expected = { values: { __proto__: null, foo: false },
positionals: [] };
assert.deepStrictEqual(result, expected);
process.argv = holdArgv;
process.execArgv = holdExecArgv;
});

0 comments on commit 0c957ea

Please sign in to comment.