mirror of
https://github.com/KeqingMoe/argparse.git
synced 2025-07-04 07:04:39 +00:00
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:
parent
f1ccf8e1ee
commit
f3e65f69a9
@ -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<Argument> mPositionalArguments;
|
||||
|
@ -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
|
||||
|
12
test/test_version.cpp
Normal file
12
test/test_version.cpp
Normal 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");
|
||||
}
|
Loading…
Reference in New Issue
Block a user