Java Commons CLI-在使用帮助参数时重写必需的()参数
我以以下方式为解析器添加选项:Java Commons CLI-在使用帮助参数时重写必需的()参数,java,command-line-interface,apache-commons,apache-commons-cli,Java,Command Line Interface,Apache Commons,Apache Commons Cli,我以以下方式为解析器添加选项: options = new Options() .addOption(Option.builder(CONFIG_PARAM) .required() .hasArg(true) .argName(CONFIG_PARAM_NAME + "_path")
options = new Options()
.addOption(Option.builder(CONFIG_PARAM)
.required()
.hasArg(true)
.argName(CONFIG_PARAM_NAME + "_path")
.desc(CONFIG_PARAM_DESC)
.longOpt(CONFIG_PARAM_NAME)
.build())
(...)
.addOption(Option.builder(HELP_PARAM)
.hasArg(false)
.longOpt(HELP_PARAM_NAME)
.desc(HELP_PARAM_DESC)
.build());
现在,我只允许用户使用help命令,例如
mypreciousapp --help
使用上述解决方案,这是不可能的-我正在接收有关缺少所需参数的信息
Missing required options: c
有没有办法标记help参数,以便它可以覆盖所需的参数,并允许单独使用它?我可以手动执行此操作,但首先我想知道CLI lib中是否有此选项。commons CLI目前似乎不支持此选项,因此我将创建一个不需要参数的第二个Options对象,并在执行完整解析之前,先解析/检查该对象,如下所示:
public static void main(String[] args) {
// define the options with required arguments as needed
Options opts = new Options()
.addOption(Option.builder("p")
.required()
.hasArg(true)
.argName("arg")
.desc("description ")
.longOpt("param")
.build())
.addOption(Option.builder("h")
.hasArg(false)
.longOpt("help")
.desc("help description")
.build());
// first check if usage-output was requested
if (handleHelp(args, opts)) {
return;
}
// now handle the full options
CommandLineParser parser = new DefaultParser();
final CommandLine cmdLine;
try {
cmdLine = parser.parse(opts, args);
} catch (ParseException ex) {
System.out.println("Syntax error: " + ex.getMessage());
printHelp(opts);
return;
}
// now handle options and do your work
}
private boolean handleHelp(String[] args, Options opts) {
Options helpOpts = new Options()
.addOption(Option.builder("p")
//.required()
.hasArg(true)
.argName("arg")
.desc("description ")
.longOpt("param")
.build())
.addOption(Option.builder("h")
.hasArg(false)
.longOpt("help")
.desc("help description")
.build());
CommandLineParser helpParser = new DefaultParser();
final CommandLine cmdLine;
try {
cmdLine = helpParser.parse(helpOpts, args);
} catch (ParseException ex) {
System.out.println("Syntax error: " + ex.getMessage());
printHelp(opts);
return true;
}
if(cmdLine.hasOption("h")) {
printHelp(opts);
return true;
}
return false;
}
private void printHelp(Options opts) {
try (PrintWriter pw = new PrintWriter(System.out)) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(pw, 80, "myapp", "test-header", opts,
formatter.getLeftPadding(), formatter.getDescPadding(), "test-footer", true);
}
}
commons cli库有一个流畅的包装器:
-h选项已经内置。您不需要在自己的代码中管理它。您可以尝试添加一个OptionGroup,它表示一组独占选项(只允许组中的一个选项出现),并将所有必需的选项放在该组中(包括
-help
)。