2

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

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

4

1 回答 1

2

更新:这现在记录在 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.

如果命令有子命令但没有实现Runnableor Callable,picocli 将强制子命令。

例如:

@Command(name = "top", subcommands = {Sub1.class, Sub2.class},
         synopsisSubcommandLabel = "COMMAND")
class TopCommand {
    public static void main(String[] args) {
        CommandLine.run(new TopCommand(), args);
    }
}
于 2018-10-29T10:52:05.870 回答