【发布时间】:2021-11-27 23:56:35
【问题描述】:
我想在不带参数运行 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:第一个函数的chow help,调用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 工具时如何显示帮助 (Case 4)?
我想我需要将自定义代码添加到 HelloCli.call() 方法中,并使用一个循环从实现这些功能的两个类中收集帮助文本。但不确定如何。我没有找到这个流行用例的任何示例代码。
我的附加问题与第一个问题类似:
我能以某种方式展示来自Case 2 和Case 3 的全部帮助吗?
【问题讨论】:
标签: java command-line-interface picocli