Added support for parsing optional arguments _while_ parsing some other variable length positional argument

This commit is contained in:
Pranav Srinivas Kumar 2019-03-30 21:50:35 -04:00
parent a385d78919
commit 41009046f2
2 changed files with 23 additions and 1 deletions

View File

@ -216,8 +216,13 @@ class ArgumentParser {
// This is a positional argument. // This is a positional argument.
// Parse and save into mPositionalArguments vector // Parse and save into mPositionalArguments vector
auto tArgument = mPositionalArguments[mNextPositionalArgument]; auto tArgument = mPositionalArguments[mNextPositionalArgument];
auto tCount = tArgument->mNumArgs; auto tCount = tArgument->mNumArgs - tArgument->mRawValues.size();
while (tCount > 0) { while (tCount > 0) {
std::map<std::string, std::shared_ptr<Argument>>::iterator tIterator = mArgumentMap.find(argv[i]);
if (tIterator != mArgumentMap.end()) {
i = i - 1;
break;
}
if (i < argc) { if (i < argc) {
tArgument->mRawValues.push_back(argv[i]); tArgument->mRawValues.push_back(argv[i]);
if (tArgument->mAction != nullptr) if (tArgument->mAction != nullptr)

View File

@ -42,4 +42,21 @@ TEST_CASE("Parse positional arguments with optional arguments", "[parse_args]")
REQUIRE(outputs.size() == 2); REQUIRE(outputs.size() == 2);
REQUIRE(outputs[0] == "thrust_profile.csv"); REQUIRE(outputs[0] == "thrust_profile.csv");
REQUIRE(outputs[1] == "output.mesh"); REQUIRE(outputs[1] == "output.mesh");
}
TEST_CASE("Parse positional arguments with optional arguments in the middle", "[parse_args]") {
argparse::ArgumentParser program("test");
program.add_argument("input");
program.add_argument("output").nargs(2);
program.add_argument("--num_iterations")
.action([](const std::string& value) { return std::stoi(value); });
program.parse_args({ "test", "rocket.mesh", "thrust_profile.csv", "--num_iterations", "15", "output.mesh" });
auto arguments = program.get_arguments();
REQUIRE(arguments.size() == 3);
REQUIRE(program.get<int>("--num_iterations") == 15);
REQUIRE(program.get("input") == "rocket.mesh");
auto outputs = program.get<std::vector<std::string>>("output");
REQUIRE(outputs.size() == 2);
REQUIRE(outputs[0] == "thrust_profile.csv");
REQUIRE(outputs[1] == "output.mesh");
} }