我想在不带参数运行 CLI 应用程序时自动显示帮助。 我发现这个问题在 StackOverflow 上出现了多次。我花了很多时间来解决这个问题,我读过 official document ,查了文章,但还是不清楚如何实现。
这就是我所拥有的:
主类
@Command(
subcommands = {C1.class, C2.class}
)
public class HelloCli implements Callable<Integer> {
@Option(names = {"?", "-h", "--help"},
usageHelp = true,
description = "display this help message")
boolean usageHelpRequested;
@Override
public Integer call() throws Exception {
System.out.println("wanna show the help here");
return 1;
}
public static void main(String... args) {
int exitCode = new CommandLine(new HelloCli()).execute(args);
System.exit(exitCode);
}
}
处理show-user函数的类:
@CommandLine.Command(name = "show-user",
aliases = "-show-user")
public class C1 implements Callable<Integer> {
@CommandLine.Option(names = {"?", "-h", "--help"},
usageHelp = true,
description = "display this help message")
boolean usageHelpRequested;
@CommandLine.Option(names = {"-p1"},
description = "show-user: param 1")
String p1;
@Override
public Integer call() throws Exception {
System.out.println("executing the 'show-user' business logic...");
System.out.println("param 1: " + p1);
return 4;
}
}
处理create-user命令的类:
@CommandLine.Command(name = "create-user",
aliases = "-create-user")
public class C2 implements Callable<Integer> {
@CommandLine.Option(names = {"?", "-h", "--help"},
usageHelp = true,
description = "display this help message")
boolean usageHelpRequested;
@CommandLine.Option(names = {"-p1"},
description = "create-user: another param 1")
String p1;
@Override
public Integer call() throws Exception {
System.out.println("executing the 'create-user' business logic...");
System.out.println("param 1: " + p1);
return 5;
}
}
情况 1:当我使用 -h
调用此应用程序时,帮助会正确显示:
Usage: <main class> [?] [COMMAND]
?, -h, --help display this help message
Commands:
show-user, -show-user
create-user, -create-user
情况 2:显示第一个函数的帮助,调用 show-user -h
:
Usage: <main class> show-user [?] [-p1=<p1>]
?, -h, --help display this help message
-p1=<p1> show-user: param 1
情况 3:获取第一个函数的帮助,调用 create-user -h
:
Usage: <main class> create-user [?] [-p1=<p1>]
?, -h, --help display this help message
-p1=<p1> create-user: another param 1
情况 4:在没有参数的情况下调用我的应用程序会显示以下内容:
wanna show the help here
我的问题很简单:
当我运行不带参数的 CLI 工具时如何显示帮助(案例 4
)?
我想我需要将自定义代码添加到 HelloCli.call()
方法中,并使用一个循环从实现函数的两个类收集帮助文本。但不确定如何。我还没有找到这个流行用例的任何示例代码。
我的附加问题与第一个问题类似:
我可以以某种方式显示将 Case 2
和 Case 3
中的所有内容一起显示的完整帮助吗?
最佳答案
这记录在有关子命令的部分中,Making Subcommands Required .
本质上,不要在顶级命令中实现 Callable 或 Runnable。这使得最终用户必须指定子命令。手册中有一个示例。
关于你的第二个问题,如何自定义使用帮助消息,请查看 picocli GitHub 项目的 picocli-examples 模块。很多示例都是关于自定义帮助的。 例如,this one在顶级命令的使用帮助中显示子命令(和子子命令)的完整层次结构。
关于java - picocli:如果没有给出参数则显示帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69488821/