class
#include <Corrade/Utility/Arguments.h>
Arguments Command-line argument parser.
Parses Unix-style command line, with positional and named arguments and options both in a short (e.g., -o file
) and long variant (e.g., --output file
as well as --output=file
), boolean options and array options. If needed, positional arguments can be separated from named ones using --
; short options can be packed together (e.g. -xzOfile.dat
is equivalent to -x -z -O file.dat
providing -x
and -z
are boolean options).
The parsing is semi-autonomous, which means that the parser will also exit with failure or print help text (and exit) on its own. if -h
or --help
is given anywhere on the command line, the parser prints full help text to the output and exits, ignoring all other arguments. If a parse error occurs (missing/unknown argument etc.), the parser prints a shorter variant of the help text 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") .setGlobalHelp("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)
It doesn't end with just the above, check out the addArrayArgument(), addArrayOption() and addFinalOptionalArgument() APIs for more involved uses.
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") .setGlobalHelp("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");
With Flag::
/* The first instance handles all arguments */ Utility::Arguments args{"formatter"}; args.addOption("width", "80").setHelp("width", "number of columns") .addOption("color", "auto").setHelp("color", "output color") .addOption("log", "default").setHelp("log", "default|verbose|quiet") .parse(argc, argv); { /* A subsystem cares only about the log option, ignoring the rest. It also doesn't need to provide help because that gets handled above already. */ Utility::Arguments arg1{"formatter", Utility::Arguments::Flag::IgnoreUnknownOptions}; arg1.addOption("log", "default") .parse(argc, argv); }
Advanced parsing logic
By default, when a parse error is encountered (such as a missing or superfluous argument), parse() exits the program. However sometimes the default logic might not be flexible enough for your needs. Setting a callback via setParseErrorCallback() allows you to override this behavior on a per-error basis. For example, the following will allow output
to not be specified when --info
is passed:
Utility::Arguments args; args.addOption("input") .addOption("output") .addBooleanOption("info") .setHelp("info", "print info about the input file and exit") .setParseErrorCallback([](const Utility::Arguments& args, Utility::Arguments::ParseError error, const std::string& key) { /* If --info is passed, we don't need the output argument */ if(error == Utility::Arguments::ParseError::MissingArgument && key == "output" && args.isSet("info")) return true; /* Handle all other errors as usual */ return false; }) .parse(argc, argv);
Note that the autogenerated help text only understands the default logic and thus you should explicitly mention special cases via setGlobalHelp().
Public types
-
enum class Flag: std::
uint8_t { IgnoreUnknownOptions = 1 << 0 new in 2019.10 } - Flag.
-
enum class ParseError: std::
uint8_t { InvalidShortArgument, InvalidArgument, InvalidBooleanOption new in Git master, UnknownShortArgument, UnknownArgument, SuperfluousArgument, PositionalArgumentAsNamed new in Git master, MissingValue, MissingArgument } new in 2020.06 - Parse error.
-
using Flags = Containers::
EnumSet<Flag> - Flags.
- using ParseErrorCallback = bool(*)(const Arguments&, ParseError, const std::string&) new in 2020.06
- Parse error callback.
Public static functions
-
static auto environment() -> std::
vector<std:: string> - Environment values.
Constructors, destructors, conversion operators
Public functions
- auto operator=(const Arguments&) -> Arguments& deleted
- Copying is not allowed.
- auto operator=(Arguments&& other) -> Arguments& noexcept
- Move assignment.
-
auto prefix() const -> std::
string - Argument prefix.
- auto isParsed() const -> bool
- Whether the arguments were successfully parsed.
-
auto addArgument(std::
string key) -> Arguments& - Add a mandatory positional argument.
-
auto addArrayArgument(std::
string key) -> Arguments& new in Git master - Add a mandatory positional array argument.
-
auto addNamedArgument(char shortKey,
std::
string key) -> Arguments& - Add a mandatory named argument with both a short and a long key alternative.
-
auto addNamedArgument(std::
string key) -> Arguments& - Add a mandatory named argument with a long key only.
-
auto addOption(char shortKey,
std::
string key, std:: string defaultValue = std:: string()) -> Arguments& - Add an option with both a short and a long key alternative.
-
auto addOption(std::
string key, std:: string defaultValue = std:: string()) -> Arguments& - Add an option with a long key only.
-
auto addArrayOption(char shortKey,
std::
string key) -> Arguments& new in 2020.06 - Add an array option with both a short and a long key alternative.
-
auto addArrayOption(std::
string key) -> Arguments& new in 2020.06 - Add an array option with a long key only.
-
auto addBooleanOption(char shortKey,
std::
string key) -> Arguments& - Add a boolean option with both a short and a long key alternative.
-
auto addBooleanOption(std::
string key) -> Arguments& - Add a boolean option with a long key only.
-
auto addFinalOptionalArgument(std::
string key, std:: string defaultValue = std:: string()) -> Arguments& new in 2019.10 - Add a final optional argument.
-
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 setGlobalHelp(std::
string help) -> Arguments& - Set global help text.
-
auto setHelp(std::
string help) -> Arguments& deprecated in 2019.10 - Set global help text.
-
auto setHelp(const std::
string& key, std:: string help, std:: string helpKey = {}) -> Arguments& - Set help text for given key.
- auto parseErrorCallback() const -> ParseErrorCallback new in 2020.06
- Parse error callback.
- auto parseErrorCallbackState() const -> void* new in 2020.06
- Parse error callback state.
- auto setParseErrorCallback(ParseErrorCallback callback, void* state = nullptr) -> Arguments& new in 2020.06
- Set parse error callback.
- void parse(int argc, const char*const* argv)
- Parse the arguments and exit on failure.
- auto tryParse(int argc, const char*const* argv) -> bool
- Try parsing the arguments.
-
auto usage() const -> std::
string - Usage string.
-
auto help() const -> std::
string - Full help text string.
-
template<class T = std::auto value(const std::
string> string& key, ConfigurationValueFlags flags = {}) const -> T - Value of given argument or option.
-
auto arrayValueCount(const std::
string& key) const -> std:: size_t new in 2020.06 - Count of parsed values in given array argument or option.
-
template<class T = std::auto arrayValue(const std::
string> string& key, const std:: size_t id, ConfigurationValueFlags flags = {}) const -> T new in 2020.06 - Value of given array argument or option.
-
auto isSet(const std::
string& key) const -> bool - Whether boolean option is set.
Enum documentation
enum class Corrade:: Utility:: Arguments:: Flag: std:: uint8_t
Flag.
Enumerators | |
---|---|
IgnoreUnknownOptions new in 2019.10 |
For prefixed arguments (constructed with Arguments(const std:: It's not allowed to use this flag on unprefixed arguments. |
enum class Corrade:: Utility:: Arguments:: ParseError: std:: uint8_t new in 2020.06
Parse error.
Enumerators | |
---|---|
InvalidShortArgument |
Either an invalid one-letter argument (i.e., not satisfying the Invalid command-line argument -? Or a long argument with just one leading dash, in which case the callback receives the multi-character argument name (again without the leading Invalid command-line argument -foo (did you mean --foo?)
|
InvalidArgument |
Invalid long argument (i.e., not satisfying the Invalid command-line argument --foo?
|
InvalidBooleanOption new in Git master |
Invalid long boolean option (i.e., specified with an equals sign). The function receives the key, equals and value without the leading Invalid command-line argument --verbose=13
|
UnknownShortArgument |
A short argument that was not added with addArgument(), addNamedArgument(), addOption() or addBooleanOption(). The function receives the key without the leading Unknown command-line argument -v
|
UnknownArgument |
A short argument that was not added with addArgument(), addNamedArgument(), addOption() or addBooleanOption(). The function receives the key without the leading Unknown command-line argument --foo
|
SuperfluousArgument |
Superfluous positional argument (i.e., there's more than how many was added with addArgument() or addFinalOptionalArgument() and there's no addArrayArgument()). The function receives the full argument value. If not handled, the default diagnostic is for example: Superfluous command-line argument /dev/null
|
PositionalArgumentAsNamed new in Git master |
A positional argument was specified as named. The function receives the key name without the leading Positional command-line argument specified as --file
|
MissingValue |
Missing value for an argument. Happens when a named argument or non-boolean option name is specified as the last element of the argument list and no value follows. The function receives the long key name (even if short key might be specified on the command line) without the leading If not handled, the default diagnostic is for example: Missing value for command-line argument --output
|
MissingArgument |
Missing argument. The function receives the long key name. At this point all arguments are parsed and you can access them with value(), arrayValueCount(), arrayValue() or isSet() to implement advanced logic, for example allowing certain arguments to be unset depending on value of others. If not handled, the default diagnostic is for example: Missing command-line argument output
|
Typedef documentation
typedef Containers:: EnumSet<Flag> Corrade:: Utility:: Arguments:: Flags
Flags.
typedef bool(*Corrade:: Utility:: Arguments:: ParseErrorCallback)(const Arguments&, ParseError, const std::string&) new in 2020.06
Parse error callback.
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,
Flags flags = {}) 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 an example.
std:: string Corrade:: Utility:: Arguments:: prefix() const
Argument prefix.
If the class was instantiated with Arguments(const std::
Arguments& Corrade:: Utility:: Arguments:: addArgument(std:: string key)
Add a mandatory positional argument.
After calling addArgument("argument")
the argument will be displayed in argument list like the following. Call setHelp() to change the displayed key:
Usage: ./app [--] argument Arguments: argument help text
If no help text is set, the argument is not displayed in the argument list. Call setHelp() to set it. Argument value can be retrieved using value().
Only non-boolean options are allowed in the prefixed version, no arguments — use addOption() in that case instead.
Arguments& Corrade:: Utility:: Arguments:: addArrayArgument(std:: string key) new in Git master
Add a mandatory positional array argument.
Compared to addArgument(), which requires exactly one argument to be present, this function requires one or more arguments. There can be only one array argument and this function can't be combined with addFinalOptionalArgument(), but it can be placed at any position relative to other positional arguments.
After calling addArrayArgument("argument")
the option will be displayed in help text like the following. Call setHelp() to change the displayed key:
Usage: ./app [--] argument... Arguments: argument help text
If no help text is set, the argument is not displayed in the argument list. Call setHelp() to set it. Array length and values can be retrieved using arrayValueCount() and arrayValue().
Only non-boolean options are allowed in the prefixed version, no arguments — use addArrayOption() in that case instead.
Arguments& Corrade:: Utility:: Arguments:: addNamedArgument(char shortKey,
std:: string key)
Add a mandatory named argument with both a short and a 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 setHelp() 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 the argument list. Call setHelp() to set it. Argument value can be retrieved using value(). It's also possible to use --argument=ARGUMENT
instead of delimiting the argument value with whitespace. If more than one -a
/ --argument
is passed, value of the last one is picked.
Only non-boolean options are allowed in the prefixed version, no arguments — use addOption() in that case instead.
Arguments& Corrade:: Utility:: Arguments:: addNamedArgument(std:: string key)
Add a mandatory named argument with a 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
Arguments& Corrade:: Utility:: Arguments:: addOption(char shortKey,
std:: string key,
std:: string defaultValue = std:: string())
Add an option with both a short and a 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 setHelp() 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)
If no help text is set, the option is not displayed in the argument list. Call setHelp() to set it. Option value can be retrieved using value(). It's also possible to use --option=OPTION
instead of delimiting the option value with whitespace. If more than one -o
/ --option
is passed, value of the last one is picked.
Short key is not allowed in the prefixed version, use addOption(std::
Arguments& Corrade:: Utility:: Arguments:: addOption(std:: string key,
std:: string defaultValue = std:: string())
Add an option with a 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:: addArrayOption(char shortKey,
std:: string key) new in 2020.06
Add an array option with both a short and a long key alternative.
Compared to addOption(), which remembers only the last value when multiple options of the same name are passed in the argument list, this function remembers the whole sequence. That also means there's no default value, the default is simply an empty sequence.
After calling addArrayOption('o', "option")
the option will be displayed in help text like the following. Option value is just uppercased key value, call setHelp() to change it:
Usage: ./app [-o|--option OPTION]... Arguments: -o, --option help text
If no help text is set, the option is not displayed in the argument list. Call setHelp() to set it. Array length and values can be retrieved using arrayValueCount() and arrayValue().
Short key is not allowed in the prefixed version, use addArrayOption(std::
Arguments& Corrade:: Utility:: Arguments:: addArrayOption(std:: string key) new in 2020.06
Add an array option with a 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
Arguments& Corrade:: Utility:: Arguments:: addBooleanOption(char shortKey,
std:: string key)
Add a boolean option with both a short and a long key alternative.
If the option is present, the option has a true
value, otherwise it has a false
value. Unlike above functions, the usage text does not display the option value and you need to set a help text with setHelp() to make it appear in option list:
Usage: ./app [-o|--option] Arguments: -o, --option help text
If no help text is set, the option is not displayed in the argument list. Call setHelp() to set it, however setting displayed key name in setHelp() is not possible with boolean options. Option presence can be queried with isSet(). Specifying -o
or --option
more than once has the same effect as specifying it just once. Option for getting help (-h
, --help
) is added automatically.
Only non-boolean options are allowed in the prefixed version, use addOption() in that case instead.
Arguments& Corrade:: Utility:: Arguments:: addBooleanOption(std:: string key)
Add a boolean option with a 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
Arguments& Corrade:: Utility:: Arguments:: addFinalOptionalArgument(std:: string key,
std:: string defaultValue = std:: string()) new in 2019.10
Add a final optional argument.
Always parsed as the last after all other positional arguments. Compared to arguments added with addArgument() this one doesn't need to be present; compared to options added with addOption() it doesn't need to be specified together with option name. There can be only one final optional argument and this function can't be combined with addArrayArgument().
After calling addFinalOptionalArgument("argument")
the argument will be displayed in help text like the following. Call setHelp() to change the displayed key:
Usage: ./app [--] [argument] Arguments: argument help text (default: defaultValue)
If no help text is set, the argument is not displayed in the argument list. Call setHelp() to set it. Argument value can be retrieved using value().
Only non-boolean options are allowed in the prefixed version, no arguments — use addOption() in that case 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:: setGlobalHelp(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(std:: string help)
Set global help text.
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.
ParseErrorCallback Corrade:: Utility:: Arguments:: parseErrorCallback() const new in 2020.06
Parse error callback.
The default callback unconditionally returns false
.
void* Corrade:: Utility:: Arguments:: parseErrorCallbackState() const new in 2020.06
Parse error callback state.
The default state is nullptr
.
Arguments& Corrade:: Utility:: Arguments:: setParseErrorCallback(ParseErrorCallback callback,
void* state = nullptr) new in 2020.06
Set parse error callback.
The callback
function receives a reference to this instance, a ParseError enum describing what exactly is wrong, and a corresponding key name or command-line argument value on which the error occurred. If the callback returns false
, an error message is printed and the program exits. If the callback returns true
, the error is ignored (assumed the application handles it gracefully) and parsing continues. The callback is also allowed to print an error message on its own and then call std::
The state
pointer is saved and can be retrieved using parseErrorCallbackState() inside the callback. Unless said otherwise for a particular ParseError, you can't call value() or isSet() from the callback as the arguments are not parsed yet.
See Advanced parsing logic for an example and particular ParseError values for detailed behavior of every error.
void Corrade:: Utility:: Arguments:: parse(int argc,
const char*const* 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
.
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 and parse() was successful. Only for non-array arguments and non-array non-boolean options, use arrayValue() or isSet() for those instead. If T
is not std::
std:: size_t Corrade:: Utility:: Arguments:: arrayValueCount(const std:: string& key) const new in 2020.06
Count of parsed values in given array argument or option.
Parameters | |
---|---|
key | Array argument or option key |
Expects that the key exists, parse() was successful and key
is an array argument or option.
template<class T = std:: string>
T Corrade:: Utility:: Arguments:: arrayValue(const std:: string& key,
const std:: size_t id,
ConfigurationValueFlags flags = {}) const new in 2020.06
Value of given array argument or option.
Parameters | |
---|---|
key | Array argument or option key |
id | Array value index |
flags | Configuration value flags |
Expects that the key exists, parse() was successful and id
is less than arrayValueCount(). Only for array arguments and options, use value() or isSet() for those instead. If T
is not std::
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, was added using addBooleanOption() and parse() was successful. The help option (-h
, --help
) is added implicitly.
Debug& operator<<(Debug& debug,
Arguments:: ParseError value) new in 2020.06
Debug output operator.