Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Impossible to validate missing arguments for a flag when multiple is set #120

Open
bakkot opened this issue Nov 16, 2021 · 1 comment
Open

Comments

@bakkot
Copy link

bakkot commented Nov 16, 2021

As in #112, I was surprised to find that parsing a flag with a type when the argument is omitted does not error, instead returning null. That issue points to the wiki, which says I should do the validation myself. Fair enough.

Unfortunately, it is impossible to do the validation myself when the flag is specified as multiple, because the output for --flag arg --flag is identical to the output to the output for --flag arg.

That is:

const commandLineArgs = require('command-line-args');

const options = [{
  name: 'flag',
  type: String,
  multiple: true,
  defaultValue: 'default',
}];

console.log(commandLineArgs(options));

invoked with

node cli-args.js --flag arg --flag

and with

node cli-args.js --flag arg

both give exactly the same output,

{ flag: [ 'arg' ] }

So it is not actually possible to check whether the user has passed a flag without specifying its (required) argument.

I was hoping that it would at least put the default value in the output array (or null, if not specified), which I could check for.

@75lb
Copy link
Owner

75lb commented Apr 17, 2023

Hi, yes the defaultValue for a multiple/lazyMultiple option is the default if the option is not specified at all, i.e.

$ node example.js
{ flag: [ 'default' ] }

This behaviour is correct and by design. But, yes that's a good point in the case that one of the supplied --flag options does not contain a value. In the example you gave, you would expect the output to be `{ flag: [ 'arg', null ] }. Will look into this, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants