Skip to content

Make number type act like .choices() for invalid or missing input #1079

Open

Description

@plroebuck

Currently for options of type number, if the user provides the option and fails to provide valid input,
the value is returned as either NaN or undefined. No idea who needs that. Can we make it act more like .choices() and just implode? Not doing so makes implementing yargs.check() function argument arduous when much is seemingly unnecessary.

binary = path.basename pkg.bin      # From "package.json"
argv = yargs
  .usage('...')
  .options(Abao.options)
  .check((argv) ->
    # Ensure single positional argument present
    if argv._.length < 1
      throw new Error binary + ': must specify path to file'
    else if argv._.length > 1
      throw new Error binary + ': accepts single positional command-line argument'

    ## Validate "timeout" option
    if _.isUndefined argv.timeout
      throw new Error binary + ': option "--timeout" given without a value'
    if _.isNaN argv.timeout
      # Would be better message if it included unparsable user argument value
      throw new Error binary + ': option "--timeout" value could not be parsed as a number'
    if !_.isInteger argv.timeout
      throw new Error binary + ': option "--timeout" value must be scalar integer'
    if argv.timeout < 0
      throw new Error binary + ': option "--timeout" value must be nonnegative'
   
    #
    # YA four-part stanza like above for EVERY numeric option...
    #

    return true
  )
  .help('help', 'Show usage information and exit')
  .version().describe('version', 'Show version number and exit')
  .argv

Technically, the above requested change only handles the first half of the stanza.
Would need to add two more API methods to handle the rest:

.scalar(key, bool) - if true, only single value accepted (no array); otherwise, false (default).
.range(key, func) - user-provided function to handle range validation

e.g.,

nonnegative = (val) -> val < 0
yargs.range('timeout', nonnegative)

For that matter, how about a sibling .integer(key) method that only accepts integers?

Continuation of now closed #110 discussion...

Activity

  1. grnch commented on Apr 4, 2018

    @grnch

    Currently for options of type number, if the user provides the option and fails to provide valid input,
    the value is returned as either NaN or undefined. No idea who needs that. Can we make it act more like .choices() and just implode?

    This part has definitely bitten me more than once. If I specify that an argument is a number, and the user enters something that is not a number, yargs should immediately let the user know they entered an invalid value. Continuing with NaN like it does now is just a recipe for weird undiagnosable errors down the line.

    P.S.
    I have no opinion on the rest of the post with the check()/scalar()/range() stuff. They seem like separate issues, to be honest. I only wanted to add support for the part I quoted above.

  2. newmanw commented on Dec 10, 2020

    @newmanw

    This got me as well. Expecting that when I define type: 'number' that the input is validated to actually be a number.

  3. Baterka commented on May 19, 2023

    @Baterka

    Same.

    This got me as well. Expecting that when I define type: 'number' that the input is validated to actually be a number.

  4. ReshetovItsMe commented on Jun 19, 2023

    @ReshetovItsMe

    This got me as well. Expecting that when I define type: 'number' that the input is validated to actually be a number.

    Same

  5. plroebuck commented on Jul 4, 2023

    @plroebuck
    Author

    @bcoe, it's been more than 5 years since this request was made... if this request won't ever get any love, just close it as "won't implement". There have been repeated requests to implode rather than return a NaN as these are causing bizarre errors that must be tracked down by package developers rather than simply being an error message saying that an argument wasn't given properly by the user.

    I personally wouldn't think .scalar() or .range() would be difficult either and their inclusion would make this significantly better. But I see no reason that the default return value should still be broken after all this time.

  6. shadowspawn commented on Jul 4, 2023

    @shadowspawn
    Member

    This is one of the more popular of the 294 open issues. I am sorry this has not been addressed yet. Or your other suggestions. I apologise on behalf of the world of people with the skills to fix it who have not done so. (Yes, I am joking on the last item. I empathise with your frustration, but taking it out on the long serving project owner is counter-productive.)

    Some quick thoughts:

    • should this issue be closed? No. It is a popular issue, and something I personally think is worth attempting.
    • is this a strict-only check? No, a quick look suggests strict is for unknown options.
    • what about option used without value? We return something for string in this case, but makes less sense for number. I think probably implode at yargs level, although probably still undefined at yargs-parser level to allow handling by libraries and lower-level use.
    • would be nice to show invalid argument with error, if feasible. (Is that accessible from yargs-parser?)
    • breaking change, will have to go in a semver major release
    • scalar: out-of-scope, open issue is Disallow multiple arguments (array) for individual key #1318
    • range() and integer(): not in first instance, get the imploding sorted before considering those
  7. plroebuck commented on Jul 5, 2023

    @plroebuck
    Author

    My apologies to @bcoe during a moment of frustration -- I've had to explain not getting issues resolved myself. But since the request was a post against yargs v13.2.1 and the package is currently v17.7.2, please help correct this outstanding software bug.

  8. shadowspawn commented on Oct 22, 2023

    @shadowspawn
    Member

    I did some experimentation today, and currently leaning towards generating an error instead of returning NaN for type: 'number'. Hand-rolling your own validation with informative error messages is a bit of work for author. Silent parsing to NaN can be achieved easily for the main cases by passing coerce: parseFloat. Having yargs do the probably more commonly wanted and more difficult job seems appropriate.

  9. shadowspawn commented on Oct 22, 2023

    @shadowspawn
    Member

    The big problem is changing an 8 year old behaviour! (Yes, could add more configuration, but in first instance would rather not.)

    Is anyone following this issue keen to preserve the current behaviour of silently returning NaN for parsing failures?

  10. plroebuck commented on Oct 23, 2023

    @plroebuck
    Author

    Cannot think of any reason someone would ever desire such an odd and unexpected behavior. If nothing is passed for a number option on the cmdline, it's just plain wrong -- user error. If an alphabetic is passed to a number option on the cmdline, it's also just plain wrong -- yet another user error. The current behavior seems more likely to cause an issue than prevent one; I still vote tossing the current behavior.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions