Run Argumnet::action functor for zero-parameter arguments

Previously, only arguments with one or more parameters would run actions.
But, at times it can be useful to run an action when an argument does not
expect any parameters.

Closes #104

Signed-off-by: Sean Robinson <sean.robinson@scottsdalecc.edu>
This commit is contained in:
Sean Robinson 2021-10-26 12:58:24 -07:00
parent 748bc95cf5
commit 2b05334a3c
3 changed files with 43 additions and 0 deletions

View File

@ -200,6 +200,24 @@ auto colors = program.get<std::vector<std::string>>("--color"); // {"red", "gre
Notice that ```.default_value``` is given an explicit template parameter to match the type you want to ```.get```.
#### Repeating an argument to increase a value
A common pattern is to repeat an argument to indicate a greater value.
```cpp
int verbosity = 0;
program.add_argument("-V", "--verbose")
.action([&](const auto &) { ++verbosity; })
.append()
.default_value(false)
.implicit_value(true)
.nargs(0);
program.parse_args(argc, argv); // Example: ./main -VVVV
std::cout << "verbose level: " << verbosity << std::endl; // verbose level: 4
```
### Negative Numbers
Optional arguments start with ```-```. Can ```argparse``` handle negative numbers? The answer is yes!

View File

@ -442,6 +442,7 @@ public:
mUsedName = usedName;
if (mNumArgs == 0) {
mValues.emplace_back(mImplicitValue);
std::visit([](auto &aAction) { aAction({}); }, mAction);
return start;
} else if (mNumArgs <= std::distance(start, end)) {
if (auto expected = maybe_nargs()) {

View File

@ -133,3 +133,27 @@ TEST_CASE("Users can use actions on remaining arguments" *
program.parse_args({"sum", "42", "100", "-3", "-20"});
REQUIRE(result == 119);
}
TEST_CASE("Users can run actions on parameterless optional arguments" *
test_suite("actions")) {
argparse::ArgumentParser program("test");
GIVEN("a flag argument with a counting action") {
int count = 0;
program.add_argument("-V", "--verbose")
.action([&](const auto &) { ++count; })
.append()
.default_value(false)
.implicit_value(true)
.nargs(0);
WHEN("the flag is repeated") {
program.parse_args({"test", "-VVVV"});
THEN("the count increments once per use") {
REQUIRE(program.get<bool>("-V"));
REQUIRE(count == 4);
}
}
}
}