The user wants a Groovy script that demonstrates the usage of CliBuilder for parsing command-line arguments.
Key features requested:
- Support for long options (e.g.,
--help, --file).
- Support for required arguments (validation).
- Usage help generation (printing the help message).
1. What is CliBuilder?
It's a standard Groovy utility (built on top of Apache Commons CLI) that makes argument parsing easy and Groovy-esque.
2. Basic Structure:
I need a main method or just a script body.
I need to instantiate CliBuilder.
I need to define the options.
I need to parse the arguments (args).
I need to handle the parsing result (checking for existence, checking for missing required args).
I need to handle the help functionality.
3. Step-by-Step Implementation Plan:
- Import:
groovy.cli.CliBuilder (or just use it, as it's in the GDK, but explicit imports are good for clarity, though CliBuilder is usually available by default in standard Groovy installations. Actually, strictly speaking, CliBuilder lives in groovy.cli since Groovy 2.5, replacing the older groovy.util.CliBuilder).
- Instantiation:
def cli = new CliBuilder(...)
- Configuration:
usage: sets the usage string header.
header: text before options.
footer: text after options.
width: column width.
- Defining Options:
h (help): longOpt: 'help', showUsage: true (or just print usage manually).
i (input): longOpt: 'input', args: 1, argName: 'file', required: true (Note: CliBuilder doesn't enforce required: true automatically in the parse method in older versions, but in newer Groovy (2.5+) it does. I should check if I need to add manual validation or rely on the library. Actually, CliBuilder does support required: true, and it throws an error or prints usage if missing. Let's rely on the modern behavior).
v (verbose): longOpt: 'verbose', flag (no args).
o (output): longOpt: 'output', args: 1.
- Parsing:
def options = cli.parse(args)
- Logic:
- If
options is null (parsing failed), exit.
- If
options.h (help) is true, print usage (cli.usage()) and exit.
- Access values:
options.input, options.verbose.
4. Refining the "Required" logic:
While CliBuilder has a required property, it's often safer to check manually if the logic is complex, but for a simple script, setting required: true on the option definition is the standard way.
However, strict enforcement behavior depends on the underlying CLI library version. The modern CliBuilder (Groovy 2.5+) uses picocli or Commons CLI. If using Commons CLI, required: true works. If using Picocli (via the annotation API or specific builder), it's even better.
Let's stick to the standard groovy.cli.CliBuilder which wraps Commons CLI by default (or Picocli if configured).
Self-Correction/Refinement: To ensure the script is robust, I will check if options is null. CliBuilder.parse(args) returns null if arguments are invalid (like missing required args). Wait, actually, strictly speaking, CliBuilder prints the error message and usage automatically if a required arg is missing if configured correctly, but often it returns null or false.
Let's verify standard behavior:
If I define required: true, and the user doesn't provide it.
cli.parse(args) is called.
- It detects the missing arg.
- It prints an error to stderr.
- It returns
null.
So the code should be:
def options = cli.parse(args)
if (!options) {
return
}
5. Code Drafting:
import groovy.cli.CliBuilder
def cli = new CliBuilder(
usage: 'groovy script.groovy [options]',
header: 'Options:',
footer: 'And here is the footer.'
)
// Define options
cli.h(longOpt: 'help', 'Print this help message.')
cli.f(longOpt: 'file', args: 1, argName: 'path', required: true, 'Input file path.')
cli.v(longOpt: 'verbose', 'Enable verbose output.')
def options = cli.parse(args)
if (!options) {
// Parsing failed (e.g., missing required arg)
System.exit(1)
}
if (options.h) {
cli.usage()
System.exit(0)
}
// Logic
def file = options.f
if (options.v) {
println "Verbose mode on."
}
println "Processing file: $file"
6. Adding Comments and Explanations:
I should provide a script that is copy-paste ready and explain the key parts:
usage: string printed at the top.
longOpt: maps short flag to long flag.
args: 1 for single argument, 2 for two, etc.
required: enforces presence.
options object: acts like a map but allows dot notation (e.g., options.h or options.help).
7. Final Polish:
Make sure to handle the case where arguments are passed but empty, or strictly testing args array.
Let's look at CliBuilder specifically.
The syntax cli.f creates an option with short name 'f'.
longOpt: 'file' maps --file to -f.
required: true ensures it must be there.
I will produce a complete, runnable script with comments.
One nuance: argName is useful for the help display (e.g., shows [path] instead of [ARG]).
Let's review the prompt requirements again:
- Long options support: Yes (
longOpt).
- Required arguments support: Yes (
required: true).
- Usage help generation: Yes (
cli.usage()).
I will write the solution now.
Here is a complete, runnable Groovy script that demonstrates how to use CliBuilder. It includes standard options, long options, required argument validation, and automatic usage help generation.
The Script (cli_example.groovy)
Save the following code into a file named cli_example.groovy.
// Import the CliBuilder class
import groovy.cli.CliBuilder
// 1. Define the CliBuilder instance
// 'usage' defines the synopsis line printed at the top of the help message.
def cli = new CliBuilder(
usage: 'groovy cli_example.groovy [options]',
header: '\nAvailable options:',
footer: '\nThis is a footer message. Example provided by Groovy expert.'
)
// 2. Define the Options
// Option 1: Help (Standard flag)
// 'h' is the short option, 'help' is the long option.
cli.h(longOpt: 'help', 'Prints this help message.')
// Option 2: Input File (Required)
// 'args: 1' indicates this option takes one argument.
// 'required: true' enforces that this flag must be present.
cli.i(longOpt: 'input', args: 1, argName: 'file', required: true, 'Path to the input file.')
// Option 3: Verbosity (Optional Flag)
cli.v(longOpt: 'verbose', 'Enable verbose output.')
// Option 4: Output Directory (Optional with Default Value)
cli.d(longOpt: 'dest', args: 1, argName: 'dir', 'Output directory (default: ./output).')
// 3. Parse the arguments
// 'args' is the implicit String[] passed to the script
def options = cli.parse(args)
// 4. Validation and Logic
// If options is null, the parser failed (usually due to missing required args or invalid input).
if (!options) {
// CliBuilder automatically prints the error message and usage for us
// when required args are missing, so we just exit.
return
}
// Handle the Help flag manually
// If the user passes -h or --help, print usage and exit.
if (options.h) {
cli.usage()
return
}
// Logic: Access options using dot notation or array notation
def inputFile = options.i // or options['input']
def verbose = options.v // boolean
def outputDir = options.d ?: './output' // Use Elvis operator for default
// 5. Execute script logic
if (verbose) {
println "Verbose mode enabled."
println "Parsing complete. Processing..."
}
println "------------------------------------------------"
println "Configuration:"
println " Input File : ${inputFile}"
println " Output Dir : ${outputDir}"
println "------------------------------------------------"
println "Processing..."
How it works
- Import:
import groovy.cli.CliBuilder brings in the class.
- Configuration: We pass a map to the constructor.
usage: Sets the command line syntax summary.
header / footer: Text printed before and after the options list.
- Definition: We define options by calling methods on the
cli object.
- The method name is the short option (e.g.,
cli.i creates -i).
longOpt: Creates the long version (e.g., --input).
args: Number of arguments following the flag (1 = single value).
required: Enforces validation.
argName: Names the argument in the help output (e.g., shows <file> instead of <arg>).
- Parsing:
cli.parse(args) processes the command line inputs. If required constraints are violated, it returns null and automatically prints an error to STDERR.
- Access: You can access values using
options.shortCode (e.g., options.i).
How to run it
1. View the Help Menu:
groovy cli_example.groovy -h
Output:
usage: groovy cli_example.groovy [options]
Available options:
-d,--dest <dir> Output directory (default: ./output).
-h,--help Prints this help message.
-i,--input <file> Path to the input file.
-v,--verbose Enable verbose output.
This is a footer message. Example provided by Groovy expert.
2. Fail Validation (Missing required argument):
groovy cli_example.groovy
Output:
error: Missing required option: i
usage: groovy cli_example.groovy [options]
...
3. Run Successfully:
groovy cli_example.groovy -i data.txt -v
Output:
Verbose mode enabled.
Parsing complete. Processing...
------------------------------------------------
Configuration:
Input File : data.txt
Output Dir : ./output
------------------------------------------------
Processing...
4. Run with Long Options:
groovy cli_example.groovy --input data.csv --dest /tmp/data