Skip to content

Commit

Permalink
Run Argumnet::action functor for zero-parameter arguments
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
skrobinson committed Oct 27, 2021
1 parent 748bc95 commit 2b05334
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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!
Expand Down
1 change: 1 addition & 0 deletions include/argparse/argparse.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,7 @@ class Argument {
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()) {
Expand Down
24 changes: 24 additions & 0 deletions test/test_actions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
}

0 comments on commit 2b05334

Please sign in to comment.