QCommandLineParser: fix crash if there's no QCoreApplication

It'll display <executable_name> instead in the help output.

Fixes: QTBUG-91430
Change-Id: Ib6211b24cdaa4683a4f62c90b5a1a20ba69f1cff
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
David Faure 2021-02-26 23:06:15 +01:00
parent b579d8a05b
commit 101581484b
2 changed files with 33 additions and 3 deletions

View File

@ -1125,10 +1125,11 @@ QString QCommandLineParserPrivate::helpText(bool includeQtOptions) const
const QLatin1Char nl('\n');
QString text;
QString usage;
usage += QCoreApplication::instance()->arguments().constFirst(); // executable name
// executable name
usage += qApp ? QCoreApplication::arguments().constFirst() : QStringLiteral("<executable_name>");
QList<QCommandLineOption> options = commandLineOptionList;
if (includeQtOptions)
QCoreApplication::instance()->d_func()->addQtOptions(&options);
if (includeQtOptions && qApp)
qApp->d_func()->addQtOptions(&options);
if (!options.isEmpty())
usage += QLatin1Char(' ') + QCommandLineParser::tr("[options]");
for (const PositionalArgumentDefinition &arg : positionalArgumentDefinitions)

View File

@ -64,6 +64,7 @@ private slots:
void testDefaultValue();
void testProcessNotCalled();
void testEmptyArgsList();
void testNoApplication();
void testMissingOptionValue();
void testStdinArgument_data();
void testStdinArgument();
@ -393,6 +394,34 @@ void tst_QCommandLineParser::testEmptyArgsList()
QVERIFY(!parser.parse(QStringList())); // invalid call, argv[0] is missing
}
void tst_QCommandLineParser::testNoApplication()
{
QCommandLineOption option(QStringLiteral("param"), QStringLiteral("Pass parameter to the backend."));
option.setValueName("key=value");
QCommandLineParser parser;
QVERIFY(parser.addOption(option));
{
QVERIFY(parser.parse(QStringList() << "tst" << "--param" << "key1=value1"));
QVERIFY(parser.isSet("param"));
QCOMPARE(parser.values("param"), QStringList() << "key1=value1");
QCOMPARE(parser.value("param"), QString("key1=value1"));
}
{
QVERIFY(parser.parse(QStringList() << "tst" << "--param" << "key1=value1" << "--param" << "key2=value2"));
QVERIFY(parser.isSet("param"));
QCOMPARE(parser.values("param"), QStringList() << "key1=value1" << "key2=value2");
QCOMPARE(parser.value("param"), QString("key2=value2"));
}
const QString expected =
"Usage: <executable_name> [options]\n"
"\n"
"Options:\n"
" --param <key=value> Pass parameter to the backend.\n";
QCOMPARE(parser.helpText(), expected);
}
void tst_QCommandLineParser::testMissingOptionValue()
{
QCoreApplication app(empty_argc, empty_argv);