From 9c918c6555e59b255ce05874d04b2c18f943d05f Mon Sep 17 00:00:00 2001 From: Riyyi Date: Mon, 13 Sep 2021 04:04:02 +0200 Subject: [PATCH] Util: Add ArgParser unhandled argument error type and messages --- src/util/argparser.cpp | 22 +++++++++++++++++++++- src/util/argparser.h | 1 + 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/util/argparser.cpp b/src/util/argparser.cpp index 92c0025..d076661 100644 --- a/src/util/argparser.cpp +++ b/src/util/argparser.cpp @@ -1,6 +1,7 @@ #include // find_if #include // size_t #include // printf +#include // strcmp #include // numeric_limits #include // stod, stoi, stoul #include @@ -39,6 +40,9 @@ void ArgParser::printOptionError(const char* name, Error error, bool longName) else if (error == Error::DoesntAllowArgument) { printf("%s: option '--%s' doesn't allow an argument\n", m_name, name); } + else if (error == Error::ExtraOperand) { + printf("%s: extra operand '%s'\n", m_name, name); + } else if (error == Error::RequiresArgument) { if (longName) { printf("%s: option '--%s' requires an argument", m_name, name); @@ -196,6 +200,7 @@ bool ArgParser::parseArgument(std::string_view argument) for (;;) { // Run out of argument handlers if (m_argumentIndex >= m_arguments.size()) { + printOptionError(argument.data(), Error::ExtraOperand); return false; } @@ -291,7 +296,22 @@ bool ArgParser::parse(int argc, const char* argv[]) } } - return result; + if (result) { + return true; + } + + for (auto& option : m_options) { + if (option.longName && strcmp(option.longName, "help") == 0) { + printf("Try '%s --help' for more information.\n", m_name); + break; + } + if (option.shortName == 'h') { + printf("Try '%s -h' for more information.\n", m_name); + break; + } + } + + return false; } // ----------------------------------------- diff --git a/src/util/argparser.h b/src/util/argparser.h index d6860b4..0a44048 100644 --- a/src/util/argparser.h +++ b/src/util/argparser.h @@ -26,6 +26,7 @@ public: None, InvalidOption, // For short options UnrecognizedOption, // For long options + ExtraOperand, // For arguments DoesntAllowArgument, RequiresArgument, };