From f3e65f69a9d644ddb13b79809110603456b803c1 Mon Sep 17 00:00:00 2001 From: Pranav Srinivas Kumar Date: Fri, 15 May 2020 19:06:00 -0500 Subject: [PATCH] Added --version as a special flag similar to --help * ArgumentParser takes a second argument - the program version (std::string) * Using --version or -v will print the program version and exit --- include/argparse/argparse.hpp | 15 ++++++++++++--- test/CMakeLists.txt | 1 + test/test_version.cpp | 12 ++++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) create mode 100644 test/test_version.cpp diff --git a/include/argparse/argparse.hpp b/include/argparse/argparse.hpp index d4c3e48..74f0f99 100644 --- a/include/argparse/argparse.hpp +++ b/include/argparse/argparse.hpp @@ -748,10 +748,13 @@ private: class ArgumentParser { public: - explicit ArgumentParser(std::string aProgramName = {}) - : mProgramName(std::move(aProgramName)) { + explicit ArgumentParser(std::string aProgramName = {}, std::string aVersion = "1.0") + : mProgramName(std::move(aProgramName)), mVersion(std::move(aVersion)) { add_argument("-h", "--help") - .help("show this help message and exit") + .help("shows help message and exits") + .nargs(0); + add_argument("-v", "--version") + .help("prints version information and exits") .nargs(0); } @@ -954,6 +957,11 @@ private: std::cout << *this; std::exit(0); } + // the second optional argument is --version + else if (tArgument == std::next(mOptionalArguments.begin(), 1)) { + std::cout << mVersion << "\n"; + std::exit(0); + } it = tArgument->consume(std::next(it), end, tIterator->first); } else if (const auto &tCompoundArgument = tCurrentArgument; @@ -1010,6 +1018,7 @@ private: } std::string mProgramName; + std::string mVersion; std::string mDescription; std::string mEpilog; std::list mPositionalArguments; diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 921297f..592fee1 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -38,6 +38,7 @@ file(GLOB ARGPARSE_TEST_SOURCES test_required_arguments.cpp test_scan.cpp test_value_semantics.cpp + test_version.cpp ) set_source_files_properties(main.cpp PROPERTIES diff --git a/test/test_version.cpp b/test/test_version.cpp new file mode 100644 index 0000000..103f96d --- /dev/null +++ b/test/test_version.cpp @@ -0,0 +1,12 @@ +#include +#include + +using doctest::test_suite; + +TEST_CASE("Users can print version and exit" * test_suite("version")) { + argparse::ArgumentParser program("cli-test", "1.9.0"); + program.add_argument("-d", "--dir") + .required(); + program.parse_args( { "test", "--version" }); + REQUIRE(program.get("--version") == "1.9.0"); +}