需要帮助在groovysh中实现新命令

时间:2014-11-19 23:40:27

标签: groovy scripting groovysh

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

我注意到groovysh中有一个“register”命令,允许您注册新命令。在找不到任何结果后,我最终查看了现有命令的源代码,并提出了这个问题:

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

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

1 个答案:

答案 0 :(得分: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"
    }
}

我同意这是不必要的过分复杂。