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
This commit is contained in:
Pranav Srinivas Kumar 2020-05-15 19:06:00 -05:00
parent f1ccf8e1ee
commit f3e65f69a9
3 changed files with 25 additions and 3 deletions

View File

@ -748,10 +748,13 @@ private:
class ArgumentParser { class ArgumentParser {
public: public:
explicit ArgumentParser(std::string aProgramName = {}) explicit ArgumentParser(std::string aProgramName = {}, std::string aVersion = "1.0")
: mProgramName(std::move(aProgramName)) { : mProgramName(std::move(aProgramName)), mVersion(std::move(aVersion)) {
add_argument("-h", "--help") 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); .nargs(0);
} }
@ -954,6 +957,11 @@ private:
std::cout << *this; std::cout << *this;
std::exit(0); 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); it = tArgument->consume(std::next(it), end, tIterator->first);
} else if (const auto &tCompoundArgument = tCurrentArgument; } else if (const auto &tCompoundArgument = tCurrentArgument;
@ -1010,6 +1018,7 @@ private:
} }
std::string mProgramName; std::string mProgramName;
std::string mVersion;
std::string mDescription; std::string mDescription;
std::string mEpilog; std::string mEpilog;
std::list<Argument> mPositionalArguments; std::list<Argument> mPositionalArguments;

View File

@ -38,6 +38,7 @@ file(GLOB ARGPARSE_TEST_SOURCES
test_required_arguments.cpp test_required_arguments.cpp
test_scan.cpp test_scan.cpp
test_value_semantics.cpp test_value_semantics.cpp
test_version.cpp
) )
set_source_files_properties(main.cpp set_source_files_properties(main.cpp
PROPERTIES PROPERTIES

12
test/test_version.cpp Normal file
View File

@ -0,0 +1,12 @@
#include <doctest.hpp>
#include <argparse/argparse.hpp>
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");
}