Module io.github.mmm.cli
Provides the API and implementation to parse the arguments of a
main
method from a command-line-interface
(CLI).Command-Line-Interfaces (CLI)
Building a Java application with a CLI is kind of tedious.The Problem
A regular Java application start with amain
method:
public static void main(String[] args) { // ... }However, you quickly notice that this was not the end of wisdom when designing an object-oriented language as Java. A main-program often starts easy and then over the time options and arguments are added. When you want to write a maintainable main-program you want to have more infrastructure than just having a
String
-array lost in a
static method. The Solution
As a minimal low-level solution we provideCliArgs
:
public class Main { private boolean verbose; private boolean debug; private boolean force; List<String> values = new ArrayList<>(); public static void main(String[] args) { int exitCode = run(newNow you can run thisCliArgs
(args)); System.exit(exitCode); } public int run(CliArgs
args) {CliArgument
arg = args.getFirst()
; while (arg != null) { if (arg.isOption()
) { switch (arg.get()) { case "-h": case "--help": printHelp(); return 0; break; case "-v": case "--verbose": this.verbose = true; break; case "-d": case "--debug": this.debug = true; break; case "-f": case "--force": this.force = true; break; default: System.err.println("Illegal option: " + arg); return -1; } } else { this.values.add(arg.get()
); } arg = arg.getNext()
; } // do something } }
Main
program with:
Main -v -d -f file1 file2You can quickly guess what will happen, but you can also do the same thing with:
Main -vdf file1 file2And if you want to provide a filename starting with a hyphen you can do
Main -vdf -- -filenameFurther, a CLI may have options that need a value:
App --option-name option-valueYour
App
does not need to be rewritten to also accept:
App --option-name=option-valueOf course the
Main
program was still complex and this is just the beginning. We provide a higher-level module
mmm-nls-cli
to make it even much simpler and add additional cool features.-
-
Packages
Exports Package Description io.github.mmm.cli Contains the API and implementation to parse the arguments of amain
method from a command-line-interface (CLI).io.github.mmm.cli.exception Contains common exceptions for CLI.io.github.mmm.cli.io io.github.mmm.cli.io.impl Contains internal implementations of this module.
-
Modules
Requires Modifier Module Description transitive io.github.mmm.base Provides fundamental APIs and helper classes.
-