1. Arity
Sometimes, you want to have more fine control of how many parameters with an option are processed when parsing operations happen. Arity is defined as min and max values, where min must be zero or a positive integer and max has to be more or equal to min.
CommandRegistration.builder()
.withOption()
.longNames("arg1")
.arity(0, 1)
.and()
.build();
Arity can also be defined as an OptionArity enum, which are shortcuts
shown in below table OptionArity.
CommandRegistration.builder()
.withOption()
.longNames("arg1")
.arity(OptionArity.EXACTLY_ONE)
.and()
.build();
| Value | min/max |
|---|---|
ZERO |
0 / 0 |
ZERO_OR_ONE |
0 / 1 |
EXACTLY_ONE |
1 / 1 |
ZERO_OR_MORE |
0 / Integer MAX |
ONE_OR_MORE |
1 / Integer MAX |
The annotation model supports defining only the max value of an arity.
public String example(@ShellOption(arity = 1) String arg1) {
return "Hello " + arg1;
}
One of a use cases to manually define arity is to impose restrictions how many parameters option accepts.
CommandRegistration.builder()
.command("arity-errors")
.withOption()
.longNames("arg1")
.type(String[].class)
.required()
.arity(1, 2)
.and()
.withTarget()
.function(ctx -> {
String[] arg1 = ctx.getOptionValue("arg1");
return "Hello " + Arrays.asList(arg1);
})
.and()
.build();
In above example we have option arg1 and it’s defined as type String[]. Arity defines that it needs at least 1 parameter and not more that 2. As seen in below spesific exceptions TooManyArgumentsOptionException and NotEnoughArgumentsOptionException are thrown to indicate arity mismatch.
shell:>e2e reg arity-errors --arg1
Not enough arguments --arg1 requires at least 1.
shell:>e2e reg arity-errors --arg1 one
Hello [one]
shell:>e2e reg arity-errors --arg1 one two
Hello [one, two]
shell:>e2e reg arity-errors --arg1 one two three
Too many arguments --arg1 requires at most 2.