From 131873ca0802d16fbac5918cf8dd99a3b08e92ee Mon Sep 17 00:00:00 2001 From: Veikko Immonen Date: Thu, 2 May 2024 10:06:50 +0300 Subject: [PATCH] If given, show allowed choices in help message. --- include/argparse/argparse.hpp | 13 +++++++++++++ test/test_choices.cpp | 13 +++++++++++++ 2 files changed, 26 insertions(+) diff --git a/include/argparse/argparse.hpp b/include/argparse/argparse.hpp index 118e2145..00719609 100644 --- a/include/argparse/argparse.hpp +++ b/include/argparse/argparse.hpp @@ -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; diff --git a/test/test_choices.cpp b/test/test_choices.cpp index 4fc4383a..78377957 100644 --- a/test/test_choices.cpp +++ b/test/test_choices.cpp @@ -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); +}