jorgebucaran / getopts

Node.js CLI options parser
MIT License
633 stars 20 forks source link

Way to disable built-in default values #53

Open julien-f opened 3 years ago

julien-f commented 3 years ago

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' ] });
  2. 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?

jorgebucaran commented 3 years ago

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.

julien-f commented 3 years ago

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

jorgebucaran commented 3 years ago

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).

julien-f commented 3 years ago

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