From b5283241076013b325a8cf881c19829ac1cbbdb5 Mon Sep 17 00:00:00 2001 From: Jarryd Beck Date: Wed, 7 Nov 2018 18:50:43 +1100 Subject: [PATCH] Fix option matching --- CHANGELOG.md | 1 + include/cxxopts.hpp | 14 ++++++++++++++ test/options.cpp | 20 ++++++++++++++++++-- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13bec43..fb92e62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ options. The project adheres to semantic versioning. * Fix a warning about possible loss of data. * Fix version numbering in CMakeLists.txt * Remove unused declaration of the undefined `ParseResult::get_option`. +* Throw on invalid option syntax when beginning with a `-`. ## 2.1.1 diff --git a/include/cxxopts.hpp b/include/cxxopts.hpp index e4bb8c3..3ed065f 100644 --- a/include/cxxopts.hpp +++ b/include/cxxopts.hpp @@ -368,6 +368,15 @@ namespace cxxopts } }; + class option_syntax_exception : public OptionParseException { + public: + option_syntax_exception(const std::string& text) + : OptionParseException(u8"Argument " + LQUOTE + text + RQUOTE + + u8" starts with a - but has incorrect syntax") + { + } + }; + class option_not_exists_exception : public OptionParseException { public: @@ -1701,6 +1710,11 @@ ParseResult::parse(int& argc, char**& argv) { //not a flag + // but if it starts with a `-`, then it's an error + if (argv[current][0] == '-') { + throw option_syntax_exception(argv[current]); + } + //if true is returned here then it was consumed, otherwise it is //ignored if (consume_positional(argv[current])) diff --git a/test/options.cpp b/test/options.cpp index a204079..1f37172 100644 --- a/test/options.cpp +++ b/test/options.cpp @@ -111,7 +111,7 @@ TEST_CASE("Short options", "[options]") CHECK(result.count("a") == 1); CHECK(result["a"].as() == "value"); - REQUIRE_THROWS_AS(options.add_options()("", "nothing option"), + REQUIRE_THROWS_AS(options.add_options()("", "nothing option"), cxxopts::invalid_option_format_error); } @@ -513,7 +513,7 @@ TEST_CASE("Unrecognised options", "[options]") { "--long", "-su", "--another_unknown", - }); + }); char** argv = av.argv(); auto argc = av.argc(); @@ -529,3 +529,19 @@ TEST_CASE("Unrecognised options", "[options]") { CHECK_THAT(argv[1], Catch::Equals("--unknown")); } } + +TEST_CASE("Invalid option syntax", "[options]") { + cxxopts::Options options("invalid_syntax", " - test invalid syntax"); + + Argv av({ + "invalid_syntax", + "--a", + }); + + char** argv = av.argv(); + auto argc = av.argc(); + + SECTION("Default behaviour") { + CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::option_syntax_exception); + } +} -- libgit2 0.21.4