Skip to content

CmdOption is a simple annotation-driven command line parser toolkit for Java 5 applications that is configured through annotations.

License

Notifications You must be signed in to change notification settings

RonStein2000/CmdOption

 
 

Repository files navigation

CmdOption - Command line parsing has never been easier

Overview

CmdOption is a simple annotation-driven command line parser toolkit for Java 5 applications. Everything you need is (at least one) simple configuration object. Each field and method annotated with an @CmdOption annotation will be processed. Based on this config, CmdOption is able to parse any commandline, guaranteeing the declared specification. The result is directly stored in the given config object. When errors occur, CmdOption gives a meaningful error message. Generated output and validation/error messages can be localized.

This document shows usage, configuration options and some advanced topics. Please also visit the project wiki for more examples and user provided content.

Download

CmdOption is available from Maven central repository.

Maven users can use the following dependency declaration:

<dependency>
    <groupId>de.tototec</groupId>
    <artifactId>de.tototec.cmdoption</artifactId>
    <version>0.4.2</version>
</dependency>

SBuild users can use the following dependency:

"mvn:de.tototec:de.tototec.cmdoption:0.4.2"

Example

A simple config class could look like this:

package org.example;

import java.util.*;
import de.tototec.cmdoption.CmdOption;

public class Config {
  @CmdOption(names = { "--help", "-h" }, description = "Show this help", isHelp = true)
  boolean help;

  @CmdOption(names = { "--verbose", "-v" }, description = "Be more verbose")
  boolean verbose;

  @CmdOption(names = { "--options", "-o" }, args = { "name", "value" }, maxCount = -1, description = "Additional options when processing names")
  Map<String, String> options = new LinkedHashMap<String, String>();

  @CmdOption(args = { "file" }, description = "Names to process", minCount = 1, maxCount = -1)
  List<String> names = new LinkedList<String>();
}

For a more complete example see also the translation example and also visit the Wiki.

The commandline based on the config object above can contain:

  • an optional --help or -h option, which (when used) disables the commandline validation

  • an optional --verbose or -v option

  • any count of additional option pairs via --options or -o

  • at least on paramter

Parsing the command line is as easy as the following three lines:

Config config = new Config();
CmdlineParser cp = new CmdlineParser(config);
cp.parse(new String[] {"-v", "file1.txt", "file2.txt"});

assert config.verbose;
assert config.names.length() == 2;
assert config.options.isEmpty();

The complete Java class could look like this:

package org.example;

import de.tototec.cmdoption.CmdlineParser;

public class Main {
  public static void main(final String[] args) {
    final Config config = new Config();
    final CmdlineParser cp = new CmdlineParser(config);
    cp.setProgramName("myapp");

    // Parse the cmdline, only continue when no errors exist
    cp.parse(args);

    if (config.help) {
      cp.usage();
      System.exit(0);
    }

    // ...
  }
}

When invoked with the --help (or -h) option, you would see the following output:

Usage: myapp [options] [parameter]

Options:
  --help,-h                Show this help
  --options,-o name value  Additional options when processing names
  --verbose,-v             Be more verbose

Parameter:
  file  Names to process

Characteristics of the parser

CmdOption processes the commandline arguments as a Java string array starting from the first element. For each argument, it checks if is a know option or command name. If it is a known option, it starts to parse that option. When the options defines itself arguments, it also parses these arguments. If the found argumemt is detected as command, than CmdOptions switches into the command mode. After CmdOption switched into command mode once, all succeeding arguments are only parsed into the scope of that command.

If the application supports parameters (non-options, declared with a @CmdOption annotation without a names parameter) the parser will scan all commandline arguemnts that are not detected as options or commands into that parameter.

Stop option detecting with --

The special option -- is supported, to stop CmdOption from parsing any succeeding arguement as option or command. That way, you can force succeeding argument to be parsed as parameters. E.g. To delete a file with the name "-r" with the Unix tool rm you can use rm — -r, otherwise rm would interpret -r as option but not as filename.

Reading arguments from file (@-Prefix)

You can also read some or all arguments from a file by writing @ followed by the file path. This can be useful in various situations including:

  • re-use of same set of arguments

  • arguments were generated by another tool

  • to overcome some platform specific limits regarding the maximal length of the commandline

If desired, you can change the prefix with CmdlineParser.setReadArgsFromFilePrefix(String). The given string must be at least one character long. With an empty string or null you can disable that feature completely.

Options and Parameters

The @CmdOption annotation can be used to declare fields and methods as options.

Attributes of the @CmdOption annotation:

  • names : String[] - The names of this option. To declare the main parameter(s) leave this attribute unset (see below).

  • description : String - The description of the option. If this option supports args, you can refer to the argument names with {0}, {1}, and so on.

  • args : String[] - The arguments (their names) supported by this option. The count of arguments is used, to determite the option handler to use. The names are used in (validation) messages and the usage display.

  • minCount : int - The minimal allowed count this option can be specified. Optional options have 0 here, which is the default.

  • maxCount : int - The maximal allowed count this option can be specified. Use -1 to specify infinity. Default is 1.

  • handler : Class - A class implementing the CmdOptionHandler interface to apply the parsed option to the annotated field or method. If this is not given, all handler registered for auto-detect will by tried in order.

  • isHelp : boolean - Special marker, that this option is a help request. Typically, such an option is used to display a usage information to the user and exit. If such an option is parsed, validation will be disabled to allow help request even when the command line is incorrect.

  • hidden : boolean - If true, do not show this option in the usage.

  • requires : String[] - If this option is only valid in conjunction with other options, those required options should be declared here. (Since 0.2.0)

  • conflictsWith : String[] - If this option can not be used in conjunction with an specific other option, those conflicting options should be declared here. (Since 0.2.0)

If a @CmdOption annotation without any names attribute is found, this option is treated as main parameter(s) of the command line interface. At most one field or method can be annotated as such. The main parameter option gets all command line arguments that are not parsed into any other option or command.

Commands

CmdOption also supports the notion of commands. At most one command can be selected and supports itself options and main parameters. The @CmdCommand annotation can be used for classes.

Examples for tools that have command-style command line interfaces: git, subversion, mdadm, emerge/portage, SBuild, cmvn, …​

Attributes of the @CmdCommand annotation:

  • names: String[] - The names of this command.

  • description: String - The description of the command.

  • hidden: boolean - If true, do not show this command in the usage.

When a command is parsed, all succeeding arguments are parsed into that command (its options, and parameter). It is possible, to have options with the same name in different commands or in a command and the main program. The position of that option decides, which handler is invoked: before the command it is treated as a main options, after the command, its treated as an option of that command. If the main program support main parameters and also has commands, than the main parameters must be given before the command starts.

You can access the parsed command through the methods getParsedCommandName() or getParsedCommandObject() of class CmdlineParser.

It is possible, to define a default command, that is implicitly assumed when the user does not use a command explicitly. When the commandline parser detects an else unknown option or parameter it will try to parse the rest of the command line as if the default command was issued. You can set the default commend with setDefaultCommandName() or setDefaultCommandClass() of class CmdlineParser.

Composition

The command line parser supports more that one config object. Each object annotated with @CmdCommand is treated as command, all other can contain options for the main program.

To use the same class (or even object) for common or shared options, e.g. to add a --verbose option to all commands, you can annotate the relevant field with @CmdOptionDelegate.

Customizing the output

The class CmdlineParser has various methods to customize the behaviour and the output generated by the parser.

  • setProgramName(String) - The name used in the usage display. If not specified, <main class> is used.

  • setAboutLine(String) - Additional text displayed in the usage output.

  • usage() - Format and print the usage display to STDOUT.

  • usage(StringBuilder) - Format and print the usage display to the given StringBuilder.

  • setUsageFormatter(UsageFormatter) - Register a custom UsageFormatter that is used to format the usage display. If not changed, the DefaultUsageFormatter is used. Please note, that DefaultUsageFormatter already has some configuration options on it’s own which you should try first, before writing you own usage formatter implementation.

Exception Handling

The parse methods of CmdlineParser will throw a CmdlineParserException when the given cmdline contains validation errors. Thus, you always can assume sane and proper initialized config object (according to the configuration). If you don’t catch the exception, the JVM typically prints the error message and a stack trace to the commandline. Although helpful, it isn’t always want you want to be shown to your users.

It is highly recommended to surround the call to the parse method with a try-catch-block and provide a sane error message and/or if you prefer so a details usage display.

Example of sane and useful error handling
CmdlineParser cp = ...
try {
  cp.parse(args);
} catch (CmdlineParserException e) {
  System.err.println("Error: " + e.getMessage() + "\nRun myprogram --help for help.");
  System.exit(1);
}

Localization

There are two source of messages, that needs localization. Those from CmdOption itself like error and validation messages, and those, provided by the user of the CmdOption toolkit.

Localized CmdOption output

CmdOption itself supports localized output. The JVM default locale (country, language, variant) is used.

Currently, CmdOption comes with the following languages:

  • English

  • German

If you want to translate CmdOption into another language, we apreciate your contribution! See link:HowToProvideTranslations.adoc for details.

Localized options and descriptions

CmdOption also supports the translation of the user-provided strings. Those strings are:

  • The AboutLine (CmdlineParser.setAboutLine())

  • The option descriptions (@CmdOption(description=".."))

  • The command descriptions (@CmdCommand(description=".."))

  • The argument names of an option (@CmdOption(args={..}))

  • The main parameter names (@CmdOption(args={}))

If you provide a ResourceBundle, CmdOption will use that bundle to translate your messages. The JVM default locale is used.

You can either create the ResourceBundle yourself and set it into the CmdlineParser (setResourceBundle(ResourceBundle)), or you can tell the CmdlineParser the name for the message catalog and the classloader (setResourceBundle(String,ClassLoader)), that should be used to access the message catalog.

Localized CmdlineParserException

The CmdlineParserException which is thrown by CmdOption when some error or validation issue occurs contains the error message in both the localized and the non-localized form. If you want to display the localized error message, please use CmdlineParserException.getLocalizedMessage().

Example: A translation via Properties file

File: org/example/Main.java
package org.example;

import java.util.*;
import de.tototec.cmdoption.*;

public class Main {

  public static class Config {
    @CmdOption(names = {"--help", "-h"}, description = "Show this help.", isHelp = true)
    public boolean help;

    @CmdOption(names = {"--verbose", "-v"}, description = "Be more verbose.")
    private boolean verbose;

    @CmdOption(names = {"--options", "-o"}, args = {"name", "value"}, maxCount = -1,
      description = "Additional options when processing names.")
    private final Map<String, String> options = new LinkedHashMap<String, String>();

    @CmdOption(args = {"file"}, description = "Names to process.", minCount = 1, maxCount = -1)
    private final List<String> names = new LinkedList<String>();
  }

  public static void main(String[] args) {
    Config config = new Config();
    CmdlineParser cp = new CmdlineParser(config);
    cp.setResourceBundle(Main.class.getPackage().getName() + ".Messages", Main.class.getClassLoader());
    cp.setProgramName("myprogram");
    cp.setAboutLine("Example names processor v1.0");

    try {
      cp.parse(args);
    } catch (CmdlineParserException e) {
      System.err.println("Error: " + e.getLocalizedMessage() + "\nRun myprogram --help for help.");
      System.exit(1);
    }

    if (config.help) {
      cp.usage();
      System.exit(0);
    }

    // ...
  }
}

We will use a properties files to provide the translations into German.

File: org/example/Messages_de.properties
Show\ this\ help.=Zeigt diese Hilfe an.
Be\ more\ verbose.=Sei ausf\u00fchrlicher.
Additional\ options\ when\ processing\ names=Zus\u00e4tzliche Optionen bei der Namensverarbeitung.
Names\ to\ process=Zu verarbeitende Namen.
Example\ names\ processor\ v1.0=Beispiel Namensprozessor v1.0
name=Name
value=Wert
Output of the program without any locale:
% LC_ALL=C java -jar myprogram --help
Example names processor v1.0

Usage: myprogram [options] [parameter]

Options:
  --help,-h                Show this help.
  --options,-o name value  Additional options when processing names.
  --verbose,-v             Be more verbose.

Parameter:
  file  Names to process.
Output of the program in a German environment:
% java -jar myprogram --help
Beispiel Namensprozessor v1.0

Aufruf: myprogram [Optionen] [Parameter]

Optionen:
  --help,-h                Zeigt diese Hilfe an.
  --options,-o Name Wert   Zusätzliche Optionen bei der Namensverarbeitung.
  --verbose,-v             Sei ausführlicher.

Parameter:
  file  Zu verarbeitende Namen.

CmdOptionHandler

CmdOption supports field and method access. The set of supported types and method signatures is not hardcoded, but determined by the registered CmdOptionHandler s. CmdOption comes with some ready-to-use CmdOptionsHandler s. You can find these in the de.tototec.cmdoption.handler package.

By default, a well-choosen set of CmdOptionsHandler s is already registered, making a good start for most usage scenarios. To customize the behavoir of CmdOption, one has some options:

  • Write and register additional CmdOptionHandler s

  • if necessary, unregister all handlers before registering

  • Explicitly select a specific CmdOptionHandler in the @CmdOption-Annotation (which needs to have a default constructor)

Please note, that newly registered CmdOptionHandler s will only have an effect for configuration objects that are added after the handler was registered. That means, when you want to parse your config with a special set of CmdOptionHandler s, you should register them before you add your config object. In this case, you cannot use the convenience constructor of CmdlineParser that accepts your config objects, but you need to use the default constructor and add your config objects with CmdlineParser.addObject(Object…​).

Example:
Config config = new Config();

CmdlineParser cp = new CmdlineParser(/* do not add the config here */);
cp.unregisterAllHandler();
cp.registerHandler(new SpecialHandler());
// ...

// now we can add the config
cp.addObject(config);

Registering an additional CmdOptionHandler

CmdlineParser cp = new CmdlineParser();
cp.registerHandler(new MyOptionHandler());

The order of registered handlers is important. The first handler, that will match a declared field or method, will be used to parse it. To explicitly force a specific handler, use the handler parameter of the @CmdOption annotation: @CmdOption(handler = TheSpecificHandler.class).

Pre-registered CmdOptionHandlers

At construction time CmdlineParser pre-registeres various handlers like the following snippet:

CmdlineParser cp = new CmdlineParser();
cp.registerHandler(new BooleanOptionHandler()); // (1)
cp.registerHandler(new BooleanHandler()); // (2)
cp.registerHandler(new StringFieldHandler()); // (3)
cp.registerHandler(new PutIntoMapHandler()); // (4)
cp.registerHandler(new AddToCollectionHandler()); // (5)
cp.registerHandler(new StringMethodHandler()); // (6)
cp.registerHandler(new IntegerHandler()); // (7)
cp.registerHandler(new EnumHandler()); // (8)
  1. BooleanOptionHandler — Apply an zero-arg option to an Boolean or boolean field. If the option is present, the field will be evaluated to true.

  2. BooleanHandler — Apply an one-arg option to a Boolean or boolean field or method. Evaluates the argument to true if it is "true", "on" or "1".

  3. StringFieldHandler — Apply an one-arg option to a field of type String.

  4. PutIntoMapHandler — Apply an two-arg option to an mutable Map.

  5. AddToCollectionHandler — Add an one-arg option argument to a mutable collection of `String`s.

  6. StringMethodHandler — Apply an n-arg option to a (setter) method with n parameters of type String.

  7. IntegerHandler — Apply an one-arg option to a Integer or int field or method.

  8. EnumHandler — Parse a Sting to a Enum of the expected type and applies it to a field or a one-arg method. The Enum.valueOf method is used.

Unregistering all registered CmdOptionHandlers

To register all CmdOptionHandler s, even the pregegistered ones, you need to use call CmdlineParser.unresgisterAllHandler().

CmdlineParser cp = new CmdlineParser();
cp.unregisterAllHandler();

Debugging

CmdOption has a fairly detailed set of error messages, that will be thrown as CmdlineParserException.

When CmdOption detects the presence of a SLF4J Logger, it will use it to log its internals. If no such logger is found on the classpath, CmdOption falls back to log to Java’s logging API (Java Util Logging). If both logging output is not available to you, you can still gather some information about what goes on under the hood by using the special command line option --CMDOPTION_DEBUG. When used, CmdOption will display detailed information about the found configurations and the parsing process. This might help to understand issues further. In most cases, this will help you to resolve your issues. Of course, you can disable this functionality with CmdlineParser.setDebugModeAllowed(false).

If you have issues you can not solve, do not hessitate to open a support ticket or search for other (open) issues in the CmdOption ticket system.

Creating a streaming command line interface

Normally, CmdOption parses a complete command line, populates the config object(s) and ensures, that the config is valid, according to the configuration. Only, if the config is checked and ok, the parse method returns.

In some cases, a streaming command line interface is more appropriate than the typical static approach. In a streaming command line interface each option and parameter is immediatly evaluated before the next option or parameter is read. The next allowed option/parameter often depends on the previously parsed one. An example for an program with a streaming command line interface is ogmtools/ogmmerge.

Creating such a streaming command line parsers is very easy with CmdOption. Of course, most context sensitive validation must be handled by the application itself. You have to add the @CmdOption annotation to methods instead of fields. The arguments of that options, if any, must match the arguments of that method. In the body of such a method the option can now immediatly processed. Typically, minCount and maxCount of the options are unconstrained, as the validity is dependent on the context.

License

CmdOption is developed and released under the Apache License, Version 2.

Contributing / Support

Your contributions are much apreciated and are assumed to be published under the terms of the project license if not stated otherwise.

If you found a bug or have a feature request, please open a new issue on GitHub. We also accept pull requests.

You can also use our Chat on Gitter.im for discussions and questions.

If you want to show appreciation for the project, please "star" it on GitHub. That helps me setting my priorities.

Building CmdOption from Source

CmdOption is build with SBuild.

Other Projects

Have a look at some other projects I’m involved with:

ChangeLog

CmdOption 0.4.2 - 2015-06-02

  • Added new EnumHandler which support parsing of enum values into Java enums.

  • Added CmdlineParser.defaultHandlers() which can be overriden to customize the set of applied default handlers.

CmdOption 0.4.1 - 2015-01-21

  • Fixed message converter/formatter for JUL logger that resulted in garbage log messages when no SLF4J API is detected.

CmdOption 0.4.0 - 2015-01-20

  • Fixed a bug where some options are silently ignored (if declared as final field).

  • Detect matching CmdOptionHandlers in scanning phase. This results in proper detection of missing handlers / unsupported fields/types. Also there will be no surprises depending on the given arguments.

  • Added support to read commandline arguments from file(s) with @-syntax.

  • Usage formatter now, by default, tries to detect the line length of the terminal (under Linux and probably Mac OSX).

  • Various internal refactorings.

  • Fixed support for config classes in the default package.

  • Fallback to java.util.logging if SLF4J is not detected.

CmdOption 0.3.3 - 2014-11-17

  • Detect and report annotations on final fields

  • Use a logging framework if one is available on the classpath

  • Support placeholder for args in option descriptions, including their translations (if any)

CmdOption 0.3.2 - 2013-11-27

  • Improved debug output.

  • Fixed a visibility bug and made class OptionHandle public.

  • Added some JavaDoc.

CmdOption 0.3.1 - 2013-08-11

  • Added new IntegerHandler which supports Integer and int fields and methods.

  • Added the line length as new constructor parameter of DefaultUsageFormatter.

  • Improved debug output.

CmdOption 0.3.0 - 2013-05-07

  • Added support for inherited fields and methods.

  • Added new BooleanHandler, which replaces BooleanFieldHandler, but also handles methods.

  • Changed SBuild-driven test runner to scalatest, for better commandline output.

  • Added more unit tests.

  • Added Changelog.

CmdOption 0.2.1 - 2013-01-19

  • Parameter names of options (args) can be translated.

CmdOption 0.2.0 - 2012-11-25

  • Localizated output of error and validation messages.

  • Localization support for user provided configuration.

  • Added new attribute requires to @CmdOption annotation.

  • Added new attribute conflictsWith to @CmdOption annotation.

  • Added user provided "AboutLine" to generated formatted usage output.

  • New handler for parsing URLs.

  • Extended OptionHandler API. The applyParams method has now an additionally parameter containing the name of the parsed option.

  • Changed UsageFormatter API.

  • Migrated build system to SBuild.

  • Updated documentation.

CmdOption 0.1.0 - 2012-03-07

  • CmdOption is now located in package de.tototec.cmdoption. The previous package was de.tobiasroeser.cmdoption.

  • No hardcoded option format - In cmdoption-0.0.4 and before you could give one long parameter (inplicitly starting with a "--") and a short option (starting with one "-"). Since version 0.1.0 you are no longer limited in format and count, just use the names argument of CmdOption annotation. Remember, to include the hyphen(s) in the name, as those are no longer implicit.

  • The Parser class is now CmdlineParser - The old one CmdOptionParser no longer exists.

  • Support for commands - When CmdOption detects a command, all subsequent arguments are parsed into that command exclusivly.

  • External UsageFormatter - You have the full control over the appearance of the usage/help.

CmdOption 0.0.4 - 2010-12-16

CmdOption 0.0.3 - 2010-08-03

About

CmdOption is a simple annotation-driven command line parser toolkit for Java 5 applications that is configured through annotations.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Java 92.9%
  • Scala 6.7%
  • Shell 0.4%