getopts icon indicating copy to clipboard operation
getopts copied to clipboard

Way to disable built-in default values

Open julien-f opened this issue 4 years ago • 4 comments

getopts assigns default values to string (''), number (0) and boolean (false) options.

Issues:

  1. Not compatible with JS default values:
const { foo = 'bar' } = getopts(argv, { string: [ 'foo' ] });
  1. Cannot distinguish between explicit options and default values:
const { baz } = getopts(argv, { string: [ 'baz' ] });
if (baz === undefined) {
  throw new Error('--baz must be passed explicitely');
}

With modern JS syntaxes like destructuring, default values and the nullish coalescing operator (??), I don't see much use default values being handled by getopts in the future.

In the meantime, a simple option like builtInDefaults: false would be good enough to cover my use case :slightly_smiling_face:

What's your opinion on this?

julien-f avatar Apr 21 '21 15:04 julien-f

Just a couple of issues to be aware of: opts.string allows you to treat contiguous characters as a single value and not individual options.

getopts(["-atabc"], {
  string: ["t"],
}) //=> { _:[], a:true, t:"abc" }

Similarly, opts.boolean says we should parse the next argument as an operand instead of as a value.

getopts(["-t", "alpha"], {
  boolean: ["t"],
}) //=> { _:["alpha"], t:true }

As long as we don't interfere with that, I'm down for it. We could even make it the default behavior since builtInDefaults: true may not be too useful in the future as you say.

jorgebucaran avatar Apr 23 '21 03:04 jorgebucaran

I just took a quick glance, but putting an if (builtInDefaults) around these two lines appear to do the job: https://github.com/jorgebucaran/getopts/blob/35dfad8997697051234aca992eb90c7abd7a5465/index.js#L189-L190

julien-f avatar Apr 25 '21 14:04 julien-f

Looks like a clean solution! Do you happen to know what other parsers out there, e.g., yargs do? If a similar feature/option already exists in another parser it may be worthwhile naming ours the same or similarly (although not necessarily).

jorgebucaran avatar May 02 '21 05:05 jorgebucaran

After a quick test, it seems that by default, yargs does not set default values to boolean/string/number options.

julien-f avatar May 02 '21 08:05 julien-f