Reputation: 6132
I have a simple Command
with one mandatory parameter:
@Parameters(index = "0", description = "manifest")
private File manifest;
When I call it from the command line without a parameter I get the expected message:
Missing required parameter: <manifest>
Usage ....
BUT: the return code for the call to java
is 0, implying everything went fine.
Is there a way to have picocli
return a non-zero code if a parameter (or option) is missing/incorrect?
Upvotes: 1
Views: 1119
Reputation: 36754
Yes this is possible.
UPDATE: Since picocli 4.0 exit code support is very easy with the
execute
method.
Example with picocli 4.0:
@Command
class ExitCodeDemo implements Callable<Integer> {
@Parameters(index = "0", description = "manifest")
private File manifest;
public Integer call() {
// business logic here
return ok ? 0 : 123;
}
public static void main(String... args) {
int exitCode = new CommandLine(new ExitCodeDemo()).execute(args);
System.exit(exitCode);
}
}
The above program will exit with 1
if an exception occurred in the business logic, 2
if the user input was invalid, and if everything went well, exit with either 0
or 123
depending on the business logic (see the call
method).
If the "standard" error codes are enough for your application, you can also implement Runnable
.
Prior to picocli 4.0, applications needed to use the parseWithHandlers
method. This is now deprecated, but here is an example. The following program will exit with exit code 456 if the user provided invalid input:
// OLD: for picocli versions before 4.0 (DEPRECATED)
//
@Command
class Deprecated implements Runnable {
@Parameters(index = "0", description = "manifest")
private File manifest;
public void run() {
// business logic here
}
public static void main(String... args) {
CommandLine cmd = new CommandLine(new Deprecated());
cmd.parseWithHandlers(
new RunLast(),
CommandLine.defaultExceptionHandler().andExit(456),
args);
}
}
There are plans for adding better exit code support to picocli in version 4.0.
Upvotes: 3