From 6f901f2c5ea63c5073bd3469960b51c5a2c68fe5 Mon Sep 17 00:00:00 2001 From: "Taylor C. Richberger" Date: Wed, 4 May 2016 15:36:00 -0600 Subject: improve validation errors, add help exception --- args.hxx | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) (limited to 'args.hxx') diff --git a/args.hxx b/args.hxx index 6434d07..c368f28 100644 --- a/args.hxx +++ b/args.hxx @@ -4,7 +4,6 @@ #include #include -#include #include #include #include @@ -19,6 +18,27 @@ namespace args virtual ~ParseError() {}; }; + class ValidationError : public std::runtime_error + { + public: + ValidationError(const char *problem) : std::runtime_error(problem) {} + virtual ~ValidationError() {}; + }; + + class Help : public std::exception + { + private: + const std::string flag; + public: + Help(const std::string &flag) : flag(flag) {} + virtual ~Help() {}; + + virtual const char *what() const noexcept override + { + return flag.c_str(); + } + }; + // A class of "matchers", specifying short and long options that can possibly be matched class Matcher { @@ -473,7 +493,7 @@ namespace args { std::ostringstream problem; problem << "Group validation failed somewhere!"; - throw ParseError(problem.str().c_str()); + throw ValidationError(problem.str().c_str()); } } @@ -524,6 +544,34 @@ namespace args }; + // Help flag class + class HelpFlag : public Flag + { + public: + HelpFlag(Group &group, const std::string &name, const std::string &help, const Matcher &matcher): Flag(group, name, help, matcher) {} + HelpFlag(Group &group, const std::string &name, const std::string &help, Matcher &&matcher): Flag(group, name, help, std::move(matcher)) {} + + virtual ~HelpFlag() {} + + virtual FlagBase *Match(const std::string &arg) override + { + if (FlagBase::Match(arg)) + { + throw Help(arg); + } + return nullptr; + } + + virtual FlagBase *Match(const char arg) override + { + if (FlagBase::Match(arg)) + { + throw Help(std::string(1, arg)); + } + return nullptr; + } + }; + // Count matches class Counter : public FlagBase { -- cgit v1.2.1