util: support 'option.required' in parseArgs#44565
Conversation
5ba57da to
7a30d9a
Compare
7a30d9a to
a8c6229
Compare
parseArgsparseArgs
| times. If `true`, all values will be collected in an array. If | ||
| `false`, values for the option are last-wins. **Default:** `false`. | ||
| * `short` {string} A single character alias for the option. | ||
| * `required` {boolean} Whether this option is required. **Default:** `false`. |
There was a problem hiding this comment.
Doesn't the default depend on strict?
There was a problem hiding this comment.
I’m not sure what it should be🤔
But in my real code, I just check if it is a truely value.
There was a problem hiding this comment.
No, I think the behaviour is independent of strict. Options which take a value generate an error in strict, but there is a difference between an option with a required option-argument (i.e. type='string') and a required option as proposed here.
| ERR_PARSE_ARGS_INVALID_OPTION_VALUE, | ||
| ERR_PARSE_ARGS_UNKNOWN_OPTION, | ||
| ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL, | ||
| ERR_PARSE_ARGS_REQUIRED_OPTION |
There was a problem hiding this comment.
This does not describe why it is an error. I suggest sayERR_PARSE_ARGS_REQUIRED_OPTION_MISSING
|
The other input configuration options are all validated. |
| ArrayPrototypeForEach( | ||
| ObjectEntries(options), | ||
| ({ 0: longOption, 1: optionConfig }) => { | ||
| if (optionConfig.required && result.values[longOption] === undefined) { |
There was a problem hiding this comment.
The options came from the user, and is subject to possible prototype pollution. There is a helper routine objectGetOwn to do this more robustly:
(The result was made internally with null prototype so can be used more conventionally with safety.)
There was a problem hiding this comment.
Actually, even more paranoid and robust is optionsGetOwn:
| bar: { | ||
| type: 'string' | ||
| type: 'string', | ||
| required: true |
There was a problem hiding this comment.
I suggest not including required in the example, as it is a less common configuration. The majority of programs will not use required, and there is some small potential for confusion between options expecting an argument, and required options.
tniessen
left a comment
There was a problem hiding this comment.
How would this be combined with options such as --help or --version?
I assume that required positional arguments are far more common than required options, which are usually optional. How would that be addressed?
Also, as @shadowspawn mentioned in #44564 (comment), some frameworks intentionally decided against supporting required options.
Co-authored-by: Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com>
Co-authored-by: Antoine du Hamel <duhamelantoine1995@gmail.com>
Fixes: #44564