SkillAgentSearch skills...

CmdOption

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

Install / Use

/learn @ToToTec/CmdOption

README

= CmdOption - Command line parsing has never been easier :toc: :toc-placement: preamble :currentversion: 0.7.1 :documentedVersion: 0.7.1 :githubUrl: https://github.com/ToToTec/CmdOption :wikiUrl: {githubUrl}/wiki

Documentation of CmdOption {documentedVersion}.

== Overview

CmdOption is a simple annotation-driven command line parser toolkit for Java 6 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 {wikiUrl}[project wiki] for more examples and user provided content.

== Download

CmdOption is available from http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22de.tototec%22%20AND%20a%3A%22de.tototec.cmdoption%22[Maven central repository].

Maven users can use the following dependency declaration:

[source,xml,subs="attributes,verbatim"]

<dependency> <groupId>de.tototec</groupId> <artifactId>de.tototec.cmdoption</artifactId> <version>{currentversion}</version> </dependency> ----

https://github.com/lihaoyi/mill[Mill] users can use the following dependency:

[source,scala,subs="attributes"]

ivy"de.tototec:de.tototec.cmdoption:{currentversion}"

== Example

A simple config class could look like this:

[source,java]

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 link:#example-a-translation-via-properties-file[the translation example] and also visit the {wikiUrl}[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:

[source,java]

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:

[source,java]

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 arguments 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 argument 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.

=== Aggregation of short options

By principle, CmdOption does not enforce any type of option format. But nevertheless, the most common variants for Java applications are the Java-style options (starting with a single dash ("-")) and GNU-style options (long options starting with a double dash ("--") and short options starting with a single dash ("-")).

A typical convenience feature of GNU-style parsers is to support aggreated short options. That means, instead of declaring each option separately as in ls -l -a you can write them as one ls -la. You can do the same with CmdOption.

If you tell CmdOption which prefix starts a short option (an option with consists of only a single character after the prefix), CmdOption can parse all those option also when given in an aggreated way. By default, this feature is disabled.

To enable aggregation of short options use CmdlineParser.setAggregateShortOptionsWithPrefix(String). An argument of null or the empty string disables this feature.

.Example for aggregated options [source,java]

import de.tototec.cmdoption.CmdOption; import de.tototec.cmdoption.CmdlineParser;

public class Config { @CmdOption(names = { "-f", "--file" }, args = { "FILE" }) String file = null;

@CmdOption(names = { "-l" }) boolean formatLong = false;

@CmdOption(names = { "-s", "--size" }) boolean showSize = false; }

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

cp.setAggregateShortOptionsWithPrefix("-"); //<1>

// demo of parsing aggregated options
cp.parse(new String[] { "-lfs", "file.txt" });
assert config.formatLong == true;
assert "file.txt".equals(config.file);
assert config.showSize == true;

} }

<1> This line enabled aggregation of short options starting with a dash ("-").

As you can see, aggregated short options can also have any number of arguments.

=== Short options support argument without a space

If you prefer to set short options with a single argument without any delimiter or space, you can enable that by setting CmdlineParser.setShortOptionsWithArgsPrefix(String). You need to give the string, that denotes the start of short options (this is probably a -). To disable, set null or the empty string.

.Example for short options that support their single-arg without a delimiter [source,java]

import de.tototec.cmdoption.CmdOption; import de.tototec.cmdoption.CmdlineParser;

public class Config { @CmdOption(names = { "-D", "--define" }, args = { "PROPERTY=VALUE" }, maxCount = -1) List<String> defines = new LinkedList<String>(); }

public class Main { public static void main(String[] args) { final Config config = new Config(); final CmdlineParser cp = new CmdlineParser(config); cp.setShortOptionsWithArgsPrefix("-"); // <1> // demo of parsing aggregated options cp.parse(new String[] { "-DTEST=true" }); assert config.defines.get(0).equals("TEST=true"); } }

WARNING: Enabled both features together with short option aggregation might result in surprising results. Option aggregation will be parsed first.

=== Stop parsing options after the first parameter was found

Sometime, you want to parse options only if they come before the first parameter. This can be enabled/diabled with CmdlineParser.setStopAcceptOptionsAfterParameterIsSet(boolean). Set it to true to enable it, false is the default.

== 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 all
View on GitHub
GitHub Stars46
CategoryDevelopment
Updated5mo ago
Forks7

Languages

Java

Security Score

92/100

Audited on Oct 10, 2025

No findings