From 848880d9312db24c643cc2d7b82ad072e23526e1 Mon Sep 17 00:00:00 2001 From: Jarryd Beck Date: Sat, 6 May 2017 14:16:00 +1000 Subject: [PATCH] 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 | 11 ++++++++++- test/options.cpp | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/include/cxxopts.hpp b/include/cxxopts.hpp index 633a419..3036504 100644 --- a/include/cxxopts.hpp +++ b/include/cxxopts.hpp @@ -1251,7 +1251,16 @@ Options::parse(int& argc, char**& argv) { while (current < argc) { - consume_positional(argv[current]); + if (!consume_positional(argv[current])) { + break; + } + ++current; + } + + //adjust argv for any that couldn't be swallowed + while (current != argc) { + argv[nextKeep] = argv[current]; + ++nextKeep; ++current; } } diff --git a/test/options.cpp b/test/options.cpp index 76fad97..6aea0da 100644 --- a/test/options.cpp +++ b/test/options.cpp @@ -153,3 +153,25 @@ TEST_CASE("Some positional explicit", "[positional]") CHECK(positional[0] == "c"); CHECK(positional[1] == "d"); } + +TEST_CASE("No positional with extras", "[positional]") +{ + cxxopts::Options options("posargmaster", "shows incorrect handling"); + options.add_options() + ("dummy", "oh no", cxxopts::value()) + ; + + Argv av({"extras", "--", "a", "b", "c", "d"}); + + char** argv = av.argv(); + auto argc = av.argc(); + + auto old_argv = argv; + auto old_argc = argc; + + options.parse(argc, argv); + + REQUIRE(argc == old_argc - 1); + CHECK(argv[0] == std::string("extras")); + CHECK(argv[1] == std::string("a")); +}