35#pragma push_macro("min")
36#pragma push_macro("max")
40#define ARGS_VERSION "6.4.16"
41#define ARGS_VERSION_MAJOR 6
42#define ARGS_VERSION_MINOR 4
43#define ARGS_VERSION_PATCH 16
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)
411 for (
const auto &element : array)
434 inline std::vector<std::string>
Wrap(
const std::string &in,
const std::string::size_type width, std::string::size_type firstlinewidth = 0)
437 const auto newlineloc = in.find(
'\n');
438 if (newlineloc != in.npos)
440 auto first =
Wrap(std::string(in, 0, newlineloc), width);
441 auto second =
Wrap(std::string(in, newlineloc + 1), width);
444 std::make_move_iterator(std::begin(second)),
445 std::make_move_iterator(std::end(second)));
449 std::istringstream stream(in);
450 std::string::size_type indent = 0;
454 if (!std::isspace(
static_cast<unsigned char>(c)))
461 return Wrap(std::istream_iterator<std::string>(stream), std::istream_iterator<std::string>(),
462 width, firstlinewidth, indent);
483 class Error :
public std::runtime_error
486 Error(
const std::string &problem) : std::runtime_error(problem) {}
549 Help(
const std::string &flag) :
Error(flag) {}
555 class SubparserError :
public Error
558 SubparserError() :
Error(
"") {}
559 virtual ~SubparserError() {}
577 const char shortFlag;
578 const std::string longFlag;
579 EitherFlag(
const std::string &flag) : isShort(
false), shortFlag(), longFlag(flag) {}
580 EitherFlag(
const char *flag) : isShort(
false), shortFlag(), longFlag(flag) {}
581 EitherFlag(
const char flag) : isShort(
true), shortFlag(flag), longFlag() {}
585 static std::unordered_set<std::string>
GetLong(std::initializer_list<EitherFlag> flags)
587 std::unordered_set<std::string> longFlags;
592 longFlags.insert(flag.longFlag);
600 static std::unordered_set<char>
GetShort(std::initializer_list<EitherFlag> flags)
602 std::unordered_set<char> shortFlags;
607 shortFlags.insert(flag.shortFlag);
613 std::string str()
const
615 return isShort ? std::string(1, shortFlag) : longFlag;
618 std::string str(
const std::string &shortPrefix,
const std::string &longPrefix)
const
620 return isShort ? shortPrefix + std::string(1, shortFlag) : longPrefix + longFlag;
635 const std::unordered_set<char> shortFlags;
636 const std::unordered_set<std::string> longFlags;
643 template <
typename ShortIt,
typename LongIt>
644 Matcher(ShortIt shortFlagsStart, ShortIt shortFlagsEnd, LongIt longFlagsStart, LongIt longFlagsEnd) :
645 shortFlags(shortFlagsStart, shortFlagsEnd),
646 longFlags(longFlagsStart, longFlagsEnd)
648 if (shortFlags.empty() && longFlags.empty())
658 Error GetError() const noexcept
660 return shortFlags.empty() && longFlags.empty() ? Error::Usage : Error::None;
668 template <
typename Short,
typename Long>
670 Matcher(std::begin(shortIn), std::end(shortIn), std::begin(longIn), std::end(longIn))
685 Matcher(std::initializer_list<EitherFlag> in) :
688 Matcher(
Matcher &&other) noexcept : shortFlags(std::move(other.shortFlags)), longFlags(std::move(other.longFlags))
697 return shortFlags.find(flag) != shortFlags.end();
702 bool Match(
const std::string &flag)
const
704 return longFlags.find(flag) != longFlags.end();
711 return flag.isShort ?
Match(flag.shortFlag) :
Match(flag.longFlag);
718 std::vector<EitherFlag> flagStrings;
719 flagStrings.reserve(shortFlags.size() + longFlags.size());
720 for (
const char flag: shortFlags)
722 flagStrings.emplace_back(flag);
724 for (
const std::string &flag: longFlags)
726 flagStrings.emplace_back(flag);
735 if (!longFlags.empty())
737 return *longFlags.begin();
740 if (!shortFlags.empty())
742 return *shortFlags.begin();
753 if (!shortFlags.empty())
755 return *shortFlags.begin();
758 if (!longFlags.empty())
760 return *longFlags.begin();
811 return static_cast<Options>(
static_cast<int>(lhs) |
static_cast<int>(rhs));
816 return static_cast<Options>(
static_cast<int>(lhs) &
static_cast<int>(rhs));
820 class PositionalBase;
822 class ArgumentParser;
988 Nargs(
size_t min_,
size_t max_) : min{min_}, max{max_}
998 Nargs(
size_t num_) : min{num_}, max{num_}
1002 friend bool operator == (
const Nargs &lhs,
const Nargs &rhs)
1004 return lhs.min == rhs.min && lhs.max == rhs.max;
1007 friend bool operator != (
const Nargs &lhs,
const Nargs &rhs)
1009 return !(lhs == rhs);
1021 bool matched =
false;
1022 const std::string help;
1025 mutable Error error = Error::None;
1026 mutable std::string errorMsg;
1030 Base(
const std::string &help_,
Options options_ = {}) : options(options_), help(help_) {}
1033 Options GetOptions()
const noexcept
1038 bool IsRequired()
const noexcept
1043 virtual bool Matched()
const noexcept
1048 virtual void Validate(
const std::string &,
const std::string &)
const
1052 operator bool()
const noexcept
1057 virtual std::vector<std::tuple<std::string, std::string, unsigned>> GetDescription(
const HelpParams &,
const unsigned indentLevel)
const
1059 std::tuple<std::string, std::string, unsigned> description;
1060 std::get<1>(description) = help;
1061 std::get<2>(description) = indentLevel;
1062 return { std::move(description) };
1065 virtual std::vector<Command*> GetCommands()
1070 virtual bool IsGroup()
const
1085 virtual std::vector<FlagBase*> GetAllFlags()
1090 virtual bool HasFlag()
const
1095 virtual bool HasPositional()
const
1100 virtual bool HasCommand()
const
1105 virtual std::vector<std::string> GetProgramLine(
const HelpParams &)
const
1129 virtual void Reset() noexcept
1133 error = Error::None;
1140 virtual Error GetError()
const
1146 virtual std::string GetErrorMsg()
const
1158 const std::string name;
1159 bool kickout =
false;
1160 std::string defaultString;
1161 bool defaultStringManual =
false;
1162 std::vector<std::string> choicesStrings;
1163 bool choicesStringManual =
false;
1165 virtual std::string GetDefaultString(
const HelpParams&)
const {
return {}; }
1167 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams&)
const {
return {}; }
1169 virtual std::string GetNameString(
const HelpParams&)
const {
return Name(); }
1171 void AddDescriptionPostfix(std::string &dest,
const bool isManual,
const std::string &manual,
bool isGenerated,
const std::string &generated,
const std::string &str)
const
1173 if (isManual && !manual.empty())
1178 else if (!isManual && isGenerated && !generated.empty())
1186 NamedBase(
const std::string &name_,
const std::string &help_,
Options options_ = {}) :
Base(help_, options_), name(name_) {}
1194 defaultStringManual =
true;
1195 defaultString = str;
1202 return defaultStringManual ? defaultString : GetDefaultString(params);
1210 choicesStringManual =
true;
1211 choicesStrings = array;
1218 return choicesStringManual ? choicesStrings : GetChoicesStrings(params);
1221 virtual std::vector<std::tuple<std::string, std::string, unsigned>> GetDescription(
const HelpParams ¶ms,
const unsigned indentLevel)
const override
1223 std::tuple<std::string, std::string, unsigned> description;
1224 std::get<0>(description) = GetNameString(params);
1225 std::get<1>(description) = help;
1226 std::get<2>(description) = indentLevel;
1228 AddDescriptionPostfix(std::get<1>(description), choicesStringManual, detail::Join(choicesStrings,
", "), params.
addChoices, detail::Join(GetChoicesStrings(params),
", "), params.
choiceString);
1229 AddDescriptionPostfix(std::get<1>(description), defaultStringManual, defaultString, params.
addDefault, GetDefaultString(params), params.
defaultString);
1231 return { std::move(description) };
1234 virtual std::string Name()
const
1242 template<
typename T>
1243 using vector = std::vector<T, std::allocator<T>>;
1245 template<
typename K,
typename T>
1246 using unordered_map = std::unordered_map<K, T, std::hash<K>,
1247 std::equal_to<K>, std::allocator<std::pair<const K, T> > >;
1249 template<
typename S,
typename T>
1252 template<
typename SS,
typename TT>
1253 static auto test(
int)
1254 ->
decltype( std::declval<SS&>() << std::declval<TT>(), std::true_type() );
1256 template<
typename,
typename>
1257 static auto test(...) -> std::false_type;
1260 using type =
decltype(test<S,T>(0));
1263 template <
typename T>
1264 using IsConvertableToString =
typename is_streamable<std::ostringstream, T>::type;
1266 template <
typename T>
1267 typename std::enable_if<IsConvertableToString<T>::value, std::string>::type
1268 ToString(
const T &value)
1270 std::ostringstream s;
1275 template <
typename T>
1276 typename std::enable_if<!IsConvertableToString<T>::value, std::string>::type
1282 template <
typename T>
1283 std::vector<std::string> MapKeysToStrings(
const T &map)
1285 std::vector<std::string> res;
1286 using K =
typename std::decay<
decltype(std::begin(map)->first)>::type;
1287 if (IsConvertableToString<K>::value)
1289 for (
const auto &p : map)
1291 res.push_back(detail::ToString(p.first));
1294 std::sort(res.begin(), res.end());
1307 virtual std::string GetNameString(
const HelpParams ¶ms)
const override
1312 const bool useValueNameOnce = flagStrings.size() == 1 ? false : params.
useValueNameOnce;
1313 for (
auto it = flagStrings.begin(); it != flagStrings.end(); ++it)
1316 if (it != flagStrings.begin())
1322 flags += flag.str();
1324 if (!postfix.empty() && (!useValueNameOnce || it + 1 == flagStrings.end()))
1337 FlagBase(
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
Options options_) :
NamedBase(name_, help_, options_), matcher(std::move(matcher_)) {}
1343 if (matcher.
Match(flag))
1347 std::ostringstream problem;
1348 problem <<
"Flag '" << flag.str() <<
"' was passed multiple times, but is only allowed to be passed once";
1350 error = Error::Extra;
1351 errorMsg = problem.str();
1362 virtual std::vector<FlagBase*> GetAllFlags()
override
1367 const Matcher &GetMatcher()
const
1372 virtual void Validate(
const std::string &shortPrefix,
const std::string &longPrefix)
const override
1374 if (!Matched() && IsRequired())
1376 std::ostringstream problem;
1377 problem <<
"Flag '" << matcher.
GetLongOrAny().str(shortPrefix, longPrefix) <<
"' is required";
1379 error = Error::Required;
1380 errorMsg = problem.str();
1387 virtual std::vector<std::string> GetProgramLine(
const HelpParams ¶ms)
const override
1397 if (!postfix.empty())
1406 virtual bool HasFlag()
const override
1413 virtual Error GetError()
const override
1416 if (nargs.min > nargs.max)
1418 return Error::Usage;
1421 const auto matcherError = matcher.GetError();
1422 if (matcherError != Error::None)
1424 return matcherError;
1441 virtual
void ParseValue(const std::vector<std::
string> &value) = 0;
1449 ValueFlagBase(
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const bool extraError_ =
false) :
FlagBase(name_, help_, std::move(matcher_), extraError_) {}
1462 std::vector<std::string> reply;
1466 template <
typename GroupClass>
1469 group_.AddCompletion(*
this);
1479 virtual void ParseValue(
const std::vector<std::string> &value_)
override
1481 syntax = value_.at(0);
1482 const std::string &raw = value_.at(1);
1483 bool failed =
false;
1485 const auto firstNonSpace = std::find_if_not(raw.begin(), raw.end(), [](
char c)
1487 return std::isspace(static_cast<unsigned char>(c)) != 0;
1493 if (firstNonSpace != raw.end() && (*firstNonSpace ==
'-' || *firstNonSpace ==
'+'))
1501 std::istringstream ss(raw);
1507 ss.imbue(std::locale::classic());
1530 error = Error::Parse;
1531 errorMsg =
"Argument 'completion' received invalid value type '" + raw +
"'";
1533 std::ostringstream problem;
1534 problem <<
"Argument 'completion' received invalid value type '" << raw <<
"'";
1547 return detail::Join(reply,
"\n");
1550 virtual void Reset() noexcept
override
1552 ValueFlagBase::Reset();
1576 virtual void ParseValue(
const std::string &value_) = 0;
1578 virtual void Reset()
noexcept override
1583 error = Error::None;
1590 return Ready() ? this :
nullptr;
1593 virtual bool HasPositional()
const override
1598 virtual std::vector<std::string> GetProgramLine(
const HelpParams ¶ms)
const override
1604 virtual void Validate(
const std::string &,
const std::string &)
const override
1606 if (IsRequired() && !Matched())
1608 std::ostringstream problem;
1609 problem <<
"Option '" << Name() <<
"' is required";
1611 error = Error::Required;
1612 errorMsg = problem.str();
1625 std::vector<Base*> children;
1626 std::function<bool(
const Group &)> validator;
1633 static bool Xor(
const Group &group)
1638 static bool AtLeastOne(
const Group &group)
1643 static bool AtMostOne(
const Group &group)
1648 static bool All(
const Group &group)
1653 static bool AllOrNone(
const Group &group)
1655 return (All(group) ||
None(group));
1658 static bool AllChildGroups(
const Group &group)
1660 return std::none_of(std::begin(group.
Children()), std::end(group.
Children()), [](
const Base* child) ->
bool {
1661 return child->IsGroup() && !child->Matched();
1665 static bool DontCare(
const Group &)
1670 static bool CareTooMuch(
const Group &)
1681 Group(
const std::string &help_ = std::string(),
const std::function<
bool(
const Group &)> &validator_ = Validators::DontCare,
Options options_ = {}) :
Base(help_, options_), validator(validator_) {}
1683 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_)
1693 children.emplace_back(&child);
1710 for (
Base *child: Children())
1712 if (
FlagBase *match = child->Match(flag))
1720 virtual std::vector<FlagBase*> GetAllFlags()
override
1722 std::vector<FlagBase*> res;
1723 for (
Base *child: Children())
1725 auto childRes = child->GetAllFlags();
1726 res.insert(res.end(), childRes.begin(), childRes.end());
1731 virtual void Validate(
const std::string &shortPrefix,
const std::string &longPrefix)
const override
1733 for (Base *child: Children())
1735 child->Validate(shortPrefix, longPrefix);
1745 for (
Base *child: Children())
1747 if (
auto next = child->GetNextPositional())
1761 return std::any_of(Children().begin(), Children().end(), [](
Base *child) {
return child->HasFlag(); });
1770 return std::any_of(Children().begin(), Children().end(), [](
Base *child) {
return child->HasPositional(); });
1779 return std::any_of(Children().begin(), Children().end(), [](
Base *child) {
return child->HasCommand(); });
1787 return static_cast<std::vector<Base *>::size_type
>(
1788 std::count_if(std::begin(Children()), std::end(Children()), [](
const Base *child){
return child->Matched();}));
1796 std::vector<Base*> matched_children;
1797 std::copy_if(children.begin(), children.end(), std::back_inserter(matched_children), [](
Base* b){
1798 return b->Matched();
1800 return matched_children;
1807 return validator(*
this);
1819 virtual std::vector<std::tuple<std::string, std::string, unsigned>>
GetDescription(
const HelpParams ¶ms,
const unsigned int indent)
const override
1821 std::vector<std::tuple<std::string, std::string, unsigned int>> descriptions;
1824 unsigned addindent = 0;
1827 descriptions.emplace_back(help,
"", indent);
1831 for (
Base *child: Children())
1833 if ((child->GetOptions() & Options::HiddenFromDescription) != Options::None)
1838 auto groupDescriptions = child->GetDescription(params, indent + addindent);
1839 descriptions.insert(
1840 std::end(descriptions),
1841 std::make_move_iterator(std::begin(groupDescriptions)),
1842 std::make_move_iterator(std::end(groupDescriptions)));
1844 return descriptions;
1851 std::vector <std::string> names;
1852 for (
Base *child: Children())
1854 if ((child->GetOptions() & Options::HiddenFromUsage) != Options::None)
1859 auto groupNames = child->GetProgramLine(params);
1862 std::make_move_iterator(std::begin(groupNames)),
1863 std::make_move_iterator(std::end(groupNames)));
1868 virtual std::vector<Command*> GetCommands()
override
1870 std::vector<Command*> res;
1871 for (
const auto &child : Children())
1873 auto subparsers = child->GetCommands();
1874 res.insert(std::end(res), std::begin(subparsers), std::end(subparsers));
1879 virtual bool IsGroup()
const override
1884 virtual void Reset() noexcept
override
1888 for (
auto &child: Children())
1893 error = Error::None;
1900 virtual Error GetError()
const override
1902 if (error != Error::None)
1907 auto it = std::find_if(Children().begin(), Children().end(), [](
const Base *child){
return child->GetError() != Error::None;});
1908 if (it == Children().end())
1913 return (*it)->GetError();
1918 virtual std::string GetErrorMsg()
const override
1920 if (error != Error::None)
1925 auto it = std::find_if(Children().begin(), Children().end(), [](
const Base *child){
return child->GetError() != Error::None;});
1926 if (it == Children().end())
1931 return (*it)->GetErrorMsg();
1969 std::vector<std::string>
args;
1970 std::vector<std::string> kicked;
1974 bool isParsed =
false;
1978 :
Group({}, Validators::AllChildGroups),
args(std::move(args_)), parser(&parser_), helpParams(helpParams_), command(command_)
2028 std::string description;
2030 std::string proglinePostfix;
2032 std::function<void(
Subparser&)> parserCoroutine;
2033 bool commandIsRequired =
true;
2034 Command *selectedCommand =
nullptr;
2036 mutable std::vector<std::tuple<std::string, std::string, unsigned>> subparserDescription;
2037 mutable std::vector<std::string> subparserProgramLine;
2038 mutable bool subparserHasFlag =
false;
2039 mutable bool subparserHasPositional =
false;
2040 mutable bool subparserHasCommand =
false;
2042 mutable Error subparserError = Error::None;
2051 RaiiSubparser(
ArgumentParser &parser_, std::vector<std::string> args_);
2056 command.subparser = oldSubparser;
2072 std::function<void(
Subparser&)> &GetCoroutine()
2074 return selectedCommand !=
nullptr ? selectedCommand->GetCoroutine() : parserCoroutine;
2080 while (res->selectedCommand !=
nullptr)
2082 res = res->selectedCommand;
2088 const Command &SelectedCommand()
const
2091 while (res->selectedCommand !=
nullptr)
2093 res = res->selectedCommand;
2099 void UpdateSubparserHelp(
const HelpParams ¶ms)
const
2101 if (parserCoroutine)
2103 RaiiSubparser coro(*
this, params);
2104#ifndef ARGS_NOEXCEPT
2107 parserCoroutine(coro.Parser());
2109 catch (args::SubparserError&)
2113 parserCoroutine(coro.Parser());
2119 Command(
Group &base_, std::string name_, std::string help_, std::function<
void(
Subparser&)> coroutine_ = {})
2120 : name(std::move(name_)), help(std::move(help_)), parserCoroutine(std::move(coroutine_))
2128 {
return proglinePostfix; }
2133 { this->proglinePostfix = proglinePostfix_; }
2138 {
return description; }
2143 { this->description = description_; }
2153 { this->epilog = epilog_; }
2170 { commandIsRequired = value; }
2172 virtual bool IsGroup()
const override
2176 {
return Base::Matched(); }
2178 operator bool() const noexcept
2179 {
return Matched(); }
2181 void Match() noexcept
2184 void SelectCommand(Command *c)
noexcept
2186 selectedCommand = c;
2196 if (selectedCommand !=
nullptr)
2198 if (
auto *res = selectedCommand->Match(flag))
2203 for (
auto *child: Children())
2205 if ((child->GetOptions() & Options::Global) != Options::None)
2207 if (
auto *res = child->Match(flag))
2217 if (subparser !=
nullptr)
2219 return subparser->
Match(flag);
2222 return Matched() ? Group::Match(flag) :
nullptr;
2225 virtual std::vector<FlagBase*> GetAllFlags()
override
2227 std::vector<FlagBase*> res;
2234 for (
auto *child: Children())
2236 if (selectedCommand ==
nullptr || (child->GetOptions() & Options::Global) != Options::None)
2238 auto childFlags = child->GetAllFlags();
2239 res.insert(res.end(), childFlags.begin(), childFlags.end());
2243 if (selectedCommand !=
nullptr)
2245 auto childFlags = selectedCommand->GetAllFlags();
2246 res.insert(res.end(), childFlags.begin(), childFlags.end());
2249 if (subparser !=
nullptr)
2251 auto childFlags = subparser->GetAllFlags();
2252 res.insert(res.end(), childFlags.begin(), childFlags.end());
2260 if (selectedCommand !=
nullptr)
2267 for (
auto *child: Children())
2269 if ((child->GetOptions() & Options::Global) != Options::None)
2271 if (
auto *res = child->GetNextPositional())
2281 if (subparser !=
nullptr)
2286 return Matched() ? Group::GetNextPositional() :
nullptr;
2291 return subparserHasFlag || Group::HasFlag();
2296 return subparserHasPositional || Group::HasPositional();
2304 std::vector<std::string> GetCommandProgramLine(
const HelpParams ¶ms)
const
2306 UpdateSubparserHelp(params);
2308 std::vector<std::string> res;
2315 auto group_res = Group::GetProgramLine(params);
2316 std::move(std::move(group_res).begin(), std::move(group_res).end(), std::back_inserter(res));
2318 res.insert(res.end(), subparserProgramLine.begin(), subparserProgramLine.end());
2320 if (!params.
proglineCommand.empty() && (Group::HasCommand() || subparserHasCommand))
2322 res.insert(res.begin(), commandIsRequired ? params.
proglineCommand :
"[" + params.proglineCommand +
"]");
2325 if (!Name().empty())
2327 res.insert(res.begin(), Name());
2330 if (!ProglinePostfix().empty())
2333 for (
auto c : ProglinePostfix())
2335 if (std::isspace(
static_cast<unsigned char>(c)))
2339 res.push_back(line);
2345 res.push_back(
"\n");
2356 res.push_back(line);
2370 return GetCommandProgramLine(params);
2373 virtual std::vector<Command*> GetCommands()
override
2375 if (selectedCommand !=
nullptr)
2377 return selectedCommand->GetCommands();
2382 return Group::GetCommands();
2388 virtual std::vector<std::tuple<std::string, std::string, unsigned>>
GetDescription(
const HelpParams ¶ms,
const unsigned int indent)
const override
2390 std::vector<std::tuple<std::string, std::string, unsigned>> descriptions;
2391 unsigned addindent = 0;
2393 UpdateSubparserHelp(params);
2399 std::ostringstream s;
2401 for (
const auto &progline: GetCommandProgramLine(params))
2415 descriptions.emplace_back(s.str(),
"", indent);
2419 descriptions.emplace_back(Name(), help, indent);
2424 return descriptions;
2432 descriptions.emplace_back(
"",
"", indent + addindent);
2433 descriptions.emplace_back(Description().empty() ?
Help() : Description(),
"", indent + addindent);
2434 descriptions.emplace_back(
"",
"", indent + addindent);
2437 for (
Base *child: Children())
2439 if ((child->GetOptions() & Options::HiddenFromDescription) != Options::None)
2444 auto groupDescriptions = child->GetDescription(params, indent + addindent);
2445 descriptions.insert(
2446 std::end(descriptions),
2447 std::make_move_iterator(std::begin(groupDescriptions)),
2448 std::make_move_iterator(std::end(groupDescriptions)));
2451 for (
auto childDescription: subparserDescription)
2453 std::get<2>(childDescription) += indent + addindent;
2454 descriptions.push_back(std::move(childDescription));
2459 descriptions.emplace_back(
"",
"", indent + addindent);
2460 if (!Epilog().empty())
2462 descriptions.emplace_back(Epilog(),
"", indent + addindent);
2463 descriptions.emplace_back(
"",
"", indent + addindent);
2467 return descriptions;
2470 virtual void Validate(
const std::string &shortprefix,
const std::string &longprefix)
const override
2477 auto onValidationError = [&]
2479 std::ostringstream problem;
2480 problem <<
"Group validation failed somewhere!";
2482 error = Error::Validation;
2483 errorMsg = problem.str();
2485 throw ValidationError(problem.str());
2489 for (Base *child: Children())
2491 if (child->IsGroup() && !child->Matched())
2493 onValidationError();
2496 child->Validate(shortprefix, longprefix);
2499 if (subparser !=
nullptr)
2501 subparser->Validate(shortprefix, longprefix);
2504 onValidationError();
2508 if (selectedCommand ==
nullptr && commandIsRequired && (Group::HasCommand() || subparserHasCommand))
2510 std::ostringstream problem;
2511 problem <<
"Command is required";
2513 error = Error::Validation;
2514 errorMsg = problem.str();
2516 throw ValidationError(problem.str());
2521 virtual void Reset() noexcept
override
2524 selectedCommand =
nullptr;
2525 subparserProgramLine.clear();
2526 subparserDescription.clear();
2527 subparserHasFlag =
false;
2528 subparserHasPositional =
false;
2529 subparserHasCommand =
false;
2531 subparserError = Error::None;
2537 virtual Error GetError()
const override
2544 if (error != Error::None)
2549 if (subparserError != Error::None)
2551 return subparserError;
2554 return Group::GetError();
2566 std::string longprefix;
2567 std::string shortprefix;
2569 std::string longseparator;
2571 std::string terminator;
2573 bool allowJoinedShortValue =
true;
2574 bool allowJoinedLongValue =
true;
2575 bool allowSeparateShortValue =
true;
2576 bool allowSeparateLongValue =
true;
2578 bool readCompletion =
false;
2582 enum class OptionType
2589 OptionType ParseOption(
const std::string &s,
bool allowEmpty =
false)
2591 const bool matchesLong = s.find(longprefix) == 0 && (allowEmpty || s.length() > longprefix.length());
2592 const bool matchesShort = s.find(shortprefix) == 0 && (allowEmpty || s.length() > shortprefix.length());
2600 if (matchesLong && matchesShort)
2602 return longprefix.length() >= shortprefix.length() ? OptionType::LongFlag : OptionType::ShortFlag;
2607 return OptionType::LongFlag;
2612 return OptionType::ShortFlag;
2615 return OptionType::Positional;
2618 template <
typename It>
2619 bool Complete(
FlagBase &flag, It it, It end)
2622 if (!readCompletion || (++nextIt != end))
2627 const auto &chunk = *it;
2630 AddCompletionReply(chunk, choice);
2633#ifndef ARGS_NOEXCEPT
2649 template <
typename It>
2651 const bool allowSeparate,
const bool allowJoined,
2652 const bool hasJoined,
const std::string &joinedArg,
2653 const bool canDiscardJoined, std::vector<std::string> &values)
2659 if (hasJoined && !allowJoined && nargs.min != 0)
2661 return "Flag '" + arg +
"' was passed a joined argument, but these are disallowed";
2666 if (!canDiscardJoined || nargs.max != 0)
2668 values.push_back(joinedArg);
2670 }
else if (!allowSeparate)
2674 return "Flag '" + arg +
"' was passed a separate argument, but these are disallowed";
2681 while (valueIt != end &&
2682 *valueIt != terminator &&
2683 values.size() < nargs.max &&
2684 (values.size() < nargs.min || ParseOption(*valueIt) == OptionType::Positional))
2686 if (Complete(flag, valueIt, end))
2701 values.push_back(*valueIt);
2707 if (values.size() > nargs.max)
2709 return "Passed an argument into a non-argument flag: " + arg;
2710 }
else if (values.size() < nargs.min)
2712 if (nargs.min == 1 && nargs.max == 1)
2714 return "Flag '" + arg +
"' requires an argument but received none";
2715 }
else if (nargs.min == 1)
2717 return "Flag '" + arg +
"' requires at least one argument but received none";
2718 }
else if (nargs.min != nargs.max)
2720 return "Flag '" + arg +
"' requires at least " + std::to_string(nargs.min) +
2721 " arguments but received " + std::to_string(values.size());
2724 return "Flag '" + arg +
"' requires " + std::to_string(nargs.min) +
2725 " arguments but received " + std::to_string(values.size());
2732 template <
typename It>
2733 bool ParseLong(It &it, It end)
2735 const auto &chunk = *it;
2736 const auto argchunk = chunk.substr(longprefix.size());
2738 const auto separator = longseparator.empty() ? argchunk.npos : argchunk.find(longseparator);
2740 const auto arg = (separator != argchunk.npos ?
2741 std::string(argchunk, 0, separator)
2743 const auto joined = (separator != argchunk.npos ?
2744 argchunk.substr(separator + longseparator.size())
2747 if (
auto flag = Match(arg))
2755 if (flag->GetError() != Error::None)
2760 std::vector<std::string> values;
2761 const std::string errorMessage = ParseArgsValues(*flag, arg, it, end, allowSeparateLongValue, allowJoinedLongValue,
2762 separator != argchunk.npos, joined,
false, values);
2763 if (!errorMessage.empty())
2765#ifndef ARGS_NOEXCEPT
2766 throw ParseError(errorMessage);
2768 error = Error::Parse;
2769 errorMsg = errorMessage;
2774 if (!readCompletion)
2783 if (flag->GetError() != Error::None)
2797 const std::string errorMessage(
"Flag could not be matched: " + arg);
2798#ifndef ARGS_NOEXCEPT
2799 throw ParseError(errorMessage);
2801 error = Error::Parse;
2802 errorMsg = errorMessage;
2810 template <
typename It>
2811 bool ParseShort(It &it, It end)
2813 const auto &chunk = *it;
2814 const auto argchunk = chunk.substr(shortprefix.size());
2815 for (
auto argit = std::begin(argchunk); argit != std::end(argchunk); ++argit)
2817 const auto arg = *argit;
2819 if (
auto flag = Match(arg))
2825 if (flag->GetError() != Error::None)
2830 const std::string value(argit + 1, std::end(argchunk));
2831 std::vector<std::string> values;
2832 const std::string errorMessage = ParseArgsValues(*flag, std::string(1, arg), it, end,
2833 allowSeparateShortValue, allowJoinedShortValue,
2834 !value.empty(), value, !value.empty(), values);
2836 if (!errorMessage.empty())
2838#ifndef ARGS_NOEXCEPT
2839 throw ParseError(errorMessage);
2841 error = Error::Parse;
2842 errorMsg = errorMessage;
2847 if (!readCompletion)
2854 if (flag->GetError() != Error::None)
2867 if (!values.empty())
2873 const std::string errorMessage(
"Flag could not be matched: '" + std::string(1, arg) +
"'");
2874#ifndef ARGS_NOEXCEPT
2875 throw ParseError(errorMessage);
2877 error = Error::Parse;
2878 errorMsg = errorMessage;
2887 bool AddCompletionReply(
const std::string &cur,
const std::string &choice)
2889 if (cur.empty() || choice.find(cur) == 0)
2891 if (completion->syntax ==
"bash" && ParseOption(choice) == OptionType::LongFlag && choice.find(longseparator) != std::string::npos)
2893 completion->reply.push_back(choice.substr(choice.find(longseparator) + longseparator.size()));
2896 completion->reply.push_back(choice);
2904 template <
typename It>
2905 bool Complete(It it, It end,
bool terminated)
2908 if (!readCompletion || (++nextIt != end))
2913 const auto &chunk = *it;
2914 auto pos = GetNextPositional();
2915 std::vector<Command *> commands = GetCommands();
2916 const auto optionType = ParseOption(chunk,
true);
2922 if (!terminated && !commands.empty() && (chunk.empty() || optionType == OptionType::Positional))
2924 for (
auto &cmd : commands)
2926 if ((cmd->GetOptions() & Options::HiddenFromCompletion) == Options::None)
2928 AddCompletionReply(chunk, cmd->Name());
2933 bool hasPositionalCompletion =
true;
2935 if (!terminated && !commands.empty())
2937 for (
auto &cmd : commands)
2939 if ((cmd->GetOptions() & Options::HiddenFromCompletion) == Options::None)
2941 AddCompletionReply(chunk, cmd->Name());
2946 if ((pos->GetOptions() & Options::HiddenFromCompletion) == Options::None)
2948 auto choices = pos->HelpChoices(helpParams);
2949 hasPositionalCompletion = !choices.empty() || optionType != OptionType::Positional;
2950 for (
auto &choice : choices)
2952 AddCompletionReply(chunk, choice);
2957 if (!terminated && hasPositionalCompletion)
2959 auto flags = GetAllFlags();
2960 for (
auto flag : flags)
2962 if ((flag->GetOptions() & Options::HiddenFromCompletion) != Options::None)
2967 auto &matcher = flag->GetMatcher();
2968 if (!AddCompletionReply(chunk, matcher.
GetShortOrAny().str(shortprefix, longprefix)))
2970 for (
auto &flagName : matcher.GetFlagStrings())
2972 if (AddCompletionReply(chunk, flagName.str(shortprefix, longprefix)))
2980 if (optionType == OptionType::LongFlag && allowJoinedLongValue)
2982 const auto separator = longseparator.empty() ? chunk.npos : chunk.find(longseparator);
2996 if (separator != chunk.npos && separator >= longprefix.size())
2998 std::string arg(chunk, 0, separator);
2999 if (
auto flag = this->Match(arg.substr(longprefix.size())))
3001 for (
auto &choice : flag->HelpChoices(helpParams))
3003 AddCompletionReply(chunk, arg + longseparator + choice);
3007 }
else if (optionType == OptionType::ShortFlag && allowJoinedShortValue)
3009 if (chunk.size() > shortprefix.size() + 1)
3011 auto arg = chunk.at(shortprefix.size());
3013 if (
auto flag = this->Match(arg))
3015 for (
auto &choice : flag->HelpChoices(helpParams))
3017 AddCompletionReply(chunk, shortprefix + arg + choice);
3025#ifndef ARGS_NOEXCEPT
3026 throw Completion(completion->
Get());
3032 template <
typename It>
3033 It Parse(It begin, It end)
3035 bool terminated =
false;
3036 std::vector<Command *> commands = GetCommands();
3039 for (
auto it = begin; it != end; ++it)
3041 if (Complete(it, end, terminated))
3046 const auto &chunk = *it;
3048 if (!terminated && chunk == terminator)
3051 }
else if (!terminated && ParseOption(chunk) == OptionType::LongFlag)
3053 if (!ParseLong(it, end))
3057 }
else if (!terminated && ParseOption(chunk) == OptionType::ShortFlag)
3059 if (!ParseShort(it, end))
3063 }
else if (!terminated && !commands.empty())
3065 auto itCommand = std::find_if(commands.begin(), commands.end(), [&chunk](Command *c) { return c->Name() == chunk; });
3066 if (itCommand == commands.end())
3068 const std::string errorMessage(
"Unknown command: " + chunk);
3069#ifndef ARGS_NOEXCEPT
3070 throw ParseError(errorMessage);
3072 error = Error::Parse;
3073 errorMsg = errorMessage;
3078 SelectCommand(*itCommand);
3080 if (
const auto &coroutine = GetCoroutine())
3083 RaiiSubparser coro(*
this, std::vector<std::string>(it, end));
3084 coroutine(coro.Parser());
3087 if (error != Error::None)
3092 if (!coro.Parser().IsParsed())
3094 error = Error::Usage;
3098 if (!coro.Parser().IsParsed())
3100 throw UsageError(
"Subparser::Parse was not called");
3107 commands = GetCommands();
3110 auto pos = GetNextPositional();
3113 pos->ParseValue(chunk);
3115 if (pos->GetError() != Error::None)
3127 const std::string errorMessage(
"Passed in argument, but no positional arguments were ready to receive it: " + chunk);
3128#ifndef ARGS_NOEXCEPT
3129 throw ParseError(errorMessage);
3131 error = Error::Parse;
3132 errorMsg = errorMessage;
3138 if (!readCompletion && completion !=
nullptr && completion->Matched())
3141 if (completion->GetError() != Error::None)
3143 error = completion->GetError();
3144 if (errorMsg.empty())
3146 errorMsg = completion->GetErrorMsg();
3151 error = Error::Completion;
3153 readCompletion =
true;
3155 const auto argsLeft =
static_cast<size_t>(std::distance(it, end));
3156 if (completion->cword == 0 || argsLeft <= 1 || completion->cword >= argsLeft)
3158#ifndef ARGS_NOEXCEPT
3159 throw Completion(
"");
3166 std::vector<std::string> curArgs;
3167 curArgs.reserve(completion->cword);
3169 for (
size_t idx = 0; idx < completion->cword && curIt != end; ++idx, ++curIt)
3171 curArgs.push_back(*curIt);
3174 if (completion->syntax ==
"bash")
3178 for (
size_t idx = 0; idx < curArgs.size(); )
3180 if (idx > 0 && curArgs[idx] ==
"=")
3182 size_t prev_idx = idx - 1;
3183 curArgs[prev_idx] +=
"=";
3184 size_t next_idx = 0;
3185 if (SafeAdd<size_t>(idx,
static_cast<size_t>(1), next_idx) && next_idx < curArgs.size())
3187 curArgs[prev_idx] += curArgs[next_idx];
3189 size_t erase_end = 0;
3190 if (SafeAdd<size_t>(next_idx,
static_cast<size_t>(1), erase_end))
3192 typedef std::vector<std::string>::difference_type diff_t;
3193 curArgs.erase(curArgs.begin() +
static_cast<diff_t
>(idx),
3194 curArgs.begin() +
static_cast<diff_t
>(erase_end));
3199 typedef std::vector<std::string>::difference_type diff_t;
3200 curArgs.erase(curArgs.begin() +
static_cast<diff_t
>(idx));
3210#ifndef ARGS_NOEXCEPT
3213 Parse(curArgs.begin(), curArgs.end());
3214 throw Completion(
"");
3216 catch (Completion &)
3222 throw Completion(
"");
3232 Parse(curArgs.begin(), curArgs.end());
3233 error = Error::Completion;
3240 Validate(shortprefix, longprefix);
3245 HelpParams helpParams;
3247 ArgumentParser(
const std::string &description_,
const std::string &epilog_ = std::string())
3249 Description(description_);
3255 SetArgumentSeparations(
true,
true,
true,
true);
3259 void AddCompletion(CompletionFlag &completionFlag)
3261 completion = &completionFlag;
3262 Add(completionFlag);
3268 {
return helpParams.programName; }
3271 void Prog(
const std::string &prog_)
3272 { this->helpParams.programName = prog_; }
3277 {
return longprefix; }
3282 this->longprefix = longprefix_;
3283 this->helpParams.longPrefix = longprefix_;
3289 {
return shortprefix; }
3294 this->shortprefix = shortprefix_;
3295 this->helpParams.shortPrefix = shortprefix_;
3301 {
return longseparator; }
3306 if (longseparator_.empty())
3308 const std::string errorMessage(
"longseparator can not be set to empty");
3310 error = Error::Usage;
3311 errorMsg = errorMessage;
3317 this->longseparator = longseparator_;
3318 this->helpParams.longSeparator = allowJoinedLongValue ? longseparator :
" ";
3325 {
return terminator; }
3329 { this->terminator = terminator_; }
3336 bool &allowJoinedShortValue_,
3337 bool &allowJoinedLongValue_,
3338 bool &allowSeparateShortValue_,
3339 bool &allowSeparateLongValue_)
const
3341 allowJoinedShortValue_ = this->allowJoinedShortValue;
3342 allowJoinedLongValue_ = this->allowJoinedLongValue;
3343 allowSeparateShortValue_ = this->allowSeparateShortValue;
3344 allowSeparateLongValue_ = this->allowSeparateLongValue;
3355 const bool allowJoinedShortValue_,
3356 const bool allowJoinedLongValue_,
3357 const bool allowSeparateShortValue_,
3358 const bool allowSeparateLongValue_)
3360 this->allowJoinedShortValue = allowJoinedShortValue_;
3361 this->allowJoinedLongValue = allowJoinedLongValue_;
3362 this->allowSeparateShortValue = allowSeparateShortValue_;
3363 this->allowSeparateLongValue = allowSeparateLongValue_;
3365 this->helpParams.longSeparator = allowJoinedLongValue ? longseparator :
" ";
3366 this->helpParams.shortSeparator = allowJoinedShortValue ?
"" :
" ";
3371 void Help(std::ostream &help_)
const
3373 auto &command = SelectedCommand();
3374 const auto &commandDescription = command.Description().empty() ? command.Help() : command.Description();
3375 const auto desc_indent = helpParams.descriptionindent;
3376 const auto effective_desc_width = (helpParams.width > desc_indent) ? helpParams.width - desc_indent : 0;
3377 const auto description_text =
Wrap(commandDescription, effective_desc_width);
3378 const auto epilog_text =
Wrap(command.Epilog(), effective_desc_width);
3380 const bool hasoptions = command.HasFlag();
3381 const bool hasarguments = command.HasPositional();
3383 std::vector<std::string> prognameline;
3384 prognameline.push_back(helpParams.usageString);
3385 prognameline.push_back(Prog());
3386 auto commandProgLine = command.GetProgramLine(helpParams);
3387 prognameline.insert(prognameline.end(), commandProgLine.begin(), commandProgLine.end());
3389 const auto prog_sum = helpParams.progindent + helpParams.progtailindent;
3390 const auto effective_prog_width = (helpParams.width > prog_sum) ? helpParams.width - prog_sum : 0;
3391 const auto effective_prog_first = (helpParams.width > helpParams.progindent) ? helpParams.width - helpParams.progindent : 0;
3392 const auto proglines =
Wrap(prognameline.begin(), prognameline.end(),
3393 effective_prog_width,
3394 effective_prog_first);
3395 auto progit = std::begin(proglines);
3396 if (progit != std::end(proglines))
3398 help_ << std::string(helpParams.progindent,
' ') << *progit <<
'\n';
3401 for (; progit != std::end(proglines); ++progit)
3403 help_ << std::string(helpParams.progtailindent,
' ') << *progit <<
'\n';
3408 if (!description_text.empty())
3410 for (
const auto &line: description_text)
3412 help_ << std::string(helpParams.descriptionindent,
' ') << line <<
"\n";
3417 bool lastDescriptionIsNewline =
false;
3419 if (!helpParams.optionsString.empty())
3421 help_ << std::string(helpParams.progindent,
' ') << helpParams.optionsString <<
"\n\n";
3424 for (
const auto &desc: command.GetDescription(helpParams, 0))
3426 lastDescriptionIsNewline = std::get<0>(desc).empty() && std::get<1>(desc).empty();
3427 const auto groupindent = std::get<2>(desc) * helpParams.eachgroupindent;
3428 const auto flag_sum = helpParams.flagindent + helpParams.helpindent + helpParams.gutter;
3429 const auto effective_flag_width = (helpParams.width > flag_sum) ? helpParams.width - flag_sum : 0;
3430 const auto flags =
Wrap(std::get<0>(desc), effective_flag_width);
3431 const auto info_sum = helpParams.helpindent + groupindent;
3432 const auto effective_info_width = (helpParams.width > info_sum) ? helpParams.width - info_sum : 0;
3433 const auto info =
Wrap(std::get<1>(desc), effective_info_width);
3435 std::string::size_type flagssize = 0;
3436 for (
auto flagsit = std::begin(flags); flagsit != std::end(flags); ++flagsit)
3438 if (flagsit != std::begin(flags))
3442 help_ << std::string(groupindent + helpParams.flagindent,
' ') << *flagsit;
3443 flagssize =
Glyphs(*flagsit);
3446 auto infoit = std::begin(info);
3448 if ((helpParams.flagindent + flagssize + helpParams.gutter) > helpParams.helpindent || infoit == std::end(info) || helpParams.addNewlineBeforeDescription)
3454 const auto indent_sum = helpParams.flagindent + flagssize;
3455 const auto effective_space = (helpParams.helpindent > indent_sum) ? helpParams.helpindent - indent_sum : 0;
3456 help_ << std::string(effective_space,
' ') << *infoit <<
'\n';
3459 for (; infoit != std::end(info); ++infoit)
3461 help_ << std::string(groupindent + helpParams.helpindent,
' ') << *infoit <<
'\n';
3464 if (hasoptions && hasarguments && helpParams.showTerminator)
3466 lastDescriptionIsNewline =
false;
3467 const auto effective_term_width = (helpParams.width > helpParams.flagindent) ? helpParams.width - helpParams.flagindent : 0;
3468 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))
3470 help_ << std::string(helpParams.flagindent,
' ') << item <<
'\n';
3474 if (!lastDescriptionIsNewline)
3479 for (
const auto &line: epilog_text)
3481 help_ << std::string(helpParams.descriptionindent,
' ') << line <<
"\n";
3491 std::ostringstream help_;
3496 virtual void Reset() noexcept
override
3500 readCompletion =
false;
3509 template <
typename It>
3516 if (error != Error::None)
3521 return Parse(begin, end);
3529 template <
typename T>
3532 return ParseArgs(std::begin(
args), std::end(
args));
3541 bool ParseCLI(
const int argc,
const char *
const * argv)
3543 if (argc > 0 && argv !=
nullptr && argv[0] !=
nullptr && Prog().empty())
3548 std::vector<std::string>
args;
3549 if (argc > 1 && argv !=
nullptr)
3551 args.assign(argv + 1, argv + argc);
3554 return ParseArgs(
args) == std::end(
args);
3557 template <
typename T>
3558 bool ParseCLI(
const T &
args)
3560 return ParseArgs(
args) == std::end(
args);
3564 inline Command::RaiiSubparser::RaiiSubparser(ArgumentParser &parser_, std::vector<std::string> args_)
3565 : command(parser_.SelectedCommand()), parser(std::move(args_), parser_, command, parser_.helpParams), oldSubparser(command.subparser)
3567 command.subparser = &parser;
3570 inline Command::RaiiSubparser::RaiiSubparser(
const Command &command_,
const HelpParams ¶ms_): command(command_), parser(command, params_), oldSubparser(command.subparser)
3572 command.subparser = &parser;
3580 command.subparserHasFlag =
HasFlag();
3584 if (parser ==
nullptr)
3586#ifndef ARGS_NOEXCEPT
3587 throw args::SubparserError();
3589 error = Error::Subparser;
3594 auto it = parser->Parse(
args.begin(),
args.end());
3596 kicked.assign(it,
args.end());
3599 command.subparserError = GetError();
3603 inline std::ostream &operator<<(std::ostream &os,
const ArgumentParser &parser)
3614 Flag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
Options options_):
FlagBase(name_, help_, std::move(matcher_), options_)
3637 virtual void ParseValue(
const std::vector<std::string>&)
override
3649 HelpFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
Options options_ = {}):
Flag(group_, name_, help_, std::move(matcher_), options_) {}
3656 error = Error::Help;
3676 const int startcount;
3680 CounterFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const int startcount_ = 0,
Options options_ = {}):
3681 Flag(group_, name_, help_, std::move(matcher_), options_), startcount(startcount_), count(startcount_) {}
3687 auto me = FlagBase::Match(arg);
3695 if (GetError() != Error::None)
3712 int &operator *() noexcept {
3716 const int &operator *() const noexcept {
3720 virtual void Reset() noexcept
override
3732 std::function<void(
const std::vector<std::string> &)> action;
3736 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_ = {}):
3737 FlagBase(name_, help_, std::move(matcher_), options_), action(std::move(action_)), nargs(nargs_)
3742 ActionFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_, std::function<
void(
const std::string &)> action_,
Options options_ = {}):
3743 FlagBase(name_, help_, std::move(matcher_), options_), nargs(1)
3746 action = [action_](
const std::vector<std::string> &a) {
return action_(a.at(0)); };
3749 ActionFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_, std::function<
void()> action_,
Options options_ = {}):
3750 FlagBase(name_, help_, std::move(matcher_), options_), nargs(0)
3753 action = [action_](
const std::vector<std::string> &) {
return action_(); };
3759 virtual void ParseValue(
const std::vector<std::string> &value)
override
3772 template <
typename T>
3773 static typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value,
bool>::type
3774 HasUnsignedNegativeSign(
const std::string &value)
3776 const auto firstNonSpace = std::find_if_not(value.begin(), value.end(), [](
char c)
3778 return std::isspace(static_cast<unsigned char>(c)) != 0;
3781 return firstNonSpace != value.end() && *firstNonSpace ==
'-';
3784 template <
typename T>
3785 static typename std::enable_if<!std::is_integral<T>::value || !std::is_unsigned<T>::value,
bool>::type
3786 HasUnsignedNegativeSign(
const std::string &)
3792 template <
typename T>
3793 typename std::enable_if<
3794 std::is_integral<T>::value &&
3795 !std::is_same<T, bool>::value &&
3796 !std::is_same<T, char>::value &&
3797 !std::is_same<T, signed char>::value &&
3798 !std::is_same<T, unsigned char>::value,
3800 ParseNumericValue(
const std::string &value, T &destination)
3802 if (HasUnsignedNegativeSign<T>(value))
3807 const char *begin = value.c_str();
3815 const char *
const stop = begin + value.size();
3821 const int saved_errno = errno;
3824 char *end =
nullptr;
3826 if (std::is_unsigned<T>::value)
3828 const unsigned long long parsed = std::strtoull(begin, &end, 0);
3831 errno = saved_errno;
3834 while (end != stop && std::isspace(
static_cast<unsigned char>(*end)))
3838 if (end != stop || errno == ERANGE ||
3839 parsed >
static_cast<unsigned long long>(std::numeric_limits<T>::max()))
3841 errno = saved_errno;
3845 destination =
static_cast<T
>(parsed);
3849 const long long parsed = std::strtoll(begin, &end, 0);
3852 errno = saved_errno;
3855 while (end != stop && std::isspace(
static_cast<unsigned char>(*end)))
3859 if (end != stop || errno == ERANGE ||
3860 parsed <
static_cast<long long>(std::numeric_limits<T>::min()) ||
3861 parsed >
static_cast<long long>(std::numeric_limits<T>::max()))
3863 errno = saved_errno;
3867 destination =
static_cast<T
>(parsed);
3870 errno = saved_errno;
3874 template <
typename T>
3875 typename std::enable_if<
3876 !std::is_integral<T>::value ||
3877 std::is_same<T, bool>::value ||
3878 std::is_same<T, char>::value ||
3879 std::is_same<T, signed char>::value ||
3880 std::is_same<T, unsigned char>::value,
3882 ParseNumericValue(
const std::string &value, T &destination)
3884 std::istringstream ss(value);
3890 ss.imbue(std::locale::classic());
3901 ss >> std::ws >> extra;
3908 ss.clear(ss.rdstate() & ~std::ios::failbit);
3915 template <
typename T>
3916 typename std::enable_if<!std::is_assignable<T, std::string>::value,
bool>::type
3917 operator ()(
const std::string &name,
const std::string &value, T &destination)
3919 const bool success = ParseNumericValue(value, destination);
3926 std::ostringstream problem;
3927 problem <<
"Argument '" << name <<
"' received invalid value type '" << value <<
"'";
3934 template <
typename T>
3935 typename std::enable_if<std::is_assignable<T, std::string>::value,
bool>::type
3936 operator()(
const std::string &,
const std::string &value, T &destination)
3938 destination = value;
3957 virtual std::string GetDefaultString(
const HelpParams&)
const override
3959 return detail::ToString(defaultValue);
3967 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_)
3972 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)
3976 ValueFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
Options options_):
ValueFlag(group_, name_, help_, std::move(matcher_), T(), options_)
3982 virtual void ParseValue(
const std::vector<std::string> &values_)
override
3984 const std::string &value_ = values_.at(0);
3987 if (!reader(name, value_, this->value))
3989 error = Error::Parse;
3992 reader(name, value_, this->value);
3996 virtual void Reset() noexcept
override
3998 ValueFlagBase::Reset();
3999 value = defaultValue;
4041 return defaultValue;
4052 typename Reader = ValueReader>
4060 ImplicitValueFlag(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const T &implicitValue_,
const T &defaultValue_ = T(),
Options options_ = {})
4061 :
ValueFlag<T, Reader>(group_, name_, help_, std::move(matcher_), defaultValue_, options_), implicitValue(implicitValue_)
4066 :
ValueFlag<T, Reader>(group_, name_, help_, std::move(matcher_), defaultValue_, options_), implicitValue(defaultValue_)
4071 :
ValueFlag<T, Reader>(group_, name_, help_, std::move(matcher_), {}, options_), implicitValue()
4082 virtual void ParseValue(
const std::vector<std::string> &value_)
override
4086 this->value = implicitValue;
4102 template <
typename...>
class List = detail::vector,
4103 typename Reader = ValueReader>
4109 const List<T> defaultValues;
4115 typedef List<T> Container;
4116 typedef T value_type;
4117 typedef typename Container::allocator_type allocator_type;
4118 typedef typename Container::pointer pointer;
4119 typedef typename Container::const_pointer const_pointer;
4120 typedef T& reference;
4121 typedef const T& const_reference;
4122 typedef typename Container::size_type size_type;
4123 typedef typename Container::difference_type difference_type;
4124 typedef typename Container::iterator iterator;
4125 typedef typename Container::const_iterator const_iterator;
4126 typedef std::reverse_iterator<iterator> reverse_iterator;
4127 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4130 :
FlagBase(name_, help_, std::move(matcher_), options_), values(defaultValues_), defaultValues(defaultValues_),nargs(nargs_)
4142 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4146 for (
const std::string &value : values_)
4150 if (!reader(name, value, v))
4152 error = Error::Parse;
4156 reader(name, value, v);
4158 values.insert(std::end(values), v);
4162 List<T> &Get() noexcept
4195 iterator begin() noexcept
4197 return values.begin();
4200 const_iterator begin() const noexcept
4202 return values.begin();
4205 const_iterator cbegin() const noexcept
4207 return values.cbegin();
4210 iterator end() noexcept
4212 return values.end();
4215 const_iterator end() const noexcept
4217 return values.end();
4220 const_iterator cend() const noexcept
4222 return values.cend();
4225 virtual void Reset() noexcept
override
4228 values = defaultValues;
4231 virtual FlagBase *Match(
const EitherFlag &arg)
override
4233 const bool wasMatched = Matched();
4234 auto me = FlagBase::Match(arg);
4235 if (me && !wasMatched)
4251 template <
typename...>
class List = detail::vector,
4252 typename Reader = ValueReader>
4256 using Container = List<T>;
4258 const Container defaultValues;
4263 typedef T value_type;
4264 typedef typename Container::allocator_type allocator_type;
4265 typedef typename Container::pointer pointer;
4266 typedef typename Container::const_pointer const_pointer;
4267 typedef T& reference;
4268 typedef const T& const_reference;
4269 typedef typename Container::size_type size_type;
4270 typedef typename Container::difference_type difference_type;
4271 typedef typename Container::iterator iterator;
4272 typedef typename Container::const_iterator const_iterator;
4273 typedef std::reverse_iterator<iterator> reverse_iterator;
4274 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4276 ValueFlagList(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const Container &defaultValues_ = Container(),
Options options_ = {}):
4277 ValueFlagBase(name_, help_, std::move(matcher_), options_), values(defaultValues_), defaultValues(defaultValues_)
4284 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4286 const std::string &value_ = values_.at(0);
4290 if (!reader(name, value_, v))
4292 error = Error::Parse;
4296 reader(name, value_, v);
4298 values.insert(std::end(values), v);
4336 virtual std::string Name()
const override
4338 return name + std::string(
"...");
4341 virtual void Reset() noexcept
override
4343 ValueFlagBase::Reset();
4344 values = defaultValues;
4347 virtual FlagBase *Match(
const EitherFlag &arg)
override
4349 const bool wasMatched = Matched();
4350 auto me = FlagBase::Match(arg);
4351 if (me && !wasMatched)
4358 iterator begin() noexcept
4360 return values.begin();
4363 const_iterator begin() const noexcept
4365 return values.begin();
4368 const_iterator cbegin() const noexcept
4370 return values.cbegin();
4373 iterator end() noexcept
4375 return values.end();
4378 const_iterator end() const noexcept
4380 return values.end();
4383 const_iterator cend() const noexcept
4385 return values.cend();
4399 typename Reader = ValueReader,
4400 template <
typename...>
class Map = detail::unordered_map>
4404 const Map<K, T> map;
4406 const T defaultValue;
4410 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
4412 return detail::MapKeysToStrings(map);
4417 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_)
4422 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)
4426 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_)
4432 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4434 const std::string &value_ = values_.at(0);
4438 if (!reader(name, value_, key))
4440 error = Error::Parse;
4444 reader(name, value_, key);
4446 auto it = map.find(key);
4447 if (it == std::end(map))
4449 std::ostringstream problem;
4450 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
4453 errorMsg = problem.str();
4459 this->value = it->second;
4498 virtual void Reset() noexcept
override
4500 ValueFlagBase::Reset();
4501 value = defaultValue;
4516 template <
typename...>
class List = detail::vector,
4517 typename Reader = ValueReader,
4518 template <
typename...>
class Map = detail::unordered_map>
4522 using Container = List<T>;
4523 const Map<K, T> map;
4525 const Container defaultValues;
4529 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
4531 return detail::MapKeysToStrings(map);
4535 typedef T value_type;
4536 typedef typename Container::allocator_type allocator_type;
4537 typedef typename Container::pointer pointer;
4538 typedef typename Container::const_pointer const_pointer;
4539 typedef T& reference;
4540 typedef const T& const_reference;
4541 typedef typename Container::size_type size_type;
4542 typedef typename Container::difference_type difference_type;
4543 typedef typename Container::iterator iterator;
4544 typedef typename Container::const_iterator const_iterator;
4545 typedef std::reverse_iterator<iterator> reverse_iterator;
4546 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4548 MapFlagList(
Group &group_,
const std::string &name_,
const std::string &help_,
Matcher &&matcher_,
const Map<K, T> &map_,
const Container &defaultValues_ = Container(),
Options options_ = {}):
4549 ValueFlagBase(name_, help_, std::move(matcher_), options_), map(map_), values(defaultValues_), defaultValues(defaultValues_)
4556 virtual void ParseValue(
const std::vector<std::string> &values_)
override
4558 const std::string &value_ = values_.at(0);
4562 if (!reader(name, value_, key))
4564 error = Error::Parse;
4568 reader(name, value_, key);
4570 auto it = map.find(key);
4571 if (it == std::end(map))
4573 std::ostringstream problem;
4574 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
4577 errorMsg = problem.str();
4583 this->values.emplace_back(it->second);
4622 virtual std::string Name()
const override
4624 return name + std::string(
"...");
4627 virtual void Reset() noexcept
override
4629 ValueFlagBase::Reset();
4630 values = defaultValues;
4633 virtual FlagBase *Match(
const EitherFlag &arg)
override
4635 const bool wasMatched = Matched();
4636 auto me = FlagBase::Match(arg);
4637 if (me && !wasMatched)
4644 iterator begin() noexcept
4646 return values.begin();
4649 const_iterator begin() const noexcept
4651 return values.begin();
4654 const_iterator cbegin() const noexcept
4656 return values.cbegin();
4659 iterator end() noexcept
4661 return values.end();
4664 const_iterator end() const noexcept
4666 return values.end();
4669 const_iterator cend() const noexcept
4671 return values.cend();
4682 typename Reader = ValueReader>
4687 const T defaultValue;
4690 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_)
4701 virtual void ParseValue(
const std::string &value_)
override
4704 if (!reader(name, value_, this->value))
4706 error = Error::Parse;
4710 reader(name, value_, this->value);
4751 virtual void Reset() noexcept
override
4753 PositionalBase::Reset();
4754 value = defaultValue;
4766 template <
typename...>
class List = detail::vector,
4767 typename Reader = ValueReader>
4771 using Container = List<T>;
4773 const Container defaultValues;
4777 typedef T value_type;
4778 typedef typename Container::allocator_type allocator_type;
4779 typedef typename Container::pointer pointer;
4780 typedef typename Container::const_pointer const_pointer;
4781 typedef T& reference;
4782 typedef const T& const_reference;
4783 typedef typename Container::size_type size_type;
4784 typedef typename Container::difference_type difference_type;
4785 typedef typename Container::iterator iterator;
4786 typedef typename Container::const_iterator const_iterator;
4787 typedef std::reverse_iterator<iterator> reverse_iterator;
4788 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
4790 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_)
4801 virtual void ParseValue(
const std::string &value_)
override
4805 if (!reader(name, value_, v))
4807 error = Error::Parse;
4811 reader(name, value_, v);
4813 values.insert(std::end(values), v);
4817 virtual std::string Name()
const override
4819 return name + std::string(
"...");
4857 virtual void Reset() noexcept
override
4859 PositionalBase::Reset();
4860 values = defaultValues;
4863 virtual PositionalBase *GetNextPositional()
override
4865 const bool wasMatched = Matched();
4866 auto me = PositionalBase::GetNextPositional();
4867 if (me && !wasMatched)
4874 iterator begin() noexcept
4876 return values.begin();
4879 const_iterator begin() const noexcept
4881 return values.begin();
4884 const_iterator cbegin() const noexcept
4886 return values.cbegin();
4889 iterator end() noexcept
4891 return values.end();
4894 const_iterator end() const noexcept
4896 return values.end();
4899 const_iterator cend() const noexcept
4901 return values.cend();
4915 typename Reader = ValueReader,
4916 template <
typename...>
class Map = detail::unordered_map>
4920 const Map<K, T> map;
4922 const T defaultValue;
4926 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
4928 return detail::MapKeysToStrings(map);
4933 MapPositional(
Group &group_,
const std::string &name_,
const std::string &help_,
const Map<K, T> &map_,
const T &defaultValue_ = T(),
Options options_ = {}):
4934 PositionalBase(name_, help_, options_), map(map_), value(defaultValue_), defaultValue(defaultValue_)
4941 virtual void ParseValue(
const std::string &value_)
override
4945 if (!reader(name, value_, key))
4947 error = Error::Parse;
4951 reader(name, value_, key);
4953 auto it = map.find(key);
4954 if (it == std::end(map))
4956 std::ostringstream problem;
4957 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
4960 errorMsg = problem.str();
4966 this->value = it->second;
5007 virtual void Reset() noexcept
override
5009 PositionalBase::Reset();
5010 value = defaultValue;
5025 template <
typename...>
class List = detail::vector,
5026 typename Reader = ValueReader,
5027 template <
typename...>
class Map = detail::unordered_map>
5031 using Container = List<T>;
5033 const Map<K, T> map;
5035 const Container defaultValues;
5039 virtual std::vector<std::string> GetChoicesStrings(
const HelpParams &)
const override
5041 return detail::MapKeysToStrings(map);
5045 typedef T value_type;
5046 typedef typename Container::allocator_type allocator_type;
5047 typedef typename Container::pointer pointer;
5048 typedef typename Container::const_pointer const_pointer;
5049 typedef T& reference;
5050 typedef const T& const_reference;
5051 typedef typename Container::size_type size_type;
5052 typedef typename Container::difference_type difference_type;
5053 typedef typename Container::iterator iterator;
5054 typedef typename Container::const_iterator const_iterator;
5055 typedef std::reverse_iterator<iterator> reverse_iterator;
5056 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
5058 MapPositionalList(
Group &group_,
const std::string &name_,
const std::string &help_,
const Map<K, T> &map_,
const Container &defaultValues_ = Container(),
Options options_ = {}):
5059 PositionalBase(name_, help_, options_), map(map_), values(defaultValues_), defaultValues(defaultValues_)
5066 virtual void ParseValue(
const std::string &value_)
override
5070 if (!reader(name, value_, key))
5072 error = Error::Parse;
5076 reader(name, value_, key);
5078 auto it = map.find(key);
5079 if (it == std::end(map))
5081 std::ostringstream problem;
5082 problem <<
"Could not find key '" << key <<
"' in map for arg '" << name <<
"'";
5085 errorMsg = problem.str();
5091 this->values.emplace_back(it->second);
5131 virtual std::string Name()
const override
5133 return name + std::string(
"...");
5136 virtual void Reset() noexcept
override
5138 PositionalBase::Reset();
5139 values = defaultValues;
5142 virtual PositionalBase *GetNextPositional()
override
5144 const bool wasMatched = Matched();
5145 auto me = PositionalBase::GetNextPositional();
5146 if (me && !wasMatched)
5153 iterator begin() noexcept
5155 return values.begin();
5158 const_iterator begin() const noexcept
5160 return values.begin();
5163 const_iterator cbegin() const noexcept
5165 return values.cbegin();
5168 iterator end() noexcept
5170 return values.end();
5173 const_iterator end() const noexcept
5175 return values.end();
5178 const_iterator cend() const noexcept
5180 return values.cend();
5185#pragma pop_macro("min")
5186#pragma pop_macro("max")
A flag class that calls a function when it's matched.
Definition args.hxx:3730
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:3756
virtual void ParseValue(const std::vector< std::string > &value) override
Parse values of this option.
Definition args.hxx:3759
The main user facing command line argument parser class.
Definition args.hxx:2562
const std::string & ShortPrefix() const
The prefix for short flags.
Definition args.hxx:3288
void SetArgumentSeparations(const bool allowJoinedShortValue_, const bool allowJoinedLongValue_, const bool allowSeparateShortValue_, const bool allowSeparateLongValue_)
Change allowed option separation.
Definition args.hxx:3354
void Prog(const std::string &prog_)
The program name for help generation.
Definition args.hxx:3271
It ParseArgs(It begin, It end)
Parse all arguments.
Definition args.hxx:3510
const std::string & Prog() const
The program name for help generation.
Definition args.hxx:3267
void LongPrefix(const std::string &longprefix_)
The prefix for long flags.
Definition args.hxx:3280
void LongSeparator(const std::string &longseparator_)
The separator for long flags.
Definition args.hxx:3304
void Help(std::ostream &help_) const
Pass the help menu into an ostream.
Definition args.hxx:3371
const std::string & LongPrefix() const
The prefix for long flags.
Definition args.hxx:3276
const std::string & LongSeparator() const
The separator for long flags.
Definition args.hxx:3300
bool ParseCLI(const int argc, const char *const *argv)
Convenience function to parse the CLI from argc and argv.
Definition args.hxx:3541
const std::string & Terminator() const
The terminator that forcibly separates flags from positionals.
Definition args.hxx:3324
auto ParseArgs(const T &args) -> decltype(std::begin(args))
Parse all arguments.
Definition args.hxx:3530
void Terminator(const std::string &terminator_)
The terminator that forcibly separates flags from positionals.
Definition args.hxx:3328
void GetArgumentSeparations(bool &allowJoinedShortValue_, bool &allowJoinedLongValue_, bool &allowSeparateShortValue_, bool &allowSeparateLongValue_) const
Get the current argument separation parameters.
Definition args.hxx:3335
std::string Help() const
Generate a help menu as a string.
Definition args.hxx:3489
void ShortPrefix(const std::string &shortprefix_)
The prefix for short flags.
Definition args.hxx:3292
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:2650
Base class for all match types.
Definition args.hxx:1016
void KickOut(bool kickout_) noexcept
Sets a kick-out value for building subparsers.
Definition args.hxx:1111
bool KickOut() const noexcept
Gets the kick-out value for building subparsers.
Definition args.hxx:1124
Main class for building subparsers.
Definition args.hxx:2022
const std::string & Name() const
The name of command.
Definition args.hxx:2157
virtual PositionalBase * GetNextPositional() override
Get the next ready positional, or nullptr if there is none.
Definition args.hxx:2258
const std::string & ProglinePostfix() const
The description that appears on the prog line after options.
Definition args.hxx:2127
void Description(const std::string &description_)
The description that appears above options.
Definition args.hxx:2142
virtual bool HasPositional() const override
Get whether this has any PositionalBase children.
Definition args.hxx:2294
const std::string & Description() const
The description that appears above options.
Definition args.hxx:2137
const std::string & Help() const
The description of command.
Definition args.hxx:2162
void Epilog(const std::string &epilog_)
The description that appears below options.
Definition args.hxx:2152
void ProglinePostfix(const std::string &proglinePostfix_)
The description that appears on the prog line after options.
Definition args.hxx:2132
virtual FlagBase * Match(const EitherFlag &flag) override
Return the first FlagBase that matches flag, or nullptr.
Definition args.hxx:2194
virtual bool HasCommand() const override
Get whether this has any Command children.
Definition args.hxx:2299
virtual std::vector< std::string > GetProgramLine(const HelpParams ¶ms) const override
Get the names of positional parameters.
Definition args.hxx:2363
virtual bool HasFlag() const override
Get whether this has any FlagBase children.
Definition args.hxx:2289
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:2388
const std::string & Epilog() const
The description that appears below options.
Definition args.hxx:2147
virtual bool Matched() const noexcept override
Whether or not this group matches validation.
Definition args.hxx:2175
void RequireCommand(bool value)
If value is true, parser will fail if no command was parsed.
Definition args.hxx:2169
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:1474
std::string Get() noexcept
Get the completion reply.
Definition args.hxx:1545
virtual void ParseValue(const std::vector< std::string > &value_) override
Parse values of this option.
Definition args.hxx:1479
An exception that contains autocompletion reply.
Definition args.hxx:565
A flag class that simply counts the number of times it's matched.
Definition args.hxx:3674
int & Get() noexcept
Get the count.
Definition args.hxx:3707
Base error class.
Definition args.hxx:484
Base class for all flag options.
Definition args.hxx:1303
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:3612
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:3632
virtual void ParseValue(const std::vector< std::string > &) override
Parse values of this option.
Definition args.hxx:3637
bool Get() const
Get whether this was matched.
Definition args.hxx:3627
Class for using global options in ArgumentParser.
Definition args.hxx:1941
Class for all kinds of validating groups, including ArgumentParser.
Definition args.hxx:1623
virtual bool HasCommand() const override
Get whether this has any Command children.
Definition args.hxx:1777
std::vector< Base * >::size_type MatchedChildren() const
Count the number of matched children this group has.
Definition args.hxx:1784
virtual bool HasPositional() const override
Get whether this has any PositionalBase children.
Definition args.hxx:1768
virtual std::vector< std::string > GetProgramLine(const HelpParams ¶ms) const override
Get the names of positional parameters.
Definition args.hxx:1849
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:1683
virtual bool HasFlag() const override
Get whether this has any FlagBase children.
Definition args.hxx:1759
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:1681
virtual bool Matched() const noexcept override
Whether or not this group matches validation.
Definition args.hxx:1805
virtual FlagBase * Match(const EitherFlag &flag) override
Return the first FlagBase that matches flag, or nullptr.
Definition args.hxx:1708
bool Get() const
Get validation.
Definition args.hxx:1812
const std::vector< Base * > & Children() const
Get all this group's children.
Definition args.hxx:1698
std::vector< Base * > GetMatchedChildren() const
Get the list of children which were matched.
Definition args.hxx:1793
void Add(Base &child)
Append a child to this Group.
Definition args.hxx:1691
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:1819
virtual PositionalBase * GetNextPositional() override
Get the next ready positional, or nullptr if there is none.
Definition args.hxx:1743
Help flag class.
Definition args.hxx:3647
bool Get() const noexcept
Get whether this was matched.
Definition args.hxx:3665
virtual void ParseValue(const std::vector< std::string > &)
Parse values of this option.
Definition args.hxx:3653
An exception that indicates that the user has requested help.
Definition args.hxx:547
An optional argument-accepting flag class.
Definition args.hxx:4054
virtual void ParseValue(const std::vector< std::string > &value_) override
Parse values of this option.
Definition args.hxx:4082
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:4077
Errors in map lookups.
Definition args.hxx:529
A mapping value flag list class.
Definition args.hxx:4520
Container * operator->() noexcept
Get the values.
Definition args.hxx:4610
Container & Get() noexcept
Get the value.
Definition args.hxx:4589
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4556
Container & operator*() noexcept
Get the value.
Definition args.hxx:4596
A mapping value flag class.
Definition args.hxx:4402
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4432
T & Get() noexcept
Get the value.
Definition args.hxx:4465
T * operator->() noexcept
Get the value.
Definition args.hxx:4486
T & operator*() noexcept
Get the value.
Definition args.hxx:4472
A positional argument mapping list class.
Definition args.hxx:5029
Container & operator*() noexcept
Get the value.
Definition args.hxx:5105
Container * operator->() noexcept
Get the values.
Definition args.hxx:5119
Container & Get() noexcept
Get the value.
Definition args.hxx:5098
A positional argument mapping class.
Definition args.hxx:4918
T * operator->() noexcept
Get the value.
Definition args.hxx:4995
T & Get() noexcept
Get the value.
Definition args.hxx:4974
T & operator*() noexcept
Get the value.
Definition args.hxx:4981
A class of "matchers", specifying short and flags that can possibly be matched.
Definition args.hxx:633
EitherFlag GetShortOrAny() const
(INTERNAL) Get short flag if it exists or any long flag
Definition args.hxx:751
std::vector< EitherFlag > GetFlagStrings() const
(INTERNAL) Get all flag strings as a vector, with the prefixes embedded
Definition args.hxx:716
Matcher(Short &&shortIn, Long &&longIn)
Specify short and long flags separately as iterables.
Definition args.hxx:669
Matcher(ShortIt shortFlagsStart, ShortIt shortFlagsEnd, LongIt longFlagsStart, LongIt longFlagsEnd)
Specify short and long flags separately as iterators.
Definition args.hxx:644
bool Match(const std::string &flag) const
(INTERNAL) Check if there is a match of a long flag
Definition args.hxx:702
EitherFlag GetLongOrAny() const
(INTERNAL) Get long flag if it exists or any short flag
Definition args.hxx:733
bool Match(const char flag) const
(INTERNAL) Check if there is a match of a short flag
Definition args.hxx:695
bool Match(const EitherFlag &flag) const
(INTERNAL) Check if there is a match of a flag
Definition args.hxx:709
Matcher(std::initializer_list< EitherFlag > in)
Specify a mixed single initializer-list of both short and long flags.
Definition args.hxx:685
Base class for all match types that have a name.
Definition args.hxx:1156
void HelpDefault(const std::string &str)
Sets default value string that will be added to argument description.
Definition args.hxx:1192
void HelpChoices(const std::vector< std::string > &array)
Sets choices strings that will be added to argument description.
Definition args.hxx:1208
std::string HelpDefault(const HelpParams ¶ms) const
Gets default value string that will be added to argument description.
Definition args.hxx:1200
std::vector< std::string > HelpChoices(const HelpParams ¶ms) const
Gets choices strings that will be added to argument description.
Definition args.hxx:1216
A variadic arguments accepting flag class.
Definition args.hxx:4105
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:4137
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4142
List< T > * operator->() noexcept
Get the values.
Definition args.hxx:4183
List< T > & operator*() noexcept
Get the value.
Definition args.hxx:4169
Errors that occur during regular parsing.
Definition args.hxx:502
Base class for positional options.
Definition args.hxx:1563
A positional argument class that pushes the found values into a list.
Definition args.hxx:4769
Container & operator*() noexcept
Get the value.
Definition args.hxx:4831
Container & Get() noexcept
Get the values.
Definition args.hxx:4824
Container * operator->() noexcept
Get the values.
Definition args.hxx:4845
A positional argument class.
Definition args.hxx:4684
T & operator*() noexcept
Get the value.
Definition args.hxx:4725
T & Get() noexcept
Get the value.
Definition args.hxx:4718
T * operator->() noexcept
Get the value.
Definition args.hxx:4739
Errors that when a required flag is omitted.
Definition args.hxx:520
Utility class for building subparsers with coroutines/callbacks.
Definition args.hxx:1967
void Parse()
Continue parsing arguments for new command.
Definition args.hxx:3575
const std::vector< std::string > & KickedOut() const noexcept
Returns a vector of kicked out arguments.
Definition args.hxx:2011
bool IsParsed() const
(INTERNAL) Determines whether Parse was called or not.
Definition args.hxx:1998
Errors that occur during usage.
Definition args.hxx:493
Errors that are detected from group validation after parsing finishes.
Definition args.hxx:511
Base class for value-accepting flag options.
Definition args.hxx:1447
virtual Nargs NumberOfArguments() const noexcept override
Defines how many values can be consumed by this option.
Definition args.hxx:1453
An argument-accepting flag class that pushes the found values into a list.
Definition args.hxx:4254
Container * operator->() noexcept
Get the values.
Definition args.hxx:4324
Container & Get() noexcept
Get the values.
Definition args.hxx:4303
Container & operator*() noexcept
Get the value.
Definition args.hxx:4310
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:4284
An argument-accepting flag class.
Definition args.hxx:3952
T & operator*() noexcept
Get the value.
Definition args.hxx:4011
T * operator->() noexcept
Get the value.
Definition args.hxx:4025
T & Get() noexcept
Get the value.
Definition args.hxx:4004
const T & GetDefault() noexcept
Get the default value.
Definition args.hxx:4039
virtual void ParseValue(const std::vector< std::string > &values_) override
Parse values of this option.
Definition args.hxx:3982
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:771
@ 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:575
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:600
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:585
Default validators.
Definition args.hxx:1632
A simple structure of parameters for easy user-modifyable help menus.
Definition args.hxx:827
std::string programName
The program name for help generation.
Definition args.hxx:884
bool showCommandFullHelp
Show command's descriptions and epilog.
Definition args.hxx:892
bool proglineShowFlags
Show flags in program line.
Definition args.hxx:928
std::string usageString
Program line prefix.
Definition args.hxx:936
unsigned int width
The width of the help menu.
Definition args.hxx:830
std::string proglineNonrequiredClose
The postfix for progline non-required argument.
Definition args.hxx:924
unsigned int helpindent
The indent of the flag descriptions.
Definition args.hxx:845
bool proglinePreferShortFlags
Use short flags in program lines when possible.
Definition args.hxx:932
std::string proglineCommand
The prefix for progline when command has any subcommands.
Definition args.hxx:900
std::string proglineOptions
The postfix for progline when showProglineOptions is true and command has any flags.
Definition args.hxx:896
std::string longSeparator
The separator for long flags.
Definition args.hxx:880
bool showValueName
Show value name.
Definition args.hxx:948
bool showTerminator
Show the terminator when both options and positional parameters are present.
Definition args.hxx:856
std::string proglineValueOpen
The prefix for progline value.
Definition args.hxx:904
std::string valueOpen
The prefix for option value.
Definition args.hxx:956
unsigned int progtailindent
The indent of the program trailing lines for long parameters.
Definition args.hxx:836
std::string proglineNonrequiredOpen
The prefix for progline non-required argument.
Definition args.hxx:920
unsigned int descriptionindent
The indent of the description and epilogs.
Definition args.hxx:839
bool showCommandChildren
Show command's flags.
Definition args.hxx:888
bool showProglineOptions
Show the {OPTIONS} on the prog line when this is true.
Definition args.hxx:860
std::string valueClose
The postfix for option value.
Definition args.hxx:960
std::string longPrefix
The prefix for long flags.
Definition args.hxx:872
std::string proglineRequiredClose
The postfix for progline required argument.
Definition args.hxx:916
unsigned int flagindent
The indent of the flags.
Definition args.hxx:842
std::string optionsString
String shown in help before flags descriptions.
Definition args.hxx:940
bool addNewlineBeforeDescription
Add newline before flag description.
Definition args.hxx:952
std::string shortPrefix
The prefix for short flags.
Definition args.hxx:868
bool addDefault
Add default values to argument description.
Definition args.hxx:972
unsigned int gutter
The minimum gutter between each flag and its help.
Definition args.hxx:852
bool showProglinePositionals
Show the positionals on the prog line when this is true.
Definition args.hxx:864
std::string shortSeparator
The separator for short flags.
Definition args.hxx:876
std::string proglineValueClose
The postfix for progline value.
Definition args.hxx:908
bool useValueNameOnce
Display value name after all the long and short flags.
Definition args.hxx:944
std::string defaultString
The prefix for default values.
Definition args.hxx:976
std::string proglineRequiredOpen
The prefix for progline required argument.
Definition args.hxx:912
unsigned int eachgroupindent
The additional indent each group adds.
Definition args.hxx:848
unsigned int progindent
The indent of the program line.
Definition args.hxx:833
bool addChoices
Add choices to argument description.
Definition args.hxx:964
std::string choiceString
The prefix for choices.
Definition args.hxx:968
A number of arguments which can be consumed by an option.
Definition args.hxx:984
A default Reader class for argument classes.
Definition args.hxx:3770