ctkCommandLineParser.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. #ifndef __ctkCommandLineParser_h
  15. #define __ctkCommandLineParser_h
  16. // Qt includes
  17. #include <QString>
  18. #include <QStringList>
  19. #include <QVariant>
  20. class QSettings;
  21. // CTK includes
  22. #include "ctkCoreExport.h"
  23. /**
  24. * \ingroup Core
  25. *
  26. * The CTK command line parser.
  27. *
  28. * Use this class to add information about the command line arguments
  29. * your program understands and to easily parse them from a given list
  30. * of strings.
  31. *
  32. * This parser provides the following features:
  33. *
  34. * <ul>
  35. * <li>Add arguments by supplying a long name and/or a short name.
  36. * Arguments are validated using a regular expression. They can have
  37. * a default value and a help string.</li>
  38. * <li>Deprecated arguments.</li>
  39. * <li>Custom regular expressions for argument validation.</li>
  40. * <li>Set different argument name prefixes for native platform look and feel.</li>
  41. * <li>QSettings support. Default values for arguments can be read from
  42. * a QSettings object.</li>
  43. * <li>Create a help text for the command line arguments with support for
  44. * grouping arguments.</li>
  45. * </ul>
  46. *
  47. * Here is an example how to use this class inside a main function:
  48. *
  49. * \snippet CommandLineParser/main.cpp 0
  50. */
  51. class CTK_CORE_EXPORT ctkCommandLineParser : public QObject
  52. {
  53. Q_OBJECT
  54. Q_PROPERTY(QString errorString READ errorString)
  55. Q_PROPERTY(QStringList unparsedArguments READ unparsedArguments)
  56. Q_PROPERTY(bool settingsEnabled READ settingsEnabled)
  57. public:
  58. typedef QObject Superclass;
  59. /**
  60. * Constructs a parser instance.
  61. *
  62. * If QSettings support is enabled by a call to <code>enableSettings()</code>
  63. * a default constructed QSettings instance will be used when parsing
  64. * the command line arguments. Make sure to call <code>QCoreApplication::setOrganizationName()</code>
  65. * and <code>QCoreApplication::setApplicationName()</code> before using default
  66. * constructed QSettings objects.
  67. *
  68. * @param newParent The QObject parent.
  69. */
  70. ctkCommandLineParser(QObject* newParent = 0);
  71. /**
  72. * Constructs a parser instance.
  73. *
  74. * If QSettings support is enabled by a call to <code>enableSettings()</code>
  75. * the provided QSettings instance will be used. If the QSettings instance is
  76. * zero, a default constructed QSettings instance will be used when parsing
  77. * the command line arguments. Using a default constructed instance is usually
  78. * what you want, if you have called <code>QCoreApplication::setOrganizationName()</code>
  79. * and <code>QCoreApplication::setApplicationName()</code>.
  80. *
  81. * @param settings A QSettings instance which should be used.
  82. * @param newParent The QObject parent.
  83. *
  84. *
  85. */
  86. ctkCommandLineParser(QSettings* settings, QObject* newParent = 0);
  87. ~ctkCommandLineParser();
  88. /**
  89. * Parse a given list of command line arguments.
  90. *
  91. * This method parses a list of QString elements considering the known arguments
  92. * added by calls to <code>addArgument()</code>. If any one of the argument
  93. * values does not match the corresponding regular expression,
  94. * <code>ok</code> is set to false and an empty QHash object is returned.
  95. *
  96. * The keys in the returned QHash object correspond to the long argument string,
  97. * if it is not empty. Otherwise, the short argument string is used as key. The
  98. * QVariant values can safely be converted to the type specified in the
  99. * <code>addArgument()</code> method call.
  100. *
  101. * @param arguments A QStringList containing command line arguments. Usually
  102. * given by <code>QCoreApplication::arguments()</code>.
  103. * @param ok A pointer to a boolean variable. Will be set to <code>true</code>
  104. * if all regular expressions matched, <code>false</code> otherwise.
  105. * @return A QHash object mapping the long argument (if empty, the short one)
  106. * to a QVariant containing the value.
  107. */
  108. QHash<QString, QVariant> parseArguments(const QStringList &arguments, bool* ok = 0);
  109. /**
  110. * Convenient method allowing to parse a given list of command line arguments.
  111. * @see parseArguments(const QStringList &, bool*)
  112. */
  113. QHash<QString, QVariant> parseArguments(int argc, char** argv, bool* ok = 0);
  114. /**
  115. * Returns a detailed error description if a call to <code>parseArguments()</code>
  116. * failed.
  117. *
  118. * @return The error description, empty if no error occured.
  119. * @see parseArguments(const QStringList&, bool*)
  120. */
  121. QString errorString() const;
  122. /**
  123. * This method returns all unparsed arguments, i.e. all arguments
  124. * for which no long or short name has been registered via a call
  125. * to <code>addArgument()</code>.
  126. *
  127. * @see addArgument()
  128. *
  129. * @return A list containing unparsed arguments.
  130. */
  131. const QStringList& unparsedArguments() const;
  132. /**
  133. * Checks if the given argument has been added via a call
  134. * to <code>addArgument()</code>.
  135. *
  136. * @see addArgument()
  137. *
  138. * @param argument The argument to be checked.
  139. * @return <code>true</code> if the argument was added, <code>false</code>
  140. * otherwise.
  141. */
  142. Q_INVOKABLE bool argumentAdded(const QString& argument) const;
  143. /**
  144. * Checks if the given argument has been parsed successfully by a previous
  145. * call to <code>parseArguments()</code>.
  146. *
  147. * @param argument The argument to be checked.
  148. * @return <code>true</code> if the argument was parsed, <code>false</code>
  149. * otherwise.
  150. */
  151. Q_INVOKABLE bool argumentParsed(const QString& argument) const;
  152. /**
  153. * Adds a command line argument. An argument can have a long name
  154. * (like --long-argument-name), a short name (like -l), or both. The type
  155. * of the argument can be specified by using the <code>type</code> parameter.
  156. * The following types are supported:
  157. *
  158. * <table>
  159. * <tr><td><b>Type</b></td><td><b># of parameters</b></td><td><b>Default regular expr</b></td>
  160. * <td><b>Example</b></td></tr>
  161. * <tr><td>QVariant::String</td><td>1</td><td>.*</td><td>--test-string StringParameter</td></tr>
  162. * <tr><td>QVariant::Bool</td><td>0</td><td>does not apply</td><td>--enable-something</td></tr>
  163. * <tr><td>QVariant::StringList</td><td>-1</td><td>.*</td><td>--test-list string1 string2</td></tr>
  164. * <tr><td>QVariant::Int</td><td>1</td><td>-?[0-9]+</td><td>--test-int -5</td></tr>
  165. * </table>
  166. *
  167. * The regular expressions are used to validate the parameters of command line
  168. * arguments. You can restrict the valid set of parameters by calling
  169. * <code>setExactMatchRegularExpression()</code> for your argument.
  170. *
  171. * Optionally, a help string and a default value can be provided for the argument. If
  172. * the QVariant type of the default value does not match <code>type</code>, an
  173. * exception is thrown. Arguments with default values are always returned by
  174. * <code>parseArguments()</code>.
  175. *
  176. * You can also declare an argument deprecated, by setting <code>deprecated</code>
  177. * to <code>true</code>. Alternatively you can add a deprecated argument by calling
  178. * <code>addDeprecatedArgument()</code>.
  179. *
  180. * If the long or short argument has already been added, or if both are empty strings,
  181. * the method call has no effect.
  182. *
  183. * @param longarg The long argument name.
  184. * @param shortarg The short argument name.
  185. * @param type The argument type (see the list above for supported types).
  186. * @param argHelp A help string describing the argument.
  187. * @param defaultValue A default value for the argument.
  188. * @param ignoreRest All arguments after the current one will be ignored.
  189. * @param deprecated Declares the argument deprecated.
  190. *
  191. * @see setExactMatchRegularExpression()
  192. * @see addDeprecatedArgument()
  193. * @throws std::logic_error If the QVariant type of <code>defaultValue</code>
  194. * does not match <code>type</code>, a <code>std::logic_error</code> is thrown.
  195. */
  196. void addArgument(const QString& longarg, const QString& shortarg,
  197. QVariant::Type type, const QString& argHelp = QString(),
  198. const QVariant& defaultValue = QVariant(),
  199. bool ignoreRest = false, bool deprecated = false);
  200. /**
  201. * Adds a deprecated command line argument. If a deprecated argument is provided
  202. * on the command line, <code>argHelp</code> is displayed in the console and
  203. * processing continues with the next argument.
  204. *
  205. * Deprecated arguments are grouped separately at the end of the help text
  206. * returned by <code>helpText()</code>.
  207. *
  208. * @param longarg The long argument name.
  209. * @param shortarg The short argument name.
  210. * @param argHelp A help string describing alternatives to the deprecated argument.
  211. */
  212. void addDeprecatedArgument(const QString& longarg, const QString& shortarg,
  213. const QString& argHelp);
  214. /**
  215. * Sets a custom regular expression for validating argument parameters. The method
  216. * <code>errorString()</code> can be used the get the last error description.
  217. *
  218. * @param argument The previously added long or short argument name.
  219. * @param expression A regular expression which the arugment parameters must match.
  220. * @param exactMatchFailedMessage An error message explaining why the parameter did
  221. * not match.
  222. *
  223. * @return <code>true</code> if the argument was found and the regular expression was set,
  224. * <code>false</code> otherwise.
  225. *
  226. * @see errorString()
  227. */
  228. bool setExactMatchRegularExpression(const QString& argument, const QString& expression,
  229. const QString& exactMatchFailedMessage);
  230. /**
  231. * The field width for the argument names without the help text.
  232. *
  233. * @return The argument names field width in the help text.
  234. */
  235. int fieldWidth() const;
  236. /**
  237. * Creates a help text containing properly formatted argument names and help strings
  238. * provided by calls to <code>addArgument()</code>. The arguments can be grouped by
  239. * using <code>beginGroup()</code> and <code>endGroup()</code>.
  240. *
  241. * @param charPad The padding character.
  242. * @return The formatted help text.
  243. */
  244. QString helpText(const char charPad = ' ') const;
  245. /**
  246. * Sets the argument prefix for long and short argument names. This can be used
  247. * to create native command line arguments without changing the calls to
  248. * <code>addArgument()</code>. For example on Unix-based systems, long argument
  249. * names start with "--" and short names with "-", while on Windows argument names
  250. * always start with "/".
  251. *
  252. * Note that all methods in ctkCommandLineParser which take an argument name
  253. * expect the name as it was supplied to <code>addArgument</code>.
  254. *
  255. * Example usage:
  256. *
  257. * \code
  258. * ctkCommandLineParser parser;
  259. * parser.setArgumentPrefix("--", "-");
  260. * parser.addArgument("long-argument", "l", QVariant::String);
  261. * QStringList args;
  262. * args << "program name" << "--long-argument Hi";
  263. * parser.parseArguments(args);
  264. * \endcode
  265. *
  266. * @param longPrefix The prefix for long argument names.
  267. * @param shortPrefix The prefix for short argument names.
  268. */
  269. void setArgumentPrefix(const QString& longPrefix, const QString& shortPrefix);
  270. /**
  271. * Begins a new group for documenting arguments. All newly added arguments via
  272. * <code>addArgument()</code> will be put in the new group. You can close the
  273. * current group by calling <code>endGroup()</code> or be opening a new group.
  274. *
  275. * Note that groups cannot be nested and all arguments which do not belong to
  276. * a group will be listed at the top of the text created by <code>helpText()</code>.
  277. *
  278. * @param description The description of the group
  279. */
  280. void beginGroup(const QString& description);
  281. /**
  282. * Ends the current group.
  283. *
  284. * @see beginGroup(const QString&)
  285. */
  286. void endGroup();
  287. /**
  288. * Enables QSettings support in ctkCommandLineParser. If an argument name is found
  289. * in the QSettings instance with a valid QVariant, the value is considered as
  290. * a default value and overwrites default values registered with
  291. * <code>addArgument()</code>. User supplied values on the command line overwrite
  292. * values in the QSettings instance, except for arguments with multiple parameters
  293. * which are merged with QSettings values. Call <code>mergeSettings(false)</code>
  294. * to disable merging.
  295. *
  296. * See <code>ctkCommandLineParser(QSettings*)</code> for information about how to
  297. * supply a QSettings instance.
  298. *
  299. * Additionally, a long and short argument name can be specified which will disable
  300. * QSettings support if supplied on the command line. The argument name must be
  301. * registered as a regular argument via <code>addArgument()</code>.
  302. *
  303. * @param disableLongArg Long argument name.
  304. * @param disableShortArg Short argument name.
  305. *
  306. * @see ctkCommandLineParser(QSettings*)
  307. */
  308. void enableSettings(const QString& disableLongArg = "",
  309. const QString& disableShortArg = "");
  310. /**
  311. * Controlls the merging behavior of user values and QSettings values.
  312. *
  313. * If merging is on (the default), user supplied values for an argument
  314. * which can take more than one parameter are merged with values stored
  315. * in the QSettings instance. If merging is off, the user values overwrite
  316. * the QSettings values.
  317. *
  318. * @param merge <code>true</code> enables QSettings merging, <code>false</code>
  319. * disables it.
  320. */
  321. void mergeSettings(bool merge);
  322. /**
  323. * Can be used to check if QSettings support has been enabled by a call to
  324. * <code>enableSettings()</code>.
  325. *
  326. * @return <code>true</code> if QSettings support is enabled, <code>false</code>
  327. * otherwise.
  328. */
  329. bool settingsEnabled() const;
  330. /**
  331. * Can be used to teach the parser to stop parsing the arguments and return False when
  332. * an unknown argument is encountered. By default <code>StrictMode</code> is disabled.
  333. *
  334. * @see parseArguments(const QStringList &, bool*)
  335. */
  336. void setStrictModeEnabled(bool strictMode);
  337. private:
  338. class ctkInternal;
  339. ctkInternal * Internal;
  340. };
  341. #endif