Browse Source

Util: Add ArgParser unhandled argument error type and messages

master
Riyyi 3 years ago
parent
commit
9c918c6555
  1. 22
      src/util/argparser.cpp
  2. 1
      src/util/argparser.h

22
src/util/argparser.cpp

@ -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
src/util/argparser.h

@ -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,
}; };

Loading…
Cancel
Save