Util: Add ArgParser unhandled argument error type and messages

This commit is contained in:
Riyyi
2021-09-13 04:04:02 +02:00
parent a5d5d2ea6d
commit 9c918c6555
2 changed files with 22 additions and 1 deletions
+21 -1
View File
@@ -1,6 +1,7 @@
#include <algorithm> // find_if #include <algorithm> // find_if
#include <cstddef> // size_t #include <cstddef> // size_t
#include <cstdio> // printf #include <cstdio> // printf
#include <cstring> // strcmp
#include <limits> // numeric_limits #include <limits> // numeric_limits
#include <string> // stod, stoi, stoul #include <string> // stod, stoi, stoul
#include <string_view> #include <string_view>
@@ -39,6 +40,9 @@ void ArgParser::printOptionError(const char* name, Error error, bool longName)
else if (error == Error::DoesntAllowArgument) { else if (error == Error::DoesntAllowArgument) {
printf("%s: option '--%s' doesn't allow an argument\n", m_name, name); 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) { else if (error == Error::RequiresArgument) {
if (longName) { if (longName) {
printf("%s: option '--%s' requires an argument", m_name, name); printf("%s: option '--%s' requires an argument", m_name, name);
@@ -196,6 +200,7 @@ bool ArgParser::parseArgument(std::string_view argument)
for (;;) { for (;;) {
// Run out of argument handlers // Run out of argument handlers
if (m_argumentIndex >= m_arguments.size()) { if (m_argumentIndex >= m_arguments.size()) {
printOptionError(argument.data(), Error::ExtraOperand);
return false; 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;
} }
// ----------------------------------------- // -----------------------------------------
+1
View File
@@ -26,6 +26,7 @@ public:
None, None,
InvalidOption, // For short options InvalidOption, // For short options
UnrecognizedOption, // For long options UnrecognizedOption, // For long options
ExtraOperand, // For arguments
DoesntAllowArgument, DoesntAllowArgument,
RequiresArgument, RequiresArgument,
}; };