I am trying to parse a command line with a wildcard command after a set of known parameters in the following format:
program [parameters] <command> [<subcommand> ...] [other-parameters]I don't know this command at compile time but at runtime have a locator available that can give me a list of all commands available in the context.
I read the docs
http://jcommander.org/#_more_complex_syntaxes_commands which sort of almost work.
The program would look like this:
program -v 2 -l profile set name fred -rIt's sort of like a token scanner that parses the command args
-v 2 and -l then tries to resolve the command arg
profile and captures the remainder
set name fred -r in an arg array for further processing.
I tried with a @Parameter without a name but that captures the command as well and swallows the [other-parameters].
Is that at all possible with JCommander?
This is what I tried but obviously not working.
import static org.junit.Assert.*;
import org.junit.Test;
import java.util.List;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
public class ParserTest {
@Test
public void commandCaptureTest() {
Args args = new Args();
JCommander.newBuilder()
.addObject(args)
.build()
.parse("-v", "2", "-l", "profile", "set", "name", "fred", "-r");
assertEquals(Integer.valueOf(2), args.verboseLevel);
assertTrue(args.longList);
assertEquals(4, args.extraArgs.size());
}
static class Args {
@Parameter(names = "-v", description = "Print verbose messages")
Integer verboseLevel = 0;
@Parameter(names = "-l", description = "Show a long listing")
boolean longList;
@Parameter
List<String> extraArgs;
}
}