ctkCommandLineParser.h 15 KB

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