75lb / command-line-args

A mature, feature-complete library to parse command-line options.
MIT License
679 stars 107 forks source link

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

Open bakkot opened 2 years ago

bakkot commented 2 years ago

As in https://github.com/75lb/command-line-args/issues/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 commented 1 year ago

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.