diff options
-rw-r--r-- | args.hxx | 36 | ||||
-rw-r--r-- | test.cxx | 22 |
2 files changed, 58 insertions, 0 deletions
@@ -2577,6 +2577,42 @@ namespace args } }; + /** A flag class that calls a function when it's matched + */ + class ActionFlag : public FlagBase + { + private: + std::function<void(const std::vector<std::string> &)> action; + Nargs nargs; + + public: + ActionFlag(Group &group_, const std::string &name_, const std::string &help_, Matcher &&matcher_, Nargs nargs_, std::function<void(const std::vector<std::string> &)> action_, Options options_ = {}): + FlagBase(name_, help_, std::move(matcher_), options_), action(std::move(action_)), nargs(nargs_) + { + group_.Add(*this); + } + + ActionFlag(Group &group_, const std::string &name_, const std::string &help_, Matcher &&matcher_, std::function<void(const std::string &)> action_, Options options_ = {}): + FlagBase(name_, help_, std::move(matcher_), options_), nargs(1) + { + group_.Add(*this); + action = [action_](const std::vector<std::string> &a) { return action_(a.at(0)); }; + } + + ActionFlag(Group &group_, const std::string &name_, const std::string &help_, Matcher &&matcher_, std::function<void()> action_, Options options_ = {}): + FlagBase(name_, help_, std::move(matcher_), options_), nargs(0) + { + group_.Add(*this); + action = [action_](const std::vector<std::string> &) { return action_(); }; + } + + virtual Nargs NumberOfArguments() const noexcept override + { return nargs; } + + virtual void ParseValue(const std::vector<std::string> &value) override + { action(value); } + }; + /** A default Reader class for argument classes * * Simply uses a std::istringstream to read into the destination type, and @@ -1066,6 +1066,28 @@ TEST_CASE("HelpParams work as expected", "[args]") } +TEST_CASE("ActionFlag works as expected", "[args]") +{ + args::ArgumentParser p("parser"); + std::string s; + + args::ActionFlag action0(p, "name", "description", {'x'}, [&]() { s = "flag"; }); + args::ActionFlag action1(p, "name", "description", {'y'}, [&](const std::string &arg) { s = arg; }); + args::ActionFlag actionN(p, "name", "description", {'z'}, 2, [&](const std::vector<std::string> &arg) { s = arg[0] + arg[1]; }); + args::ActionFlag actionThrow(p, "name", "description", {'v'}, [&]() { throw std::runtime_error(""); }); + + p.ParseArgs(std::vector<std::string>{"-x"}); + REQUIRE(s == "flag"); + + p.ParseArgs(std::vector<std::string>{"-y", "a"}); + REQUIRE(s == "a"); + + p.ParseArgs(std::vector<std::string>{"-z", "a", "b"}); + REQUIRE(s == "ab"); + + REQUIRE_THROWS_AS(p.ParseArgs(std::vector<std::string>{"-v"}), std::runtime_error); +} + #undef ARGS_HXX #define ARGS_TESTNAMESPACE #define ARGS_NOEXCEPT |