Skip to content

subcommands

h908714124 edited this page Apr 30, 2023 · 18 revisions

The SuperCommand annotation can be used to create a command/subcommand structure. A @SuperCommand parser is similar to a @Command parser, but it stops parsing after the last positional parameter was read, and simply returns the remaining tokens:

@SuperCommand(
        name = "git",
        description = "Git is software for tracking changes in any set of files.")
interface GitCommand {

  @Parameter(index = 0)
  String command();

  @VarargsParameter
  List<String> remainingTokens();
}

The generated GitCommandParser can be used as follows:

GitCommand gitCommand = new GitCommandParser().parseOrExit(new String[]{"add", "foo"});
String command = result.command(); // "add"
List<String> remainingTokens = result.remainingTokens(); // ["foo"]

We can define a "subcommand" to parse the remaining tokens. The subcommand is just a regular @Command.

@Command(
        name = "git-add",
        description = "Add file contents to the index")
interface AddCommand {
    @VarargsParameter
    List<String> pathspec();

    // more parameters and options...
}
Clone this wiki locally