From 6b6af4f56133a920b1b79bb93276c67c5b3241ec Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Bayle Date: Tue, 18 Jun 2019 09:49:15 +0200 Subject: [PATCH] Add a method to remove the implicit value of an option (#178) --- include/cxxopts.hpp | 10 ++++++++++ test/options.cpp | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 0 deletions(-) diff --git a/include/cxxopts.hpp b/include/cxxopts.hpp index a132daf..01e01ea 100644 --- a/include/cxxopts.hpp +++ b/include/cxxopts.hpp @@ -314,6 +314,9 @@ namespace cxxopts virtual std::shared_ptr implicit_value(const std::string& value) = 0; + virtual std::shared_ptr + no_implicit_value() = 0; + virtual bool is_boolean() const = 0; }; @@ -834,6 +837,13 @@ namespace cxxopts return shared_from_this(); } + std::shared_ptr + no_implicit_value() + { + m_implicit = false; + return shared_from_this(); + } + std::string get_default_value() const { diff --git a/test/options.cpp b/test/options.cpp index 79715ee..25b5ea3 100644 --- a/test/options.cpp +++ b/test/options.cpp @@ -250,6 +250,67 @@ TEST_CASE("Empty with implicit value", "[implicit]") REQUIRE(result["implicit"].as() == ""); } +TEST_CASE("Boolean without implicit value", "[implicit]") +{ + cxxopts::Options options("no_implicit", "bool without an implicit value"); + options.add_options() + ("bool", "Boolean without implicit", cxxopts::value() + ->no_implicit_value()); + + SECTION("When no value provided") { + Argv av({"no_implicit", "--bool"}); + + char** argv = av.argv(); + auto argc = av.argc(); + + CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::missing_argument_exception&); + } + + SECTION("With equal-separated true") { + Argv av({"no_implicit", "--bool=true"}); + + char** argv = av.argv(); + auto argc = av.argc(); + + auto result = options.parse(argc, argv); + CHECK(result.count("bool") == 1); + CHECK(result["bool"].as() == true); + } + + SECTION("With equal-separated false") { + Argv av({"no_implicit", "--bool=false"}); + + char** argv = av.argv(); + auto argc = av.argc(); + + auto result = options.parse(argc, argv); + CHECK(result.count("bool") == 1); + CHECK(result["bool"].as() == false); + } + + SECTION("With space-separated true") { + Argv av({"no_implicit", "--bool", "true"}); + + char** argv = av.argv(); + auto argc = av.argc(); + + auto result = options.parse(argc, argv); + CHECK(result.count("bool") == 1); + CHECK(result["bool"].as() == true); + } + + SECTION("With space-separated false") { + Argv av({"no_implicit", "--bool", "false"}); + + char** argv = av.argv(); + auto argc = av.argc(); + + auto result = options.parse(argc, argv); + CHECK(result.count("bool") == 1); + CHECK(result["bool"].as() == false); + } +} + TEST_CASE("Default values", "[default]") { cxxopts::Options options("defaults", "has defaults"); -- libgit2 0.21.4