ctkCommandLineParser.h 14 KB

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