Skip to content

Commit

Permalink
Prevent an argument with an already registered name to be added
Browse files Browse the repository at this point in the history
except if it is -h/--help/-v/--version and they are default arguments.

For very complex programs with lots of options, this can help detecting
accidental redefinitions of already used argument names.
  • Loading branch information
rouault committed Mar 16, 2024
1 parent cebee4b commit 14a7fe9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
10 changes: 10 additions & 0 deletions include/argparse/argparse.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1545,6 +1545,7 @@ class ArgumentParser {
std::ostream &os = std::cout)
: m_program_name(std::move(program_name)), m_version(std::move(version)),
m_exit_on_default_arguments(exit_on_default_arguments),
m_default_arguments(add_args),
m_parser_path(m_program_name) {
if ((add_args & default_arguments::help) == default_arguments::help) {
add_argument("-h", "--help")
Expand Down Expand Up @@ -2431,6 +2432,14 @@ class ArgumentParser {

void index_argument(argument_it it) {
for (const auto &name : std::as_const(it->m_names)) {
if (!((name == "-h" || name == "--help") &&
(m_default_arguments & default_arguments::help) == default_arguments::help) &&
!((name == "-v" || name == "--version") &&
(m_default_arguments & default_arguments::version) == default_arguments::version) &&
m_argument_map.find(name) != m_argument_map.end()) {
throw std::runtime_error("Argument with name " + name +
" already registered");
}
m_argument_map.insert_or_assign(name, it);
}
}
Expand All @@ -2440,6 +2449,7 @@ class ArgumentParser {
std::string m_description;
std::string m_epilog;
bool m_exit_on_default_arguments = true;
default_arguments m_default_arguments;
std::string m_prefix_chars{"-"};
std::string m_assign_chars{"="};
bool m_is_parsed = false;
Expand Down
14 changes: 13 additions & 1 deletion test/test_error_reporting.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,16 @@ TEST_CASE("Detect unknown subcommand" * test_suite("error_reporting")) {
"Failed to parse 'logic', did you mean 'log'",
std::runtime_error);
}
}
}

TEST_CASE("Duplicate argument" * test_suite("error_reporting")) {
argparse::ArgumentParser program("program");
program.add_argument("-a");
program.add_argument("-h"); // redefining default arguments is allowed
program.add_argument("--help"); // redefining default arguments is allowed
program.add_argument("-v"); // redefining default arguments is allowed
program.add_argument("--version"); // redefining default arguments is allowed
REQUIRE_THROWS_WITH_AS(program.add_argument("-a"),
"Argument with name -a already registered",
std::runtime_error);
}

0 comments on commit 14a7fe9

Please sign in to comment.