Commit 848880d9312db24c643cc2d7b82ad072e23526e1

Authored by Jarryd Beck
1 parent 21591dc8

Fix arguments after -- without declared positional

Fixes #36. This fixes handling arguments passed after `--` when no
positional arguments have been declared, or when the positional
arguments have all been used up. The bug was that the extra arguments
were lost. Now they are retained in the modified argv.
include/cxxopts.hpp
... ... @@ -1251,7 +1251,16 @@ Options::parse(int& argc, char**& argv)
1251 1251 {
1252 1252 while (current < argc)
1253 1253 {
1254   - consume_positional(argv[current]);
  1254 + if (!consume_positional(argv[current])) {
  1255 + break;
  1256 + }
  1257 + ++current;
  1258 + }
  1259 +
  1260 + //adjust argv for any that couldn't be swallowed
  1261 + while (current != argc) {
  1262 + argv[nextKeep] = argv[current];
  1263 + ++nextKeep;
1255 1264 ++current;
1256 1265 }
1257 1266 }
... ...
test/options.cpp
... ... @@ -153,3 +153,25 @@ TEST_CASE(&quot;Some positional explicit&quot;, &quot;[positional]&quot;)
153 153 CHECK(positional[0] == "c");
154 154 CHECK(positional[1] == "d");
155 155 }
  156 +
  157 +TEST_CASE("No positional with extras", "[positional]")
  158 +{
  159 + cxxopts::Options options("posargmaster", "shows incorrect handling");
  160 + options.add_options()
  161 + ("dummy", "oh no", cxxopts::value<std::string>())
  162 + ;
  163 +
  164 + Argv av({"extras", "--", "a", "b", "c", "d"});
  165 +
  166 + char** argv = av.argv();
  167 + auto argc = av.argc();
  168 +
  169 + auto old_argv = argv;
  170 + auto old_argc = argc;
  171 +
  172 + options.parse(argc, argv);
  173 +
  174 + REQUIRE(argc == old_argc - 1);
  175 + CHECK(argv[0] == std::string("extras"));
  176 + CHECK(argv[1] == std::string("a"));
  177 +}
... ...