diff options
author | Jarryd Beck <jarro.2783@gmail.com> | 2019-08-08 01:20:55 +0300 |
---|---|---|
committer | Jarryd Beck <jarro.2783@gmail.com> | 2019-08-08 01:21:52 +0300 |
commit | fce82fb0350c5c334c9593800dd55a6c2c797f9e (patch) | |
tree | e3fd6c9612db8c4a336b687085bdeec889c02c17 | |
parent | 6e31c227e2fd0677236e1fdf5d6306d9cef256fa (diff) |
Fix duplicate default option
Fixes #197. Don't parse default options twice when there is a short and
long option.
-rw-r--r-- | CHANGELOG.md | 1 | ||||
-rw-r--r-- | include/cxxopts.hpp | 13 | ||||
-rw-r--r-- | test/options.cpp | 11 |
3 files changed, 21 insertions, 4 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 94be76f..b030a15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ options. The project adheres to semantic versioning. * Only search for a C++ compiler in CMakeLists.txt. * Allow for exceptions to be disabled. +* Fix duplicate default options when there is a short and long option. ## 2.2 diff --git a/include/cxxopts.hpp b/include/cxxopts.hpp index 8ff3946..0e1aa40 100644 --- a/include/cxxopts.hpp +++ b/include/cxxopts.hpp @@ -1086,15 +1086,23 @@ namespace cxxopts parse_default(std::shared_ptr<const OptionDetails> details) { ensure_value(details); + m_default = true; m_value->parse(); } size_t - count() const + count() const noexcept { return m_count; } + // TODO: maybe default options should count towards the number of arguments + bool + has_default() const noexcept + { + return m_default; + } + template <typename T> const T& as() const @@ -1126,6 +1134,7 @@ namespace cxxopts std::shared_ptr<Value> m_value; size_t m_count = 0; + bool m_default = false; }; class KeyValue @@ -1989,7 +1998,7 @@ ParseResult::parse(int& argc, char**& argv) auto& store = m_results[detail]; - if(!store.count() && value.has_default()){ + if(value.has_default() && !store.count() && !store.has_default()){ parse_default(detail); } } diff --git a/test/options.cpp b/test/options.cpp index 8c3f23d..d110e01 100644 --- a/test/options.cpp +++ b/test/options.cpp @@ -315,8 +315,10 @@ TEST_CASE("Default values", "[default]") { cxxopts::Options options("defaults", "has defaults"); options.add_options() - ("default", "Has implicit", cxxopts::value<int>() - ->default_value("42")); + ("default", "Has implicit", cxxopts::value<int>()->default_value("42")) + ("v,vector", "Default vector", cxxopts::value<std::vector<int>>() + ->default_value("1,4")) + ; SECTION("Sets defaults") { Argv av({"implicit"}); @@ -327,6 +329,11 @@ TEST_CASE("Default values", "[default]") auto result = options.parse(argc, argv); CHECK(result.count("default") == 0); CHECK(result["default"].as<int>() == 42); + + auto& v = result["vector"].as<std::vector<int>>(); + REQUIRE(v.size() == 2); + CHECK(v[0] == 1); + CHECK(v[1] == 4); } SECTION("When values provided") { |