1

我发现关于为 Groovysh 构建新命令的信息非常少。我想将它用作我的开发环境的正常部分,在某种程度上取代 cmd.exe()。

我确实注意到 groovysh 中有一个“注册”命令,可让您注册新命令。在什么都没找到后,我最终查看了现有命令的源代码并提出了这个:

import org.codehaus.groovy.tools.shell.*

class test extends CommandSupport
{
    public static final String COMMAND_NAME = 'findall'

    // Printed when you use the help command specifying 'find' as an argument
    String help="Help"
    String usage="Usage"

    // Printed when you use the help command with no arguments
    String description="Description"    

    public test(org.codehaus.groovy.tools.shell.Groovysh shell)
    {
            super(shell, COMMAND_NAME, 'find')
    }
    Object execute(List<String> args)
    {
        return "Commanded "+args+" "+args.size()
    }

}

这完成了我想要的大部分工作,但我有几个问题。首先,传递给“执行”的东西以一种丑陋的方式进行了预解析。如果我试图找到一个像“测试奇怪间距”这样的字符串,我会得到 [“测试,奇怪,间距”] 我可以使用引号来重建应该作为单个字符串引用的内容,但我无法替换额外的空格"

第二个问题是我想使用制表符完成。我可以看到有 getCompleter 和 makeCompleters 命令,但没有关于完成程序是什么的信息...... javadocs 链接到一个不存在的页面。

JLine 库中有完成者,但我不确定它们是否相同(我倾向于怀疑它,因为 JLine 无法从 groovysh 访问,如果您需要使用它们来编写脚本,您会认为它们可以访问)

如果有人知道一个博客可以指导您如何做这种事情 - 或者有一些最小的例子,我会很感激帮助。

4

1 回答 1

0

您已经很好地破译了 groovy 源。您可以在覆盖的 createCompleters 方法中返回 jline completeres。您还可以使用 org.codehaus.groovy.tools.shell.util 中的 completeres。

import jline.console.completer.StringsCompleter
import org.codehaus.groovy.tools.shell.CommandSupport
import org.codehaus.groovy.tools.shell.Groovysh
import org.codehaus.groovy.tools.shell.util.SimpleCompletor;

public class GroovyshCmd extends CommandSupport {
    public static final String COMMAND_NAME = ':mycmd'
    public static final String SHORTCUT = ':my'

    protected GroovyshCmd(Groovysh shell) {
        super(shell, COMMAND_NAME, SHORTCUT)
    }

    @Override
    public List<Completer> createCompleters() {
        //return [new SimpleCompletor((String[])["what", "ever", "here"]), null]
        return [new StringsCompleter("what", "ever", "here"), null]
    }

    @Override
    public Object execute(List<String> args) {
        println "yo"
    }
}

我同意这不必要地过于复杂了。

于 2016-06-06T20:51:57.183 回答