パラメータなしで CLI アプリを実行すると、ヘルプが自動的に表示されるようにしたいと考えています。この質問が StackOverflow で複数回表示されることを確認しました。私はこれを理解するのにかなりの時間を費やしました.公式文書を読み、記事をチェックしましたが、これを達成する方法はまだ明確ではありません.
これは私が持っているものです:
メインクラス
@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: 1 番目の関数のヘルプを表示し、次を呼び出しcreate-user -h
ます。
Usage: <main class> create-user [?] [-p1=<p1>]
?, -h, --help display this help message
-p1=<p1> create-user: another param 1
ケース 4: param なしでアプリを呼び出すと、次のようになります。
wanna show the help here
私の質問は簡単です:
パラメータなしで CLI ツールを実行するときにヘルプを表示するにはどうすればよいですか ( Case 4
)?
HelloCli.call()
関数を実装する 2 つのクラスからヘルプ テキストを収集するループを使用して、メソッドにカスタム コードを追加する必要があると思います。しかし、方法がわからない。この一般的なユース ケースのサンプル コードは見つかりませんでした。
私の追加の質問は最初のものと似ています: と からすべてをまとめて表示される完全なヘルプを何らかの方法で表示できますCase 2
かCase 3
?