Green Moon Software, LLC


Pretty Command Line Parameters in Groovy

It is no secret that I love the Groovy language. I believe it is a great language for application development. It is an even better language for writing script files. A halmark of a good script or command line executable is the quality of it’s help message. What happens when you run command.sh -h? Groovy has excellent support for reading and paring command line parameters via it’s CliBuilder class. The documentation is very through, but it doesn’t really showcase how easy it is to use.

I use Jekyll to build this site. I use a log of custom scripts to manage creating posts, drafts, publishing posts, etc. These scripts are all written in Groovy. I don’t use these scripts too often, so I forget all of the command line switches. Below is the first couple lines:

Line 1 creates the CliBuilder and initializes the usage attributes. Passing “this.class.simpleName” is a nice, copy-and-paste default setting that can be utalized in most every script. No longer will you have the wrong executable script name in your usage output.

The cli.with closure is a great shorthand for defining the various parameters for the script. It maintains readability, especially if the parameters are in alphabetical order.

The parameters are read into the opts variable via the parse command. A quick check to ensure that the opts were parsed correctly with a bail out if not.

The last two lines shows that reading the parameters is as simple as pulling them out of the parsed opts via their parameter names. It is easy to add default values using the Elvis Operator

Running the script from above without any of the required parameters produces the following:

Sometimes you do not want a short, one-letter argument. You indicate these parameters using the _ character in the with {...} closure. I have an example of this is in the Porpoise project’s script.

I hope this short introduction helps highlight how easy the CliBuilder is to use. Now you have no excuses not to include beautiful help output in your Groovy command line scripts.

comments powered by Disqus