Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent an argument with an already registered name to be added #337

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
Loading