Back to DevDoc

How to add a new commend in a Groovysh?

Simply by using this king of hack:

import groovy.lang.Binding;
import java.util.List;
import org.codehaus.groovy.ant.Groovy;
import org.codehaus.groovy.tools.shell.CommandSupport;
import org.codehaus.groovy.tools.shell.Groovysh;
import org.codehaus.groovy.tools.shell.IO;
import org.codehaus.groovy.tools.shell.Shell;

public class UIConsole {

    public static void main(String[] args) {

        Binding binding = new Binding();

        Groovysh g = new Groovysh(Groovy.class.getClassLoader(), binding, new IO());

        g.leftShift(new HelloWorld(g,"helloworld", "\\hw"));
        g.run();
    }
}

class HelloWorld extends  CommandSupport {

    public HelloWorld(Shell shell, String string, String string1) {
        super(shell, string, string1);
    }

    public Object execute(List list) {
        shell.getIo().out.println("Hello World!");
        return null;
    }

}

It will produce:

Groovy Shell (1.7.0, JVM: 1.6.0_17)
Type 'help' or '\h' for help.
-------------------------------------------------------------------------------------------------------------
groovy:000> \hw
Hello World!
groovy:000> helloworld 
Hello World!
groovy:000> 

Moreover, completion works!

logo cemagref

logo iscpif

logo lifegrid

logo region auvergne

logo patres project