从弹簧壳中选择少量选项 [英] select from a small amount of options in spring shell
问题描述
我目前正在尝试使用Spring Shell制作一个cli应用程序.
I am currently trying to make an cli app with Spring Shell.
我希望用户能够快速选择2-3个选项之一.我当前的代码在eclipse中运行良好,但是当我在Powershell中启动它时,我必须多次按Enter键(至少3次)才能选择该选项.按下Enter键一次之后,什么也没发生.
I want the user to able to fast pick one of 2-3 options. My current code works fine in eclipse but when I start it in Powershell, i have to hit enter multiple times (at least 3 times) in order to select the option. After pressing enter once, nothing happens.
我当前的方法:
@ShellMethod(key = { "setService", "select" }, value = "Choose a Speech to Text Service")
public void setService() {
boolean success = false;
do {
this.console.write("Please select a speech recognition service. Type in the number and press enter:");
this.console.write("1. Google Speech API");
this.console.write("2. Bing Speech API");
// Get Input
Scanner s = new Scanner(System.in);
String input = s.nextLine();
// Select Service
switch (input) {
case "1":
/*
* do something...
*/
console.write("Google Speech API selected");
success = true;
break;
case "2":
/*
* do something...
*/
console.write("Bing Speech API selected");
success = true;
break;
default:
this.console.error("Input not valid. Please type a number and press Enter to select a Service");
break;
}
} while (!success);
}
我该如何解决Powershell的问题,还是有一种更优雅的方法来执行此输入?
How can i fix the issue with powershell or is there a more elegant way to perform this input?
推荐答案
Spring Shell 2基于 JLine 3 .对于少量选项",我建议使用选项卡补全等功能.
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.
(它可以在Powershell上运行,但是在Eclipse-Console中我从未获得任何制表符完成支持).
这很容易:
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<String> 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 + "\"";
}
}
这篇关于从弹簧壳中选择少量选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!