From 8ba1c8360996f5ff1203362b701804f10e7890ad Mon Sep 17 00:00:00 2001 From: q66 Date: Mon, 15 May 2017 21:10:41 +0200 Subject: [PATCH] predefined funcs for common argparse actions --- ostd/argparse.hh | 73 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/ostd/argparse.hh b/ostd/argparse.hh index 5fc3aec..99e727b 100644 --- a/ostd/argparse.hh +++ b/ostd/argparse.hh @@ -116,7 +116,7 @@ struct arg_optional: arg_argument { arg_optional &action(F func) { p_action = [func = std::move(func)]( iterator_range vals - ) -> std::any { + ) mutable -> std::any { return func(vals); }; return *this; @@ -277,6 +277,21 @@ struct arg_parser { return static_cast(*p_opts.emplace_back(p)); } + template + arg_optional &add_help(OutputRange out, string_range msg) { + auto &opt = add_optional('h', "help", arg_value::NONE); + opt.help(msg); + opt.action([this, out = std::move(out)](auto) mutable { + this->print_help(out); + return true; + }); + return opt; + } + + arg_optional &add_help(string_range msg) { + return add_help(cout.iter(), msg); + } + template OutputRange &&print_help(OutputRange &&range) { print_usage_impl(range); @@ -298,6 +313,11 @@ struct arg_parser { return std::any_cast(arg.p_value); } + bool used(string_range name) { + auto &arg = find_arg(name); + return arg.p_value.has_value(); + } + private: template void print_usage_impl(OR &out) { @@ -415,6 +435,7 @@ private: desc.p_lname ).get()}; } + desc.set_values(nullptr); return; } if (!has_val) { @@ -425,6 +446,7 @@ private: desc.p_lname ).get()}; } + desc.set_values(nullptr); return; } string_range tval = args.front(); @@ -438,6 +460,8 @@ private: if (arg_val) { args.pop_front(); } + } else { + desc.set_values(nullptr); } } @@ -461,6 +485,7 @@ private: desc.p_sname ).get()}; } + desc.set_values(nullptr); return; } if (!has_val) { @@ -471,6 +496,7 @@ private: desc.p_sname ).get()}; } + desc.set_values(nullptr); return; } string_range tval = args.front(); @@ -484,6 +510,8 @@ private: if (arg_val) { args.pop_front(); } + } else { + desc.set_values(nullptr); } } @@ -514,6 +542,49 @@ private: std::string p_progname; }; +template +auto arg_print_help(OutputRange o, arg_parser &p) { + struct cb { + cb(OutputRange orange, arg_parser &par): + p(par), out(orange) + {} + + bool operator()(iterator_range) { + p.print_help(out); + return true; + } + private: + arg_parser &p; + OutputRange out; + }; + return cb{o, p}; +}; + +auto arg_print_help(arg_parser &p) { + return arg_print_help(cout.iter(), p); +} + +template +auto arg_store_const(T &&val) { + struct cb { + cb(T &&cval): value(std::forward(cval)) {} + std::decay_t operator()(iterator_range) { + return std::move(value); + } + private: + std::decay_t value; + }; + return cb{std::forward(val)}; +} + +auto arg_store_true() { + return arg_store_const(true); +} + +auto arg_store_false() { + return arg_store_const(false); +} + /** @} */ } /* namespace ostd */