catchorg / Clara

A simple to use, composable, command line parser for C++ 11 and beyond
Boost Software License 1.0
649 stars 67 forks source link

Single positional argument appears not to be parsed correctly #25

Closed Mike-Crowe-BrightSign closed 6 years ago

Mike-Crowe-BrightSign commented 7 years ago

I'm having trouble getting Clara to recognise a single positional argument.

Adding this to ClaraTests.cpp:

TEST_CASE("Mike") {
    bool flag;
    std::string filename;

    auto command_line_parser
    = Opt(flag)["-f"]("Test flag")
    + Arg(filename, "filename")("Test data filename");

    SECTION("preceding flag")
    {
    auto result = command_line_parser.parse({ "-f", "the-filename" });
    REQUIRE(result);
    REQUIRE(filename == "the-filename");
    }

    SECTION("following flag")
    {
    auto result = command_line_parser.parse({ "the-filename", "-f" });
    REQUIRE(result);
    REQUIRE(filename == "the-filename");
    }

    SECTION("no flag")
    {
    auto result = command_line_parser.parse({ "the-filename" });
    REQUIRE(result);
    REQUIRE(filename == "the-filename");
    }
}

Fails with:

-------------------------------------------------------------------------------
Mike
  following flag
-------------------------------------------------------------------------------
/home/mac/git/Clara/src/ClaraTests.cpp:331
...............................................................................

/home/mac/git/Clara/src/ClaraTests.cpp:335: FAILED:
  REQUIRE( filename == "the-filename" )
with expansion:
  "" == "the-filename"

-------------------------------------------------------------------------------
Mike
  no flag
-------------------------------------------------------------------------------
/home/mac/git/Clara/src/ClaraTests.cpp:338
...............................................................................

/home/mac/git/Clara/src/ClaraTests.cpp:342: FAILED:
  REQUIRE( filename == "the-filename" )
with expansion:
  "" == "the-filename"

Compared the the other tests, I can't see what I'm doing wrong. :(

philsquared commented 6 years ago

Sorry it's taken so long to get to look at this. The issue here is that the first arg position (to parse({ ... })) should be the exe name. Because you're missing it, in the first case the -f is being treated as the exe name (and you're not checking that the flag was set). In the other cases the-filename takes the position of the filename, and hence is not setting the variable.

So Clara is working as intended. In any case I've added something similar (but fixed) to your tests to the test suite:

https://github.com/catchorg/Clara/commit/3ba504c3020b2728ac6c47021892143ab75d9c9e