Corrade::Utility::Arguments class

Command-line argument parser.

Supports positional arguments (arguments without name), short and long options (e.g. -o file or --output file) and named arguments (i.e. non-optional options) along with boolean options (e.g. --verbose). Positional and named arguments can be given in any order, it is possible to separate positional arguments from option list with --.

The parsing is semi-autonomous, which means that the parser will exit with failure or print help text (and exit) on its own: If -h or --help is given as first argument (the remaining ones are then ignored), the parser prints full help text to the output and exits. If parse error occurs (missing/unknown argument etc.), the parser prints short usage information and exits.

Example usage

Contrived example of command-line utility which prints given text given number of times, optionally redirecting the output to a file:

int main(int argc, char** argv) {
    Utility::Arguments args;
    args.addArgument("text").setHelp("text", "the text to print")
        .addNamedArgument('n', "repeat").setHelp("repeat", "repeat count")
        .addBooleanOption('v', "verbose").setHelp("verbose", "log verbosely")
        .addOption("log", "log.txt").setHelp("log", "save verbose log to given file")
        .setHelp("Repeats the text given number of times.")
        .parse(argc, argv);

    std::ofstream logOutput(args.value("log"));
    for(int i = 0; i < args.value<int>("repeat"); ++i) {
        if(args.isSet("verbose")) {
            logOutput << "Printing instance " << i << " of text " << args.value("text");
        }

        std::cout << args.value("text");
    }

    return 0;
}

Upon requesting help, the utility prints the following:

Usage
  ./printer [-h|--help] -n|--repeat REPEAT [-v|--verbose] [--log LOG] [--] text

Repeats the text given number of times.

Arguments:
  text                 the text to print
  -h, --help           display this help message and exit
  -n, --repeat REPEAT  repeat count
  -v, --verbose        log verbosely
  --log LOG            save verbose log to given file
                       (default: log.txt)

Delegating arguments to different parts of the application

Sometimes you want to have some set of arguments for the application and some for the underlying library (or libraries) without one interfering with another and without writing code that would delegate the options from one to another. It is possible to do it using prefixed arguments. The library would use (and verify) only options with given prefix and on the other hand, the application would skip those instead of reporting them as unknown. The prefixed arguments are restricted to non-boolean options with long names to keep the usage simple both for the application author and users. Example:

{
    /* The underlying library */
    Utility::Arguments args{"formatter"};
    args.addOption("width", "80").setHelp("width", "number of columns")
        .addOption("color", "auto").setHelp("color", "output color")
        .parse(argc, argv);
}

/* The application */
Utility::Arguments args;
args.addArgument("text").setHelp("text", "the text to print")
    .addNamedArgument('n', "repeat").setHelp("repeat", "repeat count")
    .addSkippedPrefix("formatter", "formatter options")
    .setHelp("Repeats the text given number of times.")
    .parse(argc, argv);

The application can be then called like the following, the prefixed and unprefixed options and named arguments can be mixed without restriction:

./printer --repeat 30 --formatter-width 80 --formatter-color ff3366 "hello there"

Upon calling -h or --help the application prints the following:

Usage
  ./printer [-h|--help] [--formatter-...] -n|--repeat REPEAT [--] text

Repeats the text given number of times.

Arguments:
  text                 the text to print
  -h, --help           display this help message and exit
  -n, --repeat REPEAT  repeat count
  --formatter-...      formatter options
                       (see --formatter-help for details)

Upon calling --formatter-help the application prints the following:

Usage
  ./printer [--formatter-help] [--formatter-width WIDTH] [--formatter-color COLOR] ...

Arguments:
  ...                      main application arguments
                           (see -h or --help for details)
  --formatter-help         display this help message and exit
  --formatter-width WIDTH  number of columns
                           (default: 80)
  --formatter-color COLOR  output color
                           (default: auto)

Boolean options would cause parsing ambiguity so they are not allowed, but you can work around the limitation like this, for example:

Utility::Arguments args{"formatter"};
args.addOption("unicode", "false");

// ...

bool handleUnicode = args.value<bool>("unicode");

Public static functions

static auto environment() -> std::vector<std::string>
Environment values.

Constructors, destructors, conversion operators

Arguments(const std::string& prefix) explicit
Construct prefixed arguments.

Public functions

auto addArgument(std::string key) -> Arguments&
Add mandatory argument.
auto addNamedArgument(char shortKey, std::string key) -> Arguments&
Add named mandatory argument with both short and long key alternative.
auto addNamedArgument(std::string key) -> Arguments&
Add named mandatory argument with long key only.
auto addOption(char shortKey, std::string key, std::string defaultValue = std::string()) -> Arguments&
Add option with both short and long key alternative.
auto addOption(std::string key, std::string defaultValue = std::string()) -> Arguments&
Add option with long key only.
auto addBooleanOption(char shortKey, std::string key) -> Arguments&
Add boolean option with both short and long key alternative.
auto addBooleanOption(std::string key) -> Arguments&
Add boolean option with long key only.
auto addSkippedPrefix(std::string prefix, std::string help = {}) -> Arguments&
Skip given prefix.
auto setFromEnvironment(const std::string& key, std::string environmentVariable) -> Arguments&
Set option from environment.
auto setFromEnvironment(const std::string& key) -> Arguments&
auto setCommand(std::string name) -> Arguments&
Set command name.
auto setHelp(std::string help) -> Arguments&
Set global help text.
auto setHelp(const std::string& key, std::string help, std::string helpKey = {}) -> Arguments&
Set help text for given key.
auto setHelpKey(const std::string& key, std::string helpKey) -> Arguments& deprecated
Set help text for given key.
void parse(int argc, const char** argv)
Parse the arguments and exit on failure.
void parse(int argc, char** argv)
void parse(int argc, std::nullptr_t argv)
auto tryParse(int argc, const char** argv) -> bool
Try parsing the arguments.
auto tryParse(int argc, char** argv) -> bool
auto tryParse(int argc, std::nullptr_t argv) -> bool
auto usage() const -> std::string
Usage string.
auto help() const -> std::string
Full help text string.
template<class T = std::string>
auto value(const std::string& key, ConfigurationValueFlags flags = {}) const -> T
Value of given argument or option.
auto isSet(const std::string& key) const -> bool
Whether boolean option is set.

Function documentation

static std::vector<std::string> Corrade::Utility::Arguments::environment()

Environment values.

Returns list of all environment values for information and debugging purposes, encoded in UTF-8.

Corrade::Utility::Arguments::Arguments(const std::string& prefix) explicit

Construct prefixed arguments.

Prefixed arguments are useful for example when you have some options related to the application and some to the underlying library and you want to handle them in separate steps. Prefixed version can have only named arguments and long options.

See class documentation for example.

Arguments& Corrade::Utility::Arguments::addArgument(std::string key)

Add mandatory argument.

After calling addArgument("argument") the argument will be displayed in argument list like the following. Call setHelpKey() to change the displayed key:

Usage:
  ./app argument

Arguments:
  argument          help text

If no help text is set, the argument is not displayed in argument list. Call setHelp() to set it. Argument value can be retrieved using value().

Only non-boolean options are allowed in the prefixed version, use addOption() instead.

Arguments& Corrade::Utility::Arguments::addNamedArgument(char shortKey, std::string key)

Add named mandatory argument with both short and long key alternative.

After calling addNamedArgument('a', "argument") the argument will be displayed in help text like the following. Argument value is just uppercased key value, call setHelpKey() to change it:

Usage:
  ./app -a|--argument ARGUMENT

Arguments:
  --a, --argument   help text

If no help text is set, the argument is not displayed in argument list. Call setHelp() to set it. Argument value can be retrieved using value().

Only non-boolean options are allowed in the prefixed version, use addOption() instead.

Arguments& Corrade::Utility::Arguments::addNamedArgument(std::string key)

Add named mandatory argument with long key only.

Similar to the above, the only difference is that the usage and help text does not mention the short option:

Usage:
  ./app --argument ARGUMENT

Arguments:
  --argument        help text

Only non-boolean options are allowed in the prefixed version, use addOption() instead.

Arguments& Corrade::Utility::Arguments::addOption(char shortKey, std::string key, std::string defaultValue = std::string())

Add option with both short and long key alternative.

After calling addOption('o', "option") the option will be displayed in help text like the following. Option value is just uppercased key value, call setHelpKey() to change it:

Usage:
  ./app [-o|--option OPTION]

Default value, if nonempty, is displayed in option list like the following, call setHelp() to add descriptional help text. If default value is empty and no help text is set, the option is not displayed in the list at all.

Arguments:
  -o, --option      help text
                    (default: defaultValue)

Option value can be retrieved using value().

Short key is not allowed in the prefixed version, use addOption(std::string, std::string) instead.

Arguments& Corrade::Utility::Arguments::addOption(std::string key, std::string defaultValue = std::string())

Add option with long key only.

Similar to the above, the only difference is that the usage and help text does not mention the short option:

Usage:
  ./app [--option OPTION]

Arguments:
  --option          help text
                    (default: defaultValue)

Arguments& Corrade::Utility::Arguments::addBooleanOption(char shortKey, std::string key)

Add boolean option with both short and long key alternative.

If the option is present, the option has true value, otherwise it has false value. Unlike above functions, the usage text does not display option value and you need to set help text with setHelp() to make it appear in option list:

Usage:
  ./app [-o|-option]

Arguments:
  -o, --option      help text

Option presence can be queried with isSet(), setHelpKey() cannot be used with boolean options. Option for getting help (-h, --help) is added automatically.

Only non-boolean options are allowed in the prefixed version, use addOption() instead.

Arguments& Corrade::Utility::Arguments::addBooleanOption(std::string key)

Add boolean option with long key only.

Similar to the above, the only difference is that the usage and help text does not mention the short option:

Usage:
  ./app [--option]

Arguments:
  --option          help text

Only non-boolean options are allowed in the prefixed version, use addOption() instead.

Arguments& Corrade::Utility::Arguments::addSkippedPrefix(std::string prefix, std::string help = {})

Skip given prefix.

Ignores all options with given prefix. See class documentation for details.

Arguments& Corrade::Utility::Arguments::setFromEnvironment(const std::string& key, std::string environmentVariable)

Set option from environment.

Allows the option to be taken from environment variable if it is not specified on command line. If environmentVariable is not set, uppercase key value with dashes converted to underscores is used by default. For example, on Unix-based systems, calling setFromEnvironment("some-option") allows you to specify that option either using

./app --some-option 42

or

SOME_OPTION=42 ./app

Boolean options are set to true if the environment value is set to ON (case-insensitive). Values are encoded in UTF-8.

Arguments& Corrade::Utility::Arguments::setFromEnvironment(const std::string& key)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Arguments& Corrade::Utility::Arguments::setCommand(std::string name)

Set command name.

If empty, the command name is extracted from arguments passed to parse() on parsing, or set to ./app if not parsed yet. The command name is then used in usage() and help(). Default is empty.

Arguments& Corrade::Utility::Arguments::setHelp(std::string help)

Set global help text.

If nonempty, the text is printed between usage text and argument and option list. Default is none.

Help text can be set only in the unprefixed version.

Arguments& Corrade::Utility::Arguments::setHelp(const std::string& key, std::string help, std::string helpKey = {})

Set help text for given key.

Arguments, boolean options and options with empty default values are not displayed in argument and option list unless they have help text set.

If helpKey is set, it replaces the placeholder for arguments and uppercased placeholder in named arguments and nonboolean options. For example, calling setHelp("input", "...", "file.bin") and setHelp("limit", "...", "N") will transform the following usage text:

./app --limit LIMIT input

to:

./app --limit N file.bin

The displayed keys are changed also in argument and option list.

Arguments& Corrade::Utility::Arguments::setHelpKey(const std::string& key, std::string helpKey)

Set help text for given key.

void Corrade::Utility::Arguments::parse(int argc, const char** argv)

Parse the arguments and exit on failure.

If the arguments contain -h or --help option, the function prints full help text and exits the program with 0. If there is parsing error (e.g. too little or too many arguments, unknown options etc.), the function prints just the usage text and exits the program with 1.

void Corrade::Utility::Arguments::parse(int argc, char** argv)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void Corrade::Utility::Arguments::parse(int argc, std::nullptr_t argv)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

bool Corrade::Utility::Arguments::tryParse(int argc, const char** argv)

Try parsing the arguments.

Unlike parse() the function does not exit on failure, but returns false instead. If the user requested help, no additional arguments are parsed, only --help option is set and true is returned.

bool Corrade::Utility::Arguments::tryParse(int argc, char** argv)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

bool Corrade::Utility::Arguments::tryParse(int argc, std::nullptr_t argv)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

std::string Corrade::Utility::Arguments::usage() const

Usage string.

Returns usage string which is printed on parsing error.

std::string Corrade::Utility::Arguments::help() const

Full help text string.

Returns full help text which is printed on -h or --help request.

template<class T = std::string>
T Corrade::Utility::Arguments::value(const std::string& key, ConfigurationValueFlags flags = {}) const

Value of given argument or option.

Parameters
key Long argument or option key
flags Configuration value flags

Expects that the key exists. Use isSet() for boolean options. If the arguments weren't parsed yet, returns empty string or default-constructed value. If T is not std::string, uses ConfigurationValue::fromString() to convert the value to given type.

bool Corrade::Utility::Arguments::isSet(const std::string& key) const

Whether boolean option is set.

Parameters
key Long option key

Expects that the option exists and is boolean. Help option (-h, --help) is present by default. If the arguments weren't parsed yet, returns false.