With CommonsCli, how do I parse an Option which can occur several times and has a flexible number of values?

和自甴很熟 提交于 2021-02-11 14:58:18

问题


In some legacy code I'm porting a diy-command-line parser to Apache CommonsCli.

I can't break previously allowed+documented Options, and one of the Options is giving me trouble:

The Option has either one or two args, and can be specified as many times as desired. Option: [-option arg1 [arg2]]+

I want the result as String[][] as following:

cli -option a b -option c should result in [ [a, b], [c,] ] and

cli -option a -option b c should result in [ [a,], [b, c] ]

My code looks something like this:

final CommandLine cmd;
final Options options = new Options()
    .addOption(Option.builder("option").hasArg().hasArgs().build());
cmd = new DefaultParser().parse(options, args);

thatOption = cmd.getOptionValues("option");

But the parser spits out [a, b, c]

(I looked at cmd.getOptionProperties, and that might be a way to bodge it.)

Is there a way or do I need to subclass DefaultParser?


回答1:


I found a way that doesn't feel very elegant, but I'll take it unless someone comes around with a better one:

Loop over Option opt : cmd.getOptions() and assemble the String[][] from the opt.getValues() String[]s

Option option = Option.builder("option").hasArg().hasArgs().build();
final Options options = new Options()
    .addOption(option)
    .addOption("dummy", false, "description");
CommandLine cmd = new DefaultParser().parse(options, new String[] {"-option", "a", "b", "-option", "c", "-dummy"});
        
List<String[]> thatOption = new ArrayList<String[]>();
for (Option opt : cmd.getOptions()) {
    LOG.debug("opt: " + opt.getOpt());
    LOG.debug("equals: " + opt.equals(option));
    if (opt.getOpt() == "model") {
        LOG.debug(Arrays.asList(opt.getValues()).toString());
        thatOption.add(opt.getValues());
    }
}
LOG.debug("size: " + thatOption.size());
DEBUG Test :: equals: true
DEBUG Test :: [a, b]
DEBUG Test :: opt: model
DEBUG Test :: equals: true
DEBUG Test :: [c]
DEBUG Test :: opt: dummy
DEBUG Test :: equals: false
DEBUG Test :: size: 2


来源:https://stackoverflow.com/questions/64611233/with-commonscli-how-do-i-parse-an-option-which-can-occur-several-times-and-has

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!