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 SignalDetectDuplicates();
1736 for (
Base *child: Children())
1738 if (
FlagBase *match = child->Match(flag))
1746 virtual std::vector<FlagBase*> GetAllFlags()
override
1748 std::vector<FlagBase*> res;
1749 for (
Base *child: Children())
1751 auto childRes = child->GetAllFlags();
1752 res.insert(res.end(), childRes.begin(), childRes.end());
1757 virtual void Validate(
const std::string &shortPrefix,
const std::string &longPrefix)
const override
1759 for (Base *child: Children())
1761 child->Validate(shortPrefix, longPrefix);
1771 for (
Base *child: Children())
1773 if (
auto next = child->GetNextPositional())
1787 return std::any_of(Children().begin(), Children().end(), [](
Base *child) {
return child->HasFlag(); });
1796 return std::any_of(Children().begin(), Children().end(), [](
Base *child) {
return child->HasPositional(); });
1805 return std::any_of(Children().begin(), Children().end(), [](
Base *child) {
return child->HasCommand(); });
1813 return static_cast<std::vector<Base *>::size_type
>(
1814 std::count_if(std::begin(Children()), std::end(Children()), [](
const Base *child){
return child->Matched();}));
1822 std::vector<Base*> matched_children;
1823 std::copy_if(children.begin(), children.end(), std::back_inserter(matched_children), [](
Base* b){
1824 return b->Matched();
1826 return matched_children;
1834 template <
typename ChildType>
1837 std::vector<ChildType *> filtered_children;
1838 for(
Base *child : children) {
1839 if(!matching || child->Matched())
1841 ChildType* cast_result =
dynamic_cast<ChildType*
>(child);
1842 if(cast_result !=
nullptr)
1844 filtered_children.push_back(cast_result);
1849 return filtered_children;
1856 return validator(*
this);
1868 virtual std::vector<std::tuple<std::string, std::string, unsigned>>
GetDescription(
const HelpParams ¶ms,
const unsigned int indent)
const override
1870 std::vector<std::tuple<std::string, std::string, unsigned int>> descriptions;
1873 unsigned addindent = 0;
1876 descriptions.emplace_back(help,
"", indent);
1880 for (
Base *child: Children())
1882 if ((child->GetOptions() & Options::HiddenFromDescription) != Options::None)
1887 auto groupDescriptions = child->GetDescription(params, indent + addindent);
1888 descriptions.insert(
1889 std::end(descriptions),
1890 std::make_move_iterator(std::begin(groupDescriptions)),
1891 std::make_move_iterator(std::end(groupDescriptions)));
1893 return descriptions;
1900 std::vector <std::string> names;
1901 for (
Base *child: Children())
1903 if ((child->GetOptions() & Options::HiddenFromUsage) != Options::None)
1908 auto groupNames = child->GetProgramLine(params);
1911 std::make_move_iterator(std::begin(groupNames)),
1912 std::make_move_iterator(std::end(groupNames)));
1917 virtual std::vector<Command*> GetCommands()
override
1919 std::vector<Command*> res;
1920 for (
const auto &child : Children())
1922 auto subparsers = child->GetCommands();
1923 res.insert(std::end(res), std::begin(subparsers), std::end(subparsers));
1928 virtual bool IsGroup()
const override
1933 virtual void Reset() noexcept
override
1937 for (
auto &child: Children())
1942 error = Error::None;
1953 else DetectDuplicateFlags();
1962 std::unordered_set<char> usedShortFlags;
1963 std::unordered_set<std::string> usedLongFlags;
1964 DetectDuplicateFlags(usedShortFlags, usedLongFlags);
1969 void DetectDuplicateFlags(std::unordered_set<char> &usedShortFlags, std::unordered_set<std::string> &usedLongFlags)
1971 for (
Base *child: Children())
1973 if(
auto flag =
dynamic_cast<FlagBase*
>(child))
1977 for(
EitherFlag flagString: flag->GetMatcher().GetFlagStrings())
1979 if(flagString.isShort)
1981 if(usedShortFlags.count(flagString.shortFlag))
1984 flag->SetUsageError();
1986 throw ParseError(
"duplicate short flag detected");
1991 usedShortFlags.insert(flagString.shortFlag);
1996 if(usedLongFlags.count(flagString.longFlag))
1999 flag->SetUsageError();
2001 throw ParseError(
"duplicate long flag detected");
2006 usedLongFlags.insert(flagString.longFlag);
2011 else if(
auto group =
dynamic_cast<Group*
>(child))
2018 if(group->IsGroup())
2020 group->DetectDuplicateFlags(usedShortFlags, usedLongFlags);
2028 virtual Error GetError()
const override
2030 if (error != Error::None)
2035 auto it = std::find_if(Children().begin(), Children().end(), [](
const Base *child){
return child->GetError() != Error::None;});
2036 if (it == Children().end())
2041 return (*it)->GetError();
2046 virtual std::string GetErrorMsg()
const override
2048 if (error != Error::None)
2053 auto it = std::find_if(Children().begin(), Children().end(), [](
const Base *child){
return child->GetError() != Error::None;});
2054 if (it == Children().end())
2059 return (*it)->GetErrorMsg();
2097 std::vector<std::string>
args;
2098 std::vector<std::string> kicked;
2102 bool isParsed =
false;
2106 :
Group({}, Validators::AllChildGroups),
args(std::move(args_)), parser(&parser_), helpParams(helpParams_), command(command_)
2156 std::string description;
2158 std::string proglinePostfix;
2160 std::function<void(
Subparser&)> parserCoroutine;
2161 bool commandIsRequired =
true;
2162 Command *selectedCommand =
nullptr;
2164 mutable std::vector<std::tuple<std::string, std::string, unsigned>> subparserDescription;
2165 mutable std::vector<std::string> subparserProgramLine;
2166 mutable bool subparserHasFlag =
false;
2167 mutable bool subparserHasPositional =
false;
2168 mutable bool subparserHasCommand =
false;
2170 mutable Error subparserError = Error::None;
2179 RaiiSubparser(
ArgumentParser &parser_, std::vector<std::string> args_);
2184 command.subparser = oldSubparser;
2200 std::function<void(
Subparser&)> &GetCoroutine()
2202 return selectedCommand !=
nullptr ? selectedCommand->GetCoroutine() : parserCoroutine;
2208 while (res->selectedCommand !=
nullptr)
2210 res = res->selectedCommand;
2216 const Command &SelectedCommand()
const
2219 while (res->selectedCommand !=
nullptr)
2221 res = res->selectedCommand;
2227 void UpdateSubparserHelp(
const HelpParams ¶ms)
const
2229 if (parserCoroutine)
2231 RaiiSubparser coro(*
this, params);
2232#ifndef ARGS_NOEXCEPT
2235 parserCoroutine(coro.Parser());
2237 catch (args::SubparserError&)
2241 parserCoroutine(coro.Parser());
2247 Command(
Group &base_, std::string name_, std::string help_, std::function<
void(
Subparser&)> coroutine_ = {})
2248 : name(std::move(name_)), help(std::move(help_)), parserCoroutine(std::move(coroutine_))
2256 {
return proglinePostfix; }
2261 { this->proglinePostfix = proglinePostfix_; }
2266 {
return description; }
2271 { this->description = description_; }
2281 { this->epilog = epilog_; }
2298 { commandIsRequired = value; }
2300 virtual bool IsGroup()
const override
2304 {
return Base::Matched(); }
2306 operator bool() const noexcept
2307 {
return Matched(); }
2309 void Match() noexcept
2312 void SelectCommand(Command *c)
noexcept
2314 selectedCommand = c;
2324 if (selectedCommand !=
nullptr)
2326 if (
auto *res = selectedCommand->Match(flag))
2331 for (
auto *child: Children())
2333 if ((child->GetOptions() & Options::Global) != Options::None)
2335 if (
auto *res = child->Match(flag))
2345 if (subparser !=
nullptr)
2347 return subparser->
Match(flag);
2350 return Matched() ? Group::Match(flag) :
nullptr;
2353 virtual std::vector<FlagBase*> GetAllFlags()
override
2355 std::vector<FlagBase*> res;
2362 for (
auto *child: Children())
2364 if (selectedCommand ==
nullptr || (child->GetOptions() & Options::Global) != Options::None)
2366 auto childFlags = child->GetAllFlags();
2367 res.insert(res.end(), childFlags.begin(), childFlags.end());
2371 if (selectedCommand !=
nullptr)
2373 auto childFlags = selectedCommand->GetAllFlags();
2374 res.insert(res.end(), childFlags.begin(), childFlags.end());
2377 if (subparser !=
nullptr)
2379 auto childFlags = subparser->GetAllFlags();
2380 res.insert(res.end(), childFlags.begin(), childFlags.end());
2388 if (selectedCommand !=
nullptr)
2395 for (
auto *child: Children())
2397 if ((child->GetOptions() & Options::Global) != Options::None)
2399 if (
auto *res = child->GetNextPositional())
2409 if (subparser !=
nullptr)
2414 return Matched() ? Group::GetNextPositional() :
nullptr;
2419 return subparserHasFlag || Group::HasFlag();
2424 return subparserHasPositional || Group::HasPositional();
2432 std::vector<std::string> GetCommandProgramLine(
const HelpParams ¶ms)
const
2434 UpdateSubparserHelp(params);
2436 std::vector<std::string> res;
2443 auto group_res = Group::GetProgramLine(params);
2444 std::move(std::move(group_res).begin(), std::move(group_res).end(), std::back_inserter(res));
2446 res.insert(res.end(), subparserProgramLine.begin(), subparserProgramLine.end());
2448 if (!params.
proglineCommand.empty() && (Group::HasCommand() || subparserHasCommand))
2450 res.insert(res.begin(), commandIsRequired ? params.
proglineCommand :
"[" + params.proglineCommand +
"]");
2453 if (!Name().empty())
2455 res.insert(res.begin(), Name());
2458 if (!ProglinePostfix().empty())
2461 for (
auto c : ProglinePostfix())
2463 if (std::isspace(
static_cast<unsigned char>(c)))
2467 res.push_back(line);
2473 res.push_back(
"\n");
2484 res.push_back(line);
2498 return GetCommandProgramLine(params);
2501 virtual std::vector<Command*> GetCommands()
override
2503 if (selectedCommand !=
nullptr)
2505 return selectedCommand->GetCommands();
2510 return Group::GetCommands();
2516 virtual std::vector<std::tuple<std::string, std::string, unsigned>>
GetDescription(
const HelpParams ¶ms,
const unsigned int indent)
const override
2518 std::vector<std::tuple<std::string, std::string, unsigned>> descriptions;
2519 unsigned addindent = 0;
2521 UpdateSubparserHelp(params);
2527 std::ostringstream s;
2529 for (
const auto &progline: GetCommandProgramLine(params))
2543 descriptions.emplace_back(s.str(),
"", indent);
2547 descriptions.emplace_back(Name(), help, indent);
2552 return descriptions;
2560 descriptions.emplace_back(
"",
"", indent + addindent);
2561 descriptions.emplace_back(Description().empty() ?
Help() : Description(),
"", indent + addindent);
2562 descriptions.emplace_back(
"",
"", indent + addindent);
2565 for (
Base *child: Children())
2567 if ((child->GetOptions() & Options::HiddenFromDescription) != Options::None)
2572 auto groupDescriptions = child->GetDescription(params, indent + addindent);
2573 descriptions.insert(
2574 std::end(descriptions),
2575 std::make_move_iterator(std::begin(groupDescriptions)),
2576 std::make_move_iterator(std::end(groupDescriptions)));
2579 for (
auto childDescription: subparserDescription)
2581 std::get<2>(childDescription) += indent + addindent;
2582 descriptions.push_back(std::move(childDescription));
2587 descriptions.emplace_back(
"",
"", indent + addindent);
2588 if (!Epilog().empty())
2590 descriptions.emplace_back(Epilog(),
"", indent + addindent);
2591 descriptions.emplace_back(
"",
"", indent + addindent);
2595 return descriptions;
2598 virtual void Validate(
const std::string &shortprefix,
const std::string &longprefix)
const override
2605 auto onValidationError = [&]
2607 std::ostringstream problem;
2608 problem <<
"Group validation failed somewhere!";
2610 error = Error::Validation;
2611 errorMsg = problem.str();
2613 throw ValidationError(problem.str());
2617 for (Base *child: Children())
2619 if (child->IsGroup() && !child->Matched())
2621 onValidationError();
2624 child->Validate(shortprefix, longprefix);
2627 if (subparser !=
nullptr)
2629 subparser->Validate(shortprefix, longprefix);
2632 onValidationError();
2636 if (selectedCommand ==
nullptr && commandIsRequired && (Group::HasCommand() || subparserHasCommand))
2638 std::ostringstream problem;
2639 problem <<
"Command is required";
2641 error = Error::Validation;
2642 errorMsg = problem.str();
2644 throw ValidationError(problem.str());
2649 virtual void Reset() noexcept
override
2652 selectedCommand =
nullptr;
2653 subparserProgramLine.clear();
2654 subparserDescription.clear();
2655 subparserHasFlag =
false;
2656 subparserHasPositional =
false;
2657 subparserHasCommand =
false;
2659 subparserError = Error::None;
2665 virtual Error GetError()
const override
2672 if (error != Error::None)
2677 if (subparserError != Error::None)
2679 return subparserError;
2682 return Group::GetError();
2694 std::string longprefix;
2695 std::string shortprefix;
2697 std::string longseparator;
2699 std::string terminator;
2701 bool allowJoinedShortValue =
true;
2702 bool allowJoinedLongValue =
true;
2703 bool allowSeparateShortValue =
true;
2704 bool allowSeparateLongValue =
true;
2706 bool readCompletion =
false;
2710 enum class OptionType
2717 OptionType ParseOption(
const std::string &s,
bool allowEmpty =
false)
2719 const bool matchesLong = s.find(longprefix) == 0 && (allowEmpty || s.length() > longprefix.length());
2720 const bool matchesShort = s.find(shortprefix) == 0 && (allowEmpty || s.length() > shortprefix.length());
2728 if (matchesLong && matchesShort)
2730 return longprefix.length() >= shortprefix.length() ? OptionType::LongFlag : OptionType::ShortFlag;
2735 return OptionType::LongFlag;
2740 return OptionType::ShortFlag;
2743 return OptionType::Positional;
2746 template <
typename It>
2747 bool Complete(
FlagBase &flag, It it, It end)
2750 if (!readCompletion || (++nextIt != end))
2755 const auto &chunk = *it;
2758 AddCompletionReply(chunk, choice);
2761#ifndef ARGS_NOEXCEPT
2777 template <
typename It>
2779 const bool allowSeparate,
const bool allowJoined,
2780 const bool hasJoined,
const std::string &joinedArg,
2781 const bool canDiscardJoined, std::vector<std::string> &values)
2787 if (hasJoined && !allowJoined && (nargs.min != 0 || !canDiscardJoined))
2789 return "Flag '" + arg +
"' was passed a joined argument, but these are disallowed";
2794 if (!canDiscardJoined || (allowJoined && nargs.max != 0))
2796 values.push_back(joinedArg);
2798 }
else if (!allowSeparate)
2802 return "Flag '" + arg +
"' was passed a separate argument, but these are disallowed";
2810 if (allowSeparate && (!hasJoined || !values.empty()))
2815 while (valueIt != end &&
2816 *valueIt != terminator &&
2817 values.size() < nargs.max &&
2818 (values.size() < nargs.min || ParseOption(*valueIt) == OptionType::Positional))
2820 if (Complete(flag, valueIt, end))
2835 values.push_back(*valueIt);
2841 if (values.size() > nargs.max)
2843 return "Passed an argument into a non-argument flag: " + arg;
2844 }
else if (values.size() < nargs.min)
2846 if (nargs.min == 1 && nargs.max == 1)
2848 return "Flag '" + arg +
"' requires an argument but received none";
2849 }
else if (nargs.min == 1)
2851 return "Flag '" + arg +
"' requires at least one argument but received none";
2852 }
else if (nargs.min != nargs.max)
2854 return "Flag '" + arg +
"' requires at least " + std::to_string(nargs.min) +
2855 " arguments but received " + std::to_string(values.size());
2858 return "Flag '" + arg +
"' requires " + std::to_string(nargs.min) +
2859 " arguments but received " + std::to_string(values.size());
2866 template <
typename It>
2867 bool ParseLong(It &it, It end)
2869 const auto &chunk = *it;
2870 const auto argchunk = chunk.substr(longprefix.size());
2872 const auto separator = longseparator.empty() ? argchunk.npos : argchunk.find(longseparator);
2874 const auto arg = (separator != argchunk.npos ?
2875 std::string(argchunk, 0, separator)
2877 const auto joined = (separator != argchunk.npos ?
2878 argchunk.substr(separator + longseparator.size())
2881 if (
auto flag = Match(arg))
2889 if (flag->GetError() != Error::None)
2894 std::vector<std::string> values;
2895 const std::string errorMessage = ParseArgsValues(*flag, arg, it, end, allowSeparateLongValue, allowJoinedLongValue,
2896 separator != argchunk.npos, joined,
false, values);
2897 if (!errorMessage.empty())
2899#ifndef ARGS_NOEXCEPT
2900 throw ParseError(errorMessage);
2902 error = Error::Parse;
2903 errorMsg = errorMessage;
2908 if (!readCompletion)
2917 if (flag->GetError() != Error::None)
2931 const std::string errorMessage(
"Flag could not be matched: " + arg);
2932#ifndef ARGS_NOEXCEPT
2933 throw ParseError(errorMessage);
2935 error = Error::Parse;
2936 errorMsg = errorMessage;
2944 template <
typename It>
2945 bool ParseShort(It &it, It end)
2947 const auto &chunk = *it;
2948 const auto argchunk = chunk.substr(shortprefix.size());
2949 for (
auto argit = std::begin(argchunk); argit != std::end(argchunk); ++argit)
2951 const auto arg = *argit;
2953 if (
auto flag = Match(arg))
2959 if (flag->GetError() != Error::None)
2964 const std::string value(argit + 1, std::end(argchunk));
2965 std::vector<std::string> values;
2966 const std::string errorMessage = ParseArgsValues(*flag, std::string(1, arg), it, end,
2967 allowSeparateShortValue, allowJoinedShortValue,
2968 !value.empty(), value, !value.empty(), values);
2970 if (!errorMessage.empty())
2972#ifndef ARGS_NOEXCEPT
2973 throw ParseError(errorMessage);
2975 error = Error::Parse;
2976 errorMsg = errorMessage;
2981 if (!readCompletion)
2988 if (flag->GetError() != Error::None)
3001 if (!values.empty())
3007 const std::string errorMessage(
"Flag could not be matched: '" + std::string(1, arg) +
"'");
3008#ifndef ARGS_NOEXCEPT
3009 throw ParseError(errorMessage);
3011 error = Error::Parse;
3012 errorMsg = errorMessage;
3021 bool AddCompletionReply(
const std::string &cur,
const std::string &choice)
3023 if (cur.empty() || choice.find(cur) == 0)
3025 if (completion->syntax ==
"bash" && ParseOption(choice) == OptionType::LongFlag && choice.find(longseparator) != std::string::npos)
3027 completion->reply.push_back(choice.substr(choice.find(longseparator) + longseparator.size()));
3030 completion->reply.push_back(choice);
3038 template <
typename It>
3039 bool Complete(It it, It end,
bool terminated)
3042 if (!readCompletion || (++nextIt != end))
3047 const auto &chunk = *it;
3048 auto pos = GetNextPositional();
3049 std::vector<Command *> commands = GetCommands();
3050 const auto optionType = ParseOption(chunk,
true);
3056 if (!terminated && !commands.empty() && (chunk.empty() || optionType == OptionType::Positional))
3058 for (
auto &cmd : commands)
3060 if ((cmd->GetOptions() & Options::HiddenFromCompletion) == Options::None)
3062 AddCompletionReply(chunk, cmd->Name());
3067 bool hasPositionalCompletion =
true;
3069 if (!terminated && !commands.empty())
3071 for (
auto &cmd : commands)
3073 if ((cmd->GetOptions() & Options::HiddenFromCompletion) == Options::None)
3075 AddCompletionReply(chunk, cmd->Name());
3080 if ((pos->GetOptions() & Options::HiddenFromCompletion) == Options::None)
3082 auto choices = pos->HelpChoices(helpParams);
3083 hasPositionalCompletion = !choices.empty() || optionType != OptionType::Positional;
3084 for (
auto &choice : choices)
3086 AddCompletionReply(chunk, choice);
3091 if (!terminated && hasPositionalCompletion)
3093 auto flags = GetAllFlags();
3094 for (
auto flag : flags)
3096 if ((flag->GetOptions() & Options::HiddenFromCompletion) != Options::None)
3101 auto &matcher = flag->GetMatcher();
3102 if (!AddCompletionReply(chunk, matcher.
GetShortOrAny().str(shortprefix, longprefix)))
3104 for (
auto &flagName : matcher.GetFlagStrings())
3106 if (AddCompletionReply(chunk, flagName.str(shortprefix, longprefix)))
3114 if (optionType == OptionType::LongFlag && allowJoinedLongValue)
3116 const auto separator = longseparator.empty() ? chunk.npos : chunk.find(longseparator);
3130 if (separator != chunk.npos && separator >= longprefix.size())
3132 std::string arg(chunk, 0, separator);
3133 if (
auto flag = this->Match(arg.substr(longprefix.size())))
3135 for (
auto &choice : flag->HelpChoices(helpParams))
3137 AddCompletionReply(chunk, arg + longseparator + choice);
3141 }
else if (optionType == OptionType::ShortFlag && allowJoinedShortValue)
3143 if (chunk.size() > shortprefix.size() + 1)
3145 auto arg = chunk.at(shortprefix.size());
3147 if (
auto flag = this->Match(arg))
3149 for (
auto &choice : flag->HelpChoices(helpParams))
3151 AddCompletionReply(chunk, shortprefix + arg + choice);
3159#ifndef ARGS_NOEXCEPT
3160 throw Completion(completion->
Get());
3166 template <
typename It>
3167 It Parse(It begin, It end)
3169 bool terminated =
false;
3170 std::vector<Command *> commands = GetCommands();
3173 for (
auto it = begin; it != end; ++it)
3175 if (Complete(it, end, terminated))
3180 const auto &chunk = *it;
3182 if (!terminated && chunk == terminator)
3185 }
else if (!terminated && ParseOption(chunk) == OptionType::LongFlag)
3187 if (!ParseLong(it, end))
3191 }
else if (!terminated && ParseOption(chunk) == OptionType::ShortFlag)
3193 if (!ParseShort(it, end))
3197 }
else if (!terminated && !commands.empty())
3199 auto itCommand = std::find_if(commands.begin(), commands.end(), [&chunk](Command *c) { return c->Name() == chunk; });
3200 if (itCommand == commands.end())
3202 const std::string errorMessage(
"Unknown command: " + chunk);
3203#ifndef ARGS_NOEXCEPT
3204 throw ParseError(errorMessage);
3206 error = Error::Parse;
3207 errorMsg = errorMessage;
3212 SelectCommand(*itCommand);
3214 if (
const auto &coroutine = GetCoroutine())
3217 RaiiSubparser coro(*
this, std::vector<std::string>(it, end));
3218 coroutine(coro.Parser());
3221 if (error != Error::None)
3226 if (!coro.Parser().IsParsed())
3228 error = Error::Usage;
3232 if (!coro.Parser().IsParsed())
3234 throw UsageError(
"Subparser::Parse was not called");
3241 commands = GetCommands();
3244 auto pos = GetNextPositional();
3247 pos->ParseValue(chunk);
3249 if (pos->GetError() != Error::None)
3261 const std::string errorMessage(
"Passed in argument, but no positional arguments were ready to receive it: " + chunk);
3262#ifndef ARGS_NOEXCEPT
3263 throw ParseError(errorMessage);
3265 error = Error::Parse;
3266 errorMsg = errorMessage;
3272 if (!readCompletion && completion !=
nullptr && completion->Matched())
3275 if (completion->GetError() != Error::None)
3277 error = completion->GetError();
3278 if (errorMsg.empty())
3280 errorMsg = completion->GetErrorMsg();
3285 error = Error::Completion;
3287 readCompletion =
true;
3289 const auto argsLeft =
static_cast<size_t>(std::distance(it, end));
3290 if (completion->cword == 0 || argsLeft <= 1 || completion->cword >= argsLeft)
3292#ifndef ARGS_NOEXCEPT
3293 throw Completion(
"");
3300 std::vector<std::string> curArgs;
3301 curArgs.reserve(completion->cword);
3303 for (
size_t idx = 0; idx < completion->cword && curIt != end; ++idx, ++curIt)
3305 curArgs.push_back(*curIt);
3308 if (completion->syntax ==
"bash")
3312 for (
size_t idx = 0; idx < curArgs.size(); )
3314 if (idx > 0 && curArgs[idx] ==
"=")
3316 size_t prev_idx = idx - 1;
3317 curArgs[prev_idx] +=
"=";
3318 size_t next_idx = 0;
3319 if (SafeAdd<size_t>(idx,
static_cast<size_t>(1), next_idx) && next_idx < curArgs.size())
3321 curArgs[prev_idx] += curArgs[next_idx];
3323 size_t erase_end = 0;
3324 if (SafeAdd<size_t>(next_idx,
static_cast<size_t>(1), erase_end))
3326 typedef std::vector<std::string>::difference_type diff_t;
3327 curArgs.erase(curArgs.begin() +
static_cast<diff_t
>(idx),
3328 curArgs.begin() +
static_cast<diff_t
>(erase_end));
3333 typedef std::vector<std::string>::difference_type diff_t;
3334 curArgs.erase(curArgs.begin() +
static_cast<diff_t
>(idx));
3344#ifndef ARGS_NOEXCEPT
3347 Parse(curArgs.begin(), curArgs.end());
3348 throw Completion(
"");
3350 catch (Completion &)
3356 throw Completion(
"");
3366 Parse(curArgs.begin(), curArgs.end());
3367 error = Error::Completion;
3374 Validate(shortprefix, longprefix);
3379 HelpParams helpParams;
3381 ArgumentParser(
const std::string &description_,
const std::string &epilog_ = std::string())
3383 Description(description_);
3389 SetArgumentSeparations(
true,
true,
true,
true);
3393 void AddCompletion(CompletionFlag &completionFlag)
3395 completion = &completionFlag;
3396 Add(completionFlag);
3402 {
return helpParams.programName; }
3405 void Prog(
const std::string &prog_)
3406 { this->helpParams.programName = prog_; }
3411 {
return longprefix; }
3416 this->longprefix = longprefix_;
3417 this->helpParams.longPrefix = longprefix_;
3423 {
return shortprefix; }
3428 this->shortprefix = shortprefix_;
3429 this->helpParams.shortPrefix = shortprefix_;
3435 {
return longseparator; }
3440 if (longseparator_.empty())
3442 const std::string errorMessage(
"longseparator can not be set to empty");
3444 error = Error::Usage;
3445 errorMsg = errorMessage;
3451 this->longseparator = longseparator_;
3452 this->helpParams.longSeparator = allowJoinedLongValue ? longseparator :
" ";
3459 {
return terminator; }
3463 { this->terminator = terminator_; }
3470 bool &allowJoinedShortValue_,
3471 bool &allowJoinedLongValue_,
3472 bool &allowSeparateShortValue_,
3473 bool &allowSeparateLongValue_)
const
3475 allowJoinedShortValue_ = this->allowJoinedShortValue;
3476 allowJoinedLongValue_ = this->allowJoinedLongValue;
3477 allowSeparateShortValue_ = this->allowSeparateShortValue;
3478 allowSeparateLongValue_ = this->allowSeparateLongValue;
3489 const bool allowJoinedShortValue_,
3490 const bool allowJoinedLongValue_,
3491 const bool allowSeparateShortValue_,
3492 const bool allowSeparateLongValue_)
3494 this->allowJoinedShortValue = allowJoinedShortValue_;
3495 this->allowJoinedLongValue = allowJoinedLongValue_;
3496 this->allowSeparateShortValue = allowSeparateShortValue_;
3497 this->allowSeparateLongValue = allowSeparateLongValue_;
3499 this->helpParams.longSeparator = allowJoinedLongValue ? longseparator :
" ";
3500 this->helpParams.shortSeparator = allowJoinedShortValue ?
"" :
" ";
3505 void Help(std::ostream &help_)
const
3507 auto &command = SelectedCommand();
3508 const auto &commandDescription = command.Description().empty() ? command.Help() : command.Description();
3509 const auto desc_indent = helpParams.descriptionindent;
3510 const auto effective_desc_width = (helpParams.width > desc_indent) ? helpParams.width - desc_indent : 0;
3511 const auto description_text =
Wrap(commandDescription, effective_desc_width);
3512 const auto epilog_text =
Wrap(command.Epilog(), effective_desc_width);
3514 const bool hasoptions = command.HasFlag();
3515 const bool hasarguments = command.HasPositional();
3517 std::vector<std::string> prognameline;
3518 prognameline.push_back(helpParams.usageString);
3519 prognameline.push_back(Prog());
3520 auto commandProgLine = command.GetProgramLine(helpParams);
3521 prognameline.insert(prognameline.end(), commandProgLine.begin(), commandProgLine.end());
3523 const auto prog_sum = helpParams.progindent + helpParams.progtailindent;
3524 const auto effective_prog_width = (helpParams.width > prog_sum) ? helpParams.width - prog_sum : 0;
3525 const auto effective_prog_first = (helpParams.width > helpParams.progindent) ? helpParams.width - helpParams.progindent : 0;
3526 const auto proglines =
Wrap(prognameline.begin(), prognameline.end(),
3527 effective_prog_width,
3528 effective_prog_first);
3529 auto progit = std::begin(proglines);
3530 if (progit != std::end(proglines))
3532 help_ << std::string(helpParams.progindent,
' ') << *progit <<
'\n';
3535 for (; progit != std::end(proglines); ++progit)
3537 help_ << std::string(helpParams.progtailindent,
' ') << *progit <<
'\n';
3542 if (!description_text.empty())
3544 for (
const auto &line: description_text)
3546 help_ << std::string(helpParams.descriptionindent,
' ') << line <<
"\n";
3551 bool lastDescriptionIsNewline =
false;
3553 if (!helpParams.optionsString.empty())
3555 help_ << std::string(helpParams.progindent,
' ') << helpParams.optionsString <<
"\n\n";
3558 for (
const auto &desc: command.GetDescription(helpParams, 0))
3560 lastDescriptionIsNewline = std::get<0>(desc).empty() && std::get<1>(desc).empty();
3561 const auto groupindent = std::get<2>(desc) * helpParams.eachgroupindent;
3562 const auto flag_sum = helpParams.flagindent + helpParams.helpindent + helpParams.gutter;
3563 const auto effective_flag_width = (helpParams.width > flag_sum) ? helpParams.width - flag_sum : 0;
3564 const auto flags =
Wrap(std::get<0>(desc), effective_flag_width);
3565 const auto info_sum = helpParams.helpindent + groupindent;
3566 const auto effective_info_width = (helpParams.width > info_sum) ? helpParams.width - info_sum : 0;
3567 const auto info =
Wrap(std::get<1>(desc), effective_info_width);
3569 std::string::size_type flagssize = 0;
3570 for (
auto flagsit = std::begin(flags); flagsit != std::end(flags); ++flagsit)
3572 if (flagsit != std::begin(flags))
3576 help_ << std::string(groupindent + helpParams.flagindent,
' ') << *flagsit;
3577 flagssize =
Glyphs(*flagsit);
3580 auto infoit = std::begin(info);
3582 if ((helpParams.flagindent + flagssize + helpParams.gutter) > helpParams.helpindent || infoit == std::end(info) || helpParams.addNewlineBeforeDescription)
3588 const auto indent_sum = helpParams.flagindent + flagssize;
3589 const auto effective_space = (helpParams.helpindent > indent_sum) ? helpParams.helpindent - indent_sum : 0;
3590 help_ << std::string(effective_space,
' ') << *infoit <<
'\n';
3593 for (; infoit != std::end(info); ++infoit)
3595 help_ << std::string(groupindent + helpParams.helpindent,
' ') << *infoit <<
'\n';
3598 if (hasoptions && hasarguments && helpParams.showTerminator)
3600 lastDescriptionIsNewline =
false;
3601 const auto effective_term_width = (helpParams.width > helpParams.flagindent) ? helpParams.width - helpParams.flagindent : 0;
3602 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))
3604 help_ << std::string(helpParams.flagindent,
' ') << item <<
'\n';
3608 if (!lastDescriptionIsNewline)
3613 for (
const auto &line: epilog_text)
3615 help_ << std::string(helpParams.descriptionindent,
' ') << line <<
"\n";
3625 std::ostringstream help_;
3630 virtual void Reset() noexcept
override
3634 readCompletion =
false;
3643 template <
typename It>
3650 if (error != Error::None)
3655 return Parse(begin, end);
3663 template <
typename T>
3666 return ParseArgs(std::begin(
args), std::end(
args));
3675 bool ParseCLI(
const int argc,
const char *
const * argv)
3677 if (argc > 0 && argv !=
nullptr && argv[0] !=
nullptr && Prog().empty())
3682 std::vector<std::string>
args;
3683 if (argc > 1 && argv !=
nullptr)
3685 args.assign(argv + 1, argv + argc);
3688 return ParseArgs(
args) == std::end(
args);
3691 template <
typename T>
3692 bool ParseCLI(
const T &
args)
3694 return ParseArgs(
args) == std::end(
args);
3698 inline Command::RaiiSubparser::RaiiSubparser(ArgumentParser &parser_, std::vector<std::string> args_)
3699 : command(parser_.SelectedCommand()), parser(std::move(args_), parser_, command, parser_.helpParams), oldSubparser(command.subparser)
3701 command.subparser = &parser;
3704 inline Command::RaiiSubparser::RaiiSubparser(
const Command &command_,
const HelpParams ¶ms_): command(command_), parser(command, params_), oldSubparser(command.subparser)
3706 command.subparser = &parser;
3714 command.subparserHasFlag =
HasFlag();
3718 if (parser ==
nullptr)
3720#ifndef ARGS_NOEXCEPT
3721 throw args::SubparserError();
3723 error = Error::Subparser;
3728 auto it = parser->Parse(
args.begin(),
args.end());
3730 kicked.assign(it,
args.end());
3733 command.subparserError = GetError();
3737 inline std::ostream &operator<<(std::ostream &os,
const ArgumentParser &parser)
3748 Flag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
Options options_):
FlagBase(name_, help_, std::move(matcher_), options_)
3771 virtual void ParseValue(
const std::vector<std::string>&)
override
3783 HelpFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
Options options_ = {}):
Flag(group_, name_, help_, std::move(matcher_), options_) {}
3790 error = Error::Help;
3810 const int startcount;
3814 CounterFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const int startcount_ = 0,
Options options_ = {}):
3815 Flag(group_, name_, help_, std::move(matcher_), options_), startcount(startcount_), count(startcount_) {}
3821 auto me = FlagBase::Match(arg);
3829 if (GetError() != Error::None)
3846 int &operator *() noexcept {
3850 const int &operator *() const noexcept {
3854 virtual void Reset() noexcept
override
3866 std::function<void(
const std::vector<std::string> &)> action;
3870 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_ = {}):
3871 FlagBase(name_, help_, std::move(matcher_), options_), action(std::move(action_)), nargs(nargs_)
3876 ActionFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_, std::function<
void(
const std::string &)> action_,
Options options_ = {}):
3877 FlagBase(name_, help_, std::move(matcher_), options_), nargs(1)
3880 action = [action_](
const std::vector<std::string> &a) {
return action_(a.at(0)); };
3883 ActionFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_, std::function<
void()> action_,
Options options_ = {}):
3884 FlagBase(name_, help_, std::move(matcher_), options_), nargs(0)
3887 action = [action_](
const std::vector<std::string> &) {
return action_(); };
3893 virtual void ParseValue(
const std::vector<std::string> &value)
override
3906 template <
typename T>
3907 static typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value,
bool>::type
3908 HasUnsignedNegativeSign(
const std::string &value)
3910 const auto firstNonSpace = std::find_if_not(value.begin(), value.end(), [](
char c)
3912 return std::isspace(static_cast<unsigned char>(c)) != 0;
3915 return firstNonSpace != value.end() && *firstNonSpace ==
'-';
3918 template <
typename T>
3919 static typename std::enable_if<!std::is_integral<T>::value || !std::is_unsigned<T>::value,
bool>::type
3920 HasUnsignedNegativeSign(
const std::string &)
3926 template <
typename T>
3927 typename std::enable_if<
3928 std::is_integral<T>::value &&
3929 !std::is_same<T, bool>::value &&
3930 !std::is_same<T, char>::value &&
3931 !std::is_same<T, signed char>::value &&
3932 !std::is_same<T, unsigned char>::value,
3934 ParseNumericValue(
const std::string &value, T &destination)
3936 if (HasUnsignedNegativeSign<T>(value))
3941 const char *begin = value.c_str();
3949 const char *
const stop = begin + value.size();
3955 const int saved_errno = errno;
3958 char *end =
nullptr;
3960 if (std::is_unsigned<T>::value)
3962 const unsigned long long parsed = std::strtoull(begin, &end, 0);
3965 errno = saved_errno;
3968 while (end != stop && std::isspace(
static_cast<unsigned char>(*end)))
3972 if (end != stop || errno == ERANGE ||
3973 parsed >
static_cast<unsigned long long>(std::numeric_limits<T>::max()))
3975 errno = saved_errno;
3979 destination =
static_cast<T
>(parsed);
3983 const long long parsed = std::strtoll(begin, &end, 0);
3986 errno = saved_errno;
3989 while (end != stop && std::isspace(
static_cast<unsigned char>(*end)))
3993 if (end != stop || errno == ERANGE ||
3994 parsed <
static_cast<long long>(std::numeric_limits<T>::min()) ||
3995 parsed >
static_cast<long long>(std::numeric_limits<T>::max()))
3997 errno = saved_errno;
4001 destination =
static_cast<T
>(parsed);
4004 errno = saved_errno;
4008 template <
typename T>
4009 typename std::enable_if<
4010 !std::is_integral<T>::value ||
4011 std::is_same<T, bool>::value ||
4012 std::is_same<T, char>::value ||
4013 std::is_same<T, signed char>::value ||
4014 std::is_same<T, unsigned char>::value,
4016 ParseNumericValue(
const std::string &value, T &destination)
4018 std::istringstream ss(value);
4024 ss.imbue(std::locale::classic());
4035 ss >> std::ws >> extra;
4042 ss.clear(ss.rdstate() & ~std::ios::failbit);
4049 template <
typename T>
4050 typename std::enable_if<!std::is_assignable<T, std::string>::value,
bool>::type
4051 operator ()(
const std::string &name,
const std::string &value, T &destination)
4053 const bool success = ParseNumericValue(value, destination);
4060 std::ostringstream problem;
4061 problem <<
"Argument '" << name <<
"' received invalid value type '" << value <<
"'";
4068 template <
typename T>
4069 typename std::enable_if<std::is_assignable<T, std::string>::value,
bool>::type
4070 operator()(
const std::string &,
const std::string &value, T &destination)
4072 destination = value;
4091 virtual std::string GetDefaultString(
const HelpParams&)
const override
4093 return detail::ToString(defaultValue);
4101 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_)
4106 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)
4110 ValueFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
Options options_):
ValueFlag(group_, name_, help_, std::move(matcher_), T(), options_)
4116 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4118 const std::string &value_ = values_.at(0);
4121 if (!reader(name, value_, this->value))
4123 error = Error::Parse;
4126 reader(name, value_, this->value);
4130 virtual void Reset() noexcept
override
4132 ValueFlagBase::Reset();
4133 value = defaultValue;
4175 return defaultValue;
4186 typename Reader = ValueReader>
4194 ImplicitValueFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const T &implicitValue_,
const T &defaultValue_ = T(),
Options options_ = {})
4195 :
ValueFlag<T, Reader>(group_, name_, help_, std::move(matcher_), defaultValue_, options_), implicitValue(implicitValue_)
4200 :
ValueFlag<T, Reader>(group_, name_, help_, std::move(matcher_), defaultValue_, options_), implicitValue(defaultValue_)
4205 :
ValueFlag<T, Reader>(group_, name_, help_, std::move(matcher_), {}, options_), implicitValue()
4216 virtual void ParseValue(
const std::vector<std::string> &value_)
override
4220 this->value = implicitValue;
4232 template <
typename T>
4240 Flag(group_, name_, help_, std::move(matcher_), options_),
4244 ConstantFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const T& value_,
bool extraError_ =
false):
4245 Flag(group_, name_, help_, std::move(matcher_), extraError_),
4249 T operator * ()
const noexcept
4254 T Get()
const noexcept
4259 const T *operator -> ()
const noexcept
4273 template <
typename...>
class List = detail::vector,
4280 const List<T> defaultValues;
4286 typedef List<T> Container;
4287 typedef T value_type;
4288 typedef typename Container::allocator_type allocator_type;
4289 typedef typename Container::pointer pointer;
4290 typedef typename Container::const_pointer const_pointer;
4291 typedef T& reference;
4292 typedef const T& const_reference;
4293 typedef typename Container::size_type size_type;
4294 typedef typename Container::difference_type difference_type;
4295 typedef typename Container::iterator iterator;
4296 typedef typename Container::const_iterator const_iterator;
4297 typedef std::reverse_iterator<iterator> reverse_iterator;
4298 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4301 :
FlagBase(name_, help_, std::move(matcher_), options_), values(defaultValues_), defaultValues(defaultValues_),nargs(nargs_)
4313 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4317 for (
const std::string &value : values_)
4321 if (!reader(name, value, v))
4323 error = Error::Parse;
4327 reader(name, value, v);
4329 values.insert(std::end(values), v);
4333 List<T> &Get() noexcept
4366 iterator begin() noexcept
4368 return values.begin();
4371 const_iterator begin() const noexcept
4373 return values.begin();
4376 const_iterator cbegin() const noexcept
4378 return values.cbegin();
4381 iterator end() noexcept
4383 return values.end();
4386 const_iterator end() const noexcept
4388 return values.end();
4391 const_iterator cend() const noexcept
4393 return values.cend();
4396 virtual void Reset() noexcept
override
4399 values = defaultValues;
4402 virtual FlagBase *Match(
const EitherFlag &arg)
override
4404 const bool wasMatched = Matched();
4405 auto me = FlagBase::Match(arg);
4406 if (me && !wasMatched)
4422 template <
typename...>
class List = detail::vector,
4423 typename Reader = ValueReader>
4427 using Container = List<T>;
4429 const Container defaultValues;
4434 typedef T value_type;
4435 typedef typename Container::allocator_type allocator_type;
4436 typedef typename Container::pointer pointer;
4437 typedef typename Container::const_pointer const_pointer;
4438 typedef T& reference;
4439 typedef const T& const_reference;
4440 typedef typename Container::size_type size_type;
4441 typedef typename Container::difference_type difference_type;
4442 typedef typename Container::iterator iterator;
4443 typedef typename Container::const_iterator const_iterator;
4444 typedef std::reverse_iterator<iterator> reverse_iterator;
4445 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4447 ValueFlagList(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const Container &defaultValues_ = Container(),
Options options_ = {}):
4448 ValueFlagBase(name_, help_, std::move(matcher_), options_), values(defaultValues_), defaultValues(defaultValues_)
4455 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4457 const std::string &value_ = values_.at(0);
4461 if (!reader(name, value_, v))
4463 error = Error::Parse;
4467 reader(name, value_, v);
4469 values.insert(std::end(values), v);
4507 virtual std::string Name()
const override
4509 return name + std::string(
"...");
4512 virtual void Reset() noexcept
override
4514 ValueFlagBase::Reset();
4515 values = defaultValues;
4518 virtual FlagBase *Match(
const EitherFlag &arg)
override
4520 const bool wasMatched = Matched();
4521 auto me = FlagBase::Match(arg);
4522 if (me && !wasMatched)
4529 iterator begin() noexcept
4531 return values.begin();
4534 const_iterator begin() const noexcept
4536 return values.begin();
4539 const_iterator cbegin() const noexcept
4541 return values.cbegin();
4544 iterator end() noexcept
4546 return values.end();
4549 const_iterator end() const noexcept
4551 return values.end();
4554 const_iterator cend() const noexcept
4556 return values.cend();
4570 typename Reader = ValueReader,
4571 template <
typename...>
class Map = detail::unordered_map>
4575 const Map<K, T> map;
4577 const T defaultValue;
4581 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
4583 return detail::MapKeysToStrings(map);
4588 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_)
4593 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)
4597 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_)
4603 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4605 const std::string &value_ = values_.at(0);
4609 if (!reader(name, value_, key))
4611 error = Error::Parse;
4615 reader(name, value_, key);
4617 auto it = map.find(key);
4618 if (it == std::end(map))
4620 std::ostringstream problem;
4621 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
4624 errorMsg = problem.str();
4630 this->value = it->second;
4669 virtual void Reset() noexcept
override
4671 ValueFlagBase::Reset();
4672 value = defaultValue;
4687 template <
typename...>
class List = detail::vector,
4688 typename Reader = ValueReader,
4689 template <
typename...>
class Map = detail::unordered_map>
4693 using Container = List<T>;
4694 const Map<K, T> map;
4696 const Container defaultValues;
4700 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
4702 return detail::MapKeysToStrings(map);
4706 typedef T value_type;
4707 typedef typename Container::allocator_type allocator_type;
4708 typedef typename Container::pointer pointer;
4709 typedef typename Container::const_pointer const_pointer;
4710 typedef T& reference;
4711 typedef const T& const_reference;
4712 typedef typename Container::size_type size_type;
4713 typedef typename Container::difference_type difference_type;
4714 typedef typename Container::iterator iterator;
4715 typedef typename Container::const_iterator const_iterator;
4716 typedef std::reverse_iterator<iterator> reverse_iterator;
4717 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4719 MapFlagList(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const Map<K, T> &map_,
const Container &defaultValues_ = Container(),
Options options_ = {}):
4720 ValueFlagBase(name_, help_, std::move(matcher_), options_), map(map_), values(defaultValues_), defaultValues(defaultValues_)
4727 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4729 const std::string &value_ = values_.at(0);
4733 if (!reader(name, value_, key))
4735 error = Error::Parse;
4739 reader(name, value_, key);
4741 auto it = map.find(key);
4742 if (it == std::end(map))
4744 std::ostringstream problem;
4745 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
4748 errorMsg = problem.str();
4754 this->values.emplace_back(it->second);
4793 virtual std::string Name()
const override
4795 return name + std::string(
"...");
4798 virtual void Reset() noexcept
override
4800 ValueFlagBase::Reset();
4801 values = defaultValues;
4804 virtual FlagBase *Match(
const EitherFlag &arg)
override
4806 const bool wasMatched = Matched();
4807 auto me = FlagBase::Match(arg);
4808 if (me && !wasMatched)
4815 iterator begin() noexcept
4817 return values.begin();
4820 const_iterator begin() const noexcept
4822 return values.begin();
4825 const_iterator cbegin() const noexcept
4827 return values.cbegin();
4830 iterator end() noexcept
4832 return values.end();
4835 const_iterator end() const noexcept
4837 return values.end();
4840 const_iterator cend() const noexcept
4842 return values.cend();
4853 typename Reader = ValueReader>
4858 const T defaultValue;
4861 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_)
4872 virtual void ParseValue(
const std::string &value_)
override
4875 if (!reader(name, value_, this->value))
4877 error = Error::Parse;
4881 reader(name, value_, this->value);
4922 virtual void Reset() noexcept
override
4924 PositionalBase::Reset();
4925 value = defaultValue;
4937 template <
typename...>
class List = detail::vector,
4938 typename Reader = ValueReader>
4942 using Container = List<T>;
4944 const Container defaultValues;
4948 typedef T value_type;
4949 typedef typename Container::allocator_type allocator_type;
4950 typedef typename Container::pointer pointer;
4951 typedef typename Container::const_pointer const_pointer;
4952 typedef T& reference;
4953 typedef const T& const_reference;
4954 typedef typename Container::size_type size_type;
4955 typedef typename Container::difference_type difference_type;
4956 typedef typename Container::iterator iterator;
4957 typedef typename Container::const_iterator const_iterator;
4958 typedef std::reverse_iterator<iterator> reverse_iterator;
4959 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4961 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_)
4972 virtual void ParseValue(
const std::string &value_)
override
4976 if (!reader(name, value_, v))
4978 error = Error::Parse;
4982 reader(name, value_, v);
4984 values.insert(std::end(values), v);
4988 virtual std::string Name()
const override
4990 return name + std::string(
"...");
5028 virtual void Reset() noexcept
override
5030 PositionalBase::Reset();
5031 values = defaultValues;
5034 virtual PositionalBase *GetNextPositional()
override
5036 const bool wasMatched = Matched();
5037 auto me = PositionalBase::GetNextPositional();
5038 if (me && !wasMatched)
5045 iterator begin() noexcept
5047 return values.begin();
5050 const_iterator begin() const noexcept
5052 return values.begin();
5055 const_iterator cbegin() const noexcept
5057 return values.cbegin();
5060 iterator end() noexcept
5062 return values.end();
5065 const_iterator end() const noexcept
5067 return values.end();
5070 const_iterator cend() const noexcept
5072 return values.cend();
5086 typename Reader = ValueReader,
5087 template <
typename...>
class Map = detail::unordered_map>
5091 const Map<K, T> map;
5093 const T defaultValue;
5097 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
5099 return detail::MapKeysToStrings(map);
5104 MapPositional(
Group &group_,
const std::string &name_,
const std::string &help_,
const Map<K, T> &map_,
const T &defaultValue_ = T(),
Options options_ = {}):
5105 PositionalBase(name_, help_, options_), map(map_), value(defaultValue_), defaultValue(defaultValue_)
5112 virtual void ParseValue(
const std::string &value_)
override
5116 if (!reader(name, value_, key))
5118 error = Error::Parse;
5122 reader(name, value_, key);
5124 auto it = map.find(key);
5125 if (it == std::end(map))
5127 std::ostringstream problem;
5128 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
5131 errorMsg = problem.str();
5137 this->value = it->second;
5178 virtual void Reset() noexcept
override
5180 PositionalBase::Reset();
5181 value = defaultValue;
5196 template <
typename...>
class List = detail::vector,
5197 typename Reader = ValueReader,
5198 template <
typename...>
class Map = detail::unordered_map>
5202 using Container = List<T>;
5204 const Map<K, T> map;
5206 const Container defaultValues;
5210 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
5212 return detail::MapKeysToStrings(map);
5216 typedef T value_type;
5217 typedef typename Container::allocator_type allocator_type;
5218 typedef typename Container::pointer pointer;
5219 typedef typename Container::const_pointer const_pointer;
5220 typedef T& reference;
5221 typedef const T& const_reference;
5222 typedef typename Container::size_type size_type;
5223 typedef typename Container::difference_type difference_type;
5224 typedef typename Container::iterator iterator;
5225 typedef typename Container::const_iterator const_iterator;
5226 typedef std::reverse_iterator<iterator> reverse_iterator;
5227 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
5229 MapPositionalList(
Group &group_,
const std::string &name_,
const std::string &help_,
const Map<K, T> &map_,
const Container &defaultValues_ = Container(),
Options options_ = {}):
5230 PositionalBase(name_, help_, options_), map(map_), values(defaultValues_), defaultValues(defaultValues_)
5237 virtual void ParseValue(
const std::string &value_)
override
5241 if (!reader(name, value_, key))
5243 error = Error::Parse;
5247 reader(name, value_, key);
5249 auto it = map.find(key);
5250 if (it == std::end(map))
5252 std::ostringstream problem;
5253 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
5256 errorMsg = problem.str();
5262 this->values.emplace_back(it->second);
5302 virtual std::string Name()
const override
5304 return name + std::string(
"...");
5307 virtual void Reset() noexcept
override
5309 PositionalBase::Reset();
5310 values = defaultValues;
5313 virtual PositionalBase *GetNextPositional()
override
5315 const bool wasMatched = Matched();
5316 auto me = PositionalBase::GetNextPositional();
5317 if (me && !wasMatched)
5324 iterator begin() noexcept
5326 return values.begin();
5329 const_iterator begin() const noexcept
5331 return values.begin();
5334 const_iterator cbegin() const noexcept
5336 return values.cbegin();
5339 iterator end() noexcept
5341 return values.end();
5344 const_iterator end() const noexcept
5346 return values.end();
5349 const_iterator cend() const noexcept
5351 return values.cend();
5356#pragma pop_macro("min")
5357#pragma pop_macro("max")
A flag class that calls a function when it's matched.
Definition args.hxx:3864
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:3890
virtual void ParseValue(const std::vector< std::string > &value) override
Parse values of this option.
Definition args.hxx:3893
The main user facing command line argument parser class.
Definition args.hxx:2690
const std::string & ShortPrefix() const
The prefix for short flags.
Definition args.hxx:3422
void SetArgumentSeparations(const bool allowJoinedShortValue_, const bool allowJoinedLongValue_, const bool allowSeparateShortValue_, const bool allowSeparateLongValue_)
Change allowed option separation.
Definition args.hxx:3488
void Prog(const std::string &prog_)
The program name for help generation.
Definition args.hxx:3405
It ParseArgs(It begin, It end)
Parse all arguments.
Definition args.hxx:3644
const std::string & Prog() const
The program name for help generation.
Definition args.hxx:3401
void LongPrefix(const std::string &longprefix_)
The prefix for long flags.
Definition args.hxx:3414
void LongSeparator(const std::string &longseparator_)
The separator for long flags.
Definition args.hxx:3438
void Help(std::ostream &help_) const
Pass the help menu into an ostream.
Definition args.hxx:3505
const std::string & LongPrefix() const
The prefix for long flags.
Definition args.hxx:3410
const std::string & LongSeparator() const
The separator for long flags.
Definition args.hxx:3434
bool ParseCLI(const int argc, const char *const *argv)
Convenience function to parse the CLI from argc and argv.
Definition args.hxx:3675
const std::string & Terminator() const
The terminator that forcibly separates flags from positionals.
Definition args.hxx:3458
auto ParseArgs(const T &args) -> decltype(std::begin(args))
Parse all arguments.
Definition args.hxx:3664
void Terminator(const std::string &terminator_)
The terminator that forcibly separates flags from positionals.
Definition args.hxx:3462
void GetArgumentSeparations(bool &allowJoinedShortValue_, bool &allowJoinedLongValue_, bool &allowSeparateShortValue_, bool &allowSeparateLongValue_) const
Get the current argument separation parameters.
Definition args.hxx:3469
std::string Help() const
Generate a help menu as a string.
Definition args.hxx:3623
void ShortPrefix(const std::string &shortprefix_)
The prefix for short flags.
Definition args.hxx:3426
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:2778
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:2150
const std::string & Name() const
The name of command.
Definition args.hxx:2285
virtual PositionalBase * GetNextPositional() override
Get the next ready positional, or nullptr if there is none.
Definition args.hxx:2386
const std::string & ProglinePostfix() const
The description that appears on the prog line after options.
Definition args.hxx:2255
void Description(const std::string &description_)
The description that appears above options.
Definition args.hxx:2270
virtual bool HasPositional() const override
Get whether this has any PositionalBase children.
Definition args.hxx:2422
const std::string & Description() const
The description that appears above options.
Definition args.hxx:2265
const std::string & Help() const
The description of command.
Definition args.hxx:2290
void Epilog(const std::string &epilog_)
The description that appears below options.
Definition args.hxx:2280
void ProglinePostfix(const std::string &proglinePostfix_)
The description that appears on the prog line after options.
Definition args.hxx:2260
virtual FlagBase * Match(const EitherFlag &flag) override
Return the first FlagBase that matches flag, or nullptr.
Definition args.hxx:2322
virtual bool HasCommand() const override
Get whether this has any Command children.
Definition args.hxx:2427
virtual std::vector< std::string > GetProgramLine(const HelpParams ¶ms) const override
Get the names of positional parameters.
Definition args.hxx:2491
virtual bool HasFlag() const override
Get whether this has any FlagBase children.
Definition args.hxx:2417
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:2516
const std::string & Epilog() const
The description that appears below options.
Definition args.hxx:2275
virtual bool Matched() const noexcept override
Whether or not this group matches validation.
Definition args.hxx:2303
void RequireCommand(bool value)
If value is true, parser will fail if no command was parsed.
Definition args.hxx:2297
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:4234
A flag class that simply counts the number of times it's matched.
Definition args.hxx:3808
int & Get() noexcept
Get the count.
Definition args.hxx:3841
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:3746
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:3766
virtual void ParseValue(const std::vector< std::string > &) override
Parse values of this option.
Definition args.hxx:3771
bool Get() const
Get whether this was matched.
Definition args.hxx:3761
Class for using global options in ArgumentParser.
Definition args.hxx:2069
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:1803
std::vector< Base * >::size_type MatchedChildren() const
Count the number of matched children this group has.
Definition args.hxx:1810
virtual bool HasPositional() const override
Get whether this has any PositionalBase children.
Definition args.hxx:1794
virtual std::vector< std::string > GetProgramLine(const HelpParams ¶ms) const override
Get the names of positional parameters.
Definition args.hxx:1898
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:1950
virtual bool HasFlag() const override
Get whether this has any FlagBase children.
Definition args.hxx:1785
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:1854
void DetectDuplicateFlags(std::unordered_set< char > &usedShortFlags, std::unordered_set< std::string > &usedLongFlags)
Used by parameterless DetectDuplicateFlags.
Definition args.hxx:1969
virtual FlagBase * Match(const EitherFlag &flag) override
Return the first FlagBase that matches flag, or nullptr.
Definition args.hxx:1734
bool Get() const
Get validation.
Definition args.hxx:1861
const std::vector< Base * > & Children() const
Get all this group's children.
Definition args.hxx:1724
std::vector< Base * > GetMatchedChildren() const
Get the list of children which were matched.
Definition args.hxx:1819
void DetectDuplicateFlags()
Detect duplicate flags.
Definition args.hxx:1960
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:1835
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:1868
virtual PositionalBase * GetNextPositional() override
Get the next ready positional, or nullptr if there is none.
Definition args.hxx:1769
Help flag class.
Definition args.hxx:3781
bool Get() const noexcept
Get whether this was matched.
Definition args.hxx:3799
virtual void ParseValue(const std::vector< std::string > &)
Parse values of this option.
Definition args.hxx:3787
An exception that indicates that the user has requested help.
Definition args.hxx:541
An optional argument-accepting flag class.
Definition args.hxx:4188
virtual void ParseValue(const std::vector< std::string > &value_) override
Parse values of this option.
Definition args.hxx:4216
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:4211
Errors in map lookups.
Definition args.hxx:523
A mapping value flag list class.
Definition args.hxx:4691
Container * operator->() noexcept
Get the values.
Definition args.hxx:4781
Container & Get() noexcept
Get the value.
Definition args.hxx:4760
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4727
Container & operator*() noexcept
Get the value.
Definition args.hxx:4767
A mapping value flag class.
Definition args.hxx:4573
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4603
T & Get() noexcept
Get the value.
Definition args.hxx:4636
T * operator->() noexcept
Get the value.
Definition args.hxx:4657
T & operator*() noexcept
Get the value.
Definition args.hxx:4643
A positional argument mapping list class.
Definition args.hxx:5200
Container & operator*() noexcept
Get the value.
Definition args.hxx:5276
Container * operator->() noexcept
Get the values.
Definition args.hxx:5290
Container & Get() noexcept
Get the value.
Definition args.hxx:5269
A positional argument mapping class.
Definition args.hxx:5089
T * operator->() noexcept
Get the value.
Definition args.hxx:5166
T & Get() noexcept
Get the value.
Definition args.hxx:5145
T & operator*() noexcept
Get the value.
Definition args.hxx:5152
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:4276
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:4308
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4313
List< T > * operator->() noexcept
Get the values.
Definition args.hxx:4354
List< T > & operator*() noexcept
Get the value.
Definition args.hxx:4340
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:4940
Container & operator*() noexcept
Get the value.
Definition args.hxx:5002
Container & Get() noexcept
Get the values.
Definition args.hxx:4995
Container * operator->() noexcept
Get the values.
Definition args.hxx:5016
A positional argument class.
Definition args.hxx:4855
T & operator*() noexcept
Get the value.
Definition args.hxx:4896
T & Get() noexcept
Get the value.
Definition args.hxx:4889
T * operator->() noexcept
Get the value.
Definition args.hxx:4910
Errors that when a required flag is omitted.
Definition args.hxx:514
Utility class for building subparsers with coroutines/callbacks.
Definition args.hxx:2095
void Parse()
Continue parsing arguments for new command.
Definition args.hxx:3709
const std::vector< std::string > & KickedOut() const noexcept
Returns a vector of kicked out arguments.
Definition args.hxx:2139
bool IsParsed() const
(INTERNAL) Determines whether Parse was called or not.
Definition args.hxx:2126
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:4425
Container * operator->() noexcept
Get the values.
Definition args.hxx:4495
Container & Get() noexcept
Get the values.
Definition args.hxx:4474
Container & operator*() noexcept
Get the value.
Definition args.hxx:4481
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4455
An argument-accepting flag class.
Definition args.hxx:4086
T & operator*() noexcept
Get the value.
Definition args.hxx:4145
T * operator->() noexcept
Get the value.
Definition args.hxx:4159
T & Get() noexcept
Get the value.
Definition args.hxx:4138
const T & GetDefault() noexcept
Get the default value.
Definition args.hxx:4173
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4116
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:3904