From f0d68de1343fc1b4412d8b0d1649b44f8a7f3e35 Mon Sep 17 00:00:00 2001 From: Sean Robinson Date: Thu, 22 Jul 2021 06:45:44 -0700 Subject: [PATCH] Confirm arguments are parsed before allowing ArgumentParser::get If the developer forgot to call ArgumentParser::parse_args<>, attempts to use ::get, ::present, etc., would raise "No value provided...". With this change, the error better describes what went wrong. Signed-off-by: Sean Robinson --- include/argparse/argparse.hpp | 6 ++++++ test/test_get.cpp | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/include/argparse/argparse.hpp b/include/argparse/argparse.hpp index 8829f31..cb427cd 100644 --- a/include/argparse/argparse.hpp +++ b/include/argparse/argparse.hpp @@ -911,12 +911,16 @@ public: } /* Getter for options with default values. + * @throws std::logic_error if parse_args() has not been previously called * @throws std::logic_error if there is no such option * @throws std::logic_error if the option has no value * @throws std::bad_any_cast if the option is not of type T */ template T get(std::string_view aArgumentName) const { + if (!mIsParsed) { + throw std::logic_error("Nothing parsed, no arguments are available."); + } return (*this)[aArgumentName].get(); } @@ -1076,6 +1080,7 @@ private: throw std::runtime_error("Unknown argument"); } } + mIsParsed = true; } /* @@ -1115,6 +1120,7 @@ private: std::string mVersion; std::string mDescription; std::string mEpilog; + bool mIsParsed = false; std::list mPositionalArguments; std::list mOptionalArguments; std::map> mArgumentMap; diff --git a/test/test_get.cpp b/test/test_get.cpp index 35d9464..db316ba 100644 --- a/test/test_get.cpp +++ b/test/test_get.cpp @@ -10,6 +10,14 @@ TEST_CASE("Getting a simple argument" * test_suite("ArgumentParser::get")) { REQUIRE(program.get("--stuff") == "./src"); } +TEST_CASE("Skipped call to parse_args" * test_suite("ArgumentParser::get")) { + argparse::ArgumentParser program("test"); + program.add_argument("stuff"); + REQUIRE_THROWS_WITH_AS(program.get("stuff"), + "Nothing parsed, no arguments are available.", + std::logic_error); +} + TEST_CASE("Missing argument" * test_suite("ArgumentParser::get")) { argparse::ArgumentParser program("test"); program.add_argument("-s", "--stuff");