Support only short option

Fixes #47. Adds support for options that only have a short option.
This commit is contained in:
Jarryd Beck 2017-05-31 17:40:14 +10:00
parent 77b1b43a7c
commit 9d16b98edd
3 changed files with 56 additions and 5 deletions

View File

@ -851,7 +851,7 @@ namespace cxxopts
("--([[:alnum:]][-_[:alnum:]]+)(=(.*))?|-([[:alnum:]]+)"); ("--([[:alnum:]][-_[:alnum:]]+)(=(.*))?|-([[:alnum:]]+)");
std::basic_regex<char> option_specifier std::basic_regex<char> option_specifier
("(([[:alnum:]]),)?([[:alnum:]][-_[:alnum:]]+)"); ("(([[:alnum:]]),)?([[:alnum:]][-_[:alnum:]]*)?");
String String
format_option format_option
@ -985,8 +985,39 @@ OptionAdder::operator()
const auto& s = result[2]; const auto& s = result[2];
const auto& l = result[3]; const auto& l = result[3];
m_options.add_option(m_group, s.str(), l.str(), desc, value, if (!s.length() && !l.length())
std::move(arg_help)); {
throw invalid_option_format_error(opts);
} else if (l.length() == 1 && s.length())
{
throw invalid_option_format_error(opts);
}
auto option_names = []
(
const std::sub_match<const char*>& s,
const std::sub_match<const char*>& l
)
{
if (l.length() == 1)
{
return std::make_tuple(l.str(), s.str());
}
else
{
return std::make_tuple(s.str(), l.str());
}
}(s, l);
m_options.add_option
(
m_group,
std::get<0>(option_names),
std::get<1>(option_names),
desc,
value,
std::move(arg_help)
);
return *this; return *this;
} }

View File

@ -1,5 +1,5 @@
if (CXXOPTS_BUILD_TESTS) if (CXXOPTS_BUILD_TESTS)
add_executable(options_test options.cpp) add_executable(options_test main.cpp options.cpp)
target_link_libraries(options_test cxxopts) target_link_libraries(options_test cxxopts)
if (MSVC) if (MSVC)

View File

@ -1,4 +1,3 @@
#define CATCH_CONFIG_MAIN
#include "catch.hpp" #include "catch.hpp"
#include <initializer_list> #include <initializer_list>
@ -80,6 +79,27 @@ TEST_CASE("Basic options", "[options]")
CHECK(options.count("6") == 1); CHECK(options.count("6") == 1);
} }
TEST_CASE("Short options", "[options]")
{
cxxopts::Options options("test_short", " - test short options");
options.add_options()
("a", "a short option", cxxopts::value<std::string>());
Argv argv({"test_short", "-a", "value"});
auto actual_argv = argv.argv();
auto argc = argv.argc();
options.parse(argc, actual_argv);
CHECK(options.count("a") == 1);
CHECK(options["a"].as<std::string>() == "value");
REQUIRE_THROWS_AS(options.add_options()("", "nothing option"),
cxxopts::invalid_option_format_error);
}
TEST_CASE("No positional", "[positional]") TEST_CASE("No positional", "[positional]")
{ {
cxxopts::Options options("test_no_positional", cxxopts::Options options("test_no_positional",