Rem*_*pma 3 command-line-arguments subcommand picocli
我有一个带有子命令的命令。在我的应用程序中,我希望用户强制指定子命令。我该怎么做?
更新:这现已记录在 picocli 手册中:https ://picocli.info/#_required_subcommands
在 picocli 4.3 之前,实现此目的的方法是显示错误或抛出ParameterException在 picocli 4.3 之前,实现此目的的方法是,如果在没有子命令的情况下调用顶级命令,则
例如:
@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");
}
}
Run Code Online (Sandbox Code Playgroud)
从 picocli 4.3 开始,通过不执行 顶级命令Runnable或Callable更轻松地完成此操作。
如果该命令有子命令但没有实现Runnable或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);
}
}
Run Code Online (Sandbox Code Playgroud)