CTK  0.1.0
The Common Toolkit is a community effort to provide support code for medical image analysis, surgical navigation, and related projects.
Public Types | Public Member Functions | Properties | List of all members
ctkCommandLineParser Class Reference

#include <Libs/Core/ctkCommandLineParser.h>

Inheritance diagram for ctkCommandLineParser:
Inheritance graph
[legend]
Collaboration diagram for ctkCommandLineParser:
Collaboration graph
[legend]

Public Types

typedef QObject Superclass
 

Public Member Functions

void addArgument (const QString &longarg, const QString &shortarg, QVariant::Type type, const QString &argHelp=QString(), const QVariant &defaultValue=QVariant(), bool ignoreRest=false, bool deprecated=false)
 
void addDeprecatedArgument (const QString &longarg, const QString &shortarg, const QString &argHelp)
 
Q_INVOKABLE bool argumentAdded (const QString &argument) const
 
Q_INVOKABLE bool argumentParsed (const QString &argument) const
 
void beginGroup (const QString &description)
 
 ctkCommandLineParser (QObject *newParent=0)
 
 ctkCommandLineParser (QSettings *settings, QObject *newParent=0)
 
void enableSettings (const QString &disableLongArg="", const QString &disableShortArg="")
 
void endGroup ()
 
QString errorString () const
 
int fieldWidth () const
 
QString helpText (const char charPad=' ') const
 
void mergeSettings (bool merge)
 
QHash< QString, QVariant > parseArguments (const QStringList &arguments, bool *ok=0)
 
QHash< QString, QVariant > parseArguments (int argc, char **argv, bool *ok=0)
 
void setArgumentPrefix (const QString &longPrefix, const QString &shortPrefix)
 
bool setExactMatchRegularExpression (const QString &argument, const QString &expression, const QString &exactMatchFailedMessage)
 
void setStrictModeEnabled (bool strictMode)
 
bool settingsEnabled () const
 
const QStringList & unparsedArguments () const
 
 ~ctkCommandLineParser ()
 

Properties

QString errorString
 
bool settingsEnabled
 
QStringList unparsedArguments
 

Detailed Description

The CTK command line parser.

Use this class to add information about the command line arguments your program understands and to easily parse them from a given list of strings.

This parser provides the following features:

Here is an example how to use this class inside a main function:

#include <QCoreApplication>
#include <QTextStream>
#include <cstdlib>
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
// This is used by QSettings
QCoreApplication::setOrganizationName("MyOrg");
QCoreApplication::setApplicationName("MyApp");
// Use Unix-style argument names
parser.setArgumentPrefix("--", "-");
// Enable QSettings support
parser.enableSettings("disable-settings");
// Add command line argument names
parser.addArgument("disable-settings", "", QVariant::Bool, "Do not use QSettings");
parser.addArgument("help", "h", QVariant::Bool, "Show this help text");
parser.addArgument("search-paths", "s", QVariant::StringList, "A list of paths to search");
// Parse the command line arguments
bool ok = false;
QHash<QString, QVariant> parsedArgs = parser.parseArguments(QCoreApplication::arguments(), &ok);
if (!ok)
{
QTextStream(stderr, QIODevice::WriteOnly) << "Error parsing arguments: "
<< parser.errorString() << "\n";
return EXIT_FAILURE;
}
// Show a help message
if (parsedArgs.contains("help") || parsedArgs.contains("h"))
{
QTextStream(stdout, QIODevice::WriteOnly) << parser.helpText();
return EXIT_SUCCESS;
}
// Do something
return EXIT_SUCCESS;
}

Definition at line 62 of file ctkCommandLineParser.h.

Member Typedef Documentation

◆ Superclass

Definition at line 71 of file ctkCommandLineParser.h.

Constructor & Destructor Documentation

◆ ctkCommandLineParser() [1/2]

ctkCommandLineParser::ctkCommandLineParser ( QObject *  newParent = 0)

Constructs a parser instance.

If QSettings support is enabled by a call to enableSettings() a default constructed QSettings instance will be used when parsing the command line arguments. Make sure to call QCoreApplication::setOrganizationName() and QCoreApplication::setApplicationName() before using default constructed QSettings objects.

Parameters
newParentThe QObject parent.

◆ ctkCommandLineParser() [2/2]

ctkCommandLineParser::ctkCommandLineParser ( QSettings *  settings,
QObject *  newParent = 0 
)

Constructs a parser instance.

If QSettings support is enabled by a call to enableSettings() the provided QSettings instance will be used. If the QSettings instance is zero, a default constructed QSettings instance will be used when parsing the command line arguments. Using a default constructed instance is usually what you want, if you have called QCoreApplication::setOrganizationName() and QCoreApplication::setApplicationName().

Parameters
settingsA QSettings instance which should be used.
newParentThe QObject parent.

◆ ~ctkCommandLineParser()

ctkCommandLineParser::~ctkCommandLineParser ( )

Member Function Documentation

◆ addArgument()

void ctkCommandLineParser::addArgument ( const QString &  longarg,
const QString &  shortarg,
QVariant::Type  type,
const QString &  argHelp = QString(),
const QVariant &  defaultValue = QVariant(),
bool  ignoreRest = false,
bool  deprecated = false 
)

Adds a command line argument. An argument can have a long name (like –long-argument-name), a short name (like -l), or both. The type of the argument can be specified by using the type parameter. The following types are supported:

Type# of parametersDefault regular expr Example
QVariant::String1.*–test-string StringParameter
QVariant::Bool0does not apply–enable-something
QVariant::StringList-1.*–test-list string1 string2
QVariant::Int1-?[0-9]+–test-int -5

The regular expressions are used to validate the parameters of command line arguments. You can restrict the valid set of parameters by calling setExactMatchRegularExpression() for your argument.

Optionally, a help string and a default value can be provided for the argument. If the QVariant type of the default value does not match type, an exception is thrown. Arguments with default values are always returned by parseArguments().

You can also declare an argument deprecated, by setting deprecated to true. Alternatively you can add a deprecated argument by calling addDeprecatedArgument().

If the long or short argument has already been added, or if both are empty strings, the method call has no effect.

Parameters
longargThe long argument name.
shortargThe short argument name.
typeThe argument type (see the list above for supported types).
argHelpA help string describing the argument.
defaultValueA default value for the argument.
ignoreRestAll arguments after the current one will be ignored.
deprecatedDeclares the argument deprecated.
See also
setExactMatchRegularExpression()
addDeprecatedArgument()
Exceptions
std::logic_errorIf the QVariant type of defaultValue does not match type, a std::logic_error is thrown.

◆ addDeprecatedArgument()

void ctkCommandLineParser::addDeprecatedArgument ( const QString &  longarg,
const QString &  shortarg,
const QString &  argHelp 
)

Adds a deprecated command line argument. If a deprecated argument is provided on the command line, argHelp is displayed in the console and processing continues with the next argument.

Deprecated arguments are grouped separately at the end of the help text returned by helpText().

Parameters
longargThe long argument name.
shortargThe short argument name.
argHelpA help string describing alternatives to the deprecated argument.

◆ argumentAdded()

Q_INVOKABLE bool ctkCommandLineParser::argumentAdded ( const QString &  argument) const

Checks if the given argument has been added via a call to addArgument().

See also
addArgument()
Parameters
argumentThe argument to be checked.
Returns
true if the argument was added, false otherwise.

◆ argumentParsed()

Q_INVOKABLE bool ctkCommandLineParser::argumentParsed ( const QString &  argument) const

Checks if the given argument has been parsed successfully by a previous call to parseArguments().

Parameters
argumentThe argument to be checked.
Returns
true if the argument was parsed, false otherwise.

◆ beginGroup()

void ctkCommandLineParser::beginGroup ( const QString &  description)

Begins a new group for documenting arguments. All newly added arguments via addArgument() will be put in the new group. You can close the current group by calling endGroup() or be opening a new group.

Note that groups cannot be nested and all arguments which do not belong to a group will be listed at the top of the text created by helpText().

Parameters
descriptionThe description of the group

◆ enableSettings()

void ctkCommandLineParser::enableSettings ( const QString &  disableLongArg = "",
const QString &  disableShortArg = "" 
)

Enables QSettings support in ctkCommandLineParser. If an argument name is found in the QSettings instance with a valid QVariant, the value is considered as a default value and overwrites default values registered with addArgument(). User supplied values on the command line overwrite values in the QSettings instance, except for arguments with multiple parameters which are merged with QSettings values. Call mergeSettings(false) to disable merging.

See ctkCommandLineParser(QSettings*) for information about how to supply a QSettings instance.

Additionally, a long and short argument name can be specified which will disable QSettings support if supplied on the command line. The argument name must be registered as a regular argument via addArgument().

Parameters
disableLongArgLong argument name.
disableShortArgShort argument name.
See also
ctkCommandLineParser(QSettings*)

◆ endGroup()

void ctkCommandLineParser::endGroup ( )

Ends the current group.

See also
beginGroup(const QString&)

◆ errorString()

QString ctkCommandLineParser::errorString ( ) const

Returns a detailed error description if a call to parseArguments() failed.

Returns
The error description, empty if no error occured.
See also
parseArguments(const QStringList&, bool*)

◆ fieldWidth()

int ctkCommandLineParser::fieldWidth ( ) const

The field width for the argument names without the help text.

Returns
The argument names field width in the help text.

◆ helpText()

QString ctkCommandLineParser::helpText ( const char  charPad = ' ') const

Creates a help text containing properly formatted argument names and help strings provided by calls to addArgument(). The arguments can be grouped by using beginGroup() and endGroup().

Parameters
charPadThe padding character.
Returns
The formatted help text.

◆ mergeSettings()

void ctkCommandLineParser::mergeSettings ( bool  merge)

Controlls the merging behavior of user values and QSettings values.

If merging is on (the default), user supplied values for an argument which can take more than one parameter are merged with values stored in the QSettings instance. If merging is off, the user values overwrite the QSettings values.

Parameters
mergetrue enables QSettings merging, false disables it.

◆ parseArguments() [1/2]

QHash<QString, QVariant> ctkCommandLineParser::parseArguments ( const QStringList &  arguments,
bool *  ok = 0 
)

Parse a given list of command line arguments.

This method parses a list of QString elements considering the known arguments added by calls to addArgument(). If any one of the argument values does not match the corresponding regular expression, ok is set to false and an empty QHash object is returned.

The keys in the returned QHash object correspond to the long argument string, if it is not empty. Otherwise, the short argument string is used as key. The QVariant values can safely be converted to the type specified in the addArgument() method call.

Parameters
argumentsA QStringList containing command line arguments. Usually given by QCoreApplication::arguments().
okA pointer to a boolean variable. Will be set to true if all regular expressions matched, false otherwise.
Returns
A QHash object mapping the long argument (if empty, the short one) to a QVariant containing the value.

◆ parseArguments() [2/2]

QHash<QString, QVariant> ctkCommandLineParser::parseArguments ( int  argc,
char **  argv,
bool *  ok = 0 
)

Convenient method allowing to parse a given list of command line arguments.

See also
parseArguments(const QStringList &, bool*)

◆ setArgumentPrefix()

void ctkCommandLineParser::setArgumentPrefix ( const QString &  longPrefix,
const QString &  shortPrefix 
)

Sets the argument prefix for long and short argument names. This can be used to create native command line arguments without changing the calls to addArgument(). For example on Unix-based systems, long argument names start with "--" and short names with "-", while on Windows argument names always start with "/".

Note that all methods in ctkCommandLineParser which take an argument name expect the name as it was supplied to addArgument.

Example usage:

parser.setArgumentPrefix("--", "-");
parser.addArgument("long-argument", "l", QVariant::String);
QStringList args;
args << "program name" << "--long-argument Hi";
parser.parseArguments(args);
Parameters
longPrefixThe prefix for long argument names.
shortPrefixThe prefix for short argument names.

◆ setExactMatchRegularExpression()

bool ctkCommandLineParser::setExactMatchRegularExpression ( const QString &  argument,
const QString &  expression,
const QString &  exactMatchFailedMessage 
)

Sets a custom regular expression for validating argument parameters. The method errorString() can be used the get the last error description.

Parameters
argumentThe previously added long or short argument name.
expressionA regular expression which the arugment parameters must match.
exactMatchFailedMessageAn error message explaining why the parameter did not match.
Returns
true if the argument was found and the regular expression was set, false otherwise.
See also
errorString()

◆ setStrictModeEnabled()

void ctkCommandLineParser::setStrictModeEnabled ( bool  strictMode)

Can be used to teach the parser to stop parsing the arguments and return False when an unknown argument is encountered. By default StrictMode is disabled.

See also
parseArguments(const QStringList &, bool*)

◆ settingsEnabled()

bool ctkCommandLineParser::settingsEnabled ( ) const

Can be used to check if QSettings support has been enabled by a call to enableSettings().

Returns
true if QSettings support is enabled, false otherwise.

◆ unparsedArguments()

const QStringList& ctkCommandLineParser::unparsedArguments ( ) const

This method returns all unparsed arguments, i.e. all arguments for which no long or short name has been registered via a call to addArgument().

See also
addArgument()
Returns
A list containing unparsed arguments.

Property Documentation

◆ errorString

QString ctkCommandLineParser::errorString
read

Definition at line 1 of file ctkCommandLineParser.h.

◆ settingsEnabled

bool ctkCommandLineParser::settingsEnabled
read

Definition at line 1 of file ctkCommandLineParser.h.

◆ unparsedArguments

QStringList ctkCommandLineParser::unparsedArguments
read

Definition at line 1 of file ctkCommandLineParser.h.


The documentation for this class was generated from the following file: