我有一个用例,我需要以指定格式发布 CLI 的整个帮助。我找到了一种使用以下方法的方法:
@CommandLine.Command(name="myAp",
synopsisSubcommandLabel = "", usageHelpWidth = 120,
commandListHeading = "",
customSynopsis = "\n\nArguments for MyApp operation.\n"
+ "\n"
+ "Operations:\n"
+ " create Create the stuff\n"
+ " list List the stuff\n"
+ " add Add things\n"
+ " -r --type One or both of [Type1, Typ2]\n"
+ " -a --annualCost AnnualCost\n"
+ " -n --number Number of each type thing\n"
+ " subtract Subtract things\n"
+ " -r --reasons Combination of\n"
+ " fiscal (fiscal reason)\n"
+ " operational (operational reason\n"
+ " other (other reason)\n"
+ " -h Display this help message and exit\n"
)
class PicoCliParser {
// All of my other Parameters and options here
@Option(names = { "-h", "--help" }, usageHelp = true, hidden = true)
boolean helpRequested = false;
public static void main(String[] args) throws Exception {
PicoCliParser parser = new PicoCliParser();
CommandLine cmd = new CommandLine(parser);
try {
CommandLine.ParseResult parseResult = cmd.parseArgs(args);
System.err.println("parseResults: " + parseResult.matchedArgs().toString());
if (cmd.isUsageHelpRequested()) {
cmd.usage(System.out);
}
} catch (CommandLine.ParameterException e) {
}
}
}
如果用户输入 -h 或 --help,帮助会以我想要的格式打印出来,如果他们不输入 -h 或 -H 则不会。
有一个更好的方法吗?
如果我们将来添加其他命令,那么添加它们的人必须记住更新帮助字符串。