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

If given, show allowed choices in help message. #349

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
13 changes: 13 additions & 0 deletions include/argparse/argparse.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1186,6 +1186,19 @@ class Argument {
stream << " ";
}
stream << "[may be repeated]";
add_space = true;
}
if (argument.m_choices.has_value()) {
if (add_space) {
stream << " ";
}
const auto &choices = argument.m_choices.value();
std::string choices_as_csv =
std::accumulate(choices.begin(), choices.end(), std::string(),
[](const std::string &a, const std::string &b) {
return a + (a.empty() ? "" : ", ") + b;
});
stream << "[allowed: " << choices_as_csv << "]";
}
stream << "\n";
return stream;
Expand Down
13 changes: 13 additions & 0 deletions test/test_choices.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,16 @@ TEST_CASE("Parse multiple arguments that are not in fixed number of allowed "
"Invalid argument \"6\" - allowed options: {1, 2, 3, 4, 5}",
std::runtime_error);
}

TEST_CASE("Show allowed choices in help test") {
argparse::ArgumentParser program("test");
program.add_argument("--color").choices("red", "green", "blue");
program.add_argument("--index").choices(1, 2, 3);

auto help_output = program.help().str();

REQUIRE(help_output.find(std::string{"[allowed: red, green, blue]"}) !=
std::string::npos);
REQUIRE(help_output.find(std::string{"[allowed: 1, 2, 3]"}) !=
std::string::npos);
}