cbeust / jcommander

Command line parsing framework for Java
Apache License 2.0
1.95k stars 332 forks source link

Repetition of same Boolean argument with arity `0` negates argument's value #530

Open twwwt opened 2 years ago

twwwt commented 2 years ago

Consider the following argument definition:

@Parameter(
    names = { "-y", "--dry-run" },
    description = "Perform a dry-run.",
    arity = 0,
    order = 9
)
private Boolean dryRun = FALSE;

Current Behavior

If the Boolean argument is used repeatedly on the command line (i.e., more than once), its effective Boolean value flips with every repetition:

$ mytool        -- dryRun is false
$ mytool -y     -- dryRun is true
$ mytool -y -y      -- dryRun is false
$ mytool -y -y -y   -- dryRun is true
... and so on

While the first two lines work as expected, starting from the third line (where -y occurs twice), the effective value of dryRun flips with every repetition of -y. This is independent of whether the argument is repeated in direct succession (as is done in the example) or whether other arguments occur in-between repetitions.

Expected Behavior

As an immediate remedy, jCommand should consider arguments to be non-repeatable by default and thus reject repeated use of the same argument by throwing an exception when parsing the command line.

Looking at the problem more generally, it occurs to me that the @Parameter annotation of jCommand needs to be extended with a Boolean parameter, let's call it repeatable, that allows to specify whether an argument can occur repeatedly on the command line. The default of that parameter should be false (i.e. it may not be repeated).

timbarlotta commented 2 years ago

This is reproducible even if the arity is left at the default of -1. The logic keeps flipping the boolean. Seems like this should either:

  1. error out as the parameter should only be specified once
  2. be set to true no matter how many times the flag is passed
mkarg commented 4 months ago

If this bug still exists on JCommander 1.83 please post a unit test here which proofs your claim. Thanks.