Implementing interactive confirmation in picocli

Ime*_*iri 4 java command-line-interface picocli

In a CLI app built using picocli, what is the most appropriate way to implement an interactive confirmation?

The scenario is, when a certain command is run, I need to get a confirmation from the user to do a certain task. I used the interactive option mentioned in the picocli documentation but it's not working as expected.

@CommandLine.Option(names = {"-c", "--copy-contract"},
            description = "Do you want to copy the contract in to the project?", interactive = true, arity = "1")
boolean isCopy;
Run Code Online (Sandbox Code Playgroud)

The above option doesn't seem to trigger a user input when the command is run.

Any idea?

Rem*_*pma 7

如果(且仅当)指定了该选项,该@Option(names = "-c", interactive = true)属性将导致 picocli 提示用户。-c

如果应用程序还需要在未指定选项时提示用户-c,目前需要在应用程序代码中完成。

从 picocli 4.3.2 开始,这可以通过以下方式完成:

class MyApp implements Runnable {
    @Option(names = {"-c", "--copy-contract"},
            description = "Do you want to copy the contract in to the project?",
            interactive = true, arity = "1")
    Boolean isCopy;

    public void run() {
        if (isCopy == null) {
            String s = System.console().readLine("Copy the contract? y/n: ");
            isCopy = Boolean.valueOf(s) || "y".equalsIgnoreCase(s);
        }
        System.out.printf("isCopy=%s%n", isCopy);
    }

    public static void main(String... args) {
        new CommandLine(new MyApp()).execute(args);
    }
}
Run Code Online (Sandbox Code Playgroud)

(有一个功能请求将其包含在未来版本的 picocli 中。)