tj / commander.js

node.js command-line interfaces made easy

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Default option value always set to `true`

garysassano opened this issue · comments

I have the following program option:

.option("-R, --retry [retryCount]", "Number of times to retry a failed test", "3")

The problem is that the retry variable gets set to true. I tryed swapping "3" with "foo" and it's the same.

I was unable to reproduce the problem using your example. I think there is something else in your program or in the command-line parameters that is setting the retry option.

The specific command is called test.

If I call cli test, I see that retry gets indeed set to "3", whereas if I call cli test --retry, I see that retry gets set to true. And if I call cli test --retry 5, I see that retry gets set to "5".

Ah, showing the command-line arguments helps, thanks.

This is expected behaviour for an option with an optional argument. Using the option alone sets the value to true. The default value is used when the option does not appear in the parsed arguments.

You can specify a "preset" value to be used when the option is used without an option-argument. This feature was added somewhat recently, in Commander v9, so if you are using an older version it won't be available.

program.addOption(
   new Option("-R, --retry [retryCount]", "Number of times to retry a failed test")
      .default("3")
      .preset("4")
);

The Option.preset() does exactly what I was looking for, thanks.

Ok, so I've discovered a quite interesting behaviour...

.addOption(
  new Option("-R, --retry [retryCount]", "Number of times to retry a failed test").preset(3)
)

Using cli test --retry, retry is a number equal to 3, whereas using cli test --retry 5, retry is a string equal to "5". Isn't there a way to parse the input value provided by the user as a number by default?

Never mind, I found the property:

.addOption(
  new Option("-R, --retry [retryCount]", "Number of times to retry a failed test")
    .preset(3)
    .argParser(parseInt)
)