From 5ce83d014c7341087e6b533e1c8f8dc4a6f88792 Mon Sep 17 00:00:00 2001 From: Jarryd Beck Date: Thu, 8 Aug 2019 08:20:55 +1000 Subject: [PATCH] Fix duplicate default option Fixes #197. Don't parse default options twice when there is a short and long option. --- CHANGELOG.md | 7 +++++++ include/cxxopts.hpp | 13 +++++++++++-- test/options.cpp | 11 +++++++++-- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96319a7..fc032f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,13 @@ This is the changelog for `cxxopts`, a C++11 library for parsing command line options. The project adheres to semantic versioning. +## Next version + +### Changed + +* Only search for a C++ compiler in CMakeLists.txt. +* Fix duplicate default options when there is a short and long option. + ## 2.2 ### Changed diff --git a/include/cxxopts.hpp b/include/cxxopts.hpp index 543101c..6d230f0 100644 --- a/include/cxxopts.hpp +++ b/include/cxxopts.hpp @@ -1054,15 +1054,23 @@ namespace cxxopts parse_default(std::shared_ptr 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 const T& as() const @@ -1090,6 +1098,7 @@ namespace cxxopts std::shared_ptr m_value; size_t m_count = 0; + bool m_default = false; }; class KeyValue @@ -1859,7 +1868,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 25b5ea3..86ce776 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() - ->default_value("42")); + ("default", "Has implicit", cxxopts::value()->default_value("42")) + ("v,vector", "Default vector", cxxopts::value>() + ->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() == 42); + + auto& v = result["vector"].as>(); + REQUIRE(v.size() == 2); + CHECK(v[0] == 1); + CHECK(v[1] == 4); } SECTION("When values provided") {