From 84b7b46ce51711cd93f82ca5cb53d5b051e6ce9b Mon Sep 17 00:00:00 2001 From: Even Rouault Date: Mon, 27 May 2024 19:21:23 +0200 Subject: [PATCH] Add argument name after 'Too few arguments' error If a non-positional argument doesn't get the number of required values, a generic "Too few arguments" error is generated, without its name, when it is not the last argument (but if it is the last argument, we get its name) --- include/argparse/argparse.hpp | 3 ++- test/test_parse_args.cpp | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/include/argparse/argparse.hpp b/include/argparse/argparse.hpp index 1269863f..72dd7883 100644 --- a/include/argparse/argparse.hpp +++ b/include/argparse/argparse.hpp @@ -997,7 +997,8 @@ class Argument { std::bind(is_optional, std::placeholders::_1, m_prefix_chars)); dist = static_cast(std::distance(start, end)); if (dist < num_args_min) { - throw std::runtime_error("Too few arguments"); + throw std::runtime_error("Too few arguments for '" + + std::string(m_used_name) + "'."); } } diff --git a/test/test_parse_args.cpp b/test/test_parse_args.cpp index bb3af2a0..6eb97bd6 100644 --- a/test/test_parse_args.cpp +++ b/test/test_parse_args.cpp @@ -17,6 +17,15 @@ TEST_CASE("Missing argument" * test_suite("parse_args")) { std::runtime_error); } +TEST_CASE("Missing argument, not last" * test_suite("parse_args")) { + argparse::ArgumentParser program("test"); + program.add_argument("--config").nargs(1); + program.add_argument("--foo"); + REQUIRE_THROWS_WITH_AS(program.parse_args({"test", "--config", "--foo"}), + "Too few arguments for '--config'.", + std::runtime_error); +} + TEST_CASE("Parse a string argument with value" * test_suite("parse_args")) { argparse::ArgumentParser program("test"); program.add_argument("--config");