Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 6

[ 131 ]

Adding a command-line interface


One more step in making our DSL roadworthy is to add a command-line interface to
it. In doing so, we move from invoking the DSL directly to allowing it to be loaded
by a DSL command. This gives us more control over the environment in which the
DSL will run, and allows us to take care of the housekeeping, such as adding the
search method to the String class.


Groovy being Groovy, adding a command line is surprisingly easy:


#!/usr/bin/env groovy
@Grab(group='org.twitter4j', module='twitter4j-core',
version='[4.0,)')

if (args)
evaluate(new File(args[0]))
else
println "Usage: GeeTwitter <script>"

The preceding shell script is all that we need in order to launch and run our
GeeTwitter DSL. Being a shell script, we can run this directly on most Linux
environments and Mac OS X, and on Windows if you have the Cygwin shell
installed. In the script, we will test to see if we have any arguments passed, and
evaluate the first argument as the name of a file containing the DSL script.


The evaluate method in Groovy allows us to pass a file containing Groovy code to
the Groovy interpreter. Any code contained within the file is compiled and executed
within the same virtual machine as the one where we are running the loading script.
When the preceding script is executed from the command, the groovy command is
invoked by the shell, which in turn launches a JVM. The evaluate method causes
the target script to be loaded and executed in the same environment, and everything
else works as if by magic.


Using the evaluate method means that any filename or extension can be used to
contain the Twitter DSL scripts. Instead of naming all of our GeeTwitter scripts with
the .groovy extension, we can decide that by convention our Twitter DSLs should
have the extension .gtwit.


By saving the command-line script as GTweet_1.0 in a file accessible on the
command path, we now have a bona fide Twitter DSL, implemented in Groovy,
and that we can invoke through a shell command.

Free download pdf