I have a command with subcommands. In my application I want it mandatory for the user to specify a subcommand. How should I do this?
(See also https://github.com/remkop/picocli/issues/529)
Update: this is now documented in the picocli manual: https://picocli.info/#_required_subcommands
Prior to picocli 4.3, the way to achieve this would be to show an error or throw a ParameterException if the top-level command is invoked without subcommand.
For example:
    @Command(name = "top", subcommands = {Sub1.class, Sub2.class},
             synopsisSubcommandLabel = "COMMAND")
    class TopCommand implements Runnable {
        @Spec CommandSpec spec;
        public void run() {
            throw new ParameterException(spec.commandLine(), "Missing required subcommand");
        }
        public static void main(String[] args) {
            CommandLine.run(new TopCommand(), args);
        }
    }
    @Command(name = "sub1)
    class Sub1 implements Runnable {
        public void run() {
            System.out.println("All good, executing Sub1");
        }
    }
    @Command(name = "sub2)
    class Sub2 implements Runnable {
        public void run() {
            System.out.println("All good, executing Sub2");
        }
    }
From picocli 4.3, this can be accomplished more easily by making the top-level command not implement Runnable or Callable.
If the command has subcommands but does not implement Runnable or Callable, picocli will make subcommands mandatory.
For example:
@Command(name = "top", subcommands = {Sub1.class, Sub2.class},
         synopsisSubcommandLabel = "COMMAND")
class TopCommand {
    public static void main(String[] args) {
        CommandLine.run(new TopCommand(), args);
    }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With