Skip to content

Commit

Permalink
Support only short option
Browse files Browse the repository at this point in the history
Fixes jarro2783#47. Adds support for options that only have a short option.
  • Loading branch information
jarro2783 committed May 31, 2017
1 parent 77b1b43 commit 9d16b98
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 5 deletions.
37 changes: 34 additions & 3 deletions include/cxxopts.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -851,7 +851,7 @@ namespace cxxopts
("--([[:alnum:]][-_[:alnum:]]+)(=(.*))?|-([[:alnum:]]+)");

std::basic_regex<char> option_specifier
("(([[:alnum:]]),)?([[:alnum:]][-_[:alnum:]]+)");
("(([[:alnum:]]),)?([[:alnum:]][-_[:alnum:]]*)?");

String
format_option
Expand Down Expand Up @@ -985,8 +985,39 @@ OptionAdder::operator()
const auto& s = result[2];
const auto& l = result[3];

m_options.add_option(m_group, s.str(), l.str(), desc, value,
std::move(arg_help));
if (!s.length() && !l.length())
{
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;
}
Expand Down
2 changes: 1 addition & 1 deletion test/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
if (CXXOPTS_BUILD_TESTS)
add_executable(options_test options.cpp)
add_executable(options_test main.cpp options.cpp)
target_link_libraries(options_test cxxopts)

if (MSVC)
Expand Down
22 changes: 21 additions & 1 deletion test/options.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include <initializer_list>
Expand Down Expand Up @@ -80,6 +79,27 @@ TEST_CASE("Basic options", "[options]")
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]")
{
cxxopts::Options options("test_no_positional",
Expand Down

0 comments on commit 9d16b98

Please sign in to comment.