--- title: "Command Line Argument Parsing for Groovy | Jarrod Roberson: Programming Missives" tags: - IT/Development/Groovy --- Groovy has some wrappers around the apache.commons.cli via their CLIBuilder class. This is a pretty old and crusty library that has some significant limitations. I prefer to use the Java Simple Argument Parser (JSAP) library. Especially since they have added the ability to declare argument definitions in a declarative XML file. This reduces the code footprint in your Groovy or Java program significantly. Normally I am adverse to XML configuration programming but in this case the syntax is very succinct and an appropriate use. Here is a partial example of argument declarations for an example program that scans for open ports on a server. ```xml help h help Display this help host StringStringParser true h host Server to use to scan for open ports ports IntegerStringParser true true , List of ports to scan on the server ``` [jsap.xml](https://gist.github.com/jarrodhroberson/8995420#file-jsap-xml) hosted with ❤ by GitHub Then you can use the following boilerplate code to initialize the parser and use it. Assuming the code is saved in file named “main.groovy” and the configuration file is named “main.jsap” and both are built into a .jar file called main.jar 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ```groovy JSAP jsap = new JSAP(main.getResource("main.jsap")); JSAPResult config = jsap.parse(args) if (config.getBoolean("help") || !config.success()) { println "Usage: java -jar main.jar " + jsap.usage println "" println jsap.help if (!config.success()) { for (e in config.getErrorMessageIterator()) { println e } } System.exit(0) } ``` [main.groovy](https://gist.github.com/jarrodhroberson/8995431#file-main-groovy) hosted with ❤ by GitHub That is basically all the code you need to easily and powerfully parse command line arguments in Groovy.