-
Notifications
You must be signed in to change notification settings - Fork 445
Executing Commands
Picocli 4.0 introduced new API to execute commands. Let’s take a quick look at what changed.
Many command line applications return an exit code to signify success or failure. Zero often means success, other than that, conventions differ.
The new execute API returns an int, and applications can use this value to call System.exit if desired.
Older versions of picocli had some exit code support where picocli would call System.exit, but this is now deprecated.
public static void main(String... args) {
CommandLine cmd = new CommandLine(new App());
int exitCode = cmd.execute(args);
System.exit(exitCode);
}@Command-annotated classes that implement Callable and @Command-annotated methods can simply return an int or Integer value that will be returned from CommandLine.execute. For example:
@Command(name = "greet")
class Greet implements Callable<Integer> {
public Integer call() {
System.out.println("hi");
return 1;
}
@Command
int shout() {
System.out.println("HI!");
return 2;
}
}Commands with a user object that implements Runnable can implement the IExitCodeGenerator interface to generate an exit code. For example:
@Command(name = "wave")
class Wave implements Runnable, IExitCodeGenerator {
public int getExitCode() {
return 3;
}
public void run() {
System.out.println("wave");
}
}The above commands define two top-level commands, greet and wave. The greet command has one subcommand, shout.