cbeust / jcommander

Command line parsing framework for Java

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Main parameter conversion has priority over arity validation

jontmy opened this issue · comments

Suppose that I have this converter which takes a String and attempts conversion into an Index - which is basically a wrapper around an int:

public class IndexConverter implements IStringConverter<Index> {
    @Override
    public Index convert(String value) {
        if (!StringUtil.isNonZeroUnsignedInteger(value)) {
            throw new ParameterException("The index must be a non-zero unsigned integer.");
        }
        return Index.fromOneBased(Integer.parseInt(value));
    }
}

However, if I define a parameter in my command class like so, and I attempt to let JCommander parse the command <command word> 123 abc, now I get the ParameterException thrown because the "abc" is not an integer - but should JCommander instead realize that the arity of 2 is incorrect before attempting conversion?:

@Parameters(commandDescription = "...")
public class ExampleCommand extends Command {

    @Parameter(description = "...", required = true, converter = IndexConverter.class, arity = 1)
    private Index targetIndex;
    ...
}

My rationale for raising this issue is that the exception message is of the wrong specificity - the exception from the failed conversion has higher priority than the exception from the arity.

This is behavior is undesirable for my use case as it's more important to reject the incorrect arity than to inform the user of a failed conversion.

Could there be a way to configure JCommander to validate arities before conversions?

@jontmy Did you find such configuration option in the source code? If not, do you agree to provide a PR for this bug?