Search code examples
spring-shell

Confirmation message Spring shell


Is there an way for a spring-shell command to first ask for a confirmation message. For example

command

Do you want to proceed [y/n]

y

executing command

I did some research on internet but I don't find example of this type of command.


Solution

  • I am using jline.console.ConsoleReader (which spring-shell currently uses as well) for this, so the code looks something like:

    public static boolean askYesNo(String question) {
        while (true) {
            String backup = ask(String.format("%s (y/n): ", question));
            if ("y".equals(backup)) {
                return true;
            }
            if ("n".equals(backup)) {
                return false;
            }
        }
    }
    
    public static String ask(String question) {
        question = "\n" + question + " > ";
    
        try {
            ConsoleReader consolereader = new ConsoleReader();
            return consolereader.readLine(question);
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return null;
    }