select from a small amount of options in spring shell

后端 未结 3 942
感情败类
感情败类 2021-01-23 15:53

I am currently trying to make an cli app with Spring Shell.

I want the user to able to fast pick one of 2-3 options. My current code works fine in eclipse but when I sta

3条回答
  •  后悔当初
    2021-01-23 16:13

    Spring Shell 2 is based on JLine 3. For just a "small amount of options" I would recommend to use a feature like tab completion.

    (It works on Powershell, but I never get any tab-completion support in Eclipse-Console).

    It is quite easy:

    import java.util.List;
    import org.jline.reader.LineReader;
    import org.jline.reader.LineReaderBuilder;
    import org.jline.reader.impl.completer.StringsCompleter;
    import org.jline.terminal.Terminal;
    import org.springframework.context.annotation.Lazy;
    import org.springframework.shell.standard.ShellComponent;
    import org.springframework.shell.standard.ShellMethod;
    
    @ShellComponent
    public class CompleterInteractionCommand {
    
        private final List OPTIONS = List.of("create", "update", "delete");
        private final Terminal terminal;
    
        public CompleterInteractionCommand(@Lazy final Terminal terminal) {
            this.terminal = terminal;
        }
    
        @ShellMethod
        public String completeSelect() {
            LineReader lineReader = LineReaderBuilder.builder()
                    .terminal(this.terminal)
                    .completer(new StringsCompleter(this.OPTIONS))
                    .build();
            /* Important: This allows completion on an empty buffer, rather than inserting a tab! */
            lineReader.unsetOpt(LineReader.Option.INSERT_TAB);
    
            String desription = "select on of this options: " + OPTIONS + "\n"
                              + " use TAB (twice) to select them\n";        
            String input = lineReader.readLine(desription + "input: ").trim();
            return "you selected \"" + input + "\"";
        }
    }
    

提交回复
热议问题