picocli 缺少参数时的非零退出代码

Non-zero exit code on missing parameter with picocli

我有一个带有一个强制参数的简单 Command

@Parameters(index = "0", description = "manifest")
private File manifest;

当我在没有参数的情况下从命令行调用它时,我得到了预期的消息:

Missing required parameter: <manifest>
Usage ....

但是:调用 java 的 return 代码为 0,表示一切正常。 如果参数(或选项)是 missing/incorrect,有没有办法让 picocli return 非零代码?

是的,这是可能的。

UPDATE: Since picocli 4.0 exit code support is very easy with the execute method.

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);
    }
}

如果业务逻辑出现异常,上述程序将退出并返回 1,如果用户输入无效,则返回 2,如果一切顺利,则退出并返回 0123 取决于业务逻辑(参见 call 方法)。

如果 "standard" error codes 足以满足您的应用,您还可以实施 Runnable


在 picocli 4.0 之前,应用程序需要使用 parseWithHandlers 方法。现在已弃用,但这是一个示例。如果用户提供了无效输入,以下程序将以退出代码 456 退出:

// 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);
    }
}

picocli 4.0版本有plans for adding better exit code support