Picocli:如何使子命令成为必需的

Picocli: how to make subcommands required

我有一个带有子命令的命令。在我的应用程序中,我希望用户必须指定一个子命令。我应该怎么做?

(另见 https://github.com/remkop/picocli/issues/529

更新:现在已记录在 picocli 手册中:https://picocli.info/#_required_subcommands


在 picocli 4.3 之前,如果在没有子命令的情况下调用顶级命令,实现此目的的方法是显示错误或抛出 ParameterException

例如:

    @Command(name = "top", subcommands = {Sub1.class, Sub2.class},
             synopsisSubcommandLabel = "COMMAND")
    class TopCommand implements Runnable {

        @Spec CommandSpec spec;

        public void run() {
            throw new ParameterException(spec.commandLine(), "Missing required subcommand");
        }

        public static void main(String[] args) {
            CommandLine.run(new TopCommand(), args);
        }
    }

    @Command(name = "sub1)
    class Sub1 implements Runnable {
        public void run() {
            System.out.println("All good, executing Sub1");
        }
    }

    @Command(name = "sub2)
    class Sub2 implements Runnable {
        public void run() {
            System.out.println("All good, executing Sub2");
        }
    }

从 picocli 4.3 开始,通过使顶级命令 不实现 RunnableCallable.[=18= 可以更轻松地完成此操作]

如果命令有子命令但没有实现 RunnableCallable,picocli 将强制执行子命令。

例如:

@Command(name = "top", subcommands = {Sub1.class, Sub2.class},
         synopsisSubcommandLabel = "COMMAND")
class TopCommand {
    public static void main(String[] args) {
        CommandLine.run(new TopCommand(), args);
    }
}