是否可以在 Spring Shell 中使用制表符补全值?

Tet*_*igi 5 java shell spring spring-shell

我目前正在尝试改进 Spring Shell 应用程序,而使其变得更好的一件事是它是否支持值和选项的制表符补全。

举个例子,如果我的 CLI 有一个命令getInfo --name <name>,其中<name>是数据库中有限名称集中的一个名称,那么能够很方便地执行以下操作

> getInfo --name Lu<tab>
  Lucy Luke Lulu
> getInfo --name Luk<tab>
> getInfo --name Luke
Run Code Online (Sandbox Code Playgroud)

有没有办法使用现有的 Spring Shell 工具来做到这一点?我浏览了文档,但找不到任何有关自动完成值的信息。

干杯!

Enr*_*uel 1

您可以注册一个 Converter 来将此功能转换为 String 类型。已经有一些已经创建的转换器,并且org.springframework.shell.converters.EnumConverter具有您正在寻找的功能。

要注册转换器,您需要实现org.springframework.shell.core.Converter 接口:

@Component
public class PropertyConverter implements Converter<String> {

    public boolean supports(Class<?> type, String optionContext) {
        return String.class.isAssignableFrom(type)
                && optionContext != null && optionContext.contains("enable-prop-converter");
    }

    public String convertFromText(String value, Class<?> targetType, String optionContext) {
        return value;
    }

    public boolean getAllPossibleValues(List<Completion> completions, Class<?> targetType, String existingData,
            String optionContext, MethodTarget target) {
        boolean result = false;

        if (String.class.isAssignableFrom(targetType)) {
            String [] values = {"ONE", "BOOKING", "BOOK"};

            for (String candidate : values) {
                if ("".equals(existingData) || candidate.startsWith(existingData) || existingData.startsWith(candidate)
                        || candidate.toUpperCase().startsWith(existingData.toUpperCase())
                        || existingData.toUpperCase().startsWith(candidate.toUpperCase())) {
                    completions.add(new Completion(candidate));
                }
            }

            result = true;
        }
        return result;
    }

}
Run Code Online (Sandbox Code Playgroud)

在前面的示例中,我为 String 对象注册了一个转换器,当 @CliOption 注解的 optionContext 具有enable-prop-converter.

您还必须禁用默认的 StringConverter。在下一行中,我禁用了 @CliOption Annotation 中的默认字符串转换器,disable-string-converter并启用了新的 PropertyConverter enable-prop-converter

@CliOption(key = { "idProp" }, mandatory = true, help = "The the id of the property", optionContext="disable-string-converter,enable-prop-converter") final String idProp
Run Code Online (Sandbox Code Playgroud)