Simplified logic in error reporting, asking user if they meant to use a specific optional argument

This commit is contained in:
Pranav Srinivas Kumar 2023-11-04 09:11:34 -05:00
parent 62052fefcb
commit c6e64ae36d

View File

@ -1844,7 +1844,9 @@ private:
if (m_positional_arguments.empty()) { if (m_positional_arguments.empty()) {
/// Check sub-parsers first // Ask the user if they argument they provided was a typo
// for some sub-parser,
// e.g., user provided `git totes` instead of `git notes`
if (!m_subparser_map.empty()) { if (!m_subparser_map.empty()) {
throw std::runtime_error( throw std::runtime_error(
"Failed to parse '" + current_argument + "', did you mean '" + "Failed to parse '" + current_argument + "', did you mean '" +
@ -1853,36 +1855,17 @@ private:
"'"); "'");
} }
// Ask the user if they meant to use a specific optional argument
if (!m_optional_arguments.empty()) { if (!m_optional_arguments.empty()) {
bool not_help_or_version{true};
for (const auto &opt : m_optional_arguments) { for (const auto &opt : m_optional_arguments) {
if (!opt.m_implicit_value.has_value()) {
// Find first optional argument that is // not a flag, requires a value
// neither help nor version
for (auto &name : opt.m_names) {
auto pos = name.find("help");
if (pos != std::string::npos) {
not_help_or_version = false;
break;
}
pos = name.find("version");
if (pos != std::string::npos) {
not_help_or_version = false;
break;
}
}
if (not_help_or_version) {
if (!opt.m_is_used) { if (!opt.m_is_used) {
throw std::runtime_error( throw std::runtime_error(
"Zero positional arguments expected, did you mean " + "Zero positional arguments expected, did you mean " +
opt.get_usage_full()); opt.get_usage_full());
} }
} }
// continue searching
not_help_or_version = true;
} }
throw std::runtime_error("Zero positional arguments expected"); throw std::runtime_error("Zero positional arguments expected");