Search code examples
javacommand-line-interfacepicocli

Java: picocli: How to provide argument to command without naming it?


Is it possible to provide argument to @CommandLine.Command without explicitly naming the argument in picocli?

As example the following command can be invoked as: open n 1. However, I would like to be able to invoke the command as open 1.

@CommandLine.Command(name = "open",
    mixinStandardHelpOptions = true,
    version = "1.0",
    description = "Open note")
@Getter
@ToString
public class OpenCommand implements Runnable {
    @CommandLine.ParentCommand TopLevelCommand parent;


    @CommandLine.Option(names = {"number", "n"}, description = "Number of note to open")
    private Integer number;


    public void run() {

        System.out.println(String.format("Number of note that will be opened: " + number));
    }
}

Solution

  • Picocli offers the @Parameters annotation for positional parameters, in addition to the @Option annotation, which is for named parameters.

    If you use the @Parameters annotation for the number, instead of @Option(names = "n"), then end users can invoke the command as open 1.

    That is a fairly minimal change, the resulting code could look like this:

    @CommandLine.Command(name = "open",
        mixinStandardHelpOptions = true,
        version = "1.0",
        description = "Open note")
    @Getter
    @ToString
    public class OpenCommand implements Runnable {
        @CommandLine.ParentCommand TopLevelCommand parent;
    
        @CommandLine.Parameters(description = "Number of notes to open")
        private Integer number;
    
        public void run() {
            System.out.printf("Number of notes that will be opened: %s%n", number);
        }
    }