35#pragma push_macro("min")
36#pragma push_macro("max")
40#define ARGS_VERSION "6.6.0"
41#define ARGS_VERSION_MAJOR 6
42#define ARGS_VERSION_MINOR 6
43#define ARGS_VERSION_PATCH 0
53#include <unordered_map>
54#include <unordered_set>
63#if defined(_MSC_VER) && _MSC_VER <= 1800
77 template <
typename Option>
78 auto get(Option &option_) ->
decltype(option_.Get())
91 inline std::string::size_type
Glyphs(
const std::string &string_)
93 std::string::size_type length = 0;
94 for (
const char c: string_)
96 if ((c & 0xc0) != 0x80)
110 static_assert(std::is_integral<T>::value,
"SafeAdd requires integral types.");
111 if (std::is_unsigned<T>::value)
113 using U =
typename std::make_unsigned<T>::type;
114 const U ua =
static_cast<U
>(a);
115 const U ub =
static_cast<U
>(b);
116 const U maxv = std::numeric_limits<U>::max();
121 out =
static_cast<T
>(ua + ub);
126#if defined(__clang__) || defined(__GNUC__)
127 return !__builtin_add_overflow(a, b, &out);
130 if (b > 0 && a > std::numeric_limits<T>::max() - b)
134 if (b < 0 && a < std::numeric_limits<T>::min() - b)
150 static_assert(std::is_integral<T>::value,
"SafeMultiply requires integral types.");
152 if (a == 0 || b == 0)
158 if (std::is_unsigned<T>::value)
160 using U =
typename std::make_unsigned<T>::type;
161 const U ua =
static_cast<U
>(a);
162 const U ub =
static_cast<U
>(b);
163 const U maxv = std::numeric_limits<U>::max();
168 out =
static_cast<T
>(ua * ub);
173#if defined(__clang__) || defined(__GNUC__)
174 return !__builtin_mul_overflow(a, b, &out);
177 if (a == -1 && b == std::numeric_limits<T>::min())
181 if (b == -1 && a == std::numeric_limits<T>::min())
185 if ((a > 0 && b > 0 && a > std::numeric_limits<T>::max() / b) ||
186 (a > 0 && b < 0 && b < std::numeric_limits<T>::min() / a) ||
187 (a < 0 && b > 0 && a < std::numeric_limits<T>::min() / b) ||
188 (a < 0 && b < 0 && a < std::numeric_limits<T>::max() / b))
204 static_assert(std::is_integral<T>::value,
"SafeSub requires integral types.");
205 if (std::is_unsigned<T>::value)
216#if defined(__clang__) || defined(__GNUC__)
217 return !__builtin_sub_overflow(a, b, &out);
220 if (b > 0 && a < std::numeric_limits<T>::min() + b)
224 if (b < 0 && a > std::numeric_limits<T>::max() + b)
239 typename std::enable_if<std::is_unsigned<T>::value,
bool>::type
242 static_assert(std::is_integral<T>::value,
"SafeNeg requires integral types.");
253 typename std::enable_if<std::is_signed<T>::value,
bool>::type
256 static_assert(std::is_integral<T>::value,
"SafeNeg requires integral types.");
257 if (a == std::numeric_limits<T>::min())
276 template <
typename It>
277 inline std::vector<std::string>
Wrap(It begin,
279 const std::string::size_type width,
280 std::string::size_type firstlinewidth = 0,
281 std::string::size_type firstlineindent = 0)
283 std::vector<std::string> output;
284 std::string line(firstlineindent,
' ');
287 if (firstlinewidth == 0)
289 firstlinewidth = width;
292 auto currentwidth = firstlinewidth;
294 for (
auto it = begin; it != end; ++it)
305 output.push_back(line);
308 currentwidth = width;
314 auto itemsize =
Glyphs(*it);
317 bool needsWrap =
false;
318 if (itemsize >= currentwidth)
324 size_t remainingWidth = (currentwidth > itemsize) ? (currentwidth - itemsize) : 0;
325 size_t nextLength = 0;
326 if (!SafeAdd<std::string::size_type>(line.length(),
static_cast<std::string::size_type
>(1), nextLength) || nextLength > remainingWidth)
336 output.push_back(line);
339 currentwidth = width;
357 output.push_back(line);
365 template <
typename T>
366 std::string Join(
const T& array,
const std::string &delimiter)
371 using size_type = std::string::size_type;
374 const size_type delim_size =
static_cast<size_type
>(delimiter.size());
375 bool can_reserve =
true;
377 for (
const auto &element : array)
379 const size_type elem_size =
static_cast<size_type
>(element.size());
380 if (!SafeAdd<size_type>(total, elem_size, total))
388 if (can_reserve && count > 1)
390 size_type delim_count = count - 1;
391 size_type delim_total = 0;
392 if (!SafeMultiply<size_type>(delim_count, delim_size, delim_total) ||
393 !SafeAdd<size_type>(total, delim_total, total))
399 if (can_reserve && total > 0)
405 for (
const auto &element : array)
428 inline std::vector<std::string>
Wrap(
const std::string &in,
const std::string::size_type width, std::string::size_type firstlinewidth = 0)
431 const auto newlineloc = in.find(
'\n');
432 if (newlineloc != in.npos)
434 auto first =
Wrap(std::string(in, 0, newlineloc), width);
435 auto second =
Wrap(std::string(in, newlineloc + 1), width);
438 std::make_move_iterator(std::begin(second)),
439 std::make_move_iterator(std::end(second)));
443 std::istringstream stream(in);
444 std::string::size_type indent = 0;
448 if (!std::isspace(
static_cast<unsigned char>(c)))
455 return Wrap(std::istream_iterator<std::string>(stream), std::istream_iterator<std::string>(),
456 width, firstlinewidth, indent);
477 class Error :
public std::runtime_error
480 Error(
const std::string &problem) : std::runtime_error(problem) {}
543 Help(
const std::string &flag) :
Error(flag) {}
549 class SubparserError :
public Error
552 SubparserError() :
Error(
"") {}
553 virtual ~SubparserError() {}
571 const char shortFlag;
572 const std::string longFlag;
573 EitherFlag(
const std::string &flag) : isShort(
false), shortFlag(), longFlag(flag) {}
574 EitherFlag(
const char *flag) : isShort(
false), shortFlag(), longFlag(flag) {}
575 EitherFlag(
const char flag) : isShort(
true), shortFlag(flag), longFlag() {}
579 static std::unordered_set<std::string>
GetLong(std::initializer_list<EitherFlag> flags)
581 std::unordered_set<std::string> longFlags;
586 longFlags.insert(flag.longFlag);
594 static std::unordered_set<char>
GetShort(std::initializer_list<EitherFlag> flags)
596 std::unordered_set<char> shortFlags;
601 shortFlags.insert(flag.shortFlag);
607 std::string str()
const
609 return isShort ? std::string(1, shortFlag) : longFlag;
612 std::string str(
const std::string &shortPrefix,
const std::string &longPrefix)
const
614 return isShort ? shortPrefix + std::string(1, shortFlag) : longPrefix + longFlag;
629 const std::unordered_set<char> shortFlags;
630 const std::unordered_set<std::string> longFlags;
637 template <
typename ShortIt,
typename LongIt>
638 Matcher(ShortIt shortFlagsStart, ShortIt shortFlagsEnd, LongIt longFlagsStart, LongIt longFlagsEnd) :
639 shortFlags(shortFlagsStart, shortFlagsEnd),
640 longFlags(longFlagsStart, longFlagsEnd)
642 if (shortFlags.empty() && longFlags.empty())
652 Error GetError() const noexcept
654 return shortFlags.empty() && longFlags.empty() ? Error::Usage : Error::None;
662 template <
typename Short,
typename Long>
664 Matcher(std::begin(shortIn), std::end(shortIn), std::begin(longIn), std::end(longIn))
679 Matcher(std::initializer_list<EitherFlag> in) :
682 Matcher(
Matcher &&other) noexcept : shortFlags(std::move(other.shortFlags)), longFlags(std::move(other.longFlags))
691 return shortFlags.find(flag) != shortFlags.end();
696 bool Match(
const std::string &flag)
const
698 return longFlags.find(flag) != longFlags.end();
705 return flag.isShort ?
Match(flag.shortFlag) :
Match(flag.longFlag);
712 std::vector<EitherFlag> flagStrings;
713 flagStrings.reserve(shortFlags.size() + longFlags.size());
714 for (
const char flag: shortFlags)
716 flagStrings.emplace_back(flag);
718 for (
const std::string &flag: longFlags)
720 flagStrings.emplace_back(flag);
729 if (!longFlags.empty())
731 return *longFlags.begin();
734 if (!shortFlags.empty())
736 return *shortFlags.begin();
747 if (!shortFlags.empty())
749 return *shortFlags.begin();
752 if (!longFlags.empty())
754 return *longFlags.begin();
805 return static_cast<Options>(
static_cast<int>(lhs) |
static_cast<int>(rhs));
810 return static_cast<Options>(
static_cast<int>(lhs) &
static_cast<int>(rhs));
814 class PositionalBase;
816 class ArgumentParser;
982 Nargs(
size_t min_,
size_t max_) : min{min_}, max{max_}
992 Nargs(
size_t num_) : min{num_}, max{num_}
996 friend bool operator == (
const Nargs &lhs,
const Nargs &rhs)
998 return lhs.min == rhs.min && lhs.max == rhs.max;
1001 friend bool operator != (
const Nargs &lhs,
const Nargs &rhs)
1003 return !(lhs == rhs);
1015 bool matched =
false;
1016 const std::string help;
1019 mutable Error error = Error::None;
1020 mutable std::string errorMsg;
1024 Base(
const std::string &help_,
Options options_ = {}) : options(options_), help(help_) {}
1027 Options GetOptions()
const noexcept
1032 bool IsRequired()
const noexcept
1037 virtual bool Matched()
const noexcept
1042 virtual void Validate(
const std::string &,
const std::string &)
const
1046 operator bool()
const noexcept
1051 virtual std::vector<std::tuple<std::string, std::string, unsigned>> GetDescription(
const HelpParams &,
const unsigned indentLevel)
const
1053 std::tuple<std::string, std::string, unsigned> description;
1054 std::get<1>(description) = help;
1055 std::get<2>(description) = indentLevel;
1056 return { std::move(description) };
1059 virtual std::vector<Command*> GetCommands()
1064 virtual bool IsGroup()
const
1069 virtual bool IsFlag()
const
1084 virtual std::vector<FlagBase*> GetAllFlags()
1089 virtual bool HasFlag()
const
1094 virtual bool HasPositional()
const
1099 virtual bool HasCommand()
const
1104 virtual std::vector<std::string> GetProgramLine(
const HelpParams &)
const
1128 virtual void Reset() noexcept
1132 error = Error::None;
1139 virtual Error GetError()
const
1145 virtual std::string GetErrorMsg()
const
1157 const std::string name;
1158 bool kickout =
false;
1159 std::string defaultString;
1160 bool defaultStringManual =
false;
1161 std::vector<std::string> choicesStrings;
1162 bool choicesStringManual =
false;
1164 virtual std::string GetDefaultString(
const HelpParams&)
const {
return {}; }
1166 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams&)
const {
return {}; }
1168 virtual std::string GetNameString(
const HelpParams&)
const {
return Name(); }
1170 void AddDescriptionPostfix(std::string &dest,
const bool isManual,
const std::string &manual,
bool isGenerated,
const std::string &generated,
const std::string &str)
const
1172 if (isManual && !manual.empty())
1177 else if (!isManual && isGenerated && !generated.empty())
1185 NamedBase(
const std::string &name_,
const std::string &help_,
Options options_ = {}) :
Base(help_, options_), name(name_) {}
1193 defaultStringManual =
true;
1194 defaultString = str;
1201 return defaultStringManual ? defaultString : GetDefaultString(params);
1209 choicesStringManual =
true;
1210 choicesStrings = array;
1217 return choicesStringManual ? choicesStrings : GetChoicesStrings(params);
1220 virtual std::vector<std::tuple<std::string, std::string, unsigned>> GetDescription(
const HelpParams ¶ms,
const unsigned indentLevel)
const override
1222 std::tuple<std::string, std::string, unsigned> description;
1223 std::get<0>(description) = GetNameString(params);
1224 std::get<1>(description) = help;
1225 std::get<2>(description) = indentLevel;
1227 AddDescriptionPostfix(std::get<1>(description), choicesStringManual, detail::Join(choicesStrings,
", "), params.
addChoices, detail::Join(GetChoicesStrings(params),
", "), params.
choiceString);
1228 AddDescriptionPostfix(std::get<1>(description), defaultStringManual, defaultString, params.
addDefault, GetDefaultString(params), params.
defaultString);
1230 return { std::move(description) };
1233 virtual std::string Name()
const
1241 template<
typename T>
1242 using vector = std::vector<T, std::allocator<T>>;
1244 template<
typename K,
typename T>
1245 using unordered_map = std::unordered_map<K, T, std::hash<K>,
1246 std::equal_to<K>, std::allocator<std::pair<const K, T> > >;
1248 template<
typename S,
typename T>
1251 template<
typename SS,
typename TT>
1252 static auto test(
int)
1253 ->
decltype( std::declval<SS&>() << std::declval<TT>(), std::true_type() );
1255 template<
typename,
typename>
1256 static auto test(...) -> std::false_type;
1259 using type =
decltype(test<S,T>(0));
1262 template <
typename T>
1263 using IsConvertableToString =
typename is_streamable<std::ostringstream, T>::type;
1265 template <
typename T>
1266 typename std::enable_if<IsConvertableToString<T>::value, std::string>::type
1267 ToString(
const T &value)
1269 std::ostringstream s;
1274 template <
typename T>
1275 typename std::enable_if<!IsConvertableToString<T>::value, std::string>::type
1281 template <
typename T>
1282 std::vector<std::string> MapKeysToStrings(
const T &map)
1284 std::vector<std::string> res;
1285 using K =
typename std::decay<
decltype(std::begin(map)->first)>::type;
1286 if (IsConvertableToString<K>::value)
1288 for (
const auto &p : map)
1290 res.push_back(detail::ToString(p.first));
1293 std::sort(res.begin(), res.end());
1306 virtual std::string GetNameString(
const HelpParams ¶ms)
const override
1311 const bool useValueNameOnce = flagStrings.size() == 1 ? false : params.
useValueNameOnce;
1312 for (
auto it = flagStrings.begin(); it != flagStrings.end(); ++it)
1315 if (it != flagStrings.begin())
1321 flags += flag.str();
1323 if (!postfix.empty() && (!useValueNameOnce || it + 1 == flagStrings.end()))
1336 FlagBase(
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
Options options_) :
NamedBase(name_, help_, options_), matcher(std::move(matcher_)) {}
1340 virtual bool IsFlag()
const override
1347 if (matcher.
Match(flag))
1351 std::ostringstream problem;
1352 problem <<
"Flag '" << flag.str() <<
"' was passed multiple times, but is only allowed to be passed once";
1354 error = Error::Extra;
1355 errorMsg = problem.str();
1366 virtual std::vector<FlagBase*> GetAllFlags()
override
1371 const Matcher &GetMatcher()
const
1376 virtual void Validate(
const std::string &shortPrefix,
const std::string &longPrefix)
const override
1378 if (!Matched() && IsRequired())
1380 std::ostringstream problem;
1381 problem <<
"Flag '" << matcher.
GetLongOrAny().str(shortPrefix, longPrefix) <<
"' is required";
1383 error = Error::Required;
1384 errorMsg = problem.str();
1391 virtual std::vector<std::string> GetProgramLine(
const HelpParams ¶ms)
const override
1401 if (!postfix.empty())
1410 virtual bool HasFlag()
const override
1417 bool usageError =
false;
1418 void SetUsageError()
1422 void ClearUsageError()
1426 virtual Error GetError()
const override
1430 return Error::Usage;
1433 if (nargs.min > nargs.max)
1435 return Error::Usage;
1438 const auto matcherError = matcher.GetError();
1439 if (matcherError != Error::None)
1441 return matcherError;
1458 virtual
void ParseValue(const std::vector<std::
string> &value) = 0;
1466 ValueFlagBase(
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const bool extraError_ =
false) :
FlagBase(name_, help_, std::move(matcher_), extraError_) {}
1479 std::vector<std::string> reply;
1483 template <
typename GroupClass>
1486 group_.AddCompletion(*
this);
1496 virtual void ParseValue(
const std::vector<std::string> &value_)
override
1498 syntax = value_.at(0);
1499 const std::string &raw = value_.at(1);
1500 bool failed =
false;
1502 const auto firstNonSpace = std::find_if_not(raw.begin(), raw.end(), [](
char c)
1504 return std::isspace(static_cast<unsigned char>(c)) != 0;
1510 if (firstNonSpace != raw.end() && (*firstNonSpace ==
'-' || *firstNonSpace ==
'+'))
1518 std::istringstream ss(raw);
1524 ss.imbue(std::locale::classic());
1547 error = Error::Parse;
1548 errorMsg =
"Argument 'completion' received invalid value type '" + raw +
"'";
1550 std::ostringstream problem;
1551 problem <<
"Argument 'completion' received invalid value type '" << raw <<
"'";
1564 return detail::Join(reply,
"\n");
1567 virtual void Reset() noexcept
override
1569 ValueFlagBase::Reset();
1593 virtual void ParseValue(
const std::string &value_) = 0;
1595 virtual void Reset()
noexcept override
1600 error = Error::None;
1607 return Ready() ? this :
nullptr;
1610 virtual bool HasPositional()
const override
1615 virtual std::vector<std::string> GetProgramLine(
const HelpParams ¶ms)
const override
1621 virtual void Validate(
const std::string &,
const std::string &)
const override
1623 if (IsRequired() && !Matched())
1625 std::ostringstream problem;
1626 problem <<
"Option '" << Name() <<
"' is required";
1628 error = Error::Required;
1629 errorMsg = problem.str();
1643 std::vector<Base*> children;
1644 std::function<bool(
const Group &)> validator;
1651 static bool Xor(
const Group &group)
1656 static bool AtLeastOne(
const Group &group)
1661 static bool AtMostOne(
const Group &group)
1666 static bool All(
const Group &group)
1671 static bool AllOrNone(
const Group &group)
1673 return (All(group) ||
None(group));
1676 static bool AllChildGroups(
const Group &group)
1678 return std::none_of(std::begin(group.
Children()), std::end(group.
Children()), [](
const Base* child) ->
bool {
1679 return child->IsGroup() && !child->Matched();
1683 static bool DontCare(
const Group &)
1688 static bool CareTooMuch(
const Group &)
1699 Group(
const std::string &help_ = std::string(),
const std::function<
bool(
const Group &)> &validator_ = Validators::DontCare,
Options options_ = {}) :
Base(help_, options_), validator(validator_)
1704 Group(
Group &group_,
const std::string &help_ = std::string(),
const std::function<
bool(
const Group &)> &validator_ = Validators::DontCare,
Options options_ = {}) :
Base(help_, options_), validator(validator_)
1715 children.emplace_back(&child);
1717 if(child.IsFlag()) {
1718#ifndef ARGS_NOEXCEPT
1726 SignalDetectDuplicates();
1730 children.pop_back();
1734 SignalDetectDuplicates();
1753 for (
Base *child: Children())
1755 if (
FlagBase *match = child->Match(flag))
1763 virtual std::vector<FlagBase*> GetAllFlags()
override
1765 std::vector<FlagBase*> res;
1766 for (
Base *child: Children())
1768 auto childRes = child->GetAllFlags();
1769 res.insert(res.end(), childRes.begin(), childRes.end());
1774 virtual void Validate(
const std::string &shortPrefix,
const std::string &longPrefix)
const override
1776 for (Base *child: Children())
1778 child->Validate(shortPrefix, longPrefix);
1788 for (
Base *child: Children())
1790 if (
auto next = child->GetNextPositional())
1804 return std::any_of(Children().begin(), Children().end(), [](
Base *child) {
return child->HasFlag(); });
1813 return std::any_of(Children().begin(), Children().end(), [](
Base *child) {
return child->HasPositional(); });
1822 return std::any_of(Children().begin(), Children().end(), [](
Base *child) {
return child->HasCommand(); });
1830 return static_cast<std::vector<Base *>::size_type
>(
1831 std::count_if(std::begin(Children()), std::end(Children()), [](
const Base *child){
return child->Matched();}));
1839 std::vector<Base*> matched_children;
1840 std::copy_if(children.begin(), children.end(), std::back_inserter(matched_children), [](
Base* b){
1841 return b->Matched();
1843 return matched_children;
1851 template <
typename ChildType>
1854 std::vector<ChildType *> filtered_children;
1855 for(
Base *child : children) {
1856 if(!matching || child->Matched())
1858 ChildType* cast_result =
dynamic_cast<ChildType*
>(child);
1859 if(cast_result !=
nullptr)
1861 filtered_children.push_back(cast_result);
1866 return filtered_children;
1873 return validator(*
this);
1885 virtual std::vector<std::tuple<std::string, std::string, unsigned>>
GetDescription(
const HelpParams ¶ms,
const unsigned int indent)
const override
1887 std::vector<std::tuple<std::string, std::string, unsigned int>> descriptions;
1890 unsigned addindent = 0;
1893 descriptions.emplace_back(help,
"", indent);
1897 for (
Base *child: Children())
1899 if ((child->GetOptions() & Options::HiddenFromDescription) != Options::None)
1904 auto groupDescriptions = child->GetDescription(params, indent + addindent);
1905 descriptions.insert(
1906 std::end(descriptions),
1907 std::make_move_iterator(std::begin(groupDescriptions)),
1908 std::make_move_iterator(std::end(groupDescriptions)));
1910 return descriptions;
1917 std::vector <std::string> names;
1918 for (
Base *child: Children())
1920 if ((child->GetOptions() & Options::HiddenFromUsage) != Options::None)
1925 auto groupNames = child->GetProgramLine(params);
1928 std::make_move_iterator(std::begin(groupNames)),
1929 std::make_move_iterator(std::end(groupNames)));
1934 virtual std::vector<Command*> GetCommands()
override
1936 std::vector<Command*> res;
1937 for (
const auto &child : Children())
1939 auto subparsers = child->GetCommands();
1940 res.insert(std::end(res), std::begin(subparsers), std::end(subparsers));
1945 virtual bool IsGroup()
const override
1950 virtual void Reset() noexcept
override
1954 for (
auto &child: Children())
1959 error = Error::None;
1970 else DetectDuplicateFlags();
1979 std::unordered_set<char> usedShortFlags;
1980 std::unordered_set<std::string> usedLongFlags;
1981 DetectDuplicateFlags(usedShortFlags, usedLongFlags);
1986 void DetectDuplicateFlags(std::unordered_set<char> &usedShortFlags, std::unordered_set<std::string> &usedLongFlags)
1988 for (
Base *child: Children())
1990 if(
auto flag =
dynamic_cast<FlagBase*
>(child))
1994 for(
EitherFlag flagString: flag->GetMatcher().GetFlagStrings())
1996 if(flagString.isShort)
1998 if(usedShortFlags.count(flagString.shortFlag))
2001 flag->SetUsageError();
2003 throw ParseError(
"duplicate short flag detected");
2008 usedShortFlags.insert(flagString.shortFlag);
2013 if(usedLongFlags.count(flagString.longFlag))
2016 flag->SetUsageError();
2018 throw ParseError(
"duplicate long flag detected");
2023 usedLongFlags.insert(flagString.longFlag);
2028 else if(
auto group =
dynamic_cast<Group*
>(child))
2035 if(group->IsGroup())
2037 group->DetectDuplicateFlags(usedShortFlags, usedLongFlags);
2045 virtual Error GetError()
const override
2047 if (error != Error::None)
2052 auto it = std::find_if(Children().begin(), Children().end(), [](
const Base *child){
return child->GetError() != Error::None;});
2053 if (it == Children().end())
2058 return (*it)->GetError();
2063 virtual std::string GetErrorMsg()
const override
2065 if (error != Error::None)
2070 auto it = std::find_if(Children().begin(), Children().end(), [](
const Base *child){
return child->GetError() != Error::None;});
2071 if (it == Children().end())
2076 return (*it)->GetErrorMsg();
2114 std::vector<std::string>
args;
2115 std::vector<std::string> kicked;
2119 bool isParsed =
false;
2123 :
Group({}, Validators::AllChildGroups),
args(std::move(args_)), parser(&parser_), helpParams(helpParams_), command(command_)
2173 std::string description;
2175 std::string proglinePostfix;
2177 std::function<void(
Subparser&)> parserCoroutine;
2178 bool commandIsRequired =
true;
2179 Command *selectedCommand =
nullptr;
2181 mutable std::vector<std::tuple<std::string, std::string, unsigned>> subparserDescription;
2182 mutable std::vector<std::string> subparserProgramLine;
2183 mutable bool subparserHasFlag =
false;
2184 mutable bool subparserHasPositional =
false;
2185 mutable bool subparserHasCommand =
false;
2187 mutable Error subparserError = Error::None;
2196 RaiiSubparser(
ArgumentParser &parser_, std::vector<std::string> args_);
2201 command.subparser = oldSubparser;
2217 std::function<void(
Subparser&)> &GetCoroutine()
2219 return selectedCommand !=
nullptr ? selectedCommand->GetCoroutine() : parserCoroutine;
2225 while (res->selectedCommand !=
nullptr)
2227 res = res->selectedCommand;
2233 const Command &SelectedCommand()
const
2236 while (res->selectedCommand !=
nullptr)
2238 res = res->selectedCommand;
2244 void UpdateSubparserHelp(
const HelpParams ¶ms)
const
2246 if (parserCoroutine)
2248 RaiiSubparser coro(*
this, params);
2249#ifndef ARGS_NOEXCEPT
2252 parserCoroutine(coro.Parser());
2254 catch (args::SubparserError&)
2258 parserCoroutine(coro.Parser());
2264 Command(
Group &base_, std::string name_, std::string help_, std::function<
void(
Subparser&)> coroutine_ = {})
2265 : name(std::move(name_)), help(std::move(help_)), parserCoroutine(std::move(coroutine_))
2273 {
return proglinePostfix; }
2278 { this->proglinePostfix = proglinePostfix_; }
2283 {
return description; }
2288 { this->description = description_; }
2298 { this->epilog = epilog_; }
2315 { commandIsRequired = value; }
2317 virtual bool IsGroup()
const override
2321 {
return Base::Matched(); }
2323 operator bool() const noexcept
2324 {
return Matched(); }
2326 void Match() noexcept
2329 void SelectCommand(Command *c)
noexcept
2331 selectedCommand = c;
2341 if (selectedCommand !=
nullptr)
2343 if (
auto *res = selectedCommand->Match(flag))
2348 for (
auto *child: Children())
2350 if ((child->GetOptions() & Options::Global) != Options::None)
2352 if (
auto *res = child->Match(flag))
2362 if (subparser !=
nullptr)
2364 return subparser->
Match(flag);
2367 return Matched() ? Group::Match(flag) :
nullptr;
2370 virtual std::vector<FlagBase*> GetAllFlags()
override
2372 std::vector<FlagBase*> res;
2379 for (
auto *child: Children())
2381 if (selectedCommand ==
nullptr || (child->GetOptions() & Options::Global) != Options::None)
2383 auto childFlags = child->GetAllFlags();
2384 res.insert(res.end(), childFlags.begin(), childFlags.end());
2388 if (selectedCommand !=
nullptr)
2390 auto childFlags = selectedCommand->GetAllFlags();
2391 res.insert(res.end(), childFlags.begin(), childFlags.end());
2394 if (subparser !=
nullptr)
2396 auto childFlags = subparser->GetAllFlags();
2397 res.insert(res.end(), childFlags.begin(), childFlags.end());
2405 if (selectedCommand !=
nullptr)
2412 for (
auto *child: Children())
2414 if ((child->GetOptions() & Options::Global) != Options::None)
2416 if (
auto *res = child->GetNextPositional())
2426 if (subparser !=
nullptr)
2431 return Matched() ? Group::GetNextPositional() :
nullptr;
2436 return subparserHasFlag || Group::HasFlag();
2441 return subparserHasPositional || Group::HasPositional();
2449 std::vector<std::string> GetCommandProgramLine(
const HelpParams ¶ms)
const
2451 UpdateSubparserHelp(params);
2453 std::vector<std::string> res;
2460 auto group_res = Group::GetProgramLine(params);
2461 std::move(std::move(group_res).begin(), std::move(group_res).end(), std::back_inserter(res));
2463 res.insert(res.end(), subparserProgramLine.begin(), subparserProgramLine.end());
2465 if (!params.
proglineCommand.empty() && (Group::HasCommand() || subparserHasCommand))
2467 res.insert(res.begin(), commandIsRequired ? params.
proglineCommand :
"[" + params.proglineCommand +
"]");
2470 if (!Name().empty())
2472 res.insert(res.begin(), Name());
2475 if (!ProglinePostfix().empty())
2478 for (
auto c : ProglinePostfix())
2480 if (std::isspace(
static_cast<unsigned char>(c)))
2484 res.push_back(line);
2490 res.push_back(
"\n");
2501 res.push_back(line);
2515 return GetCommandProgramLine(params);
2518 virtual std::vector<Command*> GetCommands()
override
2520 if (selectedCommand !=
nullptr)
2522 return selectedCommand->GetCommands();
2527 return Group::GetCommands();
2533 virtual std::vector<std::tuple<std::string, std::string, unsigned>>
GetDescription(
const HelpParams ¶ms,
const unsigned int indent)
const override
2535 std::vector<std::tuple<std::string, std::string, unsigned>> descriptions;
2536 unsigned addindent = 0;
2538 UpdateSubparserHelp(params);
2544 std::ostringstream s;
2546 for (
const auto &progline: GetCommandProgramLine(params))
2560 descriptions.emplace_back(s.str(),
"", indent);
2564 descriptions.emplace_back(Name(), help, indent);
2569 return descriptions;
2577 descriptions.emplace_back(
"",
"", indent + addindent);
2578 descriptions.emplace_back(Description().empty() ?
Help() : Description(),
"", indent + addindent);
2579 descriptions.emplace_back(
"",
"", indent + addindent);
2582 for (
Base *child: Children())
2584 if ((child->GetOptions() & Options::HiddenFromDescription) != Options::None)
2589 auto groupDescriptions = child->GetDescription(params, indent + addindent);
2590 descriptions.insert(
2591 std::end(descriptions),
2592 std::make_move_iterator(std::begin(groupDescriptions)),
2593 std::make_move_iterator(std::end(groupDescriptions)));
2596 for (
auto childDescription: subparserDescription)
2598 std::get<2>(childDescription) += indent + addindent;
2599 descriptions.push_back(std::move(childDescription));
2604 descriptions.emplace_back(
"",
"", indent + addindent);
2605 if (!Epilog().empty())
2607 descriptions.emplace_back(Epilog(),
"", indent + addindent);
2608 descriptions.emplace_back(
"",
"", indent + addindent);
2612 return descriptions;
2615 virtual void Validate(
const std::string &shortprefix,
const std::string &longprefix)
const override
2622 auto onValidationError = [&]
2624 std::ostringstream problem;
2625 problem <<
"Group validation failed somewhere!";
2627 error = Error::Validation;
2628 errorMsg = problem.str();
2630 throw ValidationError(problem.str());
2634 for (Base *child: Children())
2636 if (child->IsGroup() && !child->Matched())
2638 onValidationError();
2641 child->Validate(shortprefix, longprefix);
2644 if (subparser !=
nullptr)
2646 subparser->Validate(shortprefix, longprefix);
2649 onValidationError();
2653 if (selectedCommand ==
nullptr && commandIsRequired && (Group::HasCommand() || subparserHasCommand))
2655 std::ostringstream problem;
2656 problem <<
"Command is required";
2658 error = Error::Validation;
2659 errorMsg = problem.str();
2661 throw ValidationError(problem.str());
2666 virtual void Reset() noexcept
override
2669 selectedCommand =
nullptr;
2670 subparserProgramLine.clear();
2671 subparserDescription.clear();
2672 subparserHasFlag =
false;
2673 subparserHasPositional =
false;
2674 subparserHasCommand =
false;
2676 subparserError = Error::None;
2682 virtual Error GetError()
const override
2689 if (error != Error::None)
2694 if (subparserError != Error::None)
2696 return subparserError;
2699 return Group::GetError();
2711 std::string longprefix;
2712 std::string shortprefix;
2714 std::string longseparator;
2716 std::string terminator;
2718 bool allowJoinedShortValue =
true;
2719 bool allowJoinedLongValue =
true;
2720 bool allowSeparateShortValue =
true;
2721 bool allowSeparateLongValue =
true;
2723 bool readCompletion =
false;
2727 enum class OptionType
2734 OptionType ParseOption(
const std::string &s,
bool allowEmpty =
false)
2736 const bool matchesLong = s.find(longprefix) == 0 && (allowEmpty || s.length() > longprefix.length());
2737 const bool matchesShort = s.find(shortprefix) == 0 && (allowEmpty || s.length() > shortprefix.length());
2745 if (matchesLong && matchesShort)
2747 return longprefix.length() >= shortprefix.length() ? OptionType::LongFlag : OptionType::ShortFlag;
2752 return OptionType::LongFlag;
2757 return OptionType::ShortFlag;
2760 return OptionType::Positional;
2763 template <
typename It>
2764 bool Complete(
FlagBase &flag, It it, It end)
2767 if (!readCompletion || (++nextIt != end))
2772 const auto &chunk = *it;
2775 AddCompletionReply(chunk, choice);
2778#ifndef ARGS_NOEXCEPT
2794 template <
typename It>
2796 const bool allowSeparate,
const bool allowJoined,
2797 const bool hasJoined,
const std::string &joinedArg,
2798 const bool canDiscardJoined, std::vector<std::string> &values)
2804 if (hasJoined && !allowJoined && (nargs.min != 0 || !canDiscardJoined))
2806 return "Flag '" + arg +
"' was passed a joined argument, but these are disallowed";
2811 if (!canDiscardJoined || (allowJoined && nargs.max != 0))
2813 values.push_back(joinedArg);
2815 }
else if (!allowSeparate)
2819 return "Flag '" + arg +
"' was passed a separate argument, but these are disallowed";
2827 if (allowSeparate && (!hasJoined || !values.empty()))
2832 while (valueIt != end &&
2833 *valueIt != terminator &&
2834 values.size() < nargs.max &&
2835 (values.size() < nargs.min || ParseOption(*valueIt) == OptionType::Positional))
2837 if (Complete(flag, valueIt, end))
2852 values.push_back(*valueIt);
2858 if (values.size() > nargs.max)
2860 return "Passed an argument into a non-argument flag: " + arg;
2861 }
else if (values.size() < nargs.min)
2863 if (nargs.min == 1 && nargs.max == 1)
2865 return "Flag '" + arg +
"' requires an argument but received none";
2866 }
else if (nargs.min == 1)
2868 return "Flag '" + arg +
"' requires at least one argument but received none";
2869 }
else if (nargs.min != nargs.max)
2871 return "Flag '" + arg +
"' requires at least " + std::to_string(nargs.min) +
2872 " arguments but received " + std::to_string(values.size());
2875 return "Flag '" + arg +
"' requires " + std::to_string(nargs.min) +
2876 " arguments but received " + std::to_string(values.size());
2883 template <
typename It>
2884 bool ParseLong(It &it, It end)
2886 const auto &chunk = *it;
2887 const auto argchunk = chunk.substr(longprefix.size());
2889 const auto separator = longseparator.empty() ? argchunk.npos : argchunk.find(longseparator);
2891 const auto arg = (separator != argchunk.npos ?
2892 std::string(argchunk, 0, separator)
2894 const auto joined = (separator != argchunk.npos ?
2895 argchunk.substr(separator + longseparator.size())
2898 if (
auto flag = Match(arg))
2906 if (flag->GetError() != Error::None)
2911 std::vector<std::string> values;
2912 const std::string errorMessage = ParseArgsValues(*flag, arg, it, end, allowSeparateLongValue, allowJoinedLongValue,
2913 separator != argchunk.npos, joined,
false, values);
2914 if (!errorMessage.empty())
2916#ifndef ARGS_NOEXCEPT
2917 throw ParseError(errorMessage);
2919 error = Error::Parse;
2920 errorMsg = errorMessage;
2925 if (!readCompletion)
2934 if (flag->GetError() != Error::None)
2948 const std::string errorMessage(
"Flag could not be matched: " + arg);
2949#ifndef ARGS_NOEXCEPT
2950 throw ParseError(errorMessage);
2952 error = Error::Parse;
2953 errorMsg = errorMessage;
2961 template <
typename It>
2962 bool ParseShort(It &it, It end)
2964 const auto &chunk = *it;
2965 const auto argchunk = chunk.substr(shortprefix.size());
2966 for (
auto argit = std::begin(argchunk); argit != std::end(argchunk); ++argit)
2968 const auto arg = *argit;
2970 if (
auto flag = Match(arg))
2976 if (flag->GetError() != Error::None)
2981 const std::string value(argit + 1, std::end(argchunk));
2982 std::vector<std::string> values;
2983 const std::string errorMessage = ParseArgsValues(*flag, std::string(1, arg), it, end,
2984 allowSeparateShortValue, allowJoinedShortValue,
2985 !value.empty(), value, !value.empty(), values);
2987 if (!errorMessage.empty())
2989#ifndef ARGS_NOEXCEPT
2990 throw ParseError(errorMessage);
2992 error = Error::Parse;
2993 errorMsg = errorMessage;
2998 if (!readCompletion)
3005 if (flag->GetError() != Error::None)
3018 if (!values.empty())
3024 const std::string errorMessage(
"Flag could not be matched: '" + std::string(1, arg) +
"'");
3025#ifndef ARGS_NOEXCEPT
3026 throw ParseError(errorMessage);
3028 error = Error::Parse;
3029 errorMsg = errorMessage;
3038 bool AddCompletionReply(
const std::string &cur,
const std::string &choice)
3040 if (cur.empty() || choice.find(cur) == 0)
3042 if (completion->syntax ==
"bash" && ParseOption(choice) == OptionType::LongFlag && choice.find(longseparator) != std::string::npos)
3044 completion->reply.push_back(choice.substr(choice.find(longseparator) + longseparator.size()));
3047 completion->reply.push_back(choice);
3055 template <
typename It>
3056 bool Complete(It it, It end,
bool terminated)
3059 if (!readCompletion || (++nextIt != end))
3064 const auto &chunk = *it;
3065 auto pos = GetNextPositional();
3066 std::vector<Command *> commands = GetCommands();
3067 const auto optionType = ParseOption(chunk,
true);
3073 if (!terminated && !commands.empty() && (chunk.empty() || optionType == OptionType::Positional))
3075 for (
auto &cmd : commands)
3077 if ((cmd->GetOptions() & Options::HiddenFromCompletion) == Options::None)
3079 AddCompletionReply(chunk, cmd->Name());
3084 bool hasPositionalCompletion =
true;
3086 if (!terminated && !commands.empty())
3088 for (
auto &cmd : commands)
3090 if ((cmd->GetOptions() & Options::HiddenFromCompletion) == Options::None)
3092 AddCompletionReply(chunk, cmd->Name());
3097 if ((pos->GetOptions() & Options::HiddenFromCompletion) == Options::None)
3099 auto choices = pos->HelpChoices(helpParams);
3100 hasPositionalCompletion = !choices.empty() || optionType != OptionType::Positional;
3101 for (
auto &choice : choices)
3103 AddCompletionReply(chunk, choice);
3108 if (!terminated && hasPositionalCompletion)
3110 auto flags = GetAllFlags();
3111 for (
auto flag : flags)
3113 if ((flag->GetOptions() & Options::HiddenFromCompletion) != Options::None)
3118 auto &matcher = flag->GetMatcher();
3119 if (!AddCompletionReply(chunk, matcher.
GetShortOrAny().str(shortprefix, longprefix)))
3121 for (
auto &flagName : matcher.GetFlagStrings())
3123 if (AddCompletionReply(chunk, flagName.str(shortprefix, longprefix)))
3131 if (optionType == OptionType::LongFlag && allowJoinedLongValue)
3133 const auto separator = longseparator.empty() ? chunk.npos : chunk.find(longseparator);
3147 if (separator != chunk.npos && separator >= longprefix.size())
3149 std::string arg(chunk, 0, separator);
3150 if (
auto flag = this->Match(arg.substr(longprefix.size())))
3152 for (
auto &choice : flag->HelpChoices(helpParams))
3154 AddCompletionReply(chunk, arg + longseparator + choice);
3158 }
else if (optionType == OptionType::ShortFlag && allowJoinedShortValue)
3160 if (chunk.size() > shortprefix.size() + 1)
3162 auto arg = chunk.at(shortprefix.size());
3164 if (
auto flag = this->Match(arg))
3166 for (
auto &choice : flag->HelpChoices(helpParams))
3168 AddCompletionReply(chunk, shortprefix + arg + choice);
3176#ifndef ARGS_NOEXCEPT
3177 throw Completion(completion->
Get());
3183 template <
typename It>
3184 It Parse(It begin, It end)
3186 bool terminated =
false;
3187 std::vector<Command *> commands = GetCommands();
3190 for (
auto it = begin; it != end; ++it)
3192 if (Complete(it, end, terminated))
3197 const auto &chunk = *it;
3199 if (!terminated && chunk == terminator)
3202 }
else if (!terminated && ParseOption(chunk) == OptionType::LongFlag)
3204 if (!ParseLong(it, end))
3208 }
else if (!terminated && ParseOption(chunk) == OptionType::ShortFlag)
3210 if (!ParseShort(it, end))
3214 }
else if (!terminated && !commands.empty())
3216 auto itCommand = std::find_if(commands.begin(), commands.end(), [&chunk](Command *c) { return c->Name() == chunk; });
3217 if (itCommand == commands.end())
3219 const std::string errorMessage(
"Unknown command: " + chunk);
3220#ifndef ARGS_NOEXCEPT
3221 throw ParseError(errorMessage);
3223 error = Error::Parse;
3224 errorMsg = errorMessage;
3229 SelectCommand(*itCommand);
3231 if (
const auto &coroutine = GetCoroutine())
3234 RaiiSubparser coro(*
this, std::vector<std::string>(it, end));
3235 coroutine(coro.Parser());
3238 if (error != Error::None)
3243 if (!coro.Parser().IsParsed())
3245 error = Error::Usage;
3249 if (!coro.Parser().IsParsed())
3251 throw UsageError(
"Subparser::Parse was not called");
3258 commands = GetCommands();
3261 auto pos = GetNextPositional();
3264 pos->ParseValue(chunk);
3266 if (pos->GetError() != Error::None)
3278 const std::string errorMessage(
"Passed in argument, but no positional arguments were ready to receive it: " + chunk);
3279#ifndef ARGS_NOEXCEPT
3280 throw ParseError(errorMessage);
3282 error = Error::Parse;
3283 errorMsg = errorMessage;
3289 if (!readCompletion && completion !=
nullptr && completion->Matched())
3292 if (completion->GetError() != Error::None)
3294 error = completion->GetError();
3295 if (errorMsg.empty())
3297 errorMsg = completion->GetErrorMsg();
3302 error = Error::Completion;
3304 readCompletion =
true;
3306 const auto argsLeft =
static_cast<size_t>(std::distance(it, end));
3307 if (completion->cword == 0 || argsLeft <= 1 || completion->cword >= argsLeft)
3309#ifndef ARGS_NOEXCEPT
3310 throw Completion(
"");
3317 std::vector<std::string> curArgs;
3318 curArgs.reserve(completion->cword);
3320 for (
size_t idx = 0; idx < completion->cword && curIt != end; ++idx, ++curIt)
3322 curArgs.push_back(*curIt);
3325 if (completion->syntax ==
"bash")
3329 for (
size_t idx = 0; idx < curArgs.size(); )
3331 if (idx > 0 && curArgs[idx] ==
"=")
3333 size_t prev_idx = idx - 1;
3334 curArgs[prev_idx] +=
"=";
3335 size_t next_idx = 0;
3336 if (SafeAdd<size_t>(idx,
static_cast<size_t>(1), next_idx) && next_idx < curArgs.size())
3338 curArgs[prev_idx] += curArgs[next_idx];
3340 size_t erase_end = 0;
3341 if (SafeAdd<size_t>(next_idx,
static_cast<size_t>(1), erase_end))
3343 typedef std::vector<std::string>::difference_type diff_t;
3344 curArgs.erase(curArgs.begin() +
static_cast<diff_t
>(idx),
3345 curArgs.begin() +
static_cast<diff_t
>(erase_end));
3350 typedef std::vector<std::string>::difference_type diff_t;
3351 curArgs.erase(curArgs.begin() +
static_cast<diff_t
>(idx));
3361#ifndef ARGS_NOEXCEPT
3364 Parse(curArgs.begin(), curArgs.end());
3365 throw Completion(
"");
3367 catch (Completion &)
3373 throw Completion(
"");
3383 Parse(curArgs.begin(), curArgs.end());
3384 error = Error::Completion;
3391 Validate(shortprefix, longprefix);
3396 HelpParams helpParams;
3398 ArgumentParser(
const std::string &description_,
const std::string &epilog_ = std::string())
3400 Description(description_);
3406 SetArgumentSeparations(
true,
true,
true,
true);
3410 void AddCompletion(CompletionFlag &completionFlag)
3415 Add(completionFlag);
3416 completion = &completionFlag;
3422 {
return helpParams.programName; }
3425 void Prog(
const std::string &prog_)
3426 { this->helpParams.programName = prog_; }
3431 {
return longprefix; }
3436 this->longprefix = longprefix_;
3437 this->helpParams.longPrefix = longprefix_;
3443 {
return shortprefix; }
3448 this->shortprefix = shortprefix_;
3449 this->helpParams.shortPrefix = shortprefix_;
3455 {
return longseparator; }
3460 if (longseparator_.empty())
3462 const std::string errorMessage(
"longseparator can not be set to empty");
3464 error = Error::Usage;
3465 errorMsg = errorMessage;
3471 this->longseparator = longseparator_;
3472 this->helpParams.longSeparator = allowJoinedLongValue ? longseparator :
" ";
3479 {
return terminator; }
3483 { this->terminator = terminator_; }
3490 bool &allowJoinedShortValue_,
3491 bool &allowJoinedLongValue_,
3492 bool &allowSeparateShortValue_,
3493 bool &allowSeparateLongValue_)
const
3495 allowJoinedShortValue_ = this->allowJoinedShortValue;
3496 allowJoinedLongValue_ = this->allowJoinedLongValue;
3497 allowSeparateShortValue_ = this->allowSeparateShortValue;
3498 allowSeparateLongValue_ = this->allowSeparateLongValue;
3509 const bool allowJoinedShortValue_,
3510 const bool allowJoinedLongValue_,
3511 const bool allowSeparateShortValue_,
3512 const bool allowSeparateLongValue_)
3514 this->allowJoinedShortValue = allowJoinedShortValue_;
3515 this->allowJoinedLongValue = allowJoinedLongValue_;
3516 this->allowSeparateShortValue = allowSeparateShortValue_;
3517 this->allowSeparateLongValue = allowSeparateLongValue_;
3519 this->helpParams.longSeparator = allowJoinedLongValue ? longseparator :
" ";
3520 this->helpParams.shortSeparator = allowJoinedShortValue ?
"" :
" ";
3525 void Help(std::ostream &help_)
const
3527 auto &command = SelectedCommand();
3528 const auto &commandDescription = command.Description().empty() ? command.Help() : command.Description();
3529 const auto desc_indent = helpParams.descriptionindent;
3530 const auto effective_desc_width = (helpParams.width > desc_indent) ? helpParams.width - desc_indent : 0;
3531 const auto description_text =
Wrap(commandDescription, effective_desc_width);
3532 const auto epilog_text =
Wrap(command.Epilog(), effective_desc_width);
3534 const bool hasoptions = command.HasFlag();
3535 const bool hasarguments = command.HasPositional();
3537 std::vector<std::string> prognameline;
3538 prognameline.push_back(helpParams.usageString);
3539 prognameline.push_back(Prog());
3540 auto commandProgLine = command.GetProgramLine(helpParams);
3541 prognameline.insert(prognameline.end(), commandProgLine.begin(), commandProgLine.end());
3543 const auto prog_sum = helpParams.progindent + helpParams.progtailindent;
3544 const auto effective_prog_width = (helpParams.width > prog_sum) ? helpParams.width - prog_sum : 0;
3545 const auto effective_prog_first = (helpParams.width > helpParams.progindent) ? helpParams.width - helpParams.progindent : 0;
3546 const auto proglines =
Wrap(prognameline.begin(), prognameline.end(),
3547 effective_prog_width,
3548 effective_prog_first);
3549 auto progit = std::begin(proglines);
3550 if (progit != std::end(proglines))
3552 help_ << std::string(helpParams.progindent,
' ') << *progit <<
'\n';
3555 for (; progit != std::end(proglines); ++progit)
3557 help_ << std::string(helpParams.progtailindent,
' ') << *progit <<
'\n';
3562 if (!description_text.empty())
3564 for (
const auto &line: description_text)
3566 help_ << std::string(helpParams.descriptionindent,
' ') << line <<
"\n";
3571 bool lastDescriptionIsNewline =
false;
3573 if (!helpParams.optionsString.empty())
3575 help_ << std::string(helpParams.progindent,
' ') << helpParams.optionsString <<
"\n\n";
3578 for (
const auto &desc: command.GetDescription(helpParams, 0))
3580 lastDescriptionIsNewline = std::get<0>(desc).empty() && std::get<1>(desc).empty();
3581 const auto groupindent = std::get<2>(desc) * helpParams.eachgroupindent;
3582 const auto flag_sum = helpParams.flagindent + helpParams.helpindent + helpParams.gutter;
3583 const auto effective_flag_width = (helpParams.width > flag_sum) ? helpParams.width - flag_sum : 0;
3584 const auto flags =
Wrap(std::get<0>(desc), effective_flag_width);
3585 const auto info_sum = helpParams.helpindent + groupindent;
3586 const auto effective_info_width = (helpParams.width > info_sum) ? helpParams.width - info_sum : 0;
3587 const auto info =
Wrap(std::get<1>(desc), effective_info_width);
3589 std::string::size_type flagssize = 0;
3590 for (
auto flagsit = std::begin(flags); flagsit != std::end(flags); ++flagsit)
3592 if (flagsit != std::begin(flags))
3596 help_ << std::string(groupindent + helpParams.flagindent,
' ') << *flagsit;
3597 flagssize =
Glyphs(*flagsit);
3600 auto infoit = std::begin(info);
3602 if ((helpParams.flagindent + flagssize + helpParams.gutter) > helpParams.helpindent || infoit == std::end(info) || helpParams.addNewlineBeforeDescription)
3608 const auto indent_sum = helpParams.flagindent + flagssize;
3609 const auto effective_space = (helpParams.helpindent > indent_sum) ? helpParams.helpindent - indent_sum : 0;
3610 help_ << std::string(effective_space,
' ') << *infoit <<
'\n';
3613 for (; infoit != std::end(info); ++infoit)
3615 help_ << std::string(groupindent + helpParams.helpindent,
' ') << *infoit <<
'\n';
3618 if (hasoptions && hasarguments && helpParams.showTerminator)
3620 lastDescriptionIsNewline =
false;
3621 const auto effective_term_width = (helpParams.width > helpParams.flagindent) ? helpParams.width - helpParams.flagindent : 0;
3622 for (
const auto &item:
Wrap(std::string(
"\"") + terminator +
"\" can be used to terminate flag options and force all following arguments to be treated as positional options", effective_term_width))
3624 help_ << std::string(helpParams.flagindent,
' ') << item <<
'\n';
3628 if (!lastDescriptionIsNewline)
3633 for (
const auto &line: epilog_text)
3635 help_ << std::string(helpParams.descriptionindent,
' ') << line <<
"\n";
3645 std::ostringstream help_;
3650 virtual void Reset() noexcept
override
3654 readCompletion =
false;
3663 template <
typename It>
3670 if (error != Error::None)
3675 return Parse(begin, end);
3683 template <
typename T>
3686 return ParseArgs(std::begin(
args), std::end(
args));
3695 bool ParseCLI(
const int argc,
const char *
const * argv)
3697 if (argc > 0 && argv !=
nullptr && argv[0] !=
nullptr && Prog().empty())
3702 std::vector<std::string>
args;
3703 if (argc > 1 && argv !=
nullptr)
3705 args.assign(argv + 1, argv + argc);
3708 return ParseArgs(
args) == std::end(
args);
3711 template <
typename T>
3712 bool ParseCLI(
const T &
args)
3714 return ParseArgs(
args) == std::end(
args);
3718 inline Command::RaiiSubparser::RaiiSubparser(ArgumentParser &parser_, std::vector<std::string> args_)
3719 : command(parser_.SelectedCommand()), parser(std::move(args_), parser_, command, parser_.helpParams), oldSubparser(command.subparser)
3721 command.subparser = &parser;
3724 inline Command::RaiiSubparser::RaiiSubparser(
const Command &command_,
const HelpParams ¶ms_): command(command_), parser(command, params_), oldSubparser(command.subparser)
3726 command.subparser = &parser;
3734 command.subparserHasFlag =
HasFlag();
3738 if (parser ==
nullptr)
3740#ifndef ARGS_NOEXCEPT
3741 throw args::SubparserError();
3743 error = Error::Subparser;
3748 auto it = parser->Parse(
args.begin(),
args.end());
3750 kicked.assign(it,
args.end());
3753 command.subparserError = GetError();
3757 inline std::ostream &operator<<(std::ostream &os,
const ArgumentParser &parser)
3768 Flag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
Options options_):
FlagBase(name_, help_, std::move(matcher_), options_)
3791 virtual void ParseValue(
const std::vector<std::string>&)
override
3803 HelpFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
Options options_ = {}):
Flag(group_, name_, help_, std::move(matcher_), options_) {}
3810 error = Error::Help;
3830 const int startcount;
3834 CounterFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const int startcount_ = 0,
Options options_ = {}):
3835 Flag(group_, name_, help_, std::move(matcher_), options_), startcount(startcount_), count(startcount_) {}
3841 auto me = FlagBase::Match(arg);
3849 if (GetError() != Error::None)
3866 int &operator *() noexcept {
3870 const int &operator *() const noexcept {
3874 virtual void Reset() noexcept
override
3886 std::function<void(
const std::vector<std::string> &)> action;
3890 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_ = {}):
3891 FlagBase(name_, help_, std::move(matcher_), options_), action(std::move(action_)), nargs(nargs_)
3896 ActionFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_, std::function<
void(
const std::string &)> action_,
Options options_ = {}):
3897 FlagBase(name_, help_, std::move(matcher_), options_), nargs(1)
3900 action = [action_](
const std::vector<std::string> &a) {
return action_(a.at(0)); };
3903 ActionFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_, std::function<
void()> action_,
Options options_ = {}):
3904 FlagBase(name_, help_, std::move(matcher_), options_), nargs(0)
3907 action = [action_](
const std::vector<std::string> &) {
return action_(); };
3913 virtual void ParseValue(
const std::vector<std::string> &value)
override
3926 template <
typename T>
3927 static typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value,
bool>::type
3928 HasUnsignedNegativeSign(
const std::string &value)
3930 const auto firstNonSpace = std::find_if_not(value.begin(), value.end(), [](
char c)
3932 return std::isspace(static_cast<unsigned char>(c)) != 0;
3935 return firstNonSpace != value.end() && *firstNonSpace ==
'-';
3938 template <
typename T>
3939 static typename std::enable_if<!std::is_integral<T>::value || !std::is_unsigned<T>::value,
bool>::type
3940 HasUnsignedNegativeSign(
const std::string &)
3946 template <
typename T>
3947 typename std::enable_if<
3948 std::is_integral<T>::value &&
3949 !std::is_same<T, bool>::value &&
3950 !std::is_same<T, char>::value &&
3951 !std::is_same<T, signed char>::value &&
3952 !std::is_same<T, unsigned char>::value,
3954 ParseNumericValue(
const std::string &value, T &destination)
3956 if (HasUnsignedNegativeSign<T>(value))
3961 const char *begin = value.c_str();
3969 const char *
const stop = begin + value.size();
3975 const int saved_errno = errno;
3978 char *end =
nullptr;
3980 if (std::is_unsigned<T>::value)
3982 const unsigned long long parsed = std::strtoull(begin, &end, 0);
3985 errno = saved_errno;
3988 while (end != stop && std::isspace(
static_cast<unsigned char>(*end)))
3992 if (end != stop || errno == ERANGE ||
3993 parsed >
static_cast<unsigned long long>(std::numeric_limits<T>::max()))
3995 errno = saved_errno;
3999 destination =
static_cast<T
>(parsed);
4003 const long long parsed = std::strtoll(begin, &end, 0);
4006 errno = saved_errno;
4009 while (end != stop && std::isspace(
static_cast<unsigned char>(*end)))
4013 if (end != stop || errno == ERANGE ||
4014 parsed <
static_cast<long long>(std::numeric_limits<T>::min()) ||
4015 parsed >
static_cast<long long>(std::numeric_limits<T>::max()))
4017 errno = saved_errno;
4021 destination =
static_cast<T
>(parsed);
4024 errno = saved_errno;
4028 template <
typename T>
4029 typename std::enable_if<
4030 !std::is_integral<T>::value ||
4031 std::is_same<T, bool>::value ||
4032 std::is_same<T, char>::value ||
4033 std::is_same<T, signed char>::value ||
4034 std::is_same<T, unsigned char>::value,
4036 ParseNumericValue(
const std::string &value, T &destination)
4038 std::istringstream ss(value);
4044 ss.imbue(std::locale::classic());
4055 ss >> std::ws >> extra;
4062 ss.clear(ss.rdstate() & ~std::ios::failbit);
4069 template <
typename T>
4070 typename std::enable_if<!std::is_assignable<T, std::string>::value,
bool>::type
4071 operator ()(
const std::string &name,
const std::string &value, T &destination)
4073 const bool success = ParseNumericValue(value, destination);
4080 std::ostringstream problem;
4081 problem <<
"Argument '" << name <<
"' received invalid value type '" << value <<
"'";
4088 template <
typename T>
4089 typename std::enable_if<std::is_assignable<T, std::string>::value,
bool>::type
4090 operator()(
const std::string &,
const std::string &value, T &destination)
4092 destination = value;
4111 virtual std::string GetDefaultString(
const HelpParams&)
const override
4113 return detail::ToString(defaultValue);
4121 ValueFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const T &defaultValue_,
Options options_):
ValueFlagBase(name_, help_, std::move(matcher_), options_), value(defaultValue_), defaultValue(defaultValue_)
4126 ValueFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const T &defaultValue_ = T(),
const bool extraError_ =
false):
ValueFlag(group_, name_, help_, std::move(matcher_), defaultValue_, extraError_ ?
Options::Single :
Options::None)
4130 ValueFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
Options options_):
ValueFlag(group_, name_, help_, std::move(matcher_), T(), options_)
4136 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4138 const std::string &value_ = values_.at(0);
4141 if (!reader(name, value_, this->value))
4143 error = Error::Parse;
4146 reader(name, value_, this->value);
4150 virtual void Reset() noexcept
override
4152 ValueFlagBase::Reset();
4153 value = defaultValue;
4195 return defaultValue;
4206 typename Reader = ValueReader>
4214 ImplicitValueFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const T &implicitValue_,
const T &defaultValue_ = T(),
Options options_ = {})
4215 :
ValueFlag<T, Reader>(group_, name_, help_, std::move(matcher_), defaultValue_, options_), implicitValue(implicitValue_)
4220 :
ValueFlag<T, Reader>(group_, name_, help_, std::move(matcher_), defaultValue_, options_), implicitValue(defaultValue_)
4225 :
ValueFlag<T, Reader>(group_, name_, help_, std::move(matcher_), {}, options_), implicitValue()
4236 virtual void ParseValue(
const std::vector<std::string> &value_)
override
4240 this->value = implicitValue;
4252 template <
typename T>
4260 Flag(group_, name_, help_, std::move(matcher_), options_),
4264 ConstantFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const T& value_,
bool extraError_ =
false):
4265 Flag(group_, name_, help_, std::move(matcher_), extraError_),
4269 T operator * ()
const noexcept
4274 T Get()
const noexcept
4279 const T *operator -> ()
const noexcept
4293 template <
typename...>
class List = detail::vector,
4300 const List<T> defaultValues;
4306 typedef List<T> Container;
4307 typedef T value_type;
4308 typedef typename Container::allocator_type allocator_type;
4309 typedef typename Container::pointer pointer;
4310 typedef typename Container::const_pointer const_pointer;
4311 typedef T& reference;
4312 typedef const T& const_reference;
4313 typedef typename Container::size_type size_type;
4314 typedef typename Container::difference_type difference_type;
4315 typedef typename Container::iterator iterator;
4316 typedef typename Container::const_iterator const_iterator;
4317 typedef std::reverse_iterator<iterator> reverse_iterator;
4318 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4321 :
FlagBase(name_, help_, std::move(matcher_), options_), values(defaultValues_), defaultValues(defaultValues_),nargs(nargs_)
4333 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4337 for (
const std::string &value : values_)
4341 if (!reader(name, value, v))
4343 error = Error::Parse;
4347 reader(name, value, v);
4349 values.insert(std::end(values), v);
4353 List<T> &Get() noexcept
4386 iterator begin() noexcept
4388 return values.begin();
4391 const_iterator begin() const noexcept
4393 return values.begin();
4396 const_iterator cbegin() const noexcept
4398 return values.cbegin();
4401 iterator end() noexcept
4403 return values.end();
4406 const_iterator end() const noexcept
4408 return values.end();
4411 const_iterator cend() const noexcept
4413 return values.cend();
4416 virtual void Reset() noexcept
override
4419 values = defaultValues;
4422 virtual FlagBase *Match(
const EitherFlag &arg)
override
4424 const bool wasMatched = Matched();
4425 auto me = FlagBase::Match(arg);
4426 if (me && !wasMatched)
4442 template <
typename...>
class List = detail::vector,
4443 typename Reader = ValueReader>
4447 using Container = List<T>;
4449 const Container defaultValues;
4454 typedef T value_type;
4455 typedef typename Container::allocator_type allocator_type;
4456 typedef typename Container::pointer pointer;
4457 typedef typename Container::const_pointer const_pointer;
4458 typedef T& reference;
4459 typedef const T& const_reference;
4460 typedef typename Container::size_type size_type;
4461 typedef typename Container::difference_type difference_type;
4462 typedef typename Container::iterator iterator;
4463 typedef typename Container::const_iterator const_iterator;
4464 typedef std::reverse_iterator<iterator> reverse_iterator;
4465 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4467 ValueFlagList(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const Container &defaultValues_ = Container(),
Options options_ = {}):
4468 ValueFlagBase(name_, help_, std::move(matcher_), options_), values(defaultValues_), defaultValues(defaultValues_)
4475 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4477 const std::string &value_ = values_.at(0);
4481 if (!reader(name, value_, v))
4483 error = Error::Parse;
4487 reader(name, value_, v);
4489 values.insert(std::end(values), v);
4527 virtual std::string Name()
const override
4529 return name + std::string(
"...");
4532 virtual void Reset() noexcept
override
4534 ValueFlagBase::Reset();
4535 values = defaultValues;
4538 virtual FlagBase *Match(
const EitherFlag &arg)
override
4540 const bool wasMatched = Matched();
4541 auto me = FlagBase::Match(arg);
4542 if (me && !wasMatched)
4549 iterator begin() noexcept
4551 return values.begin();
4554 const_iterator begin() const noexcept
4556 return values.begin();
4559 const_iterator cbegin() const noexcept
4561 return values.cbegin();
4564 iterator end() noexcept
4566 return values.end();
4569 const_iterator end() const noexcept
4571 return values.end();
4574 const_iterator cend() const noexcept
4576 return values.cend();
4590 typename Reader = ValueReader,
4591 template <
typename...>
class Map = detail::unordered_map>
4595 const Map<K, T> map;
4597 const T defaultValue;
4601 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
4603 return detail::MapKeysToStrings(map);
4608 MapFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const Map<K, T> &map_,
const T &defaultValue_,
Options options_):
ValueFlagBase(name_, help_, std::move(matcher_), options_), map(map_), value(defaultValue_), defaultValue(defaultValue_)
4613 MapFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const Map<K, T> &map_,
const T &defaultValue_ = T(),
const bool extraError_ =
false):
MapFlag(group_, name_, help_, std::move(matcher_), map_, defaultValue_, extraError_ ?
Options::Single :
Options::None)
4617 MapFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const Map<K, T> &map_,
Options options_):
MapFlag(group_, name_, help_, std::move(matcher_), map_, T(), options_)
4623 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4625 const std::string &value_ = values_.at(0);
4629 if (!reader(name, value_, key))
4631 error = Error::Parse;
4635 reader(name, value_, key);
4637 auto it = map.find(key);
4638 if (it == std::end(map))
4640 std::ostringstream problem;
4641 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
4644 errorMsg = problem.str();
4650 this->value = it->second;
4689 virtual void Reset() noexcept
override
4691 ValueFlagBase::Reset();
4692 value = defaultValue;
4707 template <
typename...>
class List = detail::vector,
4708 typename Reader = ValueReader,
4709 template <
typename...>
class Map = detail::unordered_map>
4713 using Container = List<T>;
4714 const Map<K, T> map;
4716 const Container defaultValues;
4720 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
4722 return detail::MapKeysToStrings(map);
4726 typedef T value_type;
4727 typedef typename Container::allocator_type allocator_type;
4728 typedef typename Container::pointer pointer;
4729 typedef typename Container::const_pointer const_pointer;
4730 typedef T& reference;
4731 typedef const T& const_reference;
4732 typedef typename Container::size_type size_type;
4733 typedef typename Container::difference_type difference_type;
4734 typedef typename Container::iterator iterator;
4735 typedef typename Container::const_iterator const_iterator;
4736 typedef std::reverse_iterator<iterator> reverse_iterator;
4737 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4739 MapFlagList(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const Map<K, T> &map_,
const Container &defaultValues_ = Container(),
Options options_ = {}):
4740 ValueFlagBase(name_, help_, std::move(matcher_), options_), map(map_), values(defaultValues_), defaultValues(defaultValues_)
4747 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4749 const std::string &value_ = values_.at(0);
4753 if (!reader(name, value_, key))
4755 error = Error::Parse;
4759 reader(name, value_, key);
4761 auto it = map.find(key);
4762 if (it == std::end(map))
4764 std::ostringstream problem;
4765 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
4768 errorMsg = problem.str();
4774 this->values.emplace_back(it->second);
4813 virtual std::string Name()
const override
4815 return name + std::string(
"...");
4818 virtual void Reset() noexcept
override
4820 ValueFlagBase::Reset();
4821 values = defaultValues;
4824 virtual FlagBase *Match(
const EitherFlag &arg)
override
4826 const bool wasMatched = Matched();
4827 auto me = FlagBase::Match(arg);
4828 if (me && !wasMatched)
4835 iterator begin() noexcept
4837 return values.begin();
4840 const_iterator begin() const noexcept
4842 return values.begin();
4845 const_iterator cbegin() const noexcept
4847 return values.cbegin();
4850 iterator end() noexcept
4852 return values.end();
4855 const_iterator end() const noexcept
4857 return values.end();
4860 const_iterator cend() const noexcept
4862 return values.cend();
4873 typename Reader = ValueReader>
4878 const T defaultValue;
4881 Positional(
Group &group_,
const std::string &name_,
const std::string &help_,
const T &defaultValue_ = T(),
Options options_ = {}):
PositionalBase(name_, help_, options_), value(defaultValue_), defaultValue(defaultValue_)
4892 virtual void ParseValue(
const std::string &value_)
override
4895 if (!reader(name, value_, this->value))
4897 error = Error::Parse;
4901 reader(name, value_, this->value);
4942 virtual void Reset() noexcept
override
4944 PositionalBase::Reset();
4945 value = defaultValue;
4957 template <
typename...>
class List = detail::vector,
4958 typename Reader = ValueReader>
4962 using Container = List<T>;
4964 const Container defaultValues;
4968 typedef T value_type;
4969 typedef typename Container::allocator_type allocator_type;
4970 typedef typename Container::pointer pointer;
4971 typedef typename Container::const_pointer const_pointer;
4972 typedef T& reference;
4973 typedef const T& const_reference;
4974 typedef typename Container::size_type size_type;
4975 typedef typename Container::difference_type difference_type;
4976 typedef typename Container::iterator iterator;
4977 typedef typename Container::const_iterator const_iterator;
4978 typedef std::reverse_iterator<iterator> reverse_iterator;
4979 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4981 PositionalList(
Group &group_,
const std::string &name_,
const std::string &help_,
const Container &defaultValues_ = Container(),
Options options_ = {}):
PositionalBase(name_, help_, options_), values(defaultValues_), defaultValues(defaultValues_)
4992 virtual void ParseValue(
const std::string &value_)
override
4996 if (!reader(name, value_, v))
4998 error = Error::Parse;
5002 reader(name, value_, v);
5004 values.insert(std::end(values), v);
5008 virtual std::string Name()
const override
5010 return name + std::string(
"...");
5048 virtual void Reset() noexcept
override
5050 PositionalBase::Reset();
5051 values = defaultValues;
5054 virtual PositionalBase *GetNextPositional()
override
5056 const bool wasMatched = Matched();
5057 auto me = PositionalBase::GetNextPositional();
5058 if (me && !wasMatched)
5065 iterator begin() noexcept
5067 return values.begin();
5070 const_iterator begin() const noexcept
5072 return values.begin();
5075 const_iterator cbegin() const noexcept
5077 return values.cbegin();
5080 iterator end() noexcept
5082 return values.end();
5085 const_iterator end() const noexcept
5087 return values.end();
5090 const_iterator cend() const noexcept
5092 return values.cend();
5106 typename Reader = ValueReader,
5107 template <
typename...>
class Map = detail::unordered_map>
5111 const Map<K, T> map;
5113 const T defaultValue;
5117 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
5119 return detail::MapKeysToStrings(map);
5124 MapPositional(
Group &group_,
const std::string &name_,
const std::string &help_,
const Map<K, T> &map_,
const T &defaultValue_ = T(),
Options options_ = {}):
5125 PositionalBase(name_, help_, options_), map(map_), value(defaultValue_), defaultValue(defaultValue_)
5132 virtual void ParseValue(
const std::string &value_)
override
5136 if (!reader(name, value_, key))
5138 error = Error::Parse;
5142 reader(name, value_, key);
5144 auto it = map.find(key);
5145 if (it == std::end(map))
5147 std::ostringstream problem;
5148 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
5151 errorMsg = problem.str();
5157 this->value = it->second;
5198 virtual void Reset() noexcept
override
5200 PositionalBase::Reset();
5201 value = defaultValue;
5216 template <
typename...>
class List = detail::vector,
5217 typename Reader = ValueReader,
5218 template <
typename...>
class Map = detail::unordered_map>
5222 using Container = List<T>;
5224 const Map<K, T> map;
5226 const Container defaultValues;
5230 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
5232 return detail::MapKeysToStrings(map);
5236 typedef T value_type;
5237 typedef typename Container::allocator_type allocator_type;
5238 typedef typename Container::pointer pointer;
5239 typedef typename Container::const_pointer const_pointer;
5240 typedef T& reference;
5241 typedef const T& const_reference;
5242 typedef typename Container::size_type size_type;
5243 typedef typename Container::difference_type difference_type;
5244 typedef typename Container::iterator iterator;
5245 typedef typename Container::const_iterator const_iterator;
5246 typedef std::reverse_iterator<iterator> reverse_iterator;
5247 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
5249 MapPositionalList(
Group &group_,
const std::string &name_,
const std::string &help_,
const Map<K, T> &map_,
const Container &defaultValues_ = Container(),
Options options_ = {}):
5250 PositionalBase(name_, help_, options_), map(map_), values(defaultValues_), defaultValues(defaultValues_)
5257 virtual void ParseValue(
const std::string &value_)
override
5261 if (!reader(name, value_, key))
5263 error = Error::Parse;
5267 reader(name, value_, key);
5269 auto it = map.find(key);
5270 if (it == std::end(map))
5272 std::ostringstream problem;
5273 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
5276 errorMsg = problem.str();
5282 this->values.emplace_back(it->second);
5322 virtual std::string Name()
const override
5324 return name + std::string(
"...");
5327 virtual void Reset() noexcept
override
5329 PositionalBase::Reset();
5330 values = defaultValues;
5333 virtual PositionalBase *GetNextPositional()
override
5335 const bool wasMatched = Matched();
5336 auto me = PositionalBase::GetNextPositional();
5337 if (me && !wasMatched)
5344 iterator begin() noexcept
5346 return values.begin();
5349 const_iterator begin() const noexcept
5351 return values.begin();
5354 const_iterator cbegin() const noexcept
5356 return values.cbegin();
5359 iterator end() noexcept
5361 return values.end();
5364 const_iterator end() const noexcept
5366 return values.end();
5369 const_iterator cend() const noexcept
5371 return values.cend();
5376#pragma pop_macro("min")
5377#pragma pop_macro("max")
A flag class that calls a function when it's matched.
Definition args.hxx:3884
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:3910
virtual void ParseValue(const std::vector< std::string > &value) override
Parse values of this option.
Definition args.hxx:3913
The main user facing command line argument parser class.
Definition args.hxx:2707
const std::string & ShortPrefix() const
The prefix for short flags.
Definition args.hxx:3442
void SetArgumentSeparations(const bool allowJoinedShortValue_, const bool allowJoinedLongValue_, const bool allowSeparateShortValue_, const bool allowSeparateLongValue_)
Change allowed option separation.
Definition args.hxx:3508
void Prog(const std::string &prog_)
The program name for help generation.
Definition args.hxx:3425
It ParseArgs(It begin, It end)
Parse all arguments.
Definition args.hxx:3664
const std::string & Prog() const
The program name for help generation.
Definition args.hxx:3421
void LongPrefix(const std::string &longprefix_)
The prefix for long flags.
Definition args.hxx:3434
void LongSeparator(const std::string &longseparator_)
The separator for long flags.
Definition args.hxx:3458
void Help(std::ostream &help_) const
Pass the help menu into an ostream.
Definition args.hxx:3525
const std::string & LongPrefix() const
The prefix for long flags.
Definition args.hxx:3430
const std::string & LongSeparator() const
The separator for long flags.
Definition args.hxx:3454
bool ParseCLI(const int argc, const char *const *argv)
Convenience function to parse the CLI from argc and argv.
Definition args.hxx:3695
const std::string & Terminator() const
The terminator that forcibly separates flags from positionals.
Definition args.hxx:3478
auto ParseArgs(const T &args) -> decltype(std::begin(args))
Parse all arguments.
Definition args.hxx:3684
void Terminator(const std::string &terminator_)
The terminator that forcibly separates flags from positionals.
Definition args.hxx:3482
void GetArgumentSeparations(bool &allowJoinedShortValue_, bool &allowJoinedLongValue_, bool &allowSeparateShortValue_, bool &allowSeparateLongValue_) const
Get the current argument separation parameters.
Definition args.hxx:3489
std::string Help() const
Generate a help menu as a string.
Definition args.hxx:3643
void ShortPrefix(const std::string &shortprefix_)
The prefix for short flags.
Definition args.hxx:3446
std::string ParseArgsValues(FlagBase &flag, const std::string &arg, It &it, It end, const bool allowSeparate, const bool allowJoined, const bool hasJoined, const std::string &joinedArg, const bool canDiscardJoined, std::vector< std::string > &values)
(INTERNAL) Parse flag's values
Definition args.hxx:2795
Base class for all match types.
Definition args.hxx:1010
void KickOut(bool kickout_) noexcept
Sets a kick-out value for building subparsers.
Definition args.hxx:1110
bool KickOut() const noexcept
Gets the kick-out value for building subparsers.
Definition args.hxx:1123
Main class for building subparsers.
Definition args.hxx:2167
const std::string & Name() const
The name of command.
Definition args.hxx:2302
virtual PositionalBase * GetNextPositional() override
Get the next ready positional, or nullptr if there is none.
Definition args.hxx:2403
const std::string & ProglinePostfix() const
The description that appears on the prog line after options.
Definition args.hxx:2272
void Description(const std::string &description_)
The description that appears above options.
Definition args.hxx:2287
virtual bool HasPositional() const override
Get whether this has any PositionalBase children.
Definition args.hxx:2439
const std::string & Description() const
The description that appears above options.
Definition args.hxx:2282
const std::string & Help() const
The description of command.
Definition args.hxx:2307
void Epilog(const std::string &epilog_)
The description that appears below options.
Definition args.hxx:2297
void ProglinePostfix(const std::string &proglinePostfix_)
The description that appears on the prog line after options.
Definition args.hxx:2277
virtual FlagBase * Match(const EitherFlag &flag) override
Return the first FlagBase that matches flag, or nullptr.
Definition args.hxx:2339
virtual bool HasCommand() const override
Get whether this has any Command children.
Definition args.hxx:2444
virtual std::vector< std::string > GetProgramLine(const HelpParams ¶ms) const override
Get the names of positional parameters.
Definition args.hxx:2508
virtual bool HasFlag() const override
Get whether this has any FlagBase children.
Definition args.hxx:2434
virtual std::vector< std::tuple< std::string, std::string, unsigned > > GetDescription(const HelpParams ¶ms, const unsigned int indent) const override
Get all the child descriptions for help generation.
Definition args.hxx:2533
const std::string & Epilog() const
The description that appears below options.
Definition args.hxx:2292
virtual bool Matched() const noexcept override
Whether or not this group matches validation.
Definition args.hxx:2320
void RequireCommand(bool value)
If value is true, parser will fail if no command was parsed.
Definition args.hxx:2314
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:1491
std::string Get() noexcept
Get the completion reply.
Definition args.hxx:1562
virtual void ParseValue(const std::vector< std::string > &value_) override
Parse values of this option.
Definition args.hxx:1496
An exception that contains autocompletion reply.
Definition args.hxx:559
A boolean flag containing a retrievable constant.
Definition args.hxx:4254
A flag class that simply counts the number of times it's matched.
Definition args.hxx:3828
int & Get() noexcept
Get the count.
Definition args.hxx:3861
Base error class.
Definition args.hxx:478
Base class for all flag options.
Definition args.hxx:1302
virtual void ParseValue(const std::vector< std::string > &value)=0
Parse values of this option.
virtual Nargs NumberOfArguments() const noexcept=0
Defines how many values can be consumed by this option.
Boolean argument matcher.
Definition args.hxx:3766
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:3786
virtual void ParseValue(const std::vector< std::string > &) override
Parse values of this option.
Definition args.hxx:3791
bool Get() const
Get whether this was matched.
Definition args.hxx:3781
Class for using global options in ArgumentParser.
Definition args.hxx:2086
Class for all kinds of validating groups, including ArgumentParser.
Definition args.hxx:1640
virtual bool HasCommand() const override
Get whether this has any Command children.
Definition args.hxx:1820
std::vector< Base * >::size_type MatchedChildren() const
Count the number of matched children this group has.
Definition args.hxx:1827
virtual bool HasPositional() const override
Get whether this has any PositionalBase children.
Definition args.hxx:1811
virtual std::vector< std::string > GetProgramLine(const HelpParams ¶ms) const override
Get the names of positional parameters.
Definition args.hxx:1915
Group(Group &group_, const std::string &help_=std::string(), const std::function< bool(const Group &)> &validator_=Validators::DontCare, Options options_={})
If help is empty, this group will not be printed in help output.
Definition args.hxx:1704
void SignalDetectDuplicates()
Sends a signal to the root of the tree to begin checking for duplicates.
Definition args.hxx:1967
virtual bool HasFlag() const override
Get whether this has any FlagBase children.
Definition args.hxx:1802
Group(const std::string &help_=std::string(), const std::function< bool(const Group &)> &validator_=Validators::DontCare, Options options_={})
If help is empty, this group will not be printed in help output.
Definition args.hxx:1699
virtual bool Matched() const noexcept override
Whether or not this group matches validation.
Definition args.hxx:1871
void DetectDuplicateFlags(std::unordered_set< char > &usedShortFlags, std::unordered_set< std::string > &usedLongFlags)
Used by parameterless DetectDuplicateFlags.
Definition args.hxx:1986
virtual FlagBase * Match(const EitherFlag &flag) override
Return the first FlagBase that matches flag, or nullptr.
Definition args.hxx:1751
bool Get() const
Get validation.
Definition args.hxx:1878
const std::vector< Base * > & Children() const
Get all this group's children.
Definition args.hxx:1741
std::vector< Base * > GetMatchedChildren() const
Get the list of children which were matched.
Definition args.hxx:1836
void DetectDuplicateFlags()
Detect duplicate flags.
Definition args.hxx:1977
void Add(Base &child)
Append a child to this Group.
Definition args.hxx:1713
std::vector< ChildType * > GetFilteredChildren(bool matching=false) const
Gets the children which are a certain type.
Definition args.hxx:1852
virtual std::vector< std::tuple< std::string, std::string, unsigned > > GetDescription(const HelpParams ¶ms, const unsigned int indent) const override
Get all the child descriptions for help generation.
Definition args.hxx:1885
virtual PositionalBase * GetNextPositional() override
Get the next ready positional, or nullptr if there is none.
Definition args.hxx:1786
Help flag class.
Definition args.hxx:3801
bool Get() const noexcept
Get whether this was matched.
Definition args.hxx:3819
virtual void ParseValue(const std::vector< std::string > &)
Parse values of this option.
Definition args.hxx:3807
An exception that indicates that the user has requested help.
Definition args.hxx:541
An optional argument-accepting flag class.
Definition args.hxx:4208
virtual void ParseValue(const std::vector< std::string > &value_) override
Parse values of this option.
Definition args.hxx:4236
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:4231
Errors in map lookups.
Definition args.hxx:523
A mapping value flag list class.
Definition args.hxx:4711
Container * operator->() noexcept
Get the values.
Definition args.hxx:4801
Container & Get() noexcept
Get the value.
Definition args.hxx:4780
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4747
Container & operator*() noexcept
Get the value.
Definition args.hxx:4787
A mapping value flag class.
Definition args.hxx:4593
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4623
T & Get() noexcept
Get the value.
Definition args.hxx:4656
T * operator->() noexcept
Get the value.
Definition args.hxx:4677
T & operator*() noexcept
Get the value.
Definition args.hxx:4663
A positional argument mapping list class.
Definition args.hxx:5220
Container & operator*() noexcept
Get the value.
Definition args.hxx:5296
Container * operator->() noexcept
Get the values.
Definition args.hxx:5310
Container & Get() noexcept
Get the value.
Definition args.hxx:5289
A positional argument mapping class.
Definition args.hxx:5109
T * operator->() noexcept
Get the value.
Definition args.hxx:5186
T & Get() noexcept
Get the value.
Definition args.hxx:5165
T & operator*() noexcept
Get the value.
Definition args.hxx:5172
A class of "matchers", specifying short and flags that can possibly be matched.
Definition args.hxx:627
EitherFlag GetShortOrAny() const
(INTERNAL) Get short flag if it exists or any long flag
Definition args.hxx:745
std::vector< EitherFlag > GetFlagStrings() const
(INTERNAL) Get all flag strings as a vector, with the prefixes embedded
Definition args.hxx:710
Matcher(Short &&shortIn, Long &&longIn)
Specify short and long flags separately as iterables.
Definition args.hxx:663
Matcher(ShortIt shortFlagsStart, ShortIt shortFlagsEnd, LongIt longFlagsStart, LongIt longFlagsEnd)
Specify short and long flags separately as iterators.
Definition args.hxx:638
bool Match(const std::string &flag) const
(INTERNAL) Check if there is a match of a long flag
Definition args.hxx:696
EitherFlag GetLongOrAny() const
(INTERNAL) Get long flag if it exists or any short flag
Definition args.hxx:727
bool Match(const char flag) const
(INTERNAL) Check if there is a match of a short flag
Definition args.hxx:689
bool Match(const EitherFlag &flag) const
(INTERNAL) Check if there is a match of a flag
Definition args.hxx:703
Matcher(std::initializer_list< EitherFlag > in)
Specify a mixed single initializer-list of both short and long flags.
Definition args.hxx:679
Base class for all match types that have a name.
Definition args.hxx:1155
void HelpDefault(const std::string &str)
Sets default value string that will be added to argument description.
Definition args.hxx:1191
void HelpChoices(const std::vector< std::string > &array)
Sets choices strings that will be added to argument description.
Definition args.hxx:1207
std::string HelpDefault(const HelpParams ¶ms) const
Gets default value string that will be added to argument description.
Definition args.hxx:1199
std::vector< std::string > HelpChoices(const HelpParams ¶ms) const
Gets choices strings that will be added to argument description.
Definition args.hxx:1215
A variadic arguments accepting flag class.
Definition args.hxx:4296
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:4328
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4333
List< T > * operator->() noexcept
Get the values.
Definition args.hxx:4374
List< T > & operator*() noexcept
Get the value.
Definition args.hxx:4360
Errors that occur during regular parsing.
Definition args.hxx:496
Base class for positional options.
Definition args.hxx:1580
A positional argument class that pushes the found values into a list.
Definition args.hxx:4960
Container & operator*() noexcept
Get the value.
Definition args.hxx:5022
Container & Get() noexcept
Get the values.
Definition args.hxx:5015
Container * operator->() noexcept
Get the values.
Definition args.hxx:5036
A positional argument class.
Definition args.hxx:4875
T & operator*() noexcept
Get the value.
Definition args.hxx:4916
T & Get() noexcept
Get the value.
Definition args.hxx:4909
T * operator->() noexcept
Get the value.
Definition args.hxx:4930
Errors that when a required flag is omitted.
Definition args.hxx:514
Utility class for building subparsers with coroutines/callbacks.
Definition args.hxx:2112
void Parse()
Continue parsing arguments for new command.
Definition args.hxx:3729
const std::vector< std::string > & KickedOut() const noexcept
Returns a vector of kicked out arguments.
Definition args.hxx:2156
bool IsParsed() const
(INTERNAL) Determines whether Parse was called or not.
Definition args.hxx:2143
Errors that occur during usage.
Definition args.hxx:487
Errors that are detected from group validation after parsing finishes.
Definition args.hxx:505
Base class for value-accepting flag options.
Definition args.hxx:1464
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:1470
An argument-accepting flag class that pushes the found values into a list.
Definition args.hxx:4445
Container * operator->() noexcept
Get the values.
Definition args.hxx:4515
Container & Get() noexcept
Get the values.
Definition args.hxx:4494
Container & operator*() noexcept
Get the value.
Definition args.hxx:4501
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4475
An argument-accepting flag class.
Definition args.hxx:4106
T & operator*() noexcept
Get the value.
Definition args.hxx:4165
T * operator->() noexcept
Get the value.
Definition args.hxx:4179
T & Get() noexcept
Get the value.
Definition args.hxx:4158
const T & GetDefault() noexcept
Get the default value.
Definition args.hxx:4193
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4136
contains all the functionality of the args library
std::vector< std::string > Wrap(It begin, It end, const std::string::size_type width, std::string::size_type firstlinewidth=0, std::string::size_type firstlineindent=0)
(INTERNAL) Wrap a vector of words into a vector of lines
Definition args.hxx:277
bool SafeAdd(T a, T b, T &out) noexcept
Safe addition to prevent integer overflow.
Definition args.hxx:108
bool SafeMultiply(T a, T b, T &out) noexcept
Safe multiplication to prevent integer overflow.
Definition args.hxx:148
bool SafeSub(T a, T b, T &out) noexcept
Safe subtraction to prevent integer underflow.
Definition args.hxx:202
Options
Attributes for flags.
Definition args.hxx:765
@ HiddenFromCompletion
Flag is excluded from auto completion.
@ Global
Flag is global and can be used in any subcommand.
@ Single
Flag can't be passed multiple times.
@ HiddenFromUsage
Flag is excluded from usage line.
@ Hidden
Flag is excluded from options help and usage line.
@ Required
Flag can't be omitted.
@ KickOut
Flag stops a parser.
@ HiddenFromDescription
Flag is excluded from options help.
std::enable_if< std::is_unsigned< T >::value, bool >::type SafeNeg(T a, T &out) noexcept
Safe negation to prevent integer overflow.
Definition args.hxx:240
auto get(Option &option_) -> decltype(option_.Get())
Getter to grab the value from the argument type.
Definition args.hxx:78
std::string::size_type Glyphs(const std::string &string_)
(INTERNAL) Count UTF-8 glyphs
Definition args.hxx:91
A simple unified option type for unified initializer lists for the Matcher class.
Definition args.hxx:569
static std::unordered_set< char > GetShort(std::initializer_list< EitherFlag > flags)
Get just the short flags from an initializer list of EitherFlags.
Definition args.hxx:594
static std::unordered_set< std::string > GetLong(std::initializer_list< EitherFlag > flags)
Get just the long flags from an initializer list of EitherFlags.
Definition args.hxx:579
Default validators.
Definition args.hxx:1650
A simple structure of parameters for easy user-modifyable help menus.
Definition args.hxx:821
std::string programName
The program name for help generation.
Definition args.hxx:878
bool showCommandFullHelp
Show command's descriptions and epilog.
Definition args.hxx:886
bool proglineShowFlags
Show flags in program line.
Definition args.hxx:922
std::string usageString
Program line prefix.
Definition args.hxx:930
unsigned int width
The width of the help menu.
Definition args.hxx:824
std::string proglineNonrequiredClose
The postfix for progline non-required argument.
Definition args.hxx:918
unsigned int helpindent
The indent of the flag descriptions.
Definition args.hxx:839
bool proglinePreferShortFlags
Use short flags in program lines when possible.
Definition args.hxx:926
std::string proglineCommand
The prefix for progline when command has any subcommands.
Definition args.hxx:894
std::string proglineOptions
The postfix for progline when showProglineOptions is true and command has any flags.
Definition args.hxx:890
std::string longSeparator
The separator for long flags.
Definition args.hxx:874
bool showValueName
Show value name.
Definition args.hxx:942
bool showTerminator
Show the terminator when both options and positional parameters are present.
Definition args.hxx:850
std::string proglineValueOpen
The prefix for progline value.
Definition args.hxx:898
std::string valueOpen
The prefix for option value.
Definition args.hxx:950
unsigned int progtailindent
The indent of the program trailing lines for long parameters.
Definition args.hxx:830
std::string proglineNonrequiredOpen
The prefix for progline non-required argument.
Definition args.hxx:914
unsigned int descriptionindent
The indent of the description and epilogs.
Definition args.hxx:833
bool showCommandChildren
Show command's flags.
Definition args.hxx:882
bool showProglineOptions
Show the {OPTIONS} on the prog line when this is true.
Definition args.hxx:854
std::string valueClose
The postfix for option value.
Definition args.hxx:954
std::string longPrefix
The prefix for long flags.
Definition args.hxx:866
std::string proglineRequiredClose
The postfix for progline required argument.
Definition args.hxx:910
unsigned int flagindent
The indent of the flags.
Definition args.hxx:836
std::string optionsString
String shown in help before flags descriptions.
Definition args.hxx:934
bool addNewlineBeforeDescription
Add newline before flag description.
Definition args.hxx:946
std::string shortPrefix
The prefix for short flags.
Definition args.hxx:862
bool addDefault
Add default values to argument description.
Definition args.hxx:966
unsigned int gutter
The minimum gutter between each flag and its help.
Definition args.hxx:846
bool showProglinePositionals
Show the positionals on the prog line when this is true.
Definition args.hxx:858
std::string shortSeparator
The separator for short flags.
Definition args.hxx:870
std::string proglineValueClose
The postfix for progline value.
Definition args.hxx:902
bool useValueNameOnce
Display value name after all the long and short flags.
Definition args.hxx:938
std::string defaultString
The prefix for default values.
Definition args.hxx:970
std::string proglineRequiredOpen
The prefix for progline required argument.
Definition args.hxx:906
unsigned int eachgroupindent
The additional indent each group adds.
Definition args.hxx:842
unsigned int progindent
The indent of the program line.
Definition args.hxx:827
bool addChoices
Add choices to argument description.
Definition args.hxx:958
std::string choiceString
The prefix for choices.
Definition args.hxx:962
A number of arguments which can be consumed by an option.
Definition args.hxx:978
A default Reader class for argument classes.
Definition args.hxx:3924