Small ArgumentParser refactoring.

This commit is contained in:
Florian Geyer 2013-04-18 21:21:30 +02:00
parent 94e6d3f89b
commit 63f7a0685f
4 changed files with 31 additions and 16 deletions

View File

@ -17,27 +17,15 @@
#include "ArgumentParser.h"
QStringList ArgumentParser::argumentKeys = QStringList() << "password" << "config" << "filename";
QHash<QString, QString> ArgumentParser::parseArguments(const QStringList& args)
{
QStringList argumentKeys = QStringList() << "password" << "config" << "filename";
QHash<QString, QString> argumentMap;
// TODO: needs refactoring, too much nesting
for (int i = 1; i < args.size(); i++) {
if (args[i].startsWith("--")) {
if (args.size() > (i + 1)) {
QString argument(args[i].mid(2));
if (argumentKeys.contains(argument)) {
argumentMap.insert(argument, args[i + 1]);
}
else {
qWarning("Unknown option \"%s\" with value \"%s\"", qPrintable(args[i]), qPrintable(args[i+1]));
}
i++;
} else {
qWarning("No value given for option \"%s\"", qPrintable(args[i]));
}
parseOption(i, argumentMap, args);
}
else if (!args[i].startsWith("-")) {
argumentMap.insert("filename", args[i]);
@ -49,3 +37,20 @@ QHash<QString, QString> ArgumentParser::parseArguments(const QStringList& args)
return argumentMap;
}
void ArgumentParser::parseOption(int& i, QHash<QString, QString>& argumentMap, const QStringList& args)
{
if (args.size() < (i + 2)) {
qWarning("No value given for option \"%s\"", qPrintable(args[i]));
return;
}
QString argument(args[i].mid(2));
if (argumentKeys.contains(argument)) {
argumentMap.insert(argument, args[i + 1]);
}
else {
qWarning("Unknown option \"%s\" with value \"%s\"", qPrintable(args[i]), qPrintable(args[i+1]));
}
i++;
}

View File

@ -28,7 +28,9 @@ class ArgumentParser
public:
static QHash<QString, QString> parseArguments(const QStringList& args);
private:
static QStringList argumentKeys;
static void parseOption(int& i, QHash<QString, QString>& argumentMap, const QStringList& args);
};
#endif // KEEPASSX_ARGUMENT_PARSER_H

View File

@ -31,6 +31,13 @@ void TestArgumentParser::testNoArguments()
QVERIFY(argumentMap.isEmpty());
}
void TestArgumentParser::testMissingOptionValue()
{
parse(QStringList() << "--foo");
QVERIFY(argumentMap.isEmpty());
}
void TestArgumentParser::testUnknownArgument()
{
parse(QStringList() << "--foo" << "bar");

View File

@ -27,6 +27,7 @@ class TestArgumentParser : public QObject
private Q_SLOTS:
void testNoArguments();
void testMissingOptionValue();
void testUnknownArgument();
void testFilename();
void testMultipleArguments();