Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

qcommandlineparser.cpp 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2013 Laszlo Papp <lpapp@kde.org>
  4. ** Copyright (C) 2013 David Faure <faure@kde.org>
  5. ** Contact: http://www.qt.io/licensing/
  6. **
  7. ** This file is part of the QtCore module of the Qt Toolkit.
  8. **
  9. ** $QT_BEGIN_LICENSE:LGPL21$
  10. ** Commercial License Usage
  11. ** Licensees holding valid commercial Qt licenses may use this file in
  12. ** accordance with the commercial license agreement provided with the
  13. ** Software or, alternatively, in accordance with the terms contained in
  14. ** a written agreement between you and The Qt Company. For licensing terms
  15. ** and conditions see http://www.qt.io/terms-conditions. For further
  16. ** information use the contact form at http://www.qt.io/contact-us.
  17. **
  18. ** GNU Lesser General Public License Usage
  19. ** Alternatively, this file may be used under the terms of the GNU Lesser
  20. ** General Public License version 2.1 or version 3 as published by the Free
  21. ** Software Foundation and appearing in the file LICENSE.LGPLv21 and
  22. ** LICENSE.LGPLv3 included in the packaging of this file. Please review the
  23. ** following information to ensure the GNU Lesser General Public License
  24. ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
  25. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  26. **
  27. ** As a special exception, The Qt Company gives you certain additional
  28. ** rights. These rights are described in The Qt Company LGPL Exception
  29. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  30. **
  31. ** $QT_END_LICENSE$
  32. **
  33. ****************************************************************************/
  34. #include "qcommandlineparser.h"
  35. #include <qcoreapplication.h>
  36. #include <qhash.h>
  37. #include <qvector.h>
  38. #include <qdebug.h>
  39. #if defined(Q_OS_WIN) && !defined(QT_BOOTSTRAPPED) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
  40. # include <qt_windows.h>
  41. #endif
  42. #include <stdio.h>
  43. #include <stdlib.h>
  44. QT_BEGIN_NAMESPACE
  45. typedef QHash<QString, int> NameHash_t;
  46. class QCommandLineParserPrivate
  47. {
  48. public:
  49. inline QCommandLineParserPrivate()
  50. : singleDashWordOptionMode(QCommandLineParser::ParseAsCompactedShortOptions),
  51. builtinVersionOption(false),
  52. builtinHelpOption(false),
  53. needsParsing(true)
  54. { }
  55. bool parse(const QStringList &args);
  56. void checkParsed(const char *method);
  57. QStringList aliases(const QString &name) const;
  58. QString helpText() const;
  59. bool registerFoundOption(const QString &optionName);
  60. bool parseOptionValue(const QString &optionName, const QString &argument,
  61. QStringList::const_iterator *argumentIterator,
  62. QStringList::const_iterator argsEnd);
  63. //! Error text set when parse() returns false
  64. QString errorText;
  65. //! The command line options used for parsing
  66. QList<QCommandLineOption> commandLineOptionList;
  67. //! Hash mapping option names to their offsets in commandLineOptionList and optionArgumentList.
  68. NameHash_t nameHash;
  69. //! Option values found (only for options with a value)
  70. QHash<int, QStringList> optionValuesHash;
  71. //! Names of options found on the command line.
  72. QStringList optionNames;
  73. //! Arguments which did not belong to any option.
  74. QStringList positionalArgumentList;
  75. //! Names of options which were unknown.
  76. QStringList unknownOptionNames;
  77. //! Application description
  78. QString description;
  79. //! Documentation for positional arguments
  80. struct PositionalArgumentDefinition
  81. {
  82. QString name;
  83. QString description;
  84. QString syntax;
  85. };
  86. QVector<PositionalArgumentDefinition> positionalArgumentDefinitions;
  87. //! The parsing mode for "-abc"
  88. QCommandLineParser::SingleDashWordOptionMode singleDashWordOptionMode;
  89. //! Whether addVersionOption was called
  90. bool builtinVersionOption;
  91. //! Whether addHelpOption was called
  92. bool builtinHelpOption;
  93. //! True if parse() needs to be called
  94. bool needsParsing;
  95. };
  96. QStringList QCommandLineParserPrivate::aliases(const QString &optionName) const
  97. {
  98. const NameHash_t::const_iterator it = nameHash.constFind(optionName);
  99. if (it == nameHash.constEnd()) {
  100. qWarning("QCommandLineParser: option not defined: \"%s\"", qPrintable(optionName));
  101. return QStringList();
  102. }
  103. return commandLineOptionList.at(*it).names();
  104. }
  105. /*!
  106. \since 5.2
  107. \class QCommandLineParser
  108. \inmodule QtCore
  109. \ingroup tools
  110. \brief The QCommandLineParser class provides a means for handling the
  111. command line options.
  112. QCoreApplication provides the command-line arguments as a simple list of strings.
  113. QCommandLineParser provides the ability to define a set of options, parse the
  114. command-line arguments, and store which options have actually been used, as
  115. well as option values.
  116. Any argument that isn't an option (i.e. doesn't start with a \c{-}) is stored
  117. as a "positional argument".
  118. The parser handles short names, long names, more than one name for the same
  119. option, and option values.
  120. Options on the command line are recognized as starting with a single or
  121. double \c{-} character(s).
  122. The option \c{-} (single dash alone) is a special case, often meaning standard
  123. input, and not treated as an option. The parser will treat everything after the
  124. option \c{--} (double dash) as positional arguments.
  125. Short options are single letters. The option \c{v} would be specified by
  126. passing \c{-v} on the command line. In the default parsing mode, short options
  127. can be written in a compact form, for instance \c{-abc} is equivalent to \c{-a -b -c}.
  128. The parsing mode for can be set to ParseAsLongOptions, in which case \c{-abc}
  129. will be parsed as the long option \c{abc}.
  130. Long options are more than one letter long and cannot be compacted together.
  131. The long option \c{verbose} would be passed as \c{--verbose} or \c{-verbose}.
  132. Passing values to options can be done using the assignment operator: \c{-v=value}
  133. \c{--verbose=value}, or a space: \c{-v value} \c{--verbose value}, i.e. the next
  134. argument is used as value (even if it starts with a \c{-}).
  135. The parser does not support optional values - if an option is set to
  136. require a value, one must be present. If such an option is placed last
  137. and has no value, the option will be treated as if it had not been
  138. specified.
  139. The parser does not automatically support negating or disabling long options
  140. by using the format \c{--disable-option} or \c{--no-option}. However, it is
  141. possible to handle this case explicitly by making an option with \c{no-option}
  142. as one of its names, and handling the option explicitly.
  143. Example:
  144. \snippet code/src_corelib_tools_qcommandlineparser_main.cpp 0
  145. If your compiler supports the C++11 standard, the three addOption() calls in
  146. the above example can be simplified:
  147. \snippet code/src_corelib_tools_qcommandlineparser_main.cpp cxx11
  148. Known limitation: the parsing of Qt options inside QCoreApplication and subclasses
  149. happens before QCommandLineParser exists, so it can't take it into account. This
  150. means any option value that looks like a builtin Qt option, will be treated by
  151. QCoreApplication as a builtin Qt option. Example: \c{--profile -reverse} will
  152. lead to QGuiApplication seeing the -reverse option set, and removing it from
  153. QCoreApplication::arguments() before QCommandLineParser defines the \c{profile}
  154. option and parses the command line.
  155. \section2 How to Use QCommandLineParser in Complex Applications
  156. In practice, additional error checking needs to be performed on the positional
  157. arguments and option values. For example, ranges of numbers should be checked.
  158. It is then advisable to introduce a function to do the command line parsing
  159. which takes a struct or class receiving the option values returning an
  160. enumeration representing the result. The dnslookup example of the QtNetwork
  161. module illustrates this:
  162. \snippet dnslookup.h 0
  163. \snippet dnslookup.cpp 0
  164. In the main function, help should be printed to the standard output if the help option
  165. was passed and the application should return the exit code 0.
  166. If an error was detected, the error message should be printed to the standard
  167. error output and the application should return an exit code other than 0.
  168. \snippet dnslookup.cpp 1
  169. A special case to consider here are GUI applications on Windows and mobile
  170. platforms. These applications may not use the standard output or error channels
  171. since the output is either discarded or not accessible.
  172. On Windows, QCommandLineParser uses message boxes to display usage information
  173. and errors if no console window can be obtained.
  174. For other platforms, it is recommended to display help texts and error messages
  175. using a QMessageBox. To preserve the formatting of the help text, rich text
  176. with \c <pre> elements should be used:
  177. \code
  178. switch (parseCommandLine(parser, &query, &errorMessage)) {
  179. case CommandLineOk:
  180. break;
  181. case CommandLineError:
  182. QMessageBox::warning(0, QGuiApplication::applicationDisplayName(),
  183. "<html><head/><body><h2>" + errorMessage + "</h2><pre>"
  184. + parser.helpText() + "</pre></body></html>");
  185. return 1;
  186. case CommandLineVersionRequested:
  187. QMessageBox::information(0, QGuiApplication::applicationDisplayName(),
  188. QGuiApplication::applicationDisplayName() + ' '
  189. + QCoreApplication::applicationVersion());
  190. return 0;
  191. case CommandLineHelpRequested:
  192. QMessageBox::warning(0, QGuiApplication::applicationDisplayName(),
  193. "<html><head/><body><pre>"
  194. + parser.helpText() + "</pre></body></html>");
  195. return 0;
  196. }
  197. \endcode
  198. However, this does not apply to the dnslookup example, because it is a
  199. console application.
  200. \sa QCommandLineOption, QCoreApplication
  201. */
  202. /*!
  203. Constructs a command line parser object.
  204. */
  205. QCommandLineParser::QCommandLineParser()
  206. : d(new QCommandLineParserPrivate)
  207. {
  208. }
  209. /*!
  210. Destroys the command line parser object.
  211. */
  212. QCommandLineParser::~QCommandLineParser()
  213. {
  214. delete d;
  215. }
  216. /*!
  217. \enum QCommandLineParser::SingleDashWordOptionMode
  218. This enum describes the way the parser interprets command-line
  219. options that use a single dash followed by multiple letters, as as \c{-abc}.
  220. \value ParseAsCompactedShortOptions \c{-abc} is interpreted as \c{-a -b -c},
  221. i.e. as three short options that have been compacted on the command-line,
  222. if none of the options take a value. If \c{a} takes a value, then it
  223. is interpreted as \c{-a bc}, i.e. the short option \c{a} followed by the value \c{bc}.
  224. This is typically used in tools that behave like compilers, in order
  225. to handle options such as \c{-DDEFINE=VALUE} or \c{-I/include/path}.
  226. This is the default parsing mode. New applications are recommended to
  227. use this mode.
  228. \value ParseAsLongOptions \c{-abc} is interpreted as \c{--abc},
  229. i.e. as the long option named \c{abc}. This is how Qt's own tools
  230. (uic, rcc...) have always been parsing arguments. This mode should be
  231. used for preserving compatibility in applications that were parsing
  232. arguments in such a way.
  233. \sa setSingleDashWordOptionMode()
  234. */
  235. /*!
  236. Sets the parsing mode to \a singleDashWordOptionMode.
  237. This must be called before process() or parse().
  238. */
  239. void QCommandLineParser::setSingleDashWordOptionMode(QCommandLineParser::SingleDashWordOptionMode singleDashWordOptionMode)
  240. {
  241. d->singleDashWordOptionMode = singleDashWordOptionMode;
  242. }
  243. /*!
  244. Adds the option \a option to look for while parsing.
  245. Returns \c true if adding the option was successful; otherwise returns \c false.
  246. Adding the option fails if there is no name attached to the option, or
  247. the option has a name that clashes with an option name added before.
  248. */
  249. bool QCommandLineParser::addOption(const QCommandLineOption &option)
  250. {
  251. QStringList optionNames = option.names();
  252. if (!optionNames.isEmpty()) {
  253. foreach (const QString &name, optionNames) {
  254. if (d->nameHash.contains(name))
  255. return false;
  256. }
  257. d->commandLineOptionList.append(option);
  258. const int offset = d->commandLineOptionList.size() - 1;
  259. foreach (const QString &name, optionNames)
  260. d->nameHash.insert(name, offset);
  261. return true;
  262. }
  263. return false;
  264. }
  265. /*!
  266. \since 5.4
  267. Adds the options to look for while parsing. The options are specified by
  268. the parameter \a options.
  269. Returns \c true if adding all of the options was successful; otherwise
  270. returns \c false.
  271. See the documentation for addOption() for when this function may fail.
  272. */
  273. bool QCommandLineParser::addOptions(const QList<QCommandLineOption> &options)
  274. {
  275. // should be optimized (but it's no worse than what was possible before)
  276. bool result = true;
  277. for (QList<QCommandLineOption>::const_iterator it = options.begin(), end = options.end(); it != end; ++it)
  278. result &= addOption(*it);
  279. return result;
  280. }
  281. /*!
  282. Adds the \c{-v} / \c{--version} option, which displays the version string of the application.
  283. This option is handled automatically by QCommandLineParser.
  284. You can set the actual version string by using QCoreApplication::setApplicationVersion().
  285. Returns the option instance, which can be used to call isSet().
  286. */
  287. QCommandLineOption QCommandLineParser::addVersionOption()
  288. {
  289. QCommandLineOption opt(QStringList() << QString("v") << QString("version"), tr("Displays version information."));
  290. addOption(opt);
  291. d->builtinVersionOption = true;
  292. return opt;
  293. }
  294. /*!
  295. Adds the help option (\c{-h}, \c{--help} and \c{-?} on Windows)
  296. This option is handled automatically by QCommandLineParser.
  297. Remember to use setApplicationDescription to set the application description,
  298. which will be displayed when this option is used.
  299. Example:
  300. \snippet code/src_corelib_tools_qcommandlineparser_main.cpp 0
  301. Returns the option instance, which can be used to call isSet().
  302. */
  303. QCommandLineOption QCommandLineParser::addHelpOption()
  304. {
  305. QCommandLineOption opt(QStringList()
  306. #ifdef Q_OS_WIN
  307. << QString("?")
  308. #endif
  309. << QString("h")
  310. << QString("help"), tr("Displays this help."));
  311. addOption(opt);
  312. d->builtinHelpOption = true;
  313. return opt;
  314. }
  315. /*!
  316. Sets the application \a description shown by helpText().
  317. */
  318. void QCommandLineParser::setApplicationDescription(const QString &description)
  319. {
  320. d->description = description;
  321. }
  322. /*!
  323. Returns the application description set in setApplicationDescription().
  324. */
  325. QString QCommandLineParser::applicationDescription() const
  326. {
  327. return d->description;
  328. }
  329. /*!
  330. Defines an additional argument to the application, for the benefit of the help text.
  331. The argument \a name and \a description will appear under the \c{Arguments:} section
  332. of the help. If \a syntax is specified, it will be appended to the Usage line, otherwise
  333. the \a name will be appended.
  334. Example:
  335. \snippet code/src_corelib_tools_qcommandlineparser.cpp 2
  336. \sa addHelpOption(), helpText()
  337. */
  338. void QCommandLineParser::addPositionalArgument(const QString &name, const QString &description, const QString &syntax)
  339. {
  340. QCommandLineParserPrivate::PositionalArgumentDefinition arg;
  341. arg.name = name;
  342. arg.description = description;
  343. arg.syntax = syntax.isEmpty() ? name : syntax;
  344. d->positionalArgumentDefinitions.append(arg);
  345. }
  346. /*!
  347. Clears the definitions of additional arguments from the help text.
  348. This is only needed for the special case of tools which support multiple commands
  349. with different options. Once the actual command has been identified, the options
  350. for this command can be defined, and the help text for the command can be adjusted
  351. accordingly.
  352. Example:
  353. \snippet code/src_corelib_tools_qcommandlineparser.cpp 3
  354. */
  355. void QCommandLineParser::clearPositionalArguments()
  356. {
  357. d->positionalArgumentDefinitions.clear();
  358. }
  359. /*!
  360. Parses the command line \a arguments.
  361. Most programs don't need to call this, a simple call to process() is enough.
  362. parse() is more low-level, and only does the parsing. The application will have to
  363. take care of the error handling, using errorText() if parse() returns \c false.
  364. This can be useful for instance to show a graphical error message in graphical programs.
  365. Calling parse() instead of process() can also be useful in order to ignore unknown
  366. options temporarily, because more option definitions will be provided later on
  367. (depending on one of the arguments), before calling process().
  368. Don't forget that \a arguments must start with the name of the executable (ignored, though).
  369. Returns \c false in case of a parse error (unknown option or missing value); returns \c true otherwise.
  370. \sa process()
  371. */
  372. bool QCommandLineParser::parse(const QStringList &arguments)
  373. {
  374. return d->parse(arguments);
  375. }
  376. /*!
  377. Returns a translated error text for the user.
  378. This should only be called when parse() returns \c false.
  379. */
  380. QString QCommandLineParser::errorText() const
  381. {
  382. if (!d->errorText.isEmpty())
  383. return d->errorText;
  384. if (d->unknownOptionNames.count() == 1)
  385. return tr("Unknown option '%1'.").arg(d->unknownOptionNames.first());
  386. if (d->unknownOptionNames.count() > 1)
  387. return tr("Unknown options: %1.").arg(d->unknownOptionNames.join(QString(", ")));
  388. return QString();
  389. }
  390. enum MessageType { UsageMessage, ErrorMessage };
  391. #if defined(Q_OS_WIN) && !defined(QT_BOOTSTRAPPED) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
  392. // Return whether to use a message box. Use handles if a console can be obtained
  393. // or we are run with redirected handles (for example, by QProcess).
  394. static inline bool displayMessageBox()
  395. {
  396. if (GetConsoleWindow())
  397. return false;
  398. STARTUPINFO startupInfo;
  399. startupInfo.cb = sizeof(STARTUPINFO);
  400. GetStartupInfo(&startupInfo);
  401. return !(startupInfo.dwFlags & STARTF_USESTDHANDLES);
  402. }
  403. #endif // Q_OS_WIN && !QT_BOOTSTRAPPED && !Q_OS_WIN && !Q_OS_WINRT
  404. static void showParserMessage(const QString &message, MessageType type)
  405. {
  406. #if defined(Q_OS_WIN) && !defined(QT_BOOTSTRAPPED) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT)
  407. if (displayMessageBox()) {
  408. const UINT flags = MB_OK | MB_TOPMOST | MB_SETFOREGROUND
  409. | (type == UsageMessage ? MB_ICONINFORMATION : MB_ICONERROR);
  410. QString title;
  411. if (QCoreApplication::instance())
  412. title = QCoreApplication::instance()->property("applicationDisplayName").toString();
  413. if (title.isEmpty())
  414. title = QCoreApplication::applicationName();
  415. MessageBoxW(0, reinterpret_cast<const wchar_t *>(message.utf16()),
  416. reinterpret_cast<const wchar_t *>(title.utf16()), flags);
  417. return;
  418. }
  419. #endif // Q_OS_WIN && !QT_BOOTSTRAPPED && !Q_OS_WIN && !Q_OS_WINRT
  420. fputs(qPrintable(message), type == UsageMessage ? stdout : stderr);
  421. }
  422. /*!
  423. Processes the command line \a arguments.
  424. In addition to parsing the options (like parse()), this function also handles the builtin
  425. options and handles errors.
  426. The builtin options are \c{--version} if addVersionOption was called and \c{--help} if addHelpOption was called.
  427. When invoking one of these options, or when an error happens (for instance an unknown option was
  428. passed), the current process will then stop, using the exit() function.
  429. \sa QCoreApplication::arguments(), parse()
  430. */
  431. void QCommandLineParser::process(const QStringList &arguments)
  432. {
  433. if (!d->parse(arguments)) {
  434. showParserMessage(errorText() + QLatin1Char('\n'), ErrorMessage);
  435. ::exit(EXIT_FAILURE);
  436. }
  437. if (d->builtinVersionOption && isSet(QString("version")))
  438. showVersion();
  439. if (d->builtinHelpOption && isSet(QString("help")))
  440. showHelp(EXIT_SUCCESS);
  441. }
  442. /*!
  443. \overload
  444. The command line is obtained from the QCoreApplication instance \a app.
  445. */
  446. void QCommandLineParser::process(const QCoreApplication &app)
  447. {
  448. // QCoreApplication::arguments() is static, but the app instance must exist so we require it as parameter
  449. Q_UNUSED(app);
  450. process(QCoreApplication::arguments());
  451. }
  452. void QCommandLineParserPrivate::checkParsed(const char *method)
  453. {
  454. if (needsParsing)
  455. qWarning("QCommandLineParser: call process() or parse() before %s", method);
  456. }
  457. /*!
  458. \internal
  459. Looks up the option \a optionName (found on the command line) and register it as found.
  460. Returns \c true on success.
  461. */
  462. bool QCommandLineParserPrivate::registerFoundOption(const QString &optionName)
  463. {
  464. if (nameHash.contains(optionName)) {
  465. optionNames.append(optionName);
  466. return true;
  467. } else {
  468. unknownOptionNames.append(optionName);
  469. return false;
  470. }
  471. }
  472. /*!
  473. \internal
  474. \brief Parse the value for a given option, if it was defined to expect one.
  475. The value is taken from the next argument, or after the equal sign in \a argument.
  476. \param optionName the short option name
  477. \param argument the argument from the command line currently parsed. Only used for -k=value parsing.
  478. \param argumentIterator iterator to the currently parsed argument. Incremented if the next argument contains the value.
  479. \param argsEnd args.end(), to check if ++argumentIterator goes out of bounds
  480. Returns \c true on success.
  481. */
  482. bool QCommandLineParserPrivate::parseOptionValue(const QString &optionName, const QString &argument,
  483. QStringList::const_iterator *argumentIterator, QStringList::const_iterator argsEnd)
  484. {
  485. const QLatin1Char assignChar('=');
  486. const NameHash_t::const_iterator nameHashIt = nameHash.constFind(optionName);
  487. if (nameHashIt != nameHash.constEnd()) {
  488. const int assignPos = argument.indexOf(assignChar);
  489. const NameHash_t::mapped_type optionOffset = *nameHashIt;
  490. const bool withValue = !commandLineOptionList.at(optionOffset).valueName().isEmpty();
  491. if (withValue) {
  492. if (assignPos == -1) {
  493. ++(*argumentIterator);
  494. if (*argumentIterator == argsEnd) {
  495. errorText = QCommandLineParser::tr("Missing value after '%1'.").arg(argument);
  496. return false;
  497. }
  498. optionValuesHash[optionOffset].append(*(*argumentIterator));
  499. } else {
  500. optionValuesHash[optionOffset].append(argument.mid(assignPos + 1));
  501. }
  502. } else {
  503. if (assignPos != -1) {
  504. errorText = QCommandLineParser::tr("Unexpected value after '%1'.").arg(argument.left(assignPos));
  505. return false;
  506. }
  507. }
  508. }
  509. return true;
  510. }
  511. /*!
  512. \internal
  513. Parse the list of arguments \a args, and fills in
  514. optionNames, optionValuesHash, unknownOptionNames, positionalArguments, and errorText.
  515. Any results from a previous parse operation are removed.
  516. The parser will not look for further options once it encounters the option
  517. \c{--}; this does not include when \c{--} follows an option that requires a value.
  518. */
  519. bool QCommandLineParserPrivate::parse(const QStringList &args)
  520. {
  521. needsParsing = false;
  522. bool error = false;
  523. const QString doubleDashString(QString("--"));
  524. const QLatin1Char dashChar('-');
  525. const QLatin1Char assignChar('=');
  526. bool doubleDashFound = false;
  527. errorText.clear();
  528. positionalArgumentList.clear();
  529. optionNames.clear();
  530. unknownOptionNames.clear();
  531. optionValuesHash.clear();
  532. if (args.isEmpty()) {
  533. qWarning("QCommandLineParser: argument list cannot be empty, it should contain at least the executable name");
  534. return false;
  535. }
  536. QStringList::const_iterator argumentIterator = args.begin();
  537. ++argumentIterator; // skip executable name
  538. for (; argumentIterator != args.end() ; ++argumentIterator) {
  539. QString argument = *argumentIterator;
  540. if (doubleDashFound) {
  541. positionalArgumentList.append(argument);
  542. } else if (argument.startsWith(doubleDashString)) {
  543. if (argument.length() > 2) {
  544. QString optionName = argument.mid(2).section(assignChar, 0, 0);
  545. if (registerFoundOption(optionName)) {
  546. if (!parseOptionValue(optionName, argument, &argumentIterator, args.end()))
  547. error = true;
  548. } else {
  549. error = true;
  550. }
  551. } else {
  552. doubleDashFound = true;
  553. }
  554. } else if (argument.startsWith(dashChar)) {
  555. if (argument.size() == 1) { // single dash ("stdin")
  556. positionalArgumentList.append(argument);
  557. continue;
  558. }
  559. switch (singleDashWordOptionMode) {
  560. case QCommandLineParser::ParseAsCompactedShortOptions:
  561. {
  562. QString optionName;
  563. bool valueFound = false;
  564. for (int pos = 1 ; pos < argument.size(); ++pos) {
  565. optionName = argument.mid(pos, 1);
  566. if (!registerFoundOption(optionName)) {
  567. error = true;
  568. } else {
  569. const NameHash_t::const_iterator nameHashIt = nameHash.constFind(optionName);
  570. Q_ASSERT(nameHashIt != nameHash.constEnd()); // checked by registerFoundOption
  571. const NameHash_t::mapped_type optionOffset = *nameHashIt;
  572. const bool withValue = !commandLineOptionList.at(optionOffset).valueName().isEmpty();
  573. if (withValue) {
  574. if (pos + 1 < argument.size()) {
  575. if (argument.at(pos + 1) == assignChar)
  576. ++pos;
  577. optionValuesHash[optionOffset].append(argument.mid(pos + 1));
  578. valueFound = true;
  579. }
  580. break;
  581. }
  582. if (pos + 1 < argument.size() && argument.at(pos + 1) == assignChar)
  583. break;
  584. }
  585. }
  586. if (!valueFound && !parseOptionValue(optionName, argument, &argumentIterator, args.end()))
  587. error = true;
  588. break;
  589. }
  590. case QCommandLineParser::ParseAsLongOptions:
  591. {
  592. const QString optionName = argument.mid(1).section(assignChar, 0, 0);
  593. if (registerFoundOption(optionName)) {
  594. if (!parseOptionValue(optionName, argument, &argumentIterator, args.end()))
  595. error = true;
  596. } else {
  597. error = true;
  598. }
  599. break;
  600. }
  601. }
  602. } else {
  603. positionalArgumentList.append(argument);
  604. }
  605. if (argumentIterator == args.end())
  606. break;
  607. }
  608. return !error;
  609. }
  610. /*!
  611. Checks whether the option \a name was passed to the application.
  612. Returns \c true if the option \a name was set, false otherwise.
  613. The name provided can be any long or short name of any option that was
  614. added with \c addOption(). All the options names are treated as being
  615. equivalent. If the name is not recognized or that option was not present,
  616. false is returned.
  617. Example:
  618. \snippet code/src_corelib_tools_qcommandlineparser.cpp 0
  619. */
  620. bool QCommandLineParser::isSet(const QString &name) const
  621. {
  622. d->checkParsed("isSet");
  623. if (d->optionNames.contains(name))
  624. return true;
  625. const QStringList aliases = d->aliases(name);
  626. foreach (const QString &optionName, d->optionNames) {
  627. if (aliases.contains(optionName))
  628. return true;
  629. }
  630. return false;
  631. }
  632. /*!
  633. Returns the option value found for the given option name \a optionName, or
  634. an empty string if not found.
  635. The name provided can be any long or short name of any option that was
  636. added with \c addOption(). All the option names are treated as being
  637. equivalent. If the name is not recognized or that option was not present, an
  638. empty string is returned.
  639. For options found by the parser, the last value found for
  640. that option is returned. If the option wasn't specified on the command line,
  641. the default value is returned.
  642. An empty string is returned if the option does not take a value.
  643. \sa values(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()
  644. */
  645. QString QCommandLineParser::value(const QString &optionName) const
  646. {
  647. d->checkParsed("value");
  648. const QStringList valueList = values(optionName);
  649. if (!valueList.isEmpty())
  650. return valueList.last();
  651. return QString();
  652. }
  653. /*!
  654. Returns a list of option values found for the given option name \a
  655. optionName, or an empty list if not found.
  656. The name provided can be any long or short name of any option that was
  657. added with \c addOption(). All the options names are treated as being
  658. equivalent. If the name is not recognized or that option was not present, an
  659. empty list is returned.
  660. For options found by the parser, the list will contain an entry for
  661. each time the option was encountered by the parser. If the option wasn't
  662. specified on the command line, the default values are returned.
  663. An empty list is returned if the option does not take a value.
  664. \sa value(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()
  665. */
  666. QStringList QCommandLineParser::values(const QString &optionName) const
  667. {
  668. d->checkParsed("values");
  669. const NameHash_t::const_iterator it = d->nameHash.constFind(optionName);
  670. if (it != d->nameHash.constEnd()) {
  671. const int optionOffset = *it;
  672. QStringList values = d->optionValuesHash.value(optionOffset);
  673. if (values.isEmpty())
  674. values = d->commandLineOptionList.at(optionOffset).defaultValues();
  675. return values;
  676. }
  677. qWarning("QCommandLineParser: option not defined: \"%s\"", qPrintable(optionName));
  678. return QStringList();
  679. }
  680. /*!
  681. \overload
  682. Checks whether the \a option was passed to the application.
  683. Returns \c true if the \a option was set, false otherwise.
  684. This is the recommended way to check for options with no values.
  685. Example:
  686. \snippet code/src_corelib_tools_qcommandlineparser.cpp 1
  687. */
  688. bool QCommandLineParser::isSet(const QCommandLineOption &option) const
  689. {
  690. // option.names() might be empty if the constructor failed
  691. return !option.names().isEmpty() && isSet(option.names().first());
  692. }
  693. /*!
  694. \overload
  695. Returns the option value found for the given \a option, or
  696. an empty string if not found.
  697. For options found by the parser, the last value found for
  698. that option is returned. If the option wasn't specified on the command line,
  699. the default value is returned.
  700. An empty string is returned if the option does not take a value.
  701. \sa values(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()
  702. */
  703. QString QCommandLineParser::value(const QCommandLineOption &option) const
  704. {
  705. return value(option.names().first());
  706. }
  707. /*!
  708. \overload
  709. Returns a list of option values found for the given \a option,
  710. or an empty list if not found.
  711. For options found by the parser, the list will contain an entry for
  712. each time the option was encountered by the parser. If the option wasn't
  713. specified on the command line, the default values are returned.
  714. An empty list is returned if the option does not take a value.
  715. \sa value(), QCommandLineOption::setDefaultValue(), QCommandLineOption::setDefaultValues()
  716. */
  717. QStringList QCommandLineParser::values(const QCommandLineOption &option) const
  718. {
  719. return values(option.names().first());
  720. }
  721. /*!
  722. Returns a list of positional arguments.
  723. These are all of the arguments that were not recognized as part of an
  724. option.
  725. */
  726. QStringList QCommandLineParser::positionalArguments() const
  727. {
  728. d->checkParsed("positionalArguments");
  729. return d->positionalArgumentList;
  730. }
  731. /*!
  732. Returns a list of option names that were found.
  733. This returns a list of all the recognized option names found by the
  734. parser, in the order in which they were found. For any long options
  735. that were in the form {--option=value}, the value part will have been
  736. dropped.
  737. The names in this list do not include the preceding dash characters.
  738. Names may appear more than once in this list if they were encountered
  739. more than once by the parser.
  740. Any entry in the list can be used with \c value() or with
  741. \c values() to get any relevant option values.
  742. */
  743. QStringList QCommandLineParser::optionNames() const
  744. {
  745. d->checkParsed("optionNames");
  746. return d->optionNames;
  747. }
  748. /*!
  749. Returns a list of unknown option names.
  750. This list will include both long an short name options that were not
  751. recognized. For any long options that were in the form {--option=value},
  752. the value part will have been dropped and only the long name is added.
  753. The names in this list do not include the preceding dash characters.
  754. Names may appear more than once in this list if they were encountered
  755. more than once by the parser.
  756. \sa optionNames()
  757. */
  758. QStringList QCommandLineParser::unknownOptionNames() const
  759. {
  760. d->checkParsed("unknownOptionNames");
  761. return d->unknownOptionNames;
  762. }
  763. /*!
  764. Displays the version information from QCoreApplication::applicationVersion(),
  765. and exits the application.
  766. This is automatically triggered by the --version option, but can also
  767. be used to display the version when not using process().
  768. The exit code is set to EXIT_SUCCESS (0).
  769. \sa addVersionOption()
  770. \since 5.4
  771. */
  772. void QCommandLineParser::showVersion()
  773. {
  774. showParserMessage(QCoreApplication::applicationName() + QLatin1Char(' ')
  775. + QCoreApplication::applicationVersion() + QLatin1Char('\n'),
  776. UsageMessage);
  777. ::exit(EXIT_SUCCESS);
  778. }
  779. /*!
  780. Displays the help information, and exits the application.
  781. This is automatically triggered by the --help option, but can also
  782. be used to display the help when the user is not invoking the
  783. application correctly.
  784. The exit code is set to \a exitCode. It should be set to 0 if the
  785. user requested to see the help, and to any other value in case of
  786. an error.
  787. \sa helpText()
  788. */
  789. void QCommandLineParser::showHelp(int exitCode)
  790. {
  791. showParserMessage(d->helpText(), UsageMessage);
  792. ::exit(exitCode);
  793. }
  794. /*!
  795. Returns a string containing the complete help information.
  796. \sa showHelp()
  797. */
  798. QString QCommandLineParser::helpText() const
  799. {
  800. return d->helpText();
  801. }
  802. static QString wrapText(const QString &names, int longestOptionNameString, const QString &description)
  803. {
  804. const QLatin1Char nl('\n');
  805. QString text = QString(" ") + names.leftJustified(longestOptionNameString) + QLatin1Char(' ');
  806. const int indent = text.length();
  807. int lineStart = 0;
  808. int lastBreakable = -1;
  809. const int max = 79 - indent;
  810. int x = 0;
  811. const int len = description.length();
  812. for (int i = 0; i < len; ++i) {
  813. ++x;
  814. const QChar c = description.at(i);
  815. if (c.isSpace())
  816. lastBreakable = i;
  817. int breakAt = -1;
  818. int nextLineStart = -1;
  819. if (x > max && lastBreakable != -1) {
  820. // time to break and we know where
  821. breakAt = lastBreakable;
  822. nextLineStart = lastBreakable + 1;
  823. } else if ((x > max - 1 && lastBreakable == -1) || i == len - 1) {
  824. // time to break but found nowhere [-> break here], or end of last line
  825. breakAt = i + 1;
  826. nextLineStart = breakAt;
  827. } else if (c == nl) {
  828. // forced break
  829. breakAt = i;
  830. nextLineStart = i + 1;
  831. }
  832. if (breakAt != -1) {
  833. const int numChars = breakAt - lineStart;
  834. //qDebug() << "breakAt=" << description.at(breakAt) << "breakAtSpace=" << breakAtSpace << lineStart << "to" << breakAt << description.mid(lineStart, numChars);
  835. if (lineStart > 0)
  836. text += QString(indent, QLatin1Char(' '));
  837. text += description.midRef(lineStart, numChars).toString() + nl;
  838. x = 0;
  839. lastBreakable = -1;
  840. lineStart = nextLineStart;
  841. if (lineStart < len && description.at(lineStart).isSpace())
  842. ++lineStart; // don't start a line with a space
  843. i = lineStart;
  844. }
  845. }
  846. return text;
  847. }
  848. QString QCommandLineParserPrivate::helpText() const
  849. {
  850. const QLatin1Char nl('\n');
  851. QString text;
  852. const QString exeName = QCoreApplication::instance()->arguments().first();
  853. QString usage = exeName;
  854. if (!commandLineOptionList.isEmpty()) {
  855. usage += QLatin1Char(' ');
  856. usage += QCommandLineParser::tr("[options]");
  857. }
  858. foreach (const PositionalArgumentDefinition &arg, positionalArgumentDefinitions) {
  859. usage += QLatin1Char(' ');
  860. usage += arg.syntax;
  861. }
  862. text += QCommandLineParser::tr("Usage: %1").arg(usage) + nl;
  863. if (!description.isEmpty())
  864. text += description + nl;
  865. text += nl;
  866. if (!commandLineOptionList.isEmpty())
  867. text += QCommandLineParser::tr("Options:") + nl;
  868. QStringList optionNameList;
  869. int longestOptionNameString = 0;
  870. foreach (const QCommandLineOption &option, commandLineOptionList) {
  871. QStringList optionNames;
  872. foreach (const QString &optionName, option.names()) {
  873. if (optionName.length() == 1)
  874. optionNames.append(QLatin1Char('-') + optionName);
  875. else
  876. optionNames.append(QString("--") + optionName);
  877. }
  878. QString optionNamesString = optionNames.join(QString(", "));
  879. if (!option.valueName().isEmpty())
  880. {
  881. optionNamesString += QString(" <") + option.valueName();
  882. if (option.defaultValues().size() != 0)
  883. optionNamesString += "=" + option.defaultValues()[0];
  884. optionNamesString += QLatin1Char('>');
  885. }
  886. optionNameList.append(optionNamesString);
  887. longestOptionNameString = qMax(longestOptionNameString, optionNamesString.length());
  888. }
  889. ++longestOptionNameString;
  890. for (int i = 0; i < commandLineOptionList.count(); ++i) {
  891. const QCommandLineOption &option = commandLineOptionList.at(i);
  892. text += wrapText(optionNameList.at(i), longestOptionNameString, option.description());
  893. }
  894. if (!positionalArgumentDefinitions.isEmpty()) {
  895. if (!commandLineOptionList.isEmpty())
  896. text += nl;
  897. text += QCommandLineParser::tr("Arguments:") + nl;
  898. foreach (const PositionalArgumentDefinition &arg, positionalArgumentDefinitions) {
  899. text += wrapText(arg.name, longestOptionNameString, arg.description);
  900. }
  901. }
  902. return text;
  903. }
  904. QT_END_NAMESPACE