ctkCommandLineParser.h 14 KB

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