72#define CLI11_VERSION_MAJOR 2
73#define CLI11_VERSION_MINOR 4
74#define CLI11_VERSION_PATCH 2
75#define CLI11_VERSION "2.4.2"
81#if !(defined(_MSC_VER) && __cplusplus == 199711L) && !defined(__INTEL_COMPILER)
82#if __cplusplus >= 201402L
84#if __cplusplus >= 201703L
86#if __cplusplus > 201703L
91#elif defined(_MSC_VER) && __cplusplus == 199711L
94#if _MSVC_LANG >= 201402L
96#if _MSVC_LANG > 201402L && _MSC_VER >= 1910
98#if _MSVC_LANG > 201703L && _MSC_VER >= 1910
105#if defined(CLI11_CPP14)
106#define CLI11_DEPRECATED(reason) [[deprecated(reason)]]
107#elif defined(_MSC_VER)
108#define CLI11_DEPRECATED(reason) __declspec(deprecated(reason))
110#define CLI11_DEPRECATED(reason) __attribute__((deprecated(reason)))
114#if !defined(CLI11_CPP17) || \
115 (defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER) && __GNUC__ < 10 && __GNUC__ > 4)
116#define CLI11_NODISCARD
118#define CLI11_NODISCARD [[nodiscard]]
122#ifndef CLI11_USE_STATIC_RTTI
123#if(defined(_HAS_STATIC_RTTI) && _HAS_STATIC_RTTI)
124#define CLI11_USE_STATIC_RTTI 1
125#elif defined(__cpp_rtti)
126#if(defined(_CPPRTTI) && _CPPRTTI == 0)
127#define CLI11_USE_STATIC_RTTI 1
129#define CLI11_USE_STATIC_RTTI 0
131#elif(defined(__GCC_RTTI) && __GXX_RTTI)
132#define CLI11_USE_STATIC_RTTI 0
134#define CLI11_USE_STATIC_RTTI 1
139#if defined CLI11_CPP17 && defined __has_include && !defined CLI11_HAS_FILESYSTEM
140#if __has_include(<filesystem>)
142#if defined __MAC_OS_X_VERSION_MIN_REQUIRED && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500
143#define CLI11_HAS_FILESYSTEM 0
144#elif defined(__wasi__)
146#define CLI11_HAS_FILESYSTEM 0
149#if defined __cpp_lib_filesystem && __cpp_lib_filesystem >= 201703
150#if defined _GLIBCXX_RELEASE && _GLIBCXX_RELEASE >= 9
151#define CLI11_HAS_FILESYSTEM 1
152#elif defined(__GLIBCXX__)
154#define CLI11_HAS_FILESYSTEM 0
156#define CLI11_HAS_FILESYSTEM 1
159#define CLI11_HAS_FILESYSTEM 0
166#if defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER) && __GNUC__ < 5
167#define CLI11_HAS_CODECVT 0
169#define CLI11_HAS_CODECVT 1
175#define CLI11_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
176#define CLI11_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
178#define CLI11_DIAGNOSTIC_IGNORE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
180#elif defined(_MSC_VER)
181#define CLI11_DIAGNOSTIC_PUSH __pragma(warning(push))
182#define CLI11_DIAGNOSTIC_POP __pragma(warning(pop))
184#define CLI11_DIAGNOSTIC_IGNORE_DEPRECATED __pragma(warning(disable : 4996))
187#define CLI11_DIAGNOSTIC_PUSH
188#define CLI11_DIAGNOSTIC_POP
190#define CLI11_DIAGNOSTIC_IGNORE_DEPRECATED
198#define CLI11_INLINE inline
203#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
207#include <sys/types.h>
214#include <string_view>
217#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
219#include <string_view>
225#if !(defined(_AMD64_) || defined(_X86_) || defined(_ARM_))
226#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || \
229#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(__i386__) || defined(_M_IX86)
231#elif defined(__arm__) || defined(_M_ARM) || defined(_M_ARMT)
233#elif defined(__aarch64__) || defined(_M_ARM64)
235#elif defined(_M_ARM64EC)
253#include <processthreadsapi.h>
262CLI11_INLINE std::string narrow(
const std::wstring &str);
276#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
278CLI11_INLINE std::filesystem::path to_path(std::string_view str);
286#if !CLI11_HAS_CODECVT
291 for(
const auto &locale_name : unicode_locales) {
296 THROW std::runtime_error(
"CLI::narrow: could not set locale to C.UTF-8");
299template <
typename F>
struct scope_guard_t {
302 explicit scope_guard_t(F closure_) : closure(closure_) {}
303 ~scope_guard_t() { closure(); }
327 const wchar_t *it = str;
330 auto sg = scope_guard([&] {
std::setlocale(LC_ALL, old_locale.c_str()); });
331 set_unicode_locale();
335 THROW std::runtime_error(
"CLI::narrow: conversion error in std::wcsrtombs at offset " +
338 std::string result(new_size,
'\0');
339 std::wcsrtombs(
const_cast<char *
>(result.data()), &str, new_size, &state);
358 const char *it = str;
361 auto sg = scope_guard([&] {
std::setlocale(LC_ALL, old_locale.c_str()); });
362 set_unicode_locale();
366 THROW std::runtime_error(
"CLI::widen: conversion error in std::mbsrtowcs at offset " +
369 std::wstring result(new_size, L
'\0');
370 std::mbsrtowcs(
const_cast<wchar_t *
>(result.data()), &str, new_size, &state);
381CLI11_INLINE std::string narrow(
const wchar_t *str,
std::size_t str_size) {
return detail::narrow_impl(str, str_size); }
382CLI11_INLINE std::string narrow(
const std::wstring &str) {
return detail::narrow_impl(str.data(), str.size()); }
386CLI11_INLINE std::wstring widen(
const char *str,
std::size_t str_size) {
return detail::widen_impl(str, str_size); }
387CLI11_INLINE std::wstring widen(
const std::string &str) {
return detail::widen_impl(str.data(), str.size()); }
392CLI11_INLINE std::string narrow(std::wstring_view str) {
return detail::narrow_impl(str.data(), str.size()); }
393CLI11_INLINE std::wstring widen(std::string_view str) {
return detail::widen_impl(str.data(), str.size()); }
396#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
397CLI11_INLINE std::filesystem::path to_path(std::string_view str) {
398 return std::filesystem::path{
414CLI11_INLINE std::vector<std::string> compute_win32_argv();
423CLI11_INLINE std::vector<std::string> compute_win32_argv() {
424 std::vector<std::string> result;
427 auto deleter = [](
wchar_t **ptr) { LocalFree(ptr); };
432 if(wargv ==
nullptr) {
433 THROW std::runtime_error(
"CommandLineToArgvW failed with code " +
std::to_string(GetLastError()));
436 result.reserve(
static_cast<size_t>(argc));
437 for(
size_t i = 0; i < static_cast<size_t>(argc); ++i) {
438 result.push_back(narrow(wargv[i]));
455template <typename T, typename = typename std::enable_if<std::is_enum<T>::value>::type>
456std::ostream &operator<<(std::ostream &in,
const T &item) {
458 return in << static_cast<typename std::underlying_type<T>::type>(item);
464using enums::operator<<;
469constexpr int expected_max_vector_size{1 << 29};
472CLI11_INLINE std::vector<std::string> split(
const std::string &s,
char delim);
475template <
typename T> std::string join(
const T &v, std::string delim =
",") {
476 std::ostringstream s;
477 auto beg = std::begin(v);
478 auto end = std::end(v);
482 s << delim << *beg++;
491std::string join(
const T &v, Callable func, std::string delim =
",") {
492 std::ostringstream s;
493 auto beg = std::begin(v);
494 auto end = std::end(v);
495 auto loc = s.tellp();
497 auto nloc = s.tellp();
508template <
typename T> std::string rjoin(
const T &v, std::string delim =
",") {
509 std::ostringstream s;
510 for(
std::size_t start = 0; start < v.size(); start++) {
513 s << v[v.size() - start - 1];
524CLI11_INLINE std::string <rim(std::string &str,
const std::string &filter);
530CLI11_INLINE std::string &rtrim(std::string &str,
const std::string &filter);
533inline std::string &trim(std::string &str) {
return ltrim(rtrim(str)); }
536inline std::string &trim(std::string &str,
const std::string filter) {
return ltrim(rtrim(str, filter), filter); }
539inline std::string trim_copy(
const std::string &str) {
545CLI11_INLINE std::string &remove_quotes(std::string &str);
548CLI11_INLINE void remove_quotes(std::vector<std::string> &args);
554CLI11_INLINE std::string fix_newlines(
const std::string &leader, std::string input);
557inline std::string trim_copy(
const std::string &str,
const std::string &filter) {
559 return trim(s, filter);
563format_help(std::ostream &out, std::string name,
const std::string &description,
std::size_t wid);
566CLI11_INLINE std::ostream &format_aliases(std::ostream &out,
const std::vector<std::string> &aliases,
std::size_t wid);
570template <
typename T>
bool valid_first_char(T c) {
571 return ((c !=
'-') && (
static_cast<unsigned char>(c) > 33));
575template <
typename T>
bool valid_later_char(T c) {
579 return ((c !=
'=') && (c !=
':') && (c !=
'{') && ((
static_cast<unsigned char>(c) > 32) || c ==
'\t'));
583CLI11_INLINE bool valid_name_string(
const std::string &str);
586inline bool valid_alias_name_string(
const std::string &str) {
587 static const std::string badChars(std::string(
"\n") +
'\0');
588 return (str.find_first_of(badChars) == std::string::npos);
592inline bool is_separator(
const std::string &str) {
593 static const std::string sep(
"%%");
594 return (str.empty() || str == sep);
598inline bool isalpha(
const std::string &str) {
599 return std::all_of(str.begin(), str.end(), [](
char c) { return std::isalpha(c, std::locale()); });
603inline std::string to_lower(std::string str) {
604 std::transform(std::begin(str), std::end(str), std::begin(str), [](
const std::string::value_type &x) {
611inline std::string remove_underscore(std::string str) {
612 str.erase(std::remove(std::begin(str), std::end(str),
'_'), std::end(str));
617CLI11_INLINE std::string find_and_replace(std::string str, std::string from, std::string to);
620inline bool has_default_flag_values(
const std::string &flags) {
621 return (flags.find_first_of(
"{!") != std::string::npos);
624CLI11_INLINE void remove_default_flag_values(std::string &flags);
628 const std::vector<std::string> names,
629 bool ignore_case =
false,
630 bool ignore_underscore =
false);
634template <
typename Callable>
inline std::string find_and_modify(std::string str, std::string trigger, Callable modify) {
636 while((start_pos = str.find(trigger, start_pos)) != std::string::npos) {
637 start_pos = modify(str, start_pos);
648CLI11_INLINE std::vector<std::string> split_up(std::string str,
char delimiter =
'\0');
651CLI11_INLINE std::string get_environment_value(
const std::string &env_name);
662CLI11_INLINE bool has_escapable_character(
const std::string &str);
667CLI11_INLINE std::string add_escaped_characters(
const std::string &str);
670CLI11_INLINE std::string remove_escaped_characters(
const std::string &str);
673CLI11_INLINE std::string binary_escape_string(
const std::string &string_to_escape);
675CLI11_INLINE bool is_binary_escaped_string(
const std::string &escaped_string);
678CLI11_INLINE std::string extract_binary_string(
const std::string &escaped_string);
681CLI11_INLINE bool process_quoted_string(std::string &str,
char string_char =
'\"',
char literal_char =
'\'');
689CLI11_INLINE std::vector<std::string> split(
const std::string &s,
char delim) {
690 std::vector<std::string> elems;
693 elems.emplace_back();
695 std::stringstream ss;
699 elems.push_back(item);
706 auto it =
std::find_if(str.begin(), str.end(), [](
char ch) { return !std::isspace<char>(ch, std::locale()); });
707 str.erase(str.begin(), it);
711CLI11_INLINE std::string <rim(std::string &str,
const std::string &filter) {
712 auto it =
std::find_if(str.begin(), str.end(), [&filter](
char ch) { return filter.find(ch) == std::string::npos; });
713 str.erase(str.begin(), it);
718 auto it =
std::find_if(str.rbegin(), str.rend(), [](
char ch) { return !std::isspace<char>(ch, std::locale()); });
719 str.erase(it.base(), str.end());
723CLI11_INLINE std::string &rtrim(std::string &str,
const std::string &filter) {
725 std::find_if(str.rbegin(), str.rend(), [&filter](
char ch) { return filter.find(ch) == std::string::npos; });
726 str.erase(it.base(), str.end());
730CLI11_INLINE std::string &remove_quotes(std::string &str) {
731 if(str.length() > 1 && (str.front() ==
'"' || str.front() ==
'\'' || str.front() ==
'`')) {
732 if(str.front() == str.back()) {
734 str.erase(str.begin(), str.begin() + 1);
741 if(str.length() > 1 && (str.front() ==
key)) {
742 if(str.front() == str.back()) {
744 str.erase(str.begin(), str.begin() + 1);
750CLI11_INLINE std::string fix_newlines(
const std::string &leader, std::string input) {
751 std::string::size_type n = 0;
752 while(n != std::string::npos && n < input.size()) {
753 n = input.find(
'\n', n);
754 if(n != std::string::npos) {
755 input = input.substr(0, n + 1) + leader + input.substr(n + 1);
763format_help(std::ostream &out, std::string name,
const std::string &description,
std::size_t wid) {
765 out << std::setw(static_cast<int>(wid)) << std::left << name;
766 if(!description.empty()) {
767 if(name.length() >= wid)
768 out <<
"\n" <<
std::setw(
static_cast<int>(wid)) <<
"";
769 for(
const char c : description) {
772 out << std::setw(static_cast<int>(wid)) <<
"";
780CLI11_INLINE std::ostream &format_aliases(std::ostream &out,
const std::vector<std::string> &aliases,
std::size_t wid) {
781 if(!aliases.empty()) {
782 out << std::setw(static_cast<int>(wid)) <<
" aliases: ";
784 for(
const auto &alias : aliases) {
790 out << detail::fix_newlines(
" ", alias);
797CLI11_INLINE bool valid_name_string(
const std::string &str) {
798 if(str.empty() || !valid_first_char(str[0])) {
802 for(
auto c = str.begin() + 1; c != e; ++c)
803 if(!valid_later_char(*c))
808CLI11_INLINE std::string find_and_replace(std::string str, std::string from, std::string to) {
812 while((start_pos = str.find(from, start_pos)) != std::string::npos) {
813 str.replace(start_pos, from.length(), to);
814 start_pos += to.length();
820CLI11_INLINE void remove_default_flag_values(std::string &flags) {
821 auto loc = flags.find_first_of(
'{', 2);
822 while(loc != std::string::npos) {
823 auto finish = flags.find_first_of(
"},", loc + 1);
824 if((finish != std::string::npos) && (flags[finish] ==
'}')) {
828 loc = flags.find_first_of(
'{', loc + 1);
830 flags.erase(std::remove(flags.begin(), flags.end(),
'!'), flags.end());
834find_member(std::string name,
const std::vector<std::string> names,
bool ignore_case,
bool ignore_underscore) {
835 auto it = std::end(names);
837 if(ignore_underscore) {
838 name = detail::to_lower(detail::remove_underscore(name));
839 it =
std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
840 return detail::to_lower(detail::remove_underscore(local_name)) == name;
843 name = detail::to_lower(name);
844 it =
std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
845 return detail::to_lower(local_name) == name;
849 }
else if(ignore_underscore) {
850 name = detail::remove_underscore(name);
851 it =
std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
852 return detail::remove_underscore(local_name) == name;
855 it =
std::find(std::begin(names), std::end(names), name);
858 return (it != std::end(names)) ? (it - std::begin(names)) : (-1);
861static const std::string escapedChars(
"\b\t\n\f\r\"\\");
862static const std::string escapedCharsCode(
"btnfr\"\\");
863static const std::string bracketChars{
"\"'`[(<{"};
864static const std::string matchBracketChars(
"\"'`])>}");
866CLI11_INLINE bool has_escapable_character(
const std::string &str) {
867 return (str.find_first_of(escapedChars) != std::string::npos);
870CLI11_INLINE std::string add_escaped_characters(
const std::string &str) {
872 out.reserve(str.size() + 4);
874 auto sloc = escapedChars.find_first_of(s);
875 if(sloc != std::string::npos) {
877 out.push_back(escapedCharsCode[sloc]);
887 if(hc >=
'0' && hc <=
'9') {
889 }
else if(hc >=
'A' && hc <=
'F') {
890 hcode = (hc -
'A' + 10);
891 }
else if(hc >=
'a' && hc <=
'f') {
892 hcode = (hc -
'a' + 10);
896 return static_cast<uint32_t
>(hcode);
903 str.push_back(
static_cast<char>(code));
904 }
else if(code < 0x800) {
906 str.push_back(make_char(0xC0 | code >> 6));
907 str.push_back(make_char(0x80 | (code & 0x3F)));
908 }
else if(code < 0x10000) {
909 if(0xD800 <= code && code <= 0xDFFF) {
910 THROW std::invalid_argument(
"[0xD800, 0xDFFF] are not valid UTF-8.");
913 str.push_back(make_char(0xE0 | code >> 12));
914 str.push_back(make_char(0x80 | (code >> 6 & 0x3F)));
915 str.push_back(make_char(0x80 | (code & 0x3F)));
916 }
else if(code < 0x110000) {
918 str.push_back(make_char(0xF0 | code >> 18));
919 str.push_back(make_char(0x80 | (code >> 12 & 0x3F)));
920 str.push_back(make_char(0x80 | (code >> 6 & 0x3F)));
921 str.push_back(make_char(0x80 | (code & 0x3F)));
925CLI11_INLINE std::string remove_escaped_characters(
const std::string &str) {
928 out.reserve(str.size());
929 for(
auto loc = str.begin(); loc < str.end(); ++loc) {
931 if(str.end() - loc < 2) {
932 THROW std::invalid_argument(
"invalid escape sequence " + str);
934 auto ecloc = escapedCharsCode.find_first_of(*(loc + 1));
935 if(ecloc != std::string::npos) {
936 out.push_back(escapedChars[ecloc]);
938 }
else if(*(loc + 1) ==
'u') {
940 if(str.end() - loc < 6) {
941 THROW std::invalid_argument(
"unicode sequence must have 4 hex codes " + str);
945 for(
int ii = 2; ii < 6; ++ii) {
948 THROW std::invalid_argument(
"unicode sequence must have 4 hex codes " + str);
950 code += res * mplier;
951 mplier = mplier / 16;
953 append_codepoint(out, code);
955 }
else if(*(loc + 1) ==
'U') {
957 if(str.end() - loc < 10) {
958 THROW std::invalid_argument(
"unicode sequence must have 8 hex codes " + str);
962 for(
int ii = 2; ii < 10; ++ii) {
965 THROW std::invalid_argument(
"unicode sequence must have 8 hex codes " + str);
967 code += res * mplier;
968 mplier = mplier / 16;
970 append_codepoint(out, code);
972 }
else if(*(loc + 1) ==
'0') {
976 THROW std::invalid_argument(std::string(
"unrecognized escape sequence \\") + *(loc + 1) +
" in " + str);
987 for(loc = start + 1; loc < str.size(); ++loc) {
988 if(str[loc] == closure_char) {
991 if(str[loc] ==
'\\') {
1000 auto loc = str.find_first_of(closure_char, start + 1);
1001 return (loc != std::string::npos ? loc : str.size());
1006 auto bracket_loc = matchBracketChars.find(closure_char);
1007 switch(bracket_loc) {
1009 return close_string_quote(str, start, closure_char);
1012 case std::string::npos:
1013 return close_literal_quote(str, start, closure_char);
1018 std::string closures(1, closure_char);
1019 auto loc = start + 1;
1021 while(loc < str.size()) {
1022 if(str[loc] == closures.back()) {
1023 closures.pop_back();
1024 if(closures.empty()) {
1028 bracket_loc = bracketChars.find(str[loc]);
1029 if(bracket_loc != std::string::npos) {
1030 switch(bracket_loc) {
1032 loc = close_string_quote(str, loc, str[loc]);
1036 loc = close_literal_quote(str, loc, str[loc]);
1039 closures.push_back(matchBracketChars[bracket_loc]);
1045 if(loc > str.size()) {
1051CLI11_INLINE std::vector<std::string> split_up(std::string str,
char delimiter) {
1053 auto find_ws = [delimiter](
char ch) {
1058 std::vector<std::string> output;
1059 while(!str.empty()) {
1060 if(bracketChars.find_first_of(str[0]) != std::string::npos) {
1061 auto bracketLoc = bracketChars.find_first_of(str[0]);
1062 auto end = close_sequence(str, 0, matchBracketChars[bracketLoc]);
1063 if(end >= str.size()) {
1067 output.push_back(str.substr(0, end + 1));
1068 if(end + 2 < str.size()) {
1069 str = str.substr(end + 2);
1076 auto it =
std::find_if(std::begin(str), std::end(str), find_ws);
1077 if(it != std::end(str)) {
1078 std::string
value = std::string(str.begin(), it);
1079 output.push_back(
value);
1080 str = std::string(it + 1, str.end());
1082 output.push_back(str);
1092 auto next = str[
offset + 1];
1093 if((next ==
'\"') || (next ==
'\'') || (next ==
'`')) {
1094 auto astart = str.find_last_of(
"-/ \"\'`",
offset - 1);
1095 if(astart != std::string::npos) {
1096 if(str[astart] == ((str[
offset] ==
'=') ?
'-' :
'/'))
1103CLI11_INLINE std::string binary_escape_string(
const std::string &string_to_escape) {
1105 std::string escaped_string{};
1107 for(
char c : string_to_escape) {
1110 if(isprint(
static_cast<unsigned char>(c)) == 0) {
1111 std::stringstream stream;
1115 stream << std::hex << static_cast<unsigned int>(
static_cast<unsigned char>(c));
1116 std::string code = stream.str();
1117 escaped_string += std::string(
"\\x") + (code.size() < 2 ?
"0" :
"") + code;
1120 escaped_string.push_back(c);
1123 if(escaped_string != string_to_escape) {
1124 auto sqLoc = escaped_string.find(
'\'');
1125 while(sqLoc != std::string::npos) {
1126 escaped_string.replace(sqLoc, sqLoc + 1,
"\\x27");
1127 sqLoc = escaped_string.find(
'\'');
1129 escaped_string.insert(0,
"'B\"(");
1130 escaped_string.push_back(
')');
1131 escaped_string.push_back(
'"');
1132 escaped_string.push_back(
'\'');
1134 return escaped_string;
1137CLI11_INLINE bool is_binary_escaped_string(
const std::string &escaped_string) {
1138 size_t ssize = escaped_string.size();
1139 if(escaped_string.compare(0, 3,
"B\"(") == 0 && escaped_string.compare(ssize - 2, 2,
")\"") == 0) {
1142 return (escaped_string.compare(0, 4,
"'B\"(") == 0 && escaped_string.compare(ssize - 3, 3,
")\"'") == 0);
1145CLI11_INLINE std::string extract_binary_string(
const std::string &escaped_string) {
1148 size_t ssize = escaped_string.size();
1149 if(escaped_string.compare(0, 3,
"B\"(") == 0 && escaped_string.compare(ssize - 2, 2,
")\"") == 0) {
1152 }
else if(escaped_string.compare(0, 4,
"'B\"(") == 0 && escaped_string.compare(ssize - 3, 3,
")\"'") == 0) {
1158 return escaped_string;
1160 std::string outstring;
1162 outstring.reserve(ssize - start - tail);
1164 while(loc < ssize - tail) {
1166 if(escaped_string[loc] ==
'\\' && (escaped_string[loc + 1] ==
'x' || escaped_string[loc + 1] ==
'X')) {
1167 auto c1 = escaped_string[loc + 2];
1168 auto c2 = escaped_string[loc + 3];
1172 if(res1 <= 0x0F && res2 <= 0x0F) {
1174 outstring.push_back(
static_cast<char>(res1 * 16 + res2));
1178 outstring.push_back(escaped_string[loc]);
1184CLI11_INLINE void remove_quotes(std::vector<std::string> &args) {
1185 for(
auto &arg : args) {
1186 if(arg.front() ==
'\"' && arg.back() ==
'\"') {
1189 arg = remove_escaped_characters(arg);
1196CLI11_INLINE bool process_quoted_string(std::string &str,
char string_char,
char literal_char) {
1197 if(str.size() <= 1) {
1200 if(detail::is_binary_escaped_string(str)) {
1201 str = detail::extract_binary_string(str);
1204 if(str.front() == string_char && str.back() == string_char) {
1205 detail::remove_outer(str, string_char);
1206 if(str.find_first_of(
'\\') != std::string::npos) {
1207 str = detail::remove_escaped_characters(str);
1211 if((str.front() == literal_char || str.front() ==
'`') && str.back() == str.front()) {
1212 detail::remove_outer(str, str.front());
1218std::string get_environment_value(
const std::string &env_name) {
1220 std::string ename_string;
1225 if(_dupenv_s(&
buffer, &sz, env_name.c_str()) == 0 &&
buffer !=
nullptr) {
1226 ename_string = std::string(
buffer);
1233 ename_string = std::string(
buffer);
1236 return ename_string;
1245#define CLI11_ERROR_DEF(parent, name) \
1247 name(std::string ename, std::string msg, int exit_code) : parent(std::move(ename), std::move(msg), exit_code) {} \
1248 name(std::string ename, std::string msg, ExitCodes exit_code) \
1249 : parent(std::move(ename), std::move(msg), exit_code) {} \
1252 name(std::string msg, ExitCodes exit_code) : parent(#name, std::move(msg), exit_code) {} \
1253 name(std::string msg, int exit_code) : parent(#name, std::move(msg), exit_code) {}
1256#define CLI11_ERROR_SIMPLE(name) \
1257 explicit name(std::string msg) : name(#name, msg, ExitCodes::name) {}
1261enum class ExitCodes {
1263 IncorrectConstruction = 100,
1290class Error :
public std::runtime_error {
1291 int actual_exit_code;
1292 std::string error_name{
"Error"};
1295 CLI11_NODISCARD int get_exit_code()
const {
return actual_exit_code; }
1299 Error(std::string name, std::string msg,
int exit_code =
static_cast<int>(ExitCodes::BaseClass))
1300 : runtime_error(msg), actual_exit_code(exit_code), error_name(
std::move(name)) {}
1302 Error(std::string name, std::string msg, ExitCodes exit_code) : Error(name, msg,
static_cast<int>(exit_code)) {}
1308class ConstructionError :
public Error {
1313class IncorrectConstruction :
public ConstructionError {
1316 static IncorrectConstruction PositionalFlag(std::string name) {
1317 return IncorrectConstruction(name +
": Flags cannot be positional");
1319 static IncorrectConstruction Set0Opt(std::string name) {
1320 return IncorrectConstruction(name +
": Cannot set 0 expected, use a flag instead");
1322 static IncorrectConstruction SetFlag(std::string name) {
1323 return IncorrectConstruction(name +
": Cannot set an expected number for flags");
1325 static IncorrectConstruction ChangeNotVector(std::string name) {
1326 return IncorrectConstruction(name +
": You can only change the expected arguments for vectors");
1328 static IncorrectConstruction AfterMultiOpt(std::string name) {
1329 return IncorrectConstruction(
1330 name +
": You can't change expected arguments after you've changed the multi option policy!");
1332 static IncorrectConstruction MissingOption(std::string name) {
1333 return IncorrectConstruction(
"Option " + name +
" is not defined");
1335 static IncorrectConstruction MultiOptionPolicy(std::string name) {
1336 return IncorrectConstruction(name +
": multi_option_policy only works for flags and exact value options");
1341class BadNameString :
public ConstructionError {
1344 static BadNameString OneCharName(std::string name) {
return BadNameString(
"Invalid one char name: " + name); }
1345 static BadNameString MissingDash(std::string name) {
1346 return BadNameString(
"Long names strings require 2 dashes " + name);
1348 static BadNameString BadLongName(std::string name) {
return BadNameString(
"Bad long name: " + name); }
1349 static BadNameString BadPositionalName(std::string name) {
1350 return BadNameString(
"Invalid positional Name: " + name);
1352 static BadNameString DashesOnly(std::string name) {
1353 return BadNameString(
"Must have a name, not just dashes: " + name);
1355 static BadNameString MultiPositionalNames(std::string name) {
1356 return BadNameString(
"Only one positional name allowed, remove: " + name);
1361class OptionAlreadyAdded :
public ConstructionError {
1363 explicit OptionAlreadyAdded(std::string name)
1364 : OptionAlreadyAdded(name +
" is already added", ExitCodes::OptionAlreadyAdded) {}
1365 static OptionAlreadyAdded Requires(std::string name, std::string other) {
1366 return {name +
" requires " + other, ExitCodes::OptionAlreadyAdded};
1368 static OptionAlreadyAdded Excludes(std::string name, std::string other) {
1369 return {name +
" excludes " + other, ExitCodes::OptionAlreadyAdded};
1376class ParseError :
public Error {
1383class Success :
public ParseError {
1385 Success() : Success(
"Successfully completed, should be caught and quit", ExitCodes::Success) {}
1389class CallForHelp :
public Success {
1391 CallForHelp() : CallForHelp(
"This should be caught in your main function, see examples", ExitCodes::Success) {}
1395class CallForAllHelp :
public Success {
1398 : CallForAllHelp(
"This should be caught in your main function, see examples", ExitCodes::Success) {}
1402class CallForVersion :
public Success {
1405 : CallForVersion(
"This should be caught in your main function, see examples", ExitCodes::Success) {}
1409class RuntimeError :
public ParseError {
1411 explicit RuntimeError(
int exit_code = 1) : RuntimeError(
"Runtime error", exit_code) {}
1415class FileError :
public ParseError {
1418 static FileError Missing(std::string name) {
return FileError(name +
" was not readable (missing?)"); }
1422class ConversionError :
public ParseError {
1425 ConversionError(std::string member, std::string name)
1426 : ConversionError(
"The value " + member +
" is not an allowed value for " + name) {}
1427 ConversionError(std::string name, std::vector<std::string> results)
1428 : ConversionError(
"Could not convert: " + name +
" = " + detail::join(results)) {}
1429 static ConversionError TooManyInputsFlag(std::string name) {
1430 return ConversionError(name +
": too many inputs for a flag");
1432 static ConversionError TrueFalse(std::string name) {
1433 return ConversionError(name +
": Should be true/false or a number");
1438class ValidationError :
public ParseError {
1441 explicit ValidationError(std::string name, std::string msg) : ValidationError(name +
": " + msg) {}
1445class RequiredError :
public ParseError {
1447 explicit RequiredError(std::string name) : RequiredError(name +
" is required", ExitCodes::RequiredError) {}
1448 static RequiredError Subcommand(
std::size_t min_subcom) {
1449 if(min_subcom == 1) {
1450 return RequiredError(
"A subcommand");
1452 return {
"Requires at least " +
std::to_string(min_subcom) +
" subcommands", ExitCodes::RequiredError};
1454 static RequiredError
1456 if((min_option == 1) && (max_option == 1) && (used == 0))
1457 return RequiredError(
"Exactly 1 option from [" + option_list +
"]");
1458 if((min_option == 1) && (max_option == 1) && (used > 1)) {
1459 return {
"Exactly 1 option from [" + option_list +
"] is required but " +
std::to_string(used) +
1461 ExitCodes::RequiredError};
1463 if((min_option == 1) && (used == 0))
1464 return RequiredError(
"At least 1 option from [" + option_list +
"]");
1465 if(used < min_option) {
1466 return {
"Requires at least " +
std::to_string(min_option) +
" options used but only " +
1468 ExitCodes::RequiredError};
1471 return {
"Requires at most 1 options be given from [" + option_list +
"]", ExitCodes::RequiredError};
1474 " were given from [" + option_list +
"]",
1475 ExitCodes::RequiredError};
1480class ArgumentMismatch :
public ParseError {
1483 ArgumentMismatch(std::string name,
int expected,
std::size_t received)
1484 : ArgumentMismatch(expected > 0 ? (
"Expected exactly " +
std::to_string(expected) +
" arguments to " + name +
1486 : (
"Expected at least " +
std::to_string(-expected) +
" arguments to " + name +
1488 ExitCodes::ArgumentMismatch) {}
1490 static ArgumentMismatch AtLeast(std::string name,
int num,
std::size_t received) {
1491 return ArgumentMismatch(name +
": At least " +
std::to_string(num) +
" required but received " +
1494 static ArgumentMismatch AtMost(std::string name,
int num,
std::size_t received) {
1495 return ArgumentMismatch(name +
": At Most " +
std::to_string(num) +
" required but received " +
1498 static ArgumentMismatch TypedAtLeast(std::string name,
int num, std::string type) {
1499 return ArgumentMismatch(name +
": " +
std::to_string(num) +
" required " + type +
" missing");
1501 static ArgumentMismatch FlagOverride(std::string name) {
1502 return ArgumentMismatch(name +
" was given a disallowed flag override");
1504 static ArgumentMismatch PartialType(std::string name,
int num, std::string type) {
1505 return ArgumentMismatch(name +
": " + type +
" only partially specified: " +
std::to_string(num) +
1506 " required for each element");
1511class RequiresError :
public ParseError {
1513 RequiresError(std::string curname, std::string subname)
1514 : RequiresError(curname +
" requires " + subname, ExitCodes::RequiresError) {}
1518class ExcludesError :
public ParseError {
1520 ExcludesError(std::string curname, std::string subname)
1521 : ExcludesError(curname +
" excludes " + subname, ExitCodes::ExcludesError) {}
1525class ExtrasError :
public ParseError {
1527 explicit ExtrasError(std::vector<std::string> args)
1528 : ExtrasError((args.size() > 1 ?
"The following arguments were not expected: "
1529 :
"The following argument was not expected: ") +
1530 detail::rjoin(args,
" "),
1531 ExitCodes::ExtrasError) {}
1532 ExtrasError(
const std::string &name, std::vector<std::string> args)
1534 (args.size() > 1 ?
"The following arguments were not expected: "
1535 :
"The following argument was not expected: ") +
1536 detail::rjoin(args,
" "),
1537 ExitCodes::ExtrasError) {}
1541class ConfigError :
public ParseError {
1544 static ConfigError Extras(std::string item) {
return ConfigError(
"INI was not able to parse " + item); }
1545 static ConfigError NotConfigurable(std::string item) {
1546 return ConfigError(item +
": This option is not allowed in a configuration file");
1551class InvalidError :
public ParseError {
1553 explicit InvalidError(std::string name)
1554 : InvalidError(name +
": Too many positional arguments with unlimited expected args", ExitCodes::InvalidError) {
1560class HorribleError :
public ParseError {
1568class OptionNotFound :
public Error {
1570 explicit OptionNotFound(std::string name) : OptionNotFound(name +
" not found", ExitCodes::OptionNotFound) {}
1573#undef CLI11_ERROR_DEF
1574#undef CLI11_ERROR_SIMPLE
1587enum class enabler {};
1590constexpr enabler dummy = {};
1598template <
bool B,
class T =
void>
using enable_if_t =
typename std::enable_if<B, T>::type;
1601template <
typename... Ts>
struct make_void {
1606template <
typename... Ts>
using void_t =
typename make_void<Ts...>::type;
1609template <
bool B,
class T,
class F>
using conditional_t =
typename std::conditional<B, T, F>::type;
1612template <
typename T>
struct is_bool : std::false_type {};
1615template <>
struct is_bool<bool> : std::true_type {};
1618template <
typename T>
struct is_shared_ptr : std::false_type {};
1621template <
typename T>
struct is_shared_ptr<
std::shared_ptr<T>> : std::true_type {};
1624template <
typename T>
struct is_shared_ptr<const
std::shared_ptr<T>> : std::true_type {};
1627template <
typename T>
struct is_copyable_ptr {
1628 static bool const value = is_shared_ptr<T>::value || std::is_pointer<T>::value;
1632template <
typename T>
struct IsMemberType {
1637template <>
struct IsMemberType<const char *> {
1638 using type = std::string;
1641namespace adl_detail {
1647template <
typename T,
typename S = std::
string>
class is_lexical_castable {
1648 template <
typename TT,
typename SS>
1651 template <
typename,
typename>
static auto test(...) -> std::false_type;
1654 static constexpr bool value =
decltype(test<T, S>(0))
::value;
1666template <
typename T,
typename Enable =
void>
struct element_type {
1670template <
typename T>
struct element_type<T, typename
std::enable_if<is_copyable_ptr<T>::value>::type> {
1671 using type =
typename std::pointer_traits<T>::element_type;
1676template <
typename T>
struct element_value_type {
1677 using type =
typename element_type<T>::type::value_type;
1681template <
typename T,
typename _ =
void>
struct pair_adaptor : std::false_type {
1682 using value_type =
typename T::value_type;
1683 using first_type =
typename std::remove_const<value_type>::type;
1684 using second_type =
typename std::remove_const<value_type>::type;
1687 template <
typename Q>
static auto first(Q &&pair_value) ->
decltype(
std::forward<Q>(pair_value)) {
1691 template <
typename Q>
static auto second(Q &&pair_value) ->
decltype(
std::forward<Q>(pair_value)) {
1698template <
typename T>
1701 conditional_t<false, void_t<typename T::value_type::first_type, typename T::value_type::second_type>, void>>
1703 using value_type =
typename T::value_type;
1704 using first_type =
typename std::remove_const<typename value_type::first_type>::type;
1705 using second_type =
typename std::remove_const<typename value_type::second_type>::type;
1724#pragma GCC diagnostic push
1725#pragma GCC diagnostic ignored "-Wnarrowing"
1728template <
typename T,
typename C>
class is_direct_constructible {
1729 template <
typename TT,
typename CC>
1730 static auto test(
int, std::true_type) ->
decltype(
1733#ifdef __NVCC_DIAG_PRAGMA_SUPPORT__
1734#pragma nv_diag_suppress 2361
1736#pragma diag_suppress 2361
1741#ifdef __NVCC_DIAG_PRAGMA_SUPPORT__
1742#pragma nv_diag_default 2361
1744#pragma diag_default 2361
1750 template <
typename TT,
typename CC>
static auto test(
int, std::false_type) -> std::false_type;
1752 template <
typename,
typename>
static auto test(...) -> std::false_type;
1755 static constexpr bool value =
decltype(test<T, C>(0,
typename std::is_constructible<T, C>::type()))
::value;
1758#pragma GCC diagnostic pop
1764template <
typename T,
typename S = std::o
stringstream>
class is_ostreamable {
1765 template <
typename TT,
typename SS>
1768 template <
typename,
typename>
static auto test(...) -> std::false_type;
1771 static constexpr bool value =
decltype(test<T, S>(0))
::value;
1775template <
typename T,
typename S = std::i
stringstream>
class is_istreamable {
1776 template <
typename TT,
typename SS>
1779 template <
typename,
typename>
static auto test(...) -> std::false_type;
1782 static constexpr bool value =
decltype(test<T, S>(0))
::value;
1786template <
typename T>
class is_complex {
1787 template <
typename TT>
1790 template <
typename>
static auto test(...) -> std::false_type;
1793 static constexpr bool value =
decltype(test<T>(0))
::value;
1797template <typename T, enable_if_t<is_istreamable<T>::value, detail::enabler> = detail::dummy>
1798bool from_stream(
const std::string &istring, T &obj) {
1799 std::istringstream is;
1802 return !is.fail() && !is.rdbuf()->in_avail();
1805template <typename T, enable_if_t<!is_istreamable<T>::value, detail::enabler> = detail::dummy>
1806bool from_stream(
const std::string & , T & ) {
1811template <
typename T,
typename _ =
void>
struct is_mutable_container : std::false_type {};
1816template <
typename T>
1817struct is_mutable_container<
1819 conditional_t<false,
1820 void_t<typename T::value_type,
1821 decltype(std::declval<T>().end()),
1822 decltype(std::declval<T>().clear()),
1823 decltype(std::declval<T>().insert(std::declval<decltype(std::declval<T>().end())>(),
1824 std::declval<const typename T::value_type &>()))>,
1825 void>> :
public conditional_t<std::is_constructible<T, std::string>::value ||
1826 std::is_constructible<T, std::wstring>::value,
1831template <
typename T,
typename _ =
void>
struct is_readable_container : std::false_type {};
1836template <
typename T>
1837struct is_readable_container<
1839 conditional_t<false, void_t<decltype(
std::declval<T>().end()), decltype(std::declval<T>().begin())>, void>>
1840 :
public std::true_type {};
1843template <
typename T,
typename _ =
void>
struct is_wrapper : std::false_type {};
1846template <
typename T>
1847struct is_wrapper<T, conditional_t<false, void_t<typename T::value_type>, void>> :
public std::true_type {};
1850template <
typename S>
class is_tuple_like {
1851 template <
typename SS>
1855 template <
typename>
static auto test(...) -> std::false_type;
1858 static constexpr bool value =
decltype(test<S>(0))
::value;
1862template <typename T, enable_if_t<std::is_convertible<T, std::string>::value, detail::enabler> = detail::dummy>
1868template <
typename T,
1869 enable_if_t<std::is_constructible<std::string, T>::value && !std::is_convertible<T, std::string>::value,
1870 detail::enabler> = detail::dummy>
1871std::string to_string(
const T &
value) {
1872 return std::string(
value);
1876template <
typename T,
1877 enable_if_t<!std::is_convertible<std::string, T>::value && !std::is_constructible<std::string, T>::value &&
1878 is_ostreamable<T>::value,
1879 detail::enabler> = detail::dummy>
1880std::string to_string(T &&
value) {
1881 std::stringstream stream;
1883 return stream.str();
1887template <
typename T,
1888 enable_if_t<!std::is_constructible<std::string, T>::value && !is_ostreamable<T>::value &&
1889 !is_readable_container<typename std::remove_const<T>::type>
::value,
1890 detail::enabler> = detail::dummy>
1891std::string to_string(T &&) {
1896template <
typename T,
1897 enable_if_t<!std::is_constructible<std::string, T>::value && !is_ostreamable<T>::value &&
1898 is_readable_container<T>::value,
1899 detail::enabler> = detail::dummy>
1900std::string to_string(T &&variable) {
1901 auto cval = variable.begin();
1902 auto end = variable.end();
1906 std::vector<std::string> defaults;
1907 while(cval != end) {
1908 defaults.emplace_back(CLI::detail::to_string(*cval));
1911 return {
"[" + detail::join(defaults) +
"]"};
1915template <
typename T1,
1918 enable_if_t<std::is_same<T1, T2>::value, detail::enabler> = detail::dummy>
1924template <
typename T1,
1927 enable_if_t<!std::is_same<T1, T2>::value, detail::enabler> = detail::dummy>
1928std::string checked_to_string(T &&) {
1929 return std::string{};
1932template <typename T, enable_if_t<std::is_arithmetic<T>::value, detail::enabler> = detail::dummy>
1933std::string value_string(
const T &
value) {
1937template <typename T, enable_if_t<std::is_enum<T>::value, detail::enabler> = detail::dummy>
1938std::string value_string(
const T &
value) {
1942template <
typename T,
1943 enable_if_t<!std::is_enum<T>::value && !std::is_arithmetic<T>::value, detail::enabler> = detail::dummy>
1944auto value_string(
const T &
value) ->
decltype(to_string(
value)) {
1945 return to_string(
value);
1949template <
typename T,
typename def,
typename Enable =
void>
struct wrapped_type {
1954template <
typename T,
typename def>
struct wrapped_type<T, def, typename
std::enable_if<is_wrapper<T>::value>::type> {
1955 using type =
typename T::value_type;
1959template <
typename T,
typename Enable =
void>
struct type_count_base {
1960 static const int value{0};
1964template <
typename T>
1965struct type_count_base<T,
1966 typename
std::enable_if<!is_tuple_like<T>::value && !is_mutable_container<T>::value &&
1967 !std::is_void<T>::value>::type> {
1968 static constexpr int value{1};
1972template <
typename T>
1973struct type_count_base<T, typename
std::enable_if<is_tuple_like<T>::value && !is_mutable_container<T>::value>::type> {
1974 static constexpr int value{std::tuple_size<T>::value};
1978template <
typename T>
struct type_count_base<T, typename
std::enable_if<is_mutable_container<T>::value>::type> {
1979 static constexpr int value{type_count_base<typename T::value_type>::value};
1985template <
typename T>
struct subtype_count;
1988template <
typename T>
struct subtype_count_min;
1991template <
typename T,
typename Enable =
void>
struct type_count {
1992 static const int value{0};
1996template <
typename T>
1998 typename
std::enable_if<!is_wrapper<T>::value && !is_tuple_like<T>::value && !is_complex<T>::value &&
1999 !std::is_void<T>::value>::type> {
2000 static constexpr int value{1};
2004template <
typename T>
struct type_count<T, typename
std::enable_if<is_complex<T>::value>::type> {
2005 static constexpr int value{2};
2009template <
typename T>
struct type_count<T, typename
std::enable_if<is_mutable_container<T>::value>::type> {
2010 static constexpr int value{subtype_count<typename T::value_type>::value};
2014template <
typename T>
2016 typename
std::enable_if<is_wrapper<T>::value && !is_complex<T>::value && !is_tuple_like<T>::value &&
2017 !is_mutable_container<T>::value>::type> {
2018 static constexpr int value{type_count<typename T::value_type>::value};
2022template <
typename T, std::
size_t I>
2028template <
typename T, std::
size_t I>
2030 return subtype_count<typename std::tuple_element<I, T>::type>
::value + tuple_type_size<T, I + 1>();
2034template <
typename T>
struct type_count<T, typename
std::enable_if<is_tuple_like<T>::value>::type> {
2035 static constexpr int value{tuple_type_size<T, 0>()};
2039template <
typename T>
struct subtype_count {
2040 static constexpr int value{is_mutable_container<T>::value ? expected_max_vector_size : type_count<T>::value};
2044template <
typename T,
typename Enable =
void>
struct type_count_min {
2045 static const int value{0};
2049template <
typename T>
2050struct type_count_min<
2052 typename
std::enable_if<!is_mutable_container<T>::value && !is_tuple_like<T>::value && !is_wrapper<T>::value &&
2053 !is_complex<T>::value && !std::is_void<T>::value>::type> {
2054 static constexpr int value{type_count<T>::value};
2058template <
typename T>
struct type_count_min<T, typename
std::enable_if<is_complex<T>::value>::type> {
2059 static constexpr int value{1};
2063template <
typename T>
2064struct type_count_min<
2066 typename
std::enable_if<is_wrapper<T>::value && !is_complex<T>::value && !is_tuple_like<T>::value>::type> {
2067 static constexpr int value{subtype_count_min<typename T::value_type>::value};
2071template <
typename T, std::
size_t I>
2077template <
typename T, std::
size_t I>
2079 return subtype_count_min<typename std::tuple_element<I, T>::type>
::value + tuple_type_size_min<T, I + 1>();
2083template <
typename T>
struct type_count_min<T, typename
std::enable_if<is_tuple_like<T>::value>::type> {
2084 static constexpr int value{tuple_type_size_min<T, 0>()};
2088template <
typename T>
struct subtype_count_min {
2089 static constexpr int value{is_mutable_container<T>::value
2090 ? ((type_count<T>::value < expected_max_vector_size) ? type_count<T>::value : 0)
2091 : type_count_min<T>::value};
2095template <
typename T,
typename Enable =
void>
struct expected_count {
2096 static const int value{0};
2100template <
typename T>
2101struct expected_count<T,
2102 typename
std::enable_if<!is_mutable_container<T>::value && !is_wrapper<T>::value &&
2103 !std::is_void<T>::value>::type> {
2104 static constexpr int value{1};
2107template <
typename T>
struct expected_count<T, typename
std::enable_if<is_mutable_container<T>::value>::type> {
2108 static constexpr int value{expected_max_vector_size};
2112template <
typename T>
2113struct expected_count<T, typename
std::enable_if<!is_mutable_container<T>::value && is_wrapper<T>::value>::type> {
2114 static constexpr int value{expected_count<typename T::value_type>::value};
2118enum class object_category :
int {
2121 unsigned_integral = 4,
2124 floating_point = 10,
2125 number_constructible = 12,
2126 double_constructible = 14,
2127 integer_constructible = 16,
2129 string_assignable = 23,
2130 string_constructible = 24,
2131 wstring_assignable = 25,
2132 wstring_constructible = 26,
2136 complex_number = 60,
2138 container_value = 80,
2145template <
typename T,
typename Enable =
void>
struct classify_object {
2146 static constexpr object_category
value{object_category::other};
2150template <
typename T>
2151struct classify_object<
2153 typename
std::enable_if<std::is_integral<T>::value && !std::is_same<T, char>::value && std::is_signed<T>::value &&
2154 !is_bool<T>::value && !std::is_enum<T>::value>::type> {
2155 static constexpr object_category
value{object_category::integral_value};
2159template <
typename T>
2160struct classify_object<T,
2161 typename
std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value &&
2162 !std::is_same<T, char>::value && !is_bool<T>::value>::type> {
2163 static constexpr object_category
value{object_category::unsigned_integral};
2167template <
typename T>
2168struct classify_object<T, typename
std::enable_if<std::is_same<T, char>::value && !std::is_enum<T>::value>::type> {
2169 static constexpr object_category
value{object_category::char_value};
2173template <
typename T>
struct classify_object<T, typename
std::enable_if<is_bool<T>::value>::type> {
2174 static constexpr object_category
value{object_category::boolean_value};
2178template <
typename T>
struct classify_object<T, typename
std::enable_if<std::is_floating_point<T>::value>::type> {
2179 static constexpr object_category
value{object_category::floating_point};
2184#define WIDE_STRING_CHECK \
2185 !std::is_assignable<T &, std::wstring>::value && !std::is_constructible<T, std::wstring>::value
2186#define STRING_CHECK true
2188#define WIDE_STRING_CHECK true
2189#define STRING_CHECK !std::is_assignable<T &, std::string>::value && !std::is_constructible<T, std::string>::value
2193template <
typename T>
2194struct classify_object<
2196 typename
std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value && WIDE_STRING_CHECK &&
2197 std::is_assignable<T &, std::string>::value>::type> {
2198 static constexpr object_category
value{object_category::string_assignable};
2202template <
typename T>
2203struct classify_object<
2205 typename
std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
2206 !std::is_assignable<T &, std::string>::value && (type_count<T>::value == 1) &&
2207 WIDE_STRING_CHECK && std::is_constructible<T, std::string>::value>::type> {
2208 static constexpr object_category
value{object_category::string_constructible};
2212template <
typename T>
2213struct classify_object<T,
2214 typename
std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
2215 STRING_CHECK && std::is_assignable<T &, std::wstring>::value>::type> {
2216 static constexpr object_category
value{object_category::wstring_assignable};
2219template <
typename T>
2220struct classify_object<
2222 typename
std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
2223 !std::is_assignable<T &, std::wstring>::value && (type_count<T>::value == 1) &&
2224 STRING_CHECK && std::is_constructible<T, std::wstring>::value>::type> {
2225 static constexpr object_category
value{object_category::wstring_constructible};
2229template <
typename T>
struct classify_object<T, typename
std::enable_if<std::is_enum<T>::value>::type> {
2230 static constexpr object_category
value{object_category::enumeration};
2233template <
typename T>
struct classify_object<T, typename
std::enable_if<is_complex<T>::value>::type> {
2234 static constexpr object_category
value{object_category::complex_number};
2239template <
typename T>
struct uncommon_type {
2241 !std::is_floating_point<T>::value && !std::is_integral<T>::value &&
2242 !std::is_assignable<T &, std::string>::value && !std::is_constructible<T, std::string>::value &&
2243 !std::is_assignable<T &, std::wstring>::value && !std::is_constructible<T, std::wstring>::value &&
2244 !is_complex<T>::value && !is_mutable_container<T>::value && !std::is_enum<T>::value,
2246 std::false_type>::type;
2247 static constexpr bool value = type::value;
2251template <
typename T>
2252struct classify_object<T,
2253 typename
std::enable_if<(!is_mutable_container<T>::value && is_wrapper<T>::value &&
2254 !is_tuple_like<T>::value && uncommon_type<T>::value)>::type> {
2255 static constexpr object_category
value{object_category::wrapper_value};
2259template <
typename T>
2260struct classify_object<T,
2261 typename
std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
2262 !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
2263 is_direct_constructible<T, int>::value>::type> {
2264 static constexpr object_category
value{object_category::number_constructible};
2268template <
typename T>
2269struct classify_object<T,
2270 typename
std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
2271 !is_wrapper<T>::value && !is_direct_constructible<T, double>::value &&
2272 is_direct_constructible<T, int>::value>::type> {
2273 static constexpr object_category
value{object_category::integer_constructible};
2277template <
typename T>
2278struct classify_object<T,
2279 typename
std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
2280 !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
2281 !is_direct_constructible<T, int>::value>::type> {
2282 static constexpr object_category
value{object_category::double_constructible};
2286template <
typename T>
2287struct classify_object<
2289 typename
std::enable_if<is_tuple_like<T>::value &&
2290 ((type_count<T>::value >= 2 && !is_wrapper<T>::value) ||
2291 (uncommon_type<T>::value && !is_direct_constructible<T, double>::value &&
2292 !is_direct_constructible<T, int>::value) ||
2293 (uncommon_type<T>::value && type_count<T>::value >= 2))>::type> {
2294 static constexpr object_category
value{object_category::tuple_value};
2303template <
typename T>
struct classify_object<T, typename
std::enable_if<is_mutable_container<T>::value>::type> {
2304 static constexpr object_category
value{object_category::container_value};
2313template <
typename T,
2314 enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> = detail::dummy>
2315constexpr const char *type_name() {
2319template <
typename T,
2320 enable_if_t<classify_object<T>::value == object_category::integral_value ||
2321 classify_object<T>::value == object_category::integer_constructible,
2322 detail::enabler> = detail::dummy>
2323constexpr const char *type_name() {
2327template <
typename T,
2328 enable_if_t<classify_object<T>::value == object_category::unsigned_integral, detail::enabler> = detail::dummy>
2329constexpr const char *type_name() {
2333template <
typename T,
2334 enable_if_t<classify_object<T>::value == object_category::floating_point ||
2335 classify_object<T>::value == object_category::number_constructible ||
2336 classify_object<T>::value == object_category::double_constructible,
2337 detail::enabler> = detail::dummy>
2338constexpr const char *type_name() {
2343template <
typename T,
2344 enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> = detail::dummy>
2345constexpr const char *type_name() {
2350template <
typename T,
2351 enable_if_t<classify_object<T>::value == object_category::boolean_value, detail::enabler> = detail::dummy>
2352constexpr const char *type_name() {
2357template <
typename T,
2358 enable_if_t<classify_object<T>::value == object_category::complex_number, detail::enabler> = detail::dummy>
2359constexpr const char *type_name() {
2364template <
typename T,
2365 enable_if_t<classify_object<T>::value >= object_category::string_assignable &&
2366 classify_object<T>::value <= object_category::other,
2367 detail::enabler> = detail::dummy>
2368constexpr const char *type_name() {
2372template <
typename T,
2373 enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value >= 2,
2374 detail::enabler> = detail::dummy>
2375std::string type_name();
2378template <
typename T,
2379 enable_if_t<classify_object<T>::value == object_category::container_value ||
2380 classify_object<T>::value == object_category::wrapper_value,
2381 detail::enabler> = detail::dummy>
2382std::string type_name();
2385template <
typename T,
2386 enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value == 1,
2387 detail::enabler> = detail::dummy>
2388inline std::string type_name() {
2389 return type_name<typename std::decay<typename std::tuple_element<0, T>::type>::type>();
2393template <
typename T, std::
size_t I>
2395 return std::string{};
2399template <
typename T, std::
size_t I>
2400inline typename std::enable_if<(I < type_count_base<T>::value), std::string>::type tuple_name() {
2401 auto str = std::string{type_name<typename std::decay<typename std::tuple_element<I, T>::type>::type>()} +
',' +
2402 tuple_name<T, I + 1>();
2403 if(str.back() ==
',')
2409template <
typename T,
2410 enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value >= 2,
2412inline std::string type_name() {
2413 auto tname = std::string(1,
'[') + tuple_name<T, 0>();
2414 tname.push_back(
']');
2419template <
typename T,
2420 enable_if_t<classify_object<T>::value == object_category::container_value ||
2421 classify_object<T>::value == object_category::wrapper_value,
2423inline std::string type_name() {
2424 return type_name<typename T::value_type>();
2430template <typename T, enable_if_t<std::is_unsigned<T>::value, detail::enabler> = detail::dummy>
2431bool integral_conversion(
const std::string &input, T &output)
noexcept {
2432 if(input.empty() || input.front() ==
'-') {
2438 if(errno == ERANGE) {
2441 output =
static_cast<T
>(output_ll);
2442 if(val == (input.c_str() + input.size()) &&
static_cast<std::uint64_t>(output) == output_ll) {
2447 if(val == (input.c_str() + input.size())) {
2448 output = (output_sll < 0) ? static_cast<T>(0) :
static_cast<T
>(output_sll);
2449 return (
static_cast<std::int64_t>(output) == output_sll);
2452 if(input.find_first_of(
"_'") != std::string::npos) {
2453 std::string nstring = input;
2454 nstring.erase(std::remove(nstring.begin(), nstring.end(),
'_'), nstring.end());
2455 nstring.erase(std::remove(nstring.begin(), nstring.end(),
'\''), nstring.end());
2456 return integral_conversion(nstring, output);
2458 if(input.compare(0, 2,
"0o") == 0) {
2462 if(errno == ERANGE) {
2465 output =
static_cast<T
>(output_ll);
2466 return (val == (input.c_str() + input.size()) &&
static_cast<std::uint64_t>(output) == output_ll);
2468 if(input.compare(0, 2,
"0b") == 0) {
2472 if(errno == ERANGE) {
2475 output =
static_cast<T
>(output_ll);
2476 return (val == (input.c_str() + input.size()) &&
static_cast<std::uint64_t>(output) == output_ll);
2482template <typename T, enable_if_t<std::is_signed<T>::value, detail::enabler> = detail::dummy>
2483bool integral_conversion(
const std::string &input, T &output)
noexcept {
2487 char *val =
nullptr;
2490 if(errno == ERANGE) {
2493 output =
static_cast<T
>(output_ll);
2494 if(val == (input.c_str() + input.size()) &&
static_cast<std::int64_t>(output) == output_ll) {
2497 if(input ==
"true") {
2499 output =
static_cast<T
>(1);
2503 if(input.find_first_of(
"_'") != std::string::npos) {
2504 std::string nstring = input;
2505 nstring.erase(std::remove(nstring.begin(), nstring.end(),
'_'), nstring.end());
2506 nstring.erase(std::remove(nstring.begin(), nstring.end(),
'\''), nstring.end());
2507 return integral_conversion(nstring, output);
2509 if(input.compare(0, 2,
"0o") == 0) {
2513 if(errno == ERANGE) {
2516 output =
static_cast<T
>(output_ll);
2517 return (val == (input.c_str() + input.size()) &&
static_cast<std::int64_t>(output) == output_ll);
2519 if(input.compare(0, 2,
"0b") == 0) {
2523 if(errno == ERANGE) {
2526 output =
static_cast<T
>(output_ll);
2527 return (val == (input.c_str() + input.size()) &&
static_cast<std::int64_t>(output) == output_ll);
2533inline std::int64_t to_flag_value(std::string val)
noexcept {
2534 static const std::string trueString(
"true");
2535 static const std::string falseString(
"false");
2536 if(val == trueString) {
2539 if(val == falseString) {
2542 val = detail::to_lower(val);
2544 if(val.size() == 1) {
2545 if(val[0] >=
'1' && val[0] <=
'9') {
2566 if(val == trueString || val ==
"on" || val ==
"yes" || val ==
"enable") {
2568 }
else if(val == falseString || val ==
"off" || val ==
"no" || val ==
"disable") {
2571 char *loc_ptr{
nullptr};
2573 if(loc_ptr != (val.c_str() + val.size()) && errno == 0) {
2581template <
typename T,
2582 enable_if_t<classify_object<T>::value == object_category::integral_value ||
2583 classify_object<T>::value == object_category::unsigned_integral,
2584 detail::enabler> = detail::dummy>
2585bool lexical_cast(
const std::string &input, T &output) {
2586 return integral_conversion(input, output);
2590template <
typename T,
2591 enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> = detail::dummy>
2592bool lexical_cast(
const std::string &input, T &output) {
2593 if(input.size() == 1) {
2594 output =
static_cast<T
>(input[0]);
2597 return integral_conversion(input, output);
2601template <
typename T,
2602 enable_if_t<classify_object<T>::value == object_category::boolean_value, detail::enabler> = detail::dummy>
2603bool lexical_cast(
const std::string &input, T &output) {
2605 auto out = to_flag_value(input);
2608 }
else if(errno == ERANGE) {
2609 output = (input[0] !=
'-');
2617template <
typename T,
2618 enable_if_t<classify_object<T>::value == object_category::floating_point, detail::enabler> = detail::dummy>
2619bool lexical_cast(
const std::string &input, T &output) {
2623 char *val =
nullptr;
2625 output =
static_cast<T
>(output_ld);
2626 if(val == (input.c_str() + input.size())) {
2630 if(input.find_first_of(
"_'") != std::string::npos) {
2631 std::string nstring = input;
2632 nstring.erase(std::remove(nstring.begin(), nstring.end(),
'_'), nstring.end());
2633 nstring.erase(std::remove(nstring.begin(), nstring.end(),
'\''), nstring.end());
2634 return lexical_cast(nstring, output);
2640template <
typename T,
2641 enable_if_t<classify_object<T>::value == object_category::complex_number, detail::enabler> = detail::dummy>
2642bool lexical_cast(
const std::string &input, T &output) {
2643 using XC =
typename wrapped_type<T, double>::type;
2646 bool worked =
false;
2647 auto nloc = str1.find_last_of(
"+-");
2648 if(nloc != std::string::npos && nloc > 0) {
2649 worked = lexical_cast(str1.substr(0, nloc), x);
2650 str1 = str1.substr(nloc);
2651 if(str1.back() ==
'i' || str1.back() ==
'j')
2653 worked = worked && lexical_cast(str1, y);
2655 if(str1.back() ==
'i' || str1.back() ==
'j') {
2657 worked = lexical_cast(str1, y);
2660 worked = lexical_cast(str1, x);
2668 return from_stream(input, output);
2672template <
typename T,
2673 enable_if_t<classify_object<T>::value == object_category::string_assignable, detail::enabler> = detail::dummy>
2674bool lexical_cast(
const std::string &input, T &output) {
2682 enable_if_t<classify_object<T>::value == object_category::string_constructible, detail::enabler> = detail::dummy>
2683bool lexical_cast(
const std::string &input, T &output) {
2691 enable_if_t<classify_object<T>::value == object_category::wstring_assignable, detail::enabler> = detail::dummy>
2692bool lexical_cast(
const std::string &input, T &output) {
2693 output = widen(input);
2699 enable_if_t<classify_object<T>::value == object_category::wstring_constructible, detail::enabler> = detail::dummy>
2700bool lexical_cast(
const std::string &input, T &output) {
2701 output = T{widen(input)};
2706template <
typename T,
2707 enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> = detail::dummy>
2708bool lexical_cast(
const std::string &input, T &output) {
2709 typename std::underlying_type<T>::type val;
2710 if(!integral_conversion(input, val)) {
2713 output =
static_cast<T
>(val);
2718template <
typename T,
2719 enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
2720 std::is_assignable<T &, typename T::value_type>::value,
2721 detail::enabler> = detail::dummy>
2722bool lexical_cast(
const std::string &input, T &output) {
2723 typename T::value_type val;
2724 if(lexical_cast(input, val)) {
2728 return from_stream(input, output);
2731template <
typename T,
2732 enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
2733 !std::is_assignable<T &, typename T::value_type>::value && std::is_assignable<T &, T>::value,
2734 detail::enabler> = detail::dummy>
2735bool lexical_cast(
const std::string &input, T &output) {
2736 typename T::value_type val;
2737 if(lexical_cast(input, val)) {
2741 return from_stream(input, output);
2747 enable_if_t<classify_object<T>::value == object_category::number_constructible, detail::enabler> = detail::dummy>
2748bool lexical_cast(
const std::string &input, T &output) {
2750 if(integral_conversion(input, val)) {
2756 if(lexical_cast(input, dval)) {
2761 return from_stream(input, output);
2767 enable_if_t<classify_object<T>::value == object_category::integer_constructible, detail::enabler> = detail::dummy>
2768bool lexical_cast(
const std::string &input, T &output) {
2770 if(integral_conversion(input, val)) {
2774 return from_stream(input, output);
2780 enable_if_t<classify_object<T>::value == object_category::double_constructible, detail::enabler> = detail::dummy>
2781bool lexical_cast(
const std::string &input, T &output) {
2783 if(lexical_cast(input, val)) {
2787 return from_stream(input, output);
2791template <
typename T,
2792 enable_if_t<classify_object<T>::value == object_category::other && std::is_assignable<T &, int>::value,
2793 detail::enabler> = detail::dummy>
2794bool lexical_cast(
const std::string &input, T &output) {
2796 if(integral_conversion(input, val)) {
2798#pragma warning(push)
2799#pragma warning(disable : 4800)
2812 return from_stream(input, output);
2817template <
typename T,
2818 enable_if_t<classify_object<T>::value == object_category::other && !std::is_assignable<T &, int>::value &&
2819 is_istreamable<T>::value,
2820 detail::enabler> = detail::dummy>
2821bool lexical_cast(
const std::string &input, T &output) {
2822 return from_stream(input, output);
2827template <
typename T,
2828 enable_if_t<classify_object<T>::value == object_category::other && !std::is_assignable<T &, int>::value &&
2829 !is_istreamable<T>::value && !adl_detail::is_lexical_castable<T>::value,
2830 detail::enabler> = detail::dummy>
2831bool lexical_cast(
const std::string & , T & ) {
2832 static_assert(!std::is_same<T, T>::value,
2833 "option object type must have a lexical cast overload or streaming input operator(>>) defined, if it "
2834 "is convertible from another type use the add_option<T, XC>(...) with XC being the known type");
2840template <
typename AssignTo,
2842 enable_if_t<std::is_same<AssignTo, ConvertTo>::value &&
2843 (classify_object<AssignTo>::value == object_category::string_assignable ||
2844 classify_object<AssignTo>::value == object_category::string_constructible ||
2845 classify_object<AssignTo>::value == object_category::wstring_assignable ||
2846 classify_object<AssignTo>::value == object_category::wstring_constructible),
2847 detail::enabler> = detail::dummy>
2848bool lexical_assign(
const std::string &input, AssignTo &output) {
2849 return lexical_cast(input, output);
2853template <
typename AssignTo,
2855 enable_if_t<std::is_same<AssignTo, ConvertTo>::value && std::is_assignable<AssignTo &, AssignTo>::value &&
2856 classify_object<AssignTo>::value != object_category::string_assignable &&
2857 classify_object<AssignTo>::value != object_category::string_constructible &&
2858 classify_object<AssignTo>::value != object_category::wstring_assignable &&
2859 classify_object<AssignTo>::value != object_category::wstring_constructible,
2860 detail::enabler> = detail::dummy>
2861bool lexical_assign(
const std::string &input, AssignTo &output) {
2863 output = AssignTo{};
2867 return lexical_cast(input, output);
2871template <
typename AssignTo,
2873 enable_if_t<std::is_same<AssignTo, ConvertTo>::value && !std::is_assignable<AssignTo &, AssignTo>::value &&
2874 classify_object<AssignTo>::value == object_category::wrapper_value,
2875 detail::enabler> = detail::dummy>
2876bool lexical_assign(
const std::string &input, AssignTo &output) {
2878 typename AssignTo::value_type emptyVal{};
2882 return lexical_cast(input, output);
2887template <
typename AssignTo,
2889 enable_if_t<std::is_same<AssignTo, ConvertTo>::value && !std::is_assignable<AssignTo &, AssignTo>::value &&
2890 classify_object<AssignTo>::value != object_category::wrapper_value &&
2891 std::is_assignable<AssignTo &, int>::value,
2892 detail::enabler> = detail::dummy>
2893bool lexical_assign(
const std::string &input, AssignTo &output) {
2899 if(lexical_cast(input, val)) {
2900#if defined(__clang__)
2902#pragma clang diagnostic push
2903#pragma clang diagnostic ignored "-Wsign-conversion"
2906#if defined(__clang__)
2907#pragma clang diagnostic pop
2915template <
typename AssignTo,
2917 enable_if_t<!std::is_same<AssignTo, ConvertTo>::value && std::is_assignable<AssignTo &, ConvertTo &>::value,
2918 detail::enabler> = detail::dummy>
2919bool lexical_assign(
const std::string &input, AssignTo &output) {
2921 bool parse_result = (!input.empty()) ? lexical_cast(input, val) :
true;
2925 return parse_result;
2932 enable_if_t<!std::is_same<AssignTo, ConvertTo>::value && !std::is_assignable<AssignTo &, ConvertTo &>::value &&
2933 std::is_move_assignable<AssignTo>::value,
2934 detail::enabler> = detail::dummy>
2935bool lexical_assign(
const std::string &input, AssignTo &output) {
2937 bool parse_result = input.empty() ? true : lexical_cast(input, val);
2939 output = AssignTo(val);
2941 return parse_result;
2945template <
typename AssignTo,
2947 enable_if_t<classify_object<ConvertTo>::value <= object_category::other &&
2948 classify_object<AssignTo>::value <= object_category::wrapper_value,
2949 detail::enabler> = detail::dummy>
2951 return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2956template <
typename AssignTo,
2958 enable_if_t<(type_count<AssignTo>::value <= 2) && expected_count<AssignTo>::value == 1 &&
2959 is_tuple_like<ConvertTo>::value && type_count_base<ConvertTo>::value == 2,
2960 detail::enabler> = detail::dummy>
2964 using SecondType =
typename std::tuple_element<1, ConvertTo>::type;
2967 bool retval = lexical_assign<FirstType, FirstType>(strings[0], v1);
2968 retval = retval && lexical_assign<SecondType, SecondType>((strings.size() > 1) ? strings[1] : std::string{}, v2);
2970 output = AssignTo{v1, v2};
2976template <
class AssignTo,
2978 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2979 type_count<ConvertTo>::value == 1,
2980 detail::enabler> = detail::dummy>
2982 output.erase(output.begin(), output.end());
2983 if(strings.empty()) {
2986 if(strings.size() == 1 && strings[0] ==
"{}") {
2989 bool skip_remaining =
false;
2990 if(strings.size() == 2 && strings[0] ==
"{}" && is_separator(strings[1])) {
2991 skip_remaining =
true;
2993 for(
const auto &elem : strings) {
2994 typename AssignTo::value_type out;
2995 bool retval = lexical_assign<typename AssignTo::value_type, typename ConvertTo::value_type>(elem, out);
2999 output.insert(output.end(),
std::move(out));
3000 if(skip_remaining) {
3004 return (!output.empty());
3008template <class AssignTo, class ConvertTo, enable_if_t<is_complex<ConvertTo>::value, detail::enabler> = detail::dummy>
3009bool lexical_conversion(
const std::vector<std::string> &strings, AssignTo &output) {
3011 if(strings.size() >= 2 && !strings[1].empty()) {
3012 using XC2 =
typename wrapped_type<ConvertTo, double>::type;
3014 auto str1 = strings[1];
3015 if(str1.back() ==
'i' || str1.back() ==
'j') {
3018 auto worked = lexical_cast(strings[0], x) && lexical_cast(str1, y);
3020 output = ConvertTo{x, y};
3024 return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
3028template <
class AssignTo,
3030 enable_if_t<is_mutable_container<AssignTo>::value && (expected_count<ConvertTo>::value == 1) &&
3031 (type_count<ConvertTo>::value == 1),
3032 detail::enabler> = detail::dummy>
3036 output.reserve(strings.size());
3037 for(
const auto &elem : strings) {
3039 output.emplace_back();
3040 retval = retval && lexical_assign<typename AssignTo::value_type, ConvertTo>(elem, output.back());
3042 return (!output.empty()) && retval;
3048template <
class AssignTo,
3050 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
3051 type_count_base<ConvertTo>::value == 2,
3052 detail::enabler> = detail::dummy>
3053bool lexical_conversion(std::vector<std::string> strings, AssignTo &output);
3056template <
class AssignTo,
3058 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
3059 type_count_base<ConvertTo>::value != 2 &&
3060 ((type_count<ConvertTo>::value > 2) ||
3061 (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
3062 detail::enabler> = detail::dummy>
3063bool lexical_conversion(
const std::vector<std::string> &strings, AssignTo &output);
3066template <
class AssignTo,
3068 enable_if_t<is_tuple_like<AssignTo>::value && is_tuple_like<ConvertTo>::value &&
3069 (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
3070 type_count<ConvertTo>::value > 2),
3071 detail::enabler> = detail::dummy>
3072bool lexical_conversion(
const std::vector<std::string> &strings, AssignTo &output);
3076template <
typename AssignTo,
3078 enable_if_t<!is_tuple_like<AssignTo>::value && !is_mutable_container<AssignTo>::value &&
3079 classify_object<ConvertTo>::value != object_category::wrapper_value &&
3080 (is_mutable_container<ConvertTo>::value || type_count<ConvertTo>::value > 2),
3081 detail::enabler> = detail::dummy>
3084 if(strings.size() > 1 || (!strings.empty() && !(strings.front().empty()))) {
3086 auto retval = lexical_conversion<ConvertTo, ConvertTo>(strings, val);
3087 output = AssignTo{val};
3090 output = AssignTo{};
3095template <
class AssignTo,
class ConvertTo, std::
size_t I>
3096inline typename std::enable_if<(I >= type_count_base<AssignTo>::value),
bool>::type
3097tuple_conversion(
const std::vector<std::string> &, AssignTo &) {
3102template <
class AssignTo,
class ConvertTo>
3104tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
3105 auto retval = lexical_assign<AssignTo, ConvertTo>(strings[0], output);
3106 strings.erase(strings.begin());
3111template <
class AssignTo,
class ConvertTo>
3113 type_count<ConvertTo>::value == type_count_min<ConvertTo>::value,
3115tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
3116 auto retval = lexical_conversion<AssignTo, ConvertTo>(strings, output);
3117 strings.erase(strings.begin(), strings.begin() + type_count<ConvertTo>::value);
3122template <
class AssignTo,
class ConvertTo>
3124 type_count<ConvertTo>::value != type_count_min<ConvertTo>::value,
3126tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
3128 std::size_t index{subtype_count_min<ConvertTo>::value};
3129 const std::size_t mx_count{subtype_count<ConvertTo>::value};
3130 const std::size_t mx{(std::min)(mx_count, strings.size() - 1)};
3133 if(is_separator(strings[index])) {
3138 bool retval = lexical_conversion<AssignTo, ConvertTo>(
3139 std::vector<std::string>(strings.begin(), strings.begin() +
static_cast<std::ptrdiff_t>(index)), output);
3140 if(strings.size() > index) {
3141 strings.erase(strings.begin(), strings.begin() +
static_cast<std::ptrdiff_t>(index) + 1);
3149template <
class AssignTo,
class ConvertTo, std::
size_t I>
3150inline typename std::enable_if<(I < type_count_base<AssignTo>::value),
bool>::type
3151tuple_conversion(std::vector<std::string> strings, AssignTo &output) {
3153 using ConvertToElement =
typename std::
3155 if(!strings.empty()) {
3156 retval = retval && tuple_type_conversion<typename std::tuple_element<I, AssignTo>::type, ConvertToElement>(
3159 retval = retval && tuple_conversion<AssignTo, ConvertTo, I + 1>(
std::move(strings), output);
3164template <
class AssignTo,
3166 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
3167 type_count_base<ConvertTo>::value == 2,
3169bool lexical_conversion(std::vector<std::string> strings, AssignTo &output) {
3171 while(!strings.empty()) {
3174 typename std::tuple_element<1, typename ConvertTo::value_type>::type v2;
3175 bool retval = tuple_type_conversion<decltype(v1), decltype(v1)>(strings, v1);
3176 if(!strings.empty()) {
3177 retval = retval && tuple_type_conversion<decltype(v2), decltype(v2)>(strings, v2);
3180 output.insert(output.end(),
typename AssignTo::value_type{v1, v2});
3185 return (!output.empty());
3189template <
class AssignTo,
3191 enable_if_t<is_tuple_like<AssignTo>::value && is_tuple_like<ConvertTo>::value &&
3192 (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
3193 type_count<ConvertTo>::value > 2),
3197 !is_tuple_like<ConvertTo>::value || type_count_base<AssignTo>::value == type_count_base<ConvertTo>::value,
3198 "if the conversion type is defined as a tuple it must be the same size as the type you are converting to");
3199 return tuple_conversion<AssignTo, ConvertTo, 0>(strings, output);
3203template <
class AssignTo,
3205 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
3206 type_count_base<ConvertTo>::value != 2 &&
3207 ((type_count<ConvertTo>::value > 2) ||
3208 (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
3213 std::vector<std::string> temp;
3217 auto ii_max = strings.size();
3218 while(ii < ii_max) {
3219 temp.push_back(strings[ii]);
3222 if(icount == xcm || is_separator(temp.back()) || ii == ii_max) {
3223 if(
static_cast<int>(xcm) > type_count_min<ConvertTo>::value && is_separator(temp.back())) {
3226 typename AssignTo::value_type temp_out;
3228 lexical_conversion<typename AssignTo::value_type, typename ConvertTo::value_type>(temp, temp_out);
3233 output.insert(output.end(),
std::move(temp_out));
3241template <
typename AssignTo,
3243 enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
3244 std::is_assignable<ConvertTo &, ConvertTo>::value,
3245 detail::enabler> = detail::dummy>
3246bool lexical_conversion(
const std::vector<std::string> &strings, AssignTo &output) {
3247 if(strings.empty() || strings.front().empty()) {
3248 output = ConvertTo{};
3251 typename ConvertTo::value_type val;
3252 if(lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings, val)) {
3253 output = ConvertTo{val};
3260template <
typename AssignTo,
3262 enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
3263 !std::is_assignable<AssignTo &, ConvertTo>::value,
3264 detail::enabler> = detail::dummy>
3265bool lexical_conversion(
const std::vector<std::string> &strings, AssignTo &output) {
3266 using ConvertType =
typename ConvertTo::value_type;
3267 if(strings.empty() || strings.front().empty()) {
3268 output = ConvertType{};
3272 if(lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings, val)) {
3280inline std::string sum_string_vector(
const std::vector<std::string> &values) {
3284 for(
const auto &arg : values) {
3286 auto comp = lexical_cast(arg, tv);
3289 auto fv = detail::to_flag_value(arg);
3290 fail = (errno != 0);
3294 tv =
static_cast<double>(fv);
3299 for(
const auto &arg : values) {
3303 std::ostringstream out;
3318CLI11_INLINE bool split_short(
const std::string ¤t, std::string &name, std::string &rest);
3321CLI11_INLINE bool split_long(
const std::string ¤t, std::string &name, std::string &
value);
3324CLI11_INLINE bool split_windows_style(
const std::string ¤t, std::string &name, std::string &
value);
3327CLI11_INLINE std::vector<std::string> split_names(std::string current);
3334get_names(
const std::vector<std::string> &input);
3342CLI11_INLINE bool split_short(
const std::string ¤t, std::string &name, std::string &rest) {
3343 if(current.size() > 1 && current[0] ==
'-' && valid_first_char(current[1])) {
3344 name = current.substr(1, 1);
3345 rest = current.substr(2);
3351CLI11_INLINE bool split_long(
const std::string ¤t, std::string &name, std::string &
value) {
3352 if(current.size() > 2 && current.compare(0, 2,
"--") == 0 && valid_first_char(current[2])) {
3353 auto loc = current.find_first_of(
'=');
3354 if(loc != std::string::npos) {
3355 name = current.substr(2, loc - 2);
3356 value = current.substr(loc + 1);
3358 name = current.substr(2);
3366CLI11_INLINE bool split_windows_style(
const std::string ¤t, std::string &name, std::string &
value) {
3367 if(current.size() > 1 && current[0] ==
'/' && valid_first_char(current[1])) {
3368 auto loc = current.find_first_of(
':');
3369 if(loc != std::string::npos) {
3370 name = current.substr(1, loc - 1);
3371 value = current.substr(loc + 1);
3373 name = current.substr(1);
3381CLI11_INLINE std::vector<std::string> split_names(std::string current) {
3382 std::vector<std::string> output;
3384 while((val = current.find(
',')) != std::string::npos) {
3385 output.push_back(trim_copy(current.substr(0, val)));
3386 current = current.substr(val + 1);
3388 output.push_back(trim_copy(current));
3393 std::vector<std::string> flags = split_names(str);
3396 [](
const std::string &name) {
3397 return ((name.empty()) || (!(((name.find_first_of(
'{') != std::string::npos) &&
3398 (name.back() ==
'}')) ||
3399 (name[0] ==
'!'))));
3403 output.reserve(flags.size());
3404 for(
auto &flag : flags) {
3405 auto def_start = flag.find_first_of(
'{');
3406 std::string defval =
"false";
3407 if((def_start != std::string::npos) && (flag.back() ==
'}')) {
3408 defval = flag.substr(def_start + 1);
3410 flag.erase(def_start, std::string::npos);
3412 flag.erase(0, flag.find_first_not_of(
"-!"));
3413 output.emplace_back(flag, defval);
3419get_names(
const std::vector<std::string> &input) {
3421 std::vector<std::string> short_names;
3422 std::vector<std::string> long_names;
3423 std::string pos_name;
3424 for(std::string name : input) {
3425 if(name.length() == 0) {
3428 if(name.length() > 1 && name[0] ==
'-' && name[1] !=
'-') {
3429 if(name.length() == 2 && valid_first_char(name[1]))
3430 short_names.emplace_back(1, name[1]);
3431 else if(name.length() > 2)
3432 THROW BadNameString::MissingDash(name);
3434 THROW BadNameString::OneCharName(name);
3435 }
else if(name.length() > 2 && name.substr(0, 2) ==
"--") {
3436 name = name.substr(2);
3437 if(valid_name_string(name))
3438 long_names.push_back(name);
3440 THROW BadNameString::BadLongName(name);
3441 }
else if(name ==
"-" || name ==
"--") {
3442 THROW BadNameString::DashesOnly(name);
3444 if(!pos_name.empty())
3445 THROW BadNameString::MultiPositionalNames(name);
3446 if(valid_name_string(name)) {
3449 THROW BadNameString::BadPositionalName(name);
3453 return std::make_tuple(short_names, long_names, pos_name);
3465 std::vector<std::string> parents{};
3470 std::vector<std::string> inputs{};
3474 std::vector<std::string> tmp = parents;
3475 tmp.emplace_back(name);
3476 return detail::join(tmp,
".");
3487 virtual std::string to_config(
const App *,
bool,
bool, std::string)
const = 0;
3493 CLI11_NODISCARD virtual std::string to_flag(
const ConfigItem &item)
const {
3494 if(item.inputs.size() == 1) {
3495 return item.inputs.at(0);
3497 if(item.inputs.empty()) {
3500 THROW ConversionError::TooManyInputsFlag(item.fullname());
3505 std::ifstream input{name};
3507 THROW FileError::Missing(name);
3509 return from_config(input);
3513 virtual ~Config() =
default;
3517class ConfigBase :
public Config {
3520 char commentChar =
'#';
3522 char arrayStart =
'[';
3524 char arrayEnd =
']';
3526 char arraySeparator =
',';
3528 char valueDelimiter =
'=';
3530 char stringQuote =
'"';
3532 char literalQuote =
'\'';
3534 uint8_t maximumLayers{255};
3536 char parentSeparatorChar{
'.'};
3538 int16_t configIndex{-1};
3540 std::string configSection{};
3544 to_config(
const App * ,
bool default_also,
bool write_description, std::string prefix)
const override;
3548 ConfigBase *comment(
char cchar) {
3549 commentChar = cchar;
3553 ConfigBase *arrayBounds(
char aStart,
char aEnd) {
3554 arrayStart = aStart;
3559 ConfigBase *arrayDelimiter(
char aSep) {
3560 arraySeparator = aSep;
3564 ConfigBase *valueSeparator(
char vSep) {
3565 valueDelimiter = vSep;
3569 ConfigBase *quoteCharacter(
char qString,
char literalChar) {
3570 stringQuote = qString;
3571 literalQuote = literalChar;
3575 ConfigBase *maxLayers(uint8_t layers) {
3576 maximumLayers = layers;
3580 ConfigBase *parentSeparator(
char sep) {
3581 parentSeparatorChar = sep;
3585 std::string §ionRef() {
return configSection; }
3587 CLI11_NODISCARD const std::string §ion()
const {
return configSection; }
3589 ConfigBase *section(
const std::string §ionName) {
3590 configSection = sectionName;
3595 int16_t &indexRef() {
return configIndex; }
3599 ConfigBase *index(int16_t sectionIndex) {
3600 configIndex = sectionIndex;
3606using ConfigTOML = ConfigBase;
3609class ConfigINI :
public ConfigTOML {
3616 arraySeparator =
' ';
3617 valueDelimiter =
'=';
3638 std::function<std::string()> desc_function_{[]() {
return std::string{}; }};
3642 std::function<std::string(std::string &)> func_{[](std::string &) {
return std::string{}; }};
3644 std::string name_{};
3646 int application_index_ = -1;
3650 bool non_modifying_{
false};
3652 Validator(std::string validator_desc, std::function<std::string(std::string &)> func)
3653 : desc_function_([validator_desc]() {
return validator_desc; }), func_(
std::move(func)) {}
3656 Validator() =
default;
3658 explicit Validator(std::string validator_desc) : desc_function_([validator_desc]() {
return validator_desc; }) {}
3660 Validator(std::function<std::string(std::string &)> op, std::string validator_desc, std::string validator_name =
"")
3661 : desc_function_([validator_desc]() {
return validator_desc; }), func_(
std::move(op)),
3664 Validator &operation(std::function<std::string(std::string &)> op) {
3670 std::string operator()(std::string &str)
const;
3674 std::string operator()(
const std::string &str)
const {
3675 std::string
value = str;
3676 return (active_) ? func_(
value) : std::string{};
3680 Validator &description(std::string validator_desc) {
3681 desc_function_ = [validator_desc]() {
return validator_desc; };
3685 CLI11_NODISCARD Validator description(std::string validator_desc)
const;
3690 return desc_function_();
3692 return std::string{};
3695 Validator &name(std::string validator_name) {
3701 Validator newval(*
this);
3702 newval.name_ =
std::move(validator_name);
3708 Validator &active(
bool active_val =
true) {
3709 active_ = active_val;
3714 Validator newval(*
this);
3715 newval.active_ = active_val;
3720 Validator &non_modifying(
bool no_modify =
true) {
3721 non_modifying_ = no_modify;
3725 Validator &application_index(
int app_index) {
3726 application_index_ = app_index;
3731 Validator newval(*
this);
3732 newval.application_index_ = app_index;
3736 CLI11_NODISCARD int get_application_index()
const {
return application_index_; }
3741 CLI11_NODISCARD bool get_modifying()
const {
return !non_modifying_; }
3745 Validator operator&(
const Validator &other)
const;
3749 Validator operator|(
const Validator &other)
const;
3752 Validator operator!()
const;
3755 void _merge_description(
const Validator &val1,
const Validator &val2,
const std::string &merger);
3759class CustomValidator :
public Validator {
3768enum class path_type { nonexistent, file, directory };
3771CLI11_INLINE path_type check_path(
const char *file)
noexcept;
3774class ExistingFileValidator :
public Validator {
3776 ExistingFileValidator();
3780class ExistingDirectoryValidator :
public Validator {
3782 ExistingDirectoryValidator();
3786class ExistingPathValidator :
public Validator {
3788 ExistingPathValidator();
3792class NonexistentPathValidator :
public Validator {
3794 NonexistentPathValidator();
3798class IPV4Validator :
public Validator {
3803class EscapedStringTransformer :
public Validator {
3805 EscapedStringTransformer();
3813const detail::ExistingFileValidator ExistingFile;
3816const detail::ExistingDirectoryValidator ExistingDirectory;
3819const detail::ExistingPathValidator ExistingPath;
3822const detail::NonexistentPathValidator NonexistentPath;
3825const detail::IPV4Validator ValidIPV4;
3828const detail::EscapedStringTransformer EscapedString;
3831template <
typename DesiredType>
class TypeValidator :
public Validator {
3833 explicit TypeValidator(
const std::string &validator_name)
3834 : Validator(validator_name, [](std::string &input_string) {
3835 using CLI::detail::lexical_cast;
3836 auto val = DesiredType();
3837 if(!lexical_cast(input_string, val)) {
3838 return std::string(
"Failed parsing ") + input_string +
" as a " + detail::type_name<DesiredType>();
3840 return std::string();
3842 TypeValidator() : TypeValidator(detail::type_name<DesiredType>()) {}
3846const TypeValidator<double> Number(
"NUMBER");
3850class FileOnDefaultPath :
public Validator {
3852 explicit FileOnDefaultPath(std::string default_path,
bool enableErrorReturn =
true);
3856class Range :
public Validator {
3862 template <
typename T>
3863 Range(T min_val, T max_val,
const std::string &validator_name = std::string{}) : Validator(validator_name) {
3864 if(validator_name.empty()) {
3865 std::stringstream out;
3866 out << detail::type_name<T>() <<
" in [" << min_val <<
" - " << max_val <<
"]";
3867 description(out.str());
3870 func_ = [min_val, max_val](std::string &input) {
3871 using CLI::detail::lexical_cast;
3873 bool converted = lexical_cast(input, val);
3874 if((!converted) || (val < min_val || val > max_val)) {
3875 std::stringstream out;
3876 out <<
"Value " << input <<
" not in range [";
3877 out << min_val <<
" - " << max_val <<
"]";
3880 return std::string{};
3885 template <
typename T>
3886 explicit Range(T max_val,
const std::string &validator_name = std::string{})
3887 : Range(
static_cast<T
>(0), max_val, validator_name) {}
3891const Range NonNegativeNumber((std::numeric_limits<double>::max)(),
"NONNEGATIVE");
3894const Range PositiveNumber((std::numeric_limits<double>::min)(), (std::numeric_limits<double>::max)(),
"POSITIVE");
3897class Bound :
public Validator {
3903 template <
typename T> Bound(T min_val, T max_val) {
3904 std::stringstream out;
3905 out << detail::type_name<T>() <<
" bounded to [" << min_val <<
" - " << max_val <<
"]";
3906 description(out.str());
3908 func_ = [min_val, max_val](std::string &input) {
3909 using CLI::detail::lexical_cast;
3911 bool converted = lexical_cast(input, val);
3913 return std::string(
"Value ") + input +
" could not be converted";
3916 input = detail::to_string(min_val);
3917 else if(val > max_val)
3918 input = detail::to_string(max_val);
3920 return std::string{};
3925 template <
typename T>
explicit Bound(T max_val) : Bound(
static_cast<T
>(0), max_val) {}
3929template <
typename T,
3930 enable_if_t<is_copyable_ptr<typename std::remove_reference<T>::type>
::value, detail::enabler> = detail::dummy>
3931auto smart_deref(T
value) ->
decltype(*value) {
3937 enable_if_t<!is_copyable_ptr<typename std::remove_reference<T>::type>
::value, detail::enabler> = detail::dummy>
3938typename std::remove_reference<T>::type &smart_deref(T &
value) {
3942template <
typename T> std::string generate_set(
const T &set) {
3943 using element_t =
typename detail::element_type<T>::type;
3944 using iteration_type_t =
typename detail::pair_adaptor<element_t>::value_type;
3945 std::string out(1,
'{');
3946 out.append(detail::join(
3947 detail::smart_deref(set),
3948 [](
const iteration_type_t &v) {
return detail::pair_adaptor<element_t>::first(v); },
3955template <
typename T> std::string generate_map(
const T &map,
bool key_only =
false) {
3956 using element_t =
typename detail::element_type<T>::type;
3957 using iteration_type_t =
typename detail::pair_adaptor<element_t>::value_type;
3958 std::string out(1,
'{');
3959 out.append(detail::join(
3960 detail::smart_deref(map),
3961 [key_only](
const iteration_type_t &v) {
3962 std::string res{detail::to_string(detail::pair_adaptor<element_t>::first(v))};
3966 res += detail::to_string(detail::pair_adaptor<element_t>::second(v));
3975template <
typename C,
typename V>
struct has_find {
3976 template <
typename CC,
typename VV>
3978 template <
typename,
typename>
static auto test(...) ->
decltype(std::false_type());
3980 static const auto value =
decltype(test<C, V>(0))
::value;
3985template <typename T, typename V, enable_if_t<!has_find<T, V>::value, detail::enabler> = detail::dummy>
3986auto search(
const T &set,
const V &val) -> std::pair<bool,
decltype(std::begin(detail::smart_deref(set)))> {
3987 using element_t =
typename detail::element_type<T>::type;
3988 auto &setref = detail::smart_deref(set);
3989 auto it =
std::find_if(std::begin(setref), std::end(setref), [&val](
decltype(*std::begin(setref)) v) {
3990 return (detail::pair_adaptor<element_t>::first(v) == val);
3992 return {(it != std::end(setref)), it};
3996template <typename T, typename V, enable_if_t<has_find<T, V>::value, detail::enabler> = detail::dummy>
3997auto search(
const T &set,
const V &val) -> std::pair<bool,
decltype(std::begin(detail::smart_deref(set)))> {
3998 auto &setref = detail::smart_deref(set);
3999 auto it = setref.find(val);
4000 return {(it != std::end(setref)), it};
4004template <
typename T,
typename V>
4005auto search(
const T &set,
const V &val,
const std::function<V(V)> &filter_function)
4006 -> std::pair<bool,
decltype(std::begin(detail::smart_deref(set)))> {
4007 using element_t =
typename detail::element_type<T>::type;
4009 auto res = search(set, val);
4010 if((res.first) || (!(filter_function))) {
4014 auto &setref = detail::smart_deref(set);
4015 auto it =
std::find_if(std::begin(setref), std::end(setref), [&](
decltype(*std::begin(setref)) v) {
4016 V
a{detail::pair_adaptor<element_t>::first(v)};
4017 a = filter_function(
a);
4020 return {(it != std::end(setref)), it};
4027template <
typename T>
4029 if((
a > 0) == (
b > 0)) {
4035template <
typename T>
4037 return ((std::numeric_limits<T>::max)() /
a <
b);
4042 if(
a == 0 ||
b == 0 ||
a == 1 ||
b == 1) {
4046 if(
a == (std::numeric_limits<T>::min)() ||
b == (std::numeric_limits<T>::min)()) {
4049 if(overflowCheck(
a,
b)) {
4057template <
typename T>
4069class IsMember :
public Validator {
4071 using filter_fn_t = std::function<std::string(std::string)>;
4074 template <
typename T,
typename... Args>
4079 template <
typename T>
explicit IsMember(T &&set) : IsMember(
std::forward<T>(set),
nullptr) {}
4083 template <
typename T,
typename F>
explicit IsMember(T set, F filter_function) {
4087 using element_t =
typename detail::element_type<T>::type;
4088 using item_t =
typename detail::pair_adaptor<element_t>::first_type;
4090 using local_item_t =
typename IsMemberType<item_t>::type;
4094 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
4097 desc_function_ = [set]() {
return detail::generate_set(detail::smart_deref(set)); };
4101 func_ = [set, filter_fn](std::string &input) {
4102 using CLI::detail::lexical_cast;
4104 if(!lexical_cast(input,
b)) {
4105 THROW ValidationError(input);
4110 auto res = detail::search(set,
b, filter_fn);
4114 input = detail::value_string(detail::pair_adaptor<element_t>::first(*(res.second)));
4118 return std::string{};
4122 return input +
" not in " + detail::generate_set(detail::smart_deref(set));
4127 template <
typename T,
typename... Args>
4128 IsMember(T &&set, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
4131 [filter_fn_1, filter_fn_2](std::string
a) {
return filter_fn_2(filter_fn_1(
a)); },
4139class Transformer :
public Validator {
4141 using filter_fn_t = std::function<std::string(std::string)>;
4144 template <
typename... Args>
4149 template <
typename T>
explicit Transformer(T &&mapping) : Transformer(
std::forward<T>(mapping),
nullptr) {}
4153 template <
typename T,
typename F>
explicit Transformer(T mapping, F filter_function) {
4155 static_assert(detail::pair_adaptor<typename detail::element_type<T>::type>
::value,
4156 "mapping must produce value pairs");
4159 using element_t =
typename detail::element_type<T>::type;
4160 using item_t =
typename detail::pair_adaptor<element_t>::first_type;
4161 using local_item_t =
typename IsMemberType<item_t>::type;
4165 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
4168 desc_function_ = [mapping]() {
return detail::generate_map(detail::smart_deref(mapping)); };
4170 func_ = [mapping, filter_fn](std::string &input) {
4171 using CLI::detail::lexical_cast;
4173 if(!lexical_cast(input,
b)) {
4174 return std::string();
4180 auto res = detail::search(mapping,
b, filter_fn);
4182 input = detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
4184 return std::string{};
4189 template <
typename T,
typename... Args>
4190 Transformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
4193 [filter_fn_1, filter_fn_2](std::string
a) {
return filter_fn_2(filter_fn_1(
a)); },
4198class CheckedTransformer :
public Validator {
4200 using filter_fn_t = std::function<std::string(std::string)>;
4203 template <
typename... Args>
4205 : CheckedTransformer(TransformPairs<std::string>(values),
std::forward<Args>(args)...) {}
4208 template <
typename T>
explicit CheckedTransformer(T mapping) : CheckedTransformer(
std::move(mapping),
nullptr) {}
4212 template <
typename T,
typename F>
explicit CheckedTransformer(T mapping, F filter_function) {
4214 static_assert(detail::pair_adaptor<typename detail::element_type<T>::type>
::value,
4215 "mapping must produce value pairs");
4218 using element_t =
typename detail::element_type<T>::type;
4219 using item_t =
typename detail::pair_adaptor<element_t>::first_type;
4220 using local_item_t =
typename IsMemberType<item_t>::type;
4222 using iteration_type_t =
typename detail::pair_adaptor<element_t>::value_type;
4225 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
4227 auto tfunc = [mapping]() {
4228 std::string out(
"value in ");
4229 out += detail::generate_map(detail::smart_deref(mapping)) +
" OR {";
4230 out += detail::join(
4231 detail::smart_deref(mapping),
4232 [](
const iteration_type_t &v) {
return detail::to_string(detail::pair_adaptor<element_t>::second(v)); },
4238 desc_function_ = tfunc;
4240 func_ = [mapping, tfunc, filter_fn](std::string &input) {
4241 using CLI::detail::lexical_cast;
4243 bool converted = lexical_cast(input,
b);
4248 auto res = detail::search(mapping,
b, filter_fn);
4250 input = detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
4251 return std::string{};
4254 for(
const auto &v : detail::smart_deref(mapping)) {
4255 auto output_string = detail::value_string(detail::pair_adaptor<element_t>::second(v));
4256 if(output_string == input) {
4257 return std::string();
4261 return "Check " + input +
" " + tfunc() +
" FAILED";
4266 template <
typename T,
typename... Args>
4267 CheckedTransformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
4268 : CheckedTransformer(
4270 [filter_fn_1, filter_fn_2](std::string
a) {
return filter_fn_2(filter_fn_1(
a)); },
4275inline std::string ignore_case(std::string item) {
return detail::to_lower(item); }
4278inline std::string ignore_underscore(std::string item) {
return detail::remove_underscore(item); }
4281inline std::string ignore_space(std::string item) {
4282 item.erase(std::remove(std::begin(item), std::end(item),
' '), std::end(item));
4283 item.erase(std::remove(std::begin(item), std::end(item),
'\t'), std::end(item));
4298class AsNumberWithUnit :
public Validator {
4306 CASE_INSENSITIVE = 1,
4309 DEFAULT = CASE_INSENSITIVE | UNIT_OPTIONAL
4312 template <
typename Number>
4314 Options opts = DEFAULT,
4315 const std::string &unit_name =
"UNIT") {
4316 description(generate_description<Number>(unit_name, opts));
4317 validate_mapping(mapping, opts);
4320 func_ = [mapping, opts](std::string &input) -> std::string {
4323 detail::rtrim(input);
4325 THROW ValidationError(
"Input is empty");
4329 auto unit_begin = input.end();
4334 std::string unit{unit_begin, input.end()};
4336 detail::trim(input);
4338 if(opts & UNIT_REQUIRED && unit.empty()) {
4339 THROW ValidationError(
"Missing mandatory unit");
4341 if(opts & CASE_INSENSITIVE) {
4342 unit = detail::to_lower(unit);
4345 using CLI::detail::lexical_cast;
4346 if(!lexical_cast(input, num)) {
4347 THROW ValidationError(std::string(
"Value ") + input +
" could not be converted to " +
4348 detail::type_name<Number>());
4355 auto it = mapping.find(unit);
4356 if(it == mapping.end()) {
4357 THROW ValidationError(unit +
4358 " unit not recognized. "
4359 "Allowed values: " +
4360 detail::generate_map(mapping,
true));
4363 if(!input.empty()) {
4364 using CLI::detail::lexical_cast;
4365 bool converted = lexical_cast(input, num);
4367 THROW ValidationError(std::string(
"Value ") + input +
" could not be converted to " +
4368 detail::type_name<Number>());
4371 bool ok = detail::checked_multiply(num, it->second);
4373 THROW ValidationError(detail::to_string(num) +
" multiplied by " + unit +
4374 " factor would cause number overflow. Use smaller value.");
4377 num =
static_cast<Number
>(it->second);
4380 input = detail::to_string(num);
4390 for(
auto &kv : mapping) {
4391 if(kv.first.empty()) {
4392 THROW ValidationError(
"Unit must not be empty.");
4394 if(!detail::isalpha(kv.first)) {
4395 THROW ValidationError(
"Unit must contain only letters.");
4400 if(opts & CASE_INSENSITIVE) {
4402 for(
auto &kv : mapping) {
4403 auto s = detail::to_lower(kv.first);
4404 if(lower_mapping.count(s)) {
4405 THROW ValidationError(std::string(
"Several matching lowercase unit representations are found: ") +
4408 lower_mapping[detail::to_lower(kv.first)] = kv.second;
4415 template <
typename Number>
static std::string generate_description(
const std::string &name, Options opts) {
4416 std::stringstream out;
4417 out << detail::type_name<Number>() <<
' ';
4418 if(opts & UNIT_REQUIRED) {
4421 out <<
'[' << name <<
']';
4427inline AsNumberWithUnit::Options operator|(
const AsNumberWithUnit::Options &
a,
const AsNumberWithUnit::Options &
b) {
4428 return static_cast<AsNumberWithUnit::Options
>(
static_cast<int>(
a) |
static_cast<int>(
b));
4442class AsSizeValue :
public AsNumberWithUnit {
4453 explicit AsSizeValue(
bool kb_is_1000);
4476CLI11_INLINE std::string Validator::operator()(std::string &str)
const {
4477 std::string retstring;
4479 if(non_modifying_) {
4480 std::string
value = str;
4481 retstring = func_(
value);
4483 retstring = func_(str);
4490 Validator newval(*
this);
4491 newval.desc_function_ = [validator_desc]() {
return validator_desc; };
4495CLI11_INLINE Validator Validator::operator&(
const Validator &other)
const {
4498 newval._merge_description(*
this, other,
" AND ");
4501 const std::function<std::string(std::string & filename)> &f1 = func_;
4502 const std::function<std::string(std::string & filename)> &f2 = other.func_;
4504 newval.func_ = [f1, f2](std::string &input) {
4505 std::string s1 = f1(input);
4506 std::string s2 = f2(input);
4507 if(!s1.empty() && !s2.empty())
4508 return std::string(
"(") + s1 +
") AND (" + s2 +
")";
4512 newval.active_ = active_ && other.active_;
4513 newval.application_index_ = application_index_;
4517CLI11_INLINE Validator Validator::operator|(
const Validator &other)
const {
4520 newval._merge_description(*
this, other,
" OR ");
4523 const std::function<std::string(std::string &)> &f1 = func_;
4524 const std::function<std::string(std::string &)> &f2 = other.func_;
4526 newval.func_ = [f1, f2](std::string &input) {
4527 std::string s1 = f1(input);
4528 std::string s2 = f2(input);
4529 if(s1.empty() || s2.empty())
4530 return std::string();
4532 return std::string(
"(") + s1 +
") OR (" + s2 +
")";
4534 newval.active_ = active_ && other.active_;
4535 newval.application_index_ = application_index_;
4541 const std::function<std::string()> &dfunc1 = desc_function_;
4542 newval.desc_function_ = [dfunc1]() {
4543 auto str = dfunc1();
4544 return (!str.empty()) ? std::string(
"NOT ") + str : std::string{};
4547 const std::function<std::string(std::string & res)> &f1 = func_;
4549 newval.func_ = [f1, dfunc1](std::string &test) -> std::string {
4550 std::string s1 = f1(test);
4552 return std::string(
"check ") + dfunc1() +
" succeeded improperly";
4554 return std::string{};
4556 newval.active_ = active_;
4557 newval.application_index_ = application_index_;
4562Validator::_merge_description(
const Validator &val1,
const Validator &val2,
const std::string &merger) {
4564 const std::function<std::string()> &dfunc1 = val1.desc_function_;
4565 const std::function<std::string()> &dfunc2 = val2.desc_function_;
4567 desc_function_ = [=]() {
4568 std::string f1 = dfunc1();
4569 std::string f2 = dfunc2();
4570 if((f1.empty()) || (f2.empty())) {
4573 return std::string(1,
'(') + f1 +
')' + merger +
'(' + f2 +
')';
4579#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
4580CLI11_INLINE path_type check_path(
const char *file)
noexcept {
4582 auto stat = std::filesystem::status(to_path(file), ec);
4584 return path_type::nonexistent;
4586 switch(stat.type()) {
4587 case std::filesystem::file_type::none:
4588 case std::filesystem::file_type::not_found:
4589 return path_type::nonexistent;
4590 case std::filesystem::file_type::directory:
4591 return path_type::directory;
4592 case std::filesystem::file_type::symlink:
4593 case std::filesystem::file_type::block:
4594 case std::filesystem::file_type::character:
4595 case std::filesystem::file_type::fifo:
4596 case std::filesystem::file_type::socket:
4597 case std::filesystem::file_type::regular:
4598 case std::filesystem::file_type::unknown:
4600 return path_type::file;
4604CLI11_INLINE path_type check_path(
const char *file)
noexcept {
4605#if defined(_MSC_VER)
4607 if(_stat64(file, &
buffer) == 0) {
4608 return ((
buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
4612 if(stat(file, &
buffer) == 0) {
4613 return ((
buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
4616 return path_type::nonexistent;
4620CLI11_INLINE ExistingFileValidator::ExistingFileValidator() : Validator(
"FILE") {
4621 func_ = [](std::string &filename) {
4622 auto path_result = check_path(filename.c_str());
4623 if(path_result == path_type::nonexistent) {
4624 return "File does not exist: " + filename;
4626 if(path_result == path_type::directory) {
4627 return "File is actually a directory: " + filename;
4629 return std::string();
4633CLI11_INLINE ExistingDirectoryValidator::ExistingDirectoryValidator() : Validator(
"DIR") {
4634 func_ = [](std::string &filename) {
4635 auto path_result = check_path(filename.c_str());
4636 if(path_result == path_type::nonexistent) {
4637 return "Directory does not exist: " + filename;
4639 if(path_result == path_type::file) {
4640 return "Directory is actually a file: " + filename;
4642 return std::string();
4646CLI11_INLINE ExistingPathValidator::ExistingPathValidator() : Validator(
"PATH(existing)") {
4647 func_ = [](std::string &filename) {
4648 auto path_result = check_path(filename.c_str());
4649 if(path_result == path_type::nonexistent) {
4650 return "Path does not exist: " + filename;
4652 return std::string();
4656CLI11_INLINE NonexistentPathValidator::NonexistentPathValidator() : Validator(
"PATH(non-existing)") {
4657 func_ = [](std::string &filename) {
4658 auto path_result = check_path(filename.c_str());
4659 if(path_result != path_type::nonexistent) {
4660 return "Path already exists: " + filename;
4662 return std::string();
4666CLI11_INLINE IPV4Validator::IPV4Validator() : Validator(
"IPV4") {
4667 func_ = [](std::string &ip_addr) {
4668 auto result = CLI::detail::split(ip_addr,
'.');
4669 if(result.size() != 4) {
4670 return std::string(
"Invalid IPV4 address must have four parts (") + ip_addr +
')';
4673 for(
const auto &var : result) {
4674 using CLI::detail::lexical_cast;
4675 bool retval = lexical_cast(var, num);
4677 return std::string(
"Failed parsing number (") + var +
')';
4679 if(num < 0 || num > 255) {
4680 return std::string(
"Each IP number must be between 0 and 255 ") + var;
4683 return std::string{};
4687CLI11_INLINE EscapedStringTransformer::EscapedStringTransformer() {
4688 func_ = [](std::string &str) {
4690 if(str.size() > 1 && (str.front() ==
'\"' || str.front() ==
'\'' || str.front() ==
'`') &&
4691 str.front() == str.back()) {
4692 process_quoted_string(str);
4693 }
else if(str.find_first_of(
'\\') != std::string::npos) {
4694 if(detail::is_binary_escaped_string(str)) {
4695 str = detail::extract_binary_string(str);
4697 str = remove_escaped_characters(str);
4700 return std::string{};
4701 }
catch(
const std::invalid_argument &ia) {
4702#ifndef BB_NO_EXCEPTIONS
4703 return std::string(ia.what());
4710CLI11_INLINE FileOnDefaultPath::FileOnDefaultPath(std::string default_path,
bool enableErrorReturn)
4711 : Validator(
"FILE") {
4712 func_ = [default_path, enableErrorReturn](std::string &filename) {
4713 auto path_result = detail::check_path(filename.c_str());
4714 if(path_result == detail::path_type::nonexistent) {
4715 std::string test_file_path = default_path;
4716 if(default_path.back() !=
'/' && default_path.back() !=
'\\') {
4718 test_file_path +=
'/';
4720 test_file_path.append(filename);
4721 path_result = detail::check_path(test_file_path.c_str());
4722 if(path_result == detail::path_type::file) {
4723 filename = test_file_path;
4725 if(enableErrorReturn) {
4726 return "File does not exist: " + filename;
4730 return std::string{};
4734CLI11_INLINE AsSizeValue::AsSizeValue(
bool kb_is_1000) : AsNumberWithUnit(get_mapping(kb_is_1000)) {
4736 description(
"SIZE [b, kb(=1000b), kib(=1024b), ...]");
4738 description(
"SIZE [b, kb(=1024b), ...]");
4744 result_t k_factor = kb_is_1000 ? 1000 : 1024;
4745 result_t ki_factor = 1024;
4749 for(std::string p : {
"k",
"m",
"g",
"t",
"p",
"e"}) {
4762 static auto m = init_mapping(
true);
4765 static auto m = init_mapping(
false);
4775 auto esp = commandline.find_first_of(
' ', 1);
4776 while(detail::check_path(commandline.substr(0, esp).c_str()) != path_type::file) {
4777 esp = commandline.find_first_of(
' ', esp + 1);
4778 if(esp == std::string::npos) {
4781 if(commandline[0] ==
'"' || commandline[0] ==
'\'' || commandline[0] ==
'`') {
4782 bool embeddedQuote =
false;
4783 auto keyChar = commandline[0];
4784 auto end = commandline.find_first_of(keyChar, 1);
4785 while((end != std::string::npos) && (commandline[end - 1] ==
'\\')) {
4786 end = commandline.find_first_of(keyChar, end + 1);
4787 embeddedQuote =
true;
4789 if(end != std::string::npos) {
4790 vals.first = commandline.substr(1, end - 1);
4793 vals.first = find_and_replace(vals.first, std::string(
"\\") + keyChar, std::string(1, keyChar));
4796 esp = commandline.find_first_of(
' ', 1);
4799 esp = commandline.find_first_of(
' ', 1);
4805 if(vals.first.empty()) {
4806 vals.first = commandline.substr(0, esp);
4811 vals.second = (esp < commandline.length() - 1) ? commandline.substr(esp + 1) : std::string{};
4830enum class AppFormatMode {
4840class FormatterBase {
4850 std::map<std::string, std::string> labels_{};
4857 FormatterBase() =
default;
4858 FormatterBase(
const FormatterBase &) =
default;
4859 FormatterBase(FormatterBase &&) =
default;
4860 FormatterBase &operator=(
const FormatterBase &) =
default;
4861 FormatterBase &operator=(FormatterBase &&) =
default;
4864 virtual ~FormatterBase()
noexcept {}
4867 virtual std::string make_help(
const App *, std::string, AppFormatMode)
const = 0;
4874 void label(std::string
key, std::string val) { labels_[
key] = val; }
4877 void column_width(
std::size_t val) { column_width_ = val; }
4885 if(labels_.find(
key) == labels_.end())
4887 return labels_.at(
key);
4897class FormatterLambda final :
public FormatterBase {
4898 using funct_t = std::function<std::string(
const App *, std::string, AppFormatMode)>;
4905 explicit FormatterLambda(funct_t funct) : lambda_(
std::move(funct)) {}
4908 ~FormatterLambda()
noexcept override {}
4911 std::string make_help(
const App *app, std::string name, AppFormatMode mode)
const override {
4912 return lambda_(app, name, mode);
4918class Formatter :
public FormatterBase {
4920 Formatter() =
default;
4921 Formatter(
const Formatter &) =
default;
4922 Formatter(Formatter &&) =
default;
4923 Formatter &operator=(
const Formatter &) =
default;
4924 Formatter &operator=(Formatter &&) =
default;
4935 virtual std::string make_positionals(
const App *app)
const;
4938 std::string make_groups(
const App *app, AppFormatMode mode)
const;
4941 virtual std::string make_subcommands(
const App *app, AppFormatMode mode)
const;
4944 virtual std::string make_subcommand(
const App *sub)
const;
4947 virtual std::string make_expanded(
const App *sub)
const;
4950 virtual std::string make_footer(
const App *app)
const;
4953 virtual std::string make_description(
const App *app)
const;
4956 virtual std::string make_usage(
const App *app, std::string name)
const;
4959 std::string make_help(
const App * , std::string, AppFormatMode)
const override;
4966 virtual std::string make_option(
const Option *opt,
bool is_positional)
const {
4967 std::stringstream out;
4968 detail::format_help(
4969 out, make_option_name(opt, is_positional) + make_option_opts(opt), make_option_desc(opt), column_width_);
4974 virtual std::string make_option_name(
const Option *,
bool)
const;
4977 virtual std::string make_option_opts(
const Option *)
const;
4980 virtual std::string make_option_desc(
const Option *)
const;
4983 virtual std::string make_option_usage(
const Option *opt)
const;
4991using results_t = std::vector<std::string>;
4993using callback_t = std::function<bool(
const results_t &)>;
5000enum class MultiOptionPolicy :
char {
5012template <
typename CRTP>
class OptionBase {
5017 std::string group_ = std::string(
"Options");
5020 bool required_{
false};
5023 bool ignore_case_{
false};
5026 bool ignore_underscore_{
false};
5029 bool configurable_{
true};
5032 bool disable_flag_override_{
false};
5035 char delimiter_{
'\0'};
5038 bool always_capture_default_{
false};
5041 MultiOptionPolicy multi_option_policy_{MultiOptionPolicy::Throw};
5044 template <
typename T>
void copy_to(T *other)
const;
5050 CRTP *group(
const std::string &name) {
5051 if(!detail::valid_alias_name_string(name)) {
5052 THROW IncorrectConstruction(
"Group names may not contain newlines or null characters");
5055 return static_cast<CRTP *
>(
this);
5059 CRTP *required(
bool value =
true) {
5061 return static_cast<CRTP *
>(
this);
5065 CRTP *mandatory(
bool value =
true) {
return required(
value); }
5067 CRTP *always_capture_default(
bool value =
true) {
5068 always_capture_default_ =
value;
5069 return static_cast<CRTP *
>(
this);
5075 CLI11_NODISCARD const std::string &get_group()
const {
return group_; }
5084 CLI11_NODISCARD bool get_ignore_underscore()
const {
return ignore_underscore_; }
5087 CLI11_NODISCARD bool get_configurable()
const {
return configurable_; }
5090 CLI11_NODISCARD bool get_disable_flag_override()
const {
return disable_flag_override_; }
5096 CLI11_NODISCARD bool get_always_capture_default()
const {
return always_capture_default_; }
5099 CLI11_NODISCARD MultiOptionPolicy get_multi_option_policy()
const {
return multi_option_policy_; }
5105 auto *self =
static_cast<CRTP *
>(
this);
5106 self->multi_option_policy(MultiOptionPolicy::TakeLast);
5111 CRTP *take_first() {
5112 auto *self =
static_cast<CRTP *
>(
this);
5113 self->multi_option_policy(MultiOptionPolicy::TakeFirst);
5119 auto self =
static_cast<CRTP *
>(
this);
5120 self->multi_option_policy(MultiOptionPolicy::TakeAll);
5126 auto *self =
static_cast<CRTP *
>(
this);
5127 self->multi_option_policy(MultiOptionPolicy::Join);
5132 CRTP *join(
char delim) {
5133 auto self =
static_cast<CRTP *
>(
this);
5134 self->delimiter_ = delim;
5135 self->multi_option_policy(MultiOptionPolicy::Join);
5140 CRTP *configurable(
bool value =
true) {
5141 configurable_ =
value;
5142 return static_cast<CRTP *
>(
this);
5146 CRTP *delimiter(
char value =
'\0') {
5148 return static_cast<CRTP *
>(
this);
5154class OptionDefaults :
public OptionBase<OptionDefaults> {
5156 OptionDefaults() =
default;
5161 OptionDefaults *multi_option_policy(MultiOptionPolicy
value = MultiOptionPolicy::Throw) {
5162 multi_option_policy_ =
value;
5167 OptionDefaults *ignore_case(
bool value =
true) {
5168 ignore_case_ =
value;
5173 OptionDefaults *ignore_underscore(
bool value =
true) {
5174 ignore_underscore_ =
value;
5179 OptionDefaults *disable_flag_override(
bool value =
true) {
5180 disable_flag_override_ =
value;
5185 OptionDefaults *delimiter(
char value =
'\0') {
5191class Option :
public OptionBase<Option> {
5199 std::vector<std::string> snames_{};
5202 std::vector<std::string> lnames_{};
5209 std::vector<std::string> fnames_{};
5212 std::string pname_{};
5215 std::string envname_{};
5222 std::string description_{};
5225 std::string default_str_{};
5228 std::string option_text_{};
5233 std::function<std::string()> type_name_{[]() {
return std::string(); }};
5236 std::function<std::string()> default_function_{};
5244 int type_size_max_{1};
5246 int type_size_min_{1};
5249 int expected_min_{1};
5251 int expected_max_{1};
5267 App *parent_{
nullptr};
5270 callback_t callback_{};
5277 results_t results_{};
5279 results_t proc_results_{};
5281 enum class option_state :
char {
5288 option_state current_option_state_{option_state::parsing};
5290 bool allow_extra_args_{
false};
5292 bool flag_like_{
false};
5294 bool run_callback_for_default_{
false};
5296 bool inject_separator_{
false};
5298 bool trigger_on_result_{
false};
5300 bool force_callback_{
false};
5304 Option(std::string option_name, std::string option_description, callback_t callback, App *parent)
5305 : description_(
std::move(option_description)), parent_(parent), callback_(
std::move(callback)) {
5306 std::tie(snames_, lnames_, pname_) = detail::get_names(detail::split_names(option_name));
5313 Option(
const Option &) =
delete;
5314 Option &operator=(
const Option &) =
delete;
5323 explicit operator bool()
const {
return !empty() || force_callback_; }
5328 current_option_state_ = option_state::parsing;
5336 Option *expected(
int value);
5339 Option *expected(
int value_min,
int value_max);
5343 Option *allow_extra_args(
bool value =
true) {
5344 allow_extra_args_ =
value;
5348 CLI11_NODISCARD bool get_allow_extra_args()
const {
return allow_extra_args_; }
5350 Option *trigger_on_parse(
bool value =
true) {
5351 trigger_on_result_ =
value;
5355 CLI11_NODISCARD bool get_trigger_on_parse()
const {
return trigger_on_result_; }
5358 Option *force_callback(
bool value =
true) {
5359 force_callback_ =
value;
5363 CLI11_NODISCARD bool get_force_callback()
const {
return force_callback_; }
5367 Option *run_callback_for_default(
bool value =
true) {
5368 run_callback_for_default_ =
value;
5372 CLI11_NODISCARD bool get_run_callback_for_default()
const {
return run_callback_for_default_; }
5375 Option *check(Validator validator,
const std::string &validator_name =
"");
5378 Option *check(std::function<std::string(
const std::string &)> Validator,
5379 std::string Validator_description =
"",
5380 std::string Validator_name =
"");
5383 Option *transform(Validator Validator,
const std::string &Validator_name =
"");
5386 Option *transform(
const std::function<std::string(std::string)> &func,
5387 std::string transform_description =
"",
5388 std::string transform_name =
"");
5391 Option *each(
const std::function<
void(std::string)> &func);
5394 Validator *get_validator(
const std::string &Validator_name =
"");
5397 Validator *get_validator(
int index);
5400 Option *needs(Option *opt) {
5408 template <
typename T = App> Option *needs(std::string opt_name) {
5409 auto opt =
static_cast<T *
>(parent_)->get_option_no_THROW(opt_name);
5410 if(opt ==
nullptr) {
5411 THROW IncorrectConstruction::MissingOption(opt_name);
5417 template <
typename A,
typename B,
typename... ARG> Option *needs(A opt, B opt1, ARG... args) {
5419 return needs(opt1, args...);
5423 bool remove_needs(Option *opt);
5426 Option *excludes(Option *opt);
5429 template <
typename T = App> Option *excludes(std::string opt_name) {
5430 auto opt =
static_cast<T *
>(parent_)->get_option_no_THROW(opt_name);
5431 if(opt ==
nullptr) {
5432 THROW IncorrectConstruction::MissingOption(opt_name);
5434 return excludes(opt);
5438 template <
typename A,
typename B,
typename... ARG> Option *excludes(A opt, B opt1, ARG... args) {
5440 return excludes(opt1, args...);
5444 bool remove_excludes(Option *opt);
5447 Option *envname(std::string name) {
5456 template <
typename T = App> Option *ignore_case(
bool value =
true);
5462 template <
typename T = App> Option *ignore_underscore(
bool value =
true);
5465 Option *multi_option_policy(MultiOptionPolicy
value = MultiOptionPolicy::Throw);
5468 Option *disable_flag_override(
bool value =
true) {
5469 disable_flag_override_ =
value;
5480 CLI11_NODISCARD int get_type_size_min()
const {
return type_size_min_; }
5482 CLI11_NODISCARD int get_type_size_max()
const {
return type_size_max_; }
5485 CLI11_NODISCARD bool get_inject_separator()
const {
return inject_separator_; }
5497 CLI11_NODISCARD std::string get_default_str()
const {
return default_str_; }
5503 CLI11_NODISCARD const std::vector<std::string> &get_lnames()
const {
return lnames_; }
5506 CLI11_NODISCARD const std::vector<std::string> &get_snames()
const {
return snames_; }
5509 CLI11_NODISCARD const std::vector<std::string> &get_fnames()
const {
return fnames_; }
5512 if(!lnames_.empty()) {
5515 if(!snames_.empty()) {
5518 if(!pname_.empty()) {
5527 CLI11_NODISCARD int get_expected_min()
const {
return expected_min_; }
5529 CLI11_NODISCARD int get_expected_max()
const {
return expected_max_; }
5532 CLI11_NODISCARD int get_items_expected_min()
const {
return type_size_min_ * expected_min_; }
5536 int t = type_size_max_;
5537 return detail::checked_multiply(t, expected_max_) ? t : detail::expected_max_vector_size;
5540 CLI11_NODISCARD int get_items_expected()
const {
return get_items_expected_min(); }
5543 CLI11_NODISCARD bool get_positional()
const {
return !pname_.empty(); }
5546 CLI11_NODISCARD bool nonpositional()
const {
return (!lnames_.empty() || !snames_.empty()); }
5549 CLI11_NODISCARD bool has_description()
const {
return !description_.empty(); }
5552 CLI11_NODISCARD const std::string &get_description()
const {
return description_; }
5555 Option *description(std::string option_description) {
5556 description_ =
std::move(option_description);
5560 Option *option_text(std::string text) {
5565 CLI11_NODISCARD const std::string &get_option_text()
const {
return option_text_; }
5576 bool all_options =
false
5584 void run_callback();
5587 CLI11_NODISCARD const std::string &matching_name(
const Option &other)
const;
5590 bool operator==(
const Option &other)
const {
return !matching_name(other).empty(); }
5597 return (detail::find_member(
std::move(name), snames_, ignore_case_) >= 0);
5602 return (detail::find_member(
std::move(name), lnames_, ignore_case_, ignore_underscore_) >= 0);
5607 if(fnames_.empty()) {
5610 return (detail::find_member(
std::move(name), fnames_, ignore_case_, ignore_underscore_) >= 0);
5615 CLI11_NODISCARD std::string get_flag_value(
const std::string &name, std::string input_value)
const;
5618 Option *add_result(std::string s);
5621 Option *add_result(std::string s,
int &results_added);
5624 Option *add_result(std::vector<std::string> s);
5633 template <
typename T>
void results(T &output)
const {
5634 bool retval =
false;
5635 if(current_option_state_ >= option_state::reduced || (results_.size() == 1 && validators_.empty())) {
5636 const results_t &res = (proc_results_.empty()) ? results_ : proc_results_;
5637 retval = detail::lexical_conversion<T, T>(res, output);
5640 if(results_.empty()) {
5641 if(!default_str_.empty()) {
5643 _add_result(std::string(default_str_), res);
5644 _validate_results(res);
5646 _reduce_results(extra, res);
5647 if(!extra.empty()) {
5654 res = reduced_results();
5656 retval = detail::lexical_conversion<T, T>(res, output);
5659 THROW ConversionError(get_name(), results_);
5671 CLI11_NODISCARD bool get_callback_run()
const {
return (current_option_state_ == option_state::callback_run); }
5678 Option *type_name_fn(std::function<std::string()> typefun) {
5684 Option *type_name(std::string typeval) {
5685 type_name_fn([typeval]() {
return typeval; });
5690 Option *type_size(
int option_type_size);
5693 Option *type_size(
int option_type_size_min,
int option_type_size_max);
5696 void inject_separator(
bool value =
true) { inject_separator_ =
value; }
5699 Option *default_function(
const std::function<std::string()> &func) {
5700 default_function_ = func;
5705 Option *capture_default_str() {
5706 if(default_function_) {
5707 default_str_ = default_function_();
5713 Option *default_str(std::string val) {
5720 template <
typename X> Option *default_val(
const X &val) {
5721 std::string val_str = detail::to_string(val);
5722 auto old_option_state = current_option_state_;
5723 results_t old_results{
std::move(results_)};
5726 add_result(val_str);
5728 if(run_callback_for_default_ && !trigger_on_result_) {
5730 current_option_state_ = option_state::parsing;
5732 _validate_results(results_);
5733 current_option_state_ = old_option_state;
5735 }
catch(
const CLI::Error &) {
5738 current_option_state_ = old_option_state;
5751 void _validate_results(results_t &res)
const;
5756 void _reduce_results(results_t &out,
const results_t &original)
const;
5759 std::string _validate(std::string &result,
int index)
const;
5762 int _add_result(std::string &&result, std::vector<std::string> &res)
const;
5768template <
typename CRTP>
template <
typename T>
void OptionBase<CRTP>::copy_to(T *other)
const {
5769 other->group(group_);
5770 other->required(required_);
5771 other->ignore_case(ignore_case_);
5772 other->ignore_underscore(ignore_underscore_);
5773 other->configurable(configurable_);
5774 other->disable_flag_override(disable_flag_override_);
5775 other->delimiter(delimiter_);
5776 other->always_capture_default(always_capture_default_);
5777 other->multi_option_policy(multi_option_policy_);
5782 expected_min_ = -
value;
5783 if(expected_max_ < expected_min_) {
5784 expected_max_ = expected_min_;
5786 allow_extra_args_ =
true;
5788 }
else if(
value == detail::expected_max_vector_size) {
5790 expected_max_ = detail::expected_max_vector_size;
5791 allow_extra_args_ =
true;
5794 expected_min_ =
value;
5795 expected_max_ =
value;
5796 flag_like_ = (expected_min_ == 0);
5801CLI11_INLINE Option *Option::expected(
int value_min,
int value_max) {
5803 value_min = -value_min;
5807 value_max = detail::expected_max_vector_size;
5809 if(value_max < value_min) {
5810 expected_min_ = value_max;
5811 expected_max_ = value_min;
5813 expected_max_ = value_max;
5814 expected_min_ = value_min;
5820CLI11_INLINE Option *Option::check(Validator validator,
const std::string &validator_name) {
5821 validator.non_modifying();
5822 validators_.push_back(
std::move(validator));
5823 if(!validator_name.empty())
5824 validators_.back().name(validator_name);
5828CLI11_INLINE Option *Option::check(std::function<std::string(
const std::string &)> Validator,
5829 std::string Validator_description,
5830 std::string Validator_name) {
5831 validators_.emplace_back(Validator,
std::move(Validator_description),
std::move(Validator_name));
5832 validators_.back().non_modifying();
5836CLI11_INLINE Option *Option::transform(Validator Validator,
const std::string &Validator_name) {
5837 validators_.insert(validators_.begin(),
std::move(Validator));
5838 if(!Validator_name.empty())
5839 validators_.front().name(Validator_name);
5843CLI11_INLINE Option *Option::transform(
const std::function<std::string(std::string)> &func,
5844 std::string transform_description,
5845 std::string transform_name) {
5846 validators_.insert(validators_.begin(),
5848 [func](std::string &val) {
5850 return std::string{};
5858CLI11_INLINE Option *Option::each(
const std::function<
void(std::string)> &func) {
5859 validators_.emplace_back(
5860 [func](std::string &inout) {
5862 return std::string{};
5868CLI11_INLINE Validator *Option::get_validator(
const std::string &Validator_name) {
5869 for(
auto &Validator : validators_) {
5870 if(Validator_name == Validator.get_name()) {
5874 if((Validator_name.empty()) && (!validators_.empty())) {
5875 return &(validators_.front());
5877 THROW OptionNotFound(std::string{
"Validator "} + Validator_name +
" Not Found");
5880CLI11_INLINE Validator *Option::get_validator(
int index) {
5882 if(index >= 0 && index <
static_cast<int>(validators_.size())) {
5883 return &(validators_[
static_cast<decltype(validators_)::size_type
>(index)]);
5885 THROW OptionNotFound(
"Validator index is not valid");
5889 auto iterator =
std::find(std::begin(needs_), std::end(needs_), opt);
5891 if(iterator == std::end(needs_)) {
5894 needs_.erase(iterator);
5900 THROW(IncorrectConstruction(
"and option cannot exclude itself"));
5902 excludes_.insert(opt);
5905 opt->excludes_.insert(
this);
5913CLI11_INLINE bool Option::remove_excludes(Option *opt) {
5914 auto iterator =
std::find(std::begin(excludes_), std::end(excludes_), opt);
5916 if(iterator == std::end(excludes_)) {
5919 excludes_.erase(iterator);
5923template <
typename T> Option *Option::ignore_case(
bool value) {
5924 if(!ignore_case_ &&
value) {
5925 ignore_case_ =
value;
5926 auto *parent =
static_cast<T *
>(parent_);
5927 for(
const Option_p &opt : parent->options_) {
5928 if(opt.get() ==
this) {
5931 const auto &omatch = opt->matching_name(*
this);
5932 if(!omatch.empty()) {
5933 ignore_case_ =
false;
5934 THROW OptionAlreadyAdded(
"adding ignore case caused a name conflict with " + omatch);
5938 ignore_case_ =
value;
5943template <
typename T> Option *Option::ignore_underscore(
bool value) {
5945 if(!ignore_underscore_ &&
value) {
5946 ignore_underscore_ =
value;
5947 auto *parent =
static_cast<T *
>(parent_);
5948 for(
const Option_p &opt : parent->options_) {
5949 if(opt.get() ==
this) {
5952 const auto &omatch = opt->matching_name(*
this);
5953 if(!omatch.empty()) {
5954 ignore_underscore_ =
false;
5955 THROW OptionAlreadyAdded(
"adding ignore underscore caused a name conflict with " + omatch);
5959 ignore_underscore_ =
value;
5965 if(
value != multi_option_policy_) {
5966 if(multi_option_policy_ == MultiOptionPolicy::Throw && expected_max_ == detail::expected_max_vector_size &&
5967 expected_min_ > 1) {
5969 expected_max_ = expected_min_;
5971 multi_option_policy_ =
value;
5972 current_option_state_ = option_state::parsing;
5978 if(get_group().empty())
5983 std::vector<std::string> name_list;
5986 if((positional && (!pname_.empty())) || (snames_.empty() && lnames_.empty())) {
5987 name_list.push_back(pname_);
5989 if((get_items_expected() == 0) && (!fnames_.empty())) {
5990 for(
const std::string &sname : snames_) {
5991 name_list.push_back(
"-" + sname);
5992 if(check_fname(sname)) {
5993 name_list.back() +=
"{" + get_flag_value(sname,
"") +
"}";
5997 for(
const std::string &lname : lnames_) {
5998 name_list.push_back(
"--" + lname);
5999 if(check_fname(lname)) {
6000 name_list.back() +=
"{" + get_flag_value(lname,
"") +
"}";
6004 for(
const std::string &sname : snames_)
6005 name_list.push_back(
"-" + sname);
6007 for(
const std::string &lname : lnames_)
6008 name_list.push_back(
"--" + lname);
6011 return detail::join(name_list);
6019 if(!lnames_.empty())
6020 return std::string(2,
'-') + lnames_[0];
6023 if(!snames_.empty())
6024 return std::string(1,
'-') + snames_[0];
6031 if(force_callback_ && results_.empty()) {
6032 add_result(default_str_);
6034 if(current_option_state_ == option_state::parsing) {
6035 _validate_results(results_);
6036 current_option_state_ = option_state::validated;
6039 if(current_option_state_ < option_state::reduced) {
6040 _reduce_results(proc_results_, results_);
6041 current_option_state_ = option_state::reduced;
6043 if(current_option_state_ >= option_state::reduced) {
6044 current_option_state_ = option_state::callback_run;
6048 const results_t &send_results = proc_results_.empty() ? results_ : proc_results_;
6049 bool local_result = callback_(send_results);
6052 THROW ConversionError(get_name(), results_);
6057 static const std::string estring;
6058 for(
const std::string &sname : snames_) {
6059 if(other.check_sname(sname))
6061 if(other.check_lname(sname))
6064 for(
const std::string &lname : lnames_) {
6065 if(other.check_lname(lname))
6067 if(lname.size() == 1) {
6068 if(other.check_sname(lname)) {
6073 if(snames_.empty() && lnames_.empty() && !pname_.empty()) {
6074 if(other.check_sname(pname_) || other.check_lname(pname_) || pname_ == other.pname_)
6077 if(other.snames_.empty() && other.fnames_.empty() && !other.pname_.empty()) {
6078 if(check_sname(other.pname_) || check_lname(other.pname_) || (pname_ == other.pname_))
6079 return other.pname_;
6082 ignore_underscore_) {
6083 for(
const std::string &sname : other.snames_)
6084 if(check_sname(sname))
6086 for(
const std::string &lname : other.lnames_)
6087 if(check_lname(lname))
6095 if(name.length() > 2 && name[0] ==
'-' && name[1] ==
'-')
6096 return check_lname(name.substr(2));
6097 if(name.length() > 1 && name.front() ==
'-')
6098 return check_sname(name.substr(1));
6099 if(!pname_.empty()) {
6100 std::string local_pname = pname_;
6101 std::string local_name = name;
6102 if(ignore_underscore_) {
6103 local_pname = detail::remove_underscore(local_pname);
6104 local_name = detail::remove_underscore(local_name);
6107 local_pname = detail::to_lower(local_pname);
6108 local_name = detail::to_lower(local_name);
6110 if(local_name == local_pname) {
6115 if(!envname_.empty()) {
6117 return (name == envname_);
6123 std::string input_value)
const {
6124 static const std::string trueString{
"true"};
6125 static const std::string falseString{
"false"};
6126 static const std::string emptyString{
"{}"};
6128 if(disable_flag_override_) {
6129 if(!((input_value.empty()) || (input_value == emptyString))) {
6130 auto default_ind = detail::find_member(name, fnames_, ignore_case_, ignore_underscore_);
6131 if(default_ind >= 0) {
6133 if(default_flag_values_[
static_cast<std::size_t>(default_ind)].second != input_value) {
6134 if(input_value == default_str_ && force_callback_) {
6137 THROW(ArgumentMismatch::FlagOverride(name));
6140 if(input_value != trueString) {
6141 THROW(ArgumentMismatch::FlagOverride(name));
6146 auto ind = detail::find_member(name, fnames_, ignore_case_, ignore_underscore_);
6147 if((input_value.empty()) || (input_value == emptyString)) {
6149 return (ind < 0) ? trueString : default_flag_values_[
static_cast<std::size_t>(ind)].second;
6151 return (ind < 0) ? default_str_ : default_flag_values_[
static_cast<std::size_t>(ind)].second;
6156 if(default_flag_values_[
static_cast<std::size_t>(ind)].second == falseString) {
6158 auto val = detail::to_flag_value(input_value);
6163 return (val == 1) ? falseString : (val == (-1) ? trueString :
std::to_string(-val));
6168CLI11_INLINE Option *Option::add_result(std::string s) {
6170 current_option_state_ = option_state::parsing;
6174CLI11_INLINE Option *Option::add_result(std::string s,
int &results_added) {
6175 results_added = _add_result(
std::move(s), results_);
6176 current_option_state_ = option_state::parsing;
6180CLI11_INLINE Option *Option::add_result(std::vector<std::string> s) {
6181 current_option_state_ = option_state::parsing;
6182 for(
auto &str : s) {
6189 results_t res = proc_results_.empty() ? results_ : proc_results_;
6190 if(current_option_state_ < option_state::reduced) {
6191 if(current_option_state_ == option_state::parsing) {
6193 _validate_results(res);
6197 _reduce_results(extra, res);
6198 if(!extra.empty()) {
6206CLI11_INLINE Option *Option::type_size(
int option_type_size) {
6207 if(option_type_size < 0) {
6209 type_size_max_ = -option_type_size;
6210 type_size_min_ = -option_type_size;
6211 expected_max_ = detail::expected_max_vector_size;
6213 type_size_max_ = option_type_size;
6214 if(type_size_max_ < detail::expected_max_vector_size) {
6215 type_size_min_ = option_type_size;
6217 inject_separator_ =
true;
6219 if(type_size_max_ == 0)
6225CLI11_INLINE Option *Option::type_size(
int option_type_size_min,
int option_type_size_max) {
6226 if(option_type_size_min < 0 || option_type_size_max < 0) {
6228 expected_max_ = detail::expected_max_vector_size;
6229 option_type_size_min = (
std::abs)(option_type_size_min);
6230 option_type_size_max = (
std::abs)(option_type_size_max);
6233 if(option_type_size_min > option_type_size_max) {
6234 type_size_max_ = option_type_size_min;
6235 type_size_min_ = option_type_size_max;
6237 type_size_min_ = option_type_size_min;
6238 type_size_max_ = option_type_size_max;
6240 if(type_size_max_ == 0) {
6243 if(type_size_max_ >= detail::expected_max_vector_size) {
6244 inject_separator_ =
true;
6250 std::string full_type_name = type_name_();
6251 if(!validators_.empty()) {
6252 for(
const auto &Validator : validators_) {
6253 std::string vtype = Validator.get_description();
6254 if(!vtype.empty()) {
6255 full_type_name +=
":" + vtype;
6259 return full_type_name;
6262CLI11_INLINE void Option::_validate_results(results_t &res)
const {
6264 if(!validators_.empty()) {
6265 if(type_size_max_ > 1) {
6267 if(get_items_expected_max() <
static_cast<int>(res.size()) &&
6268 (multi_option_policy_ == CLI::MultiOptionPolicy::TakeLast ||
6269 multi_option_policy_ == CLI::MultiOptionPolicy::Reverse)) {
6271 index = get_items_expected_max() -
static_cast<int>(res.size());
6274 for(std::string &result : res) {
6275 if(detail::is_separator(result) && type_size_max_ != type_size_min_ && index >= 0) {
6279 auto err_msg = _validate(result, (index >= 0) ? (index % type_size_max_) : index);
6280 if(!err_msg.empty())
6281 THROW ValidationError(get_name(), err_msg);
6286 if(expected_max_ <
static_cast<int>(res.size()) &&
6287 (multi_option_policy_ == CLI::MultiOptionPolicy::TakeLast ||
6288 multi_option_policy_ == CLI::MultiOptionPolicy::Reverse)) {
6290 index = expected_max_ -
static_cast<int>(res.size());
6292 for(std::string &result : res) {
6293 auto err_msg = _validate(result, index);
6295 if(!err_msg.empty())
6296 THROW ValidationError(get_name(), err_msg);
6302CLI11_INLINE void Option::_reduce_results(results_t &out,
const results_t &original)
const {
6309 switch(multi_option_policy_) {
6310 case MultiOptionPolicy::TakeAll:
6312 case MultiOptionPolicy::TakeLast: {
6316 if(original.size() != trim_size) {
6317 out.assign(original.end() -
static_cast<results_t::difference_type
>(trim_size), original.end());
6320 case MultiOptionPolicy::Reverse: {
6324 if(original.size() != trim_size || trim_size > 1) {
6325 out.assign(original.end() -
static_cast<results_t::difference_type
>(trim_size), original.end());
6327 std::reverse(out.begin(), out.end());
6329 case MultiOptionPolicy::TakeFirst: {
6332 if(original.size() != trim_size) {
6333 out.assign(original.begin(), original.begin() +
static_cast<results_t::difference_type
>(trim_size));
6336 case MultiOptionPolicy::Join:
6337 if(results_.size() > 1) {
6338 out.push_back(detail::join(original, std::string(1, (delimiter_ ==
'\0') ?
'\n' : delimiter_)));
6341 case MultiOptionPolicy::Sum:
6342 out.push_back(detail::sum_string_vector(original));
6344 case MultiOptionPolicy::Throw:
6346 auto num_min =
static_cast<std::size_t>(get_items_expected_min());
6347 auto num_max =
static_cast<std::size_t>(get_items_expected_max());
6354 if(original.size() < num_min) {
6355 THROW ArgumentMismatch::AtLeast(get_name(),
static_cast<int>(num_min), original.size());
6357 if(original.size() > num_max) {
6358 if(original.size() == 2 && num_max == 1 && original[1] ==
"%%" && original[0] ==
"{}") {
6362 THROW ArgumentMismatch::AtMost(get_name(),
static_cast<int>(num_max), original.size());
6371 if(original.size() == 1 && original[0] ==
"{}" && get_items_expected_min() > 0) {
6372 out.emplace_back(
"{}");
6373 out.emplace_back(
"%%");
6375 }
else if(out.size() == 1 && out[0] ==
"{}" && get_items_expected_min() > 0) {
6376 out.emplace_back(
"%%");
6380CLI11_INLINE std::string Option::_validate(std::string &result,
int index)
const {
6381 std::string err_msg;
6382 if(result.empty() && expected_min_ == 0) {
6386 for(
const auto &vali : validators_) {
6387 auto v = vali.get_application_index();
6388 if(v == -1 || v == index) {
6390 err_msg = vali(result);
6391 }
catch(
const ValidationError &err) {
6392#ifndef BB_NO_EXCEPTIONS
6393 err_msg = err.what();
6396 if(!err_msg.empty())
6404CLI11_INLINE int Option::_add_result(std::string &&result, std::vector<std::string> &res)
const {
6405 int result_count = 0;
6406 if(allow_extra_args_ && !result.empty() && result.front() ==
'[' &&
6407 result.back() ==
']') {
6410 for(
auto &var : CLI::detail::split(result.substr(1),
',')) {
6412 result_count += _add_result(
std::move(var), res);
6415 return result_count;
6417 if(delimiter_ ==
'\0') {
6421 if((result.find_first_of(delimiter_) != std::string::npos)) {
6422 for(
const auto &var : CLI::detail::split(result, delimiter_)) {
6433 return result_count;
6439#ifdef BB_NO_EXCEPTIONS
6440#define CLI11_PARSE(app, ...) (app).parse(__VA_ARGS__)
6442#define CLI11_PARSE(app, ...) \
6444 (app).parse(__VA_ARGS__); \
6445 } catch(const CLI::ParseError &e) { \
6446 return (app).exit(e); \
6452enum class Classifier { NONE, POSITIONAL_MARK, SHORT, LONG, WINDOWS_STYLE, SUBCOMMAND, SUBCOMMAND_TERMINATOR };
6456namespace FailureMessage {
6458CLI11_INLINE std::string simple(
const App *app,
const Error &e);
6461CLI11_INLINE std::string help(
const App *app,
const Error &e);
6466enum class config_extras_mode :
char { error = 0, ignore, ignore_all, capture };
6475template <typename T, enable_if_t<!std::is_integral<T>::value || (
sizeof(T) <= 1U), detail::enabler> = detail::dummy>
6476Option *default_flag_modifiers(Option *opt) {
6477 return opt->always_capture_default();
6481template <typename T, enable_if_t<std::is_integral<T>::value && (
sizeof(T) > 1U), detail::enabler> = detail::dummy>
6482Option *default_flag_modifiers(Option *opt) {
6483 return opt->multi_option_policy(MultiOptionPolicy::Sum)->default_str(
"0")->force_callback();
6495 friend detail::AppFriend;
6504 std::string name_{};
6507 std::string description_{};
6510 bool allow_extras_{
false};
6514 config_extras_mode allow_config_extras_{config_extras_mode::ignore};
6517 bool prefix_command_{
false};
6520 bool has_automatic_name_{
false};
6523 bool required_{
false};
6526 bool disabled_{
false};
6529 bool pre_parse_called_{
false};
6533 bool immediate_callback_{
false};
6536 std::function<void(
std::size_t)> pre_parse_callback_{};
6539 std::function<void()> parse_complete_callback_{};
6542 std::function<void()> final_callback_{};
6549 OptionDefaults option_defaults_{};
6559 std::string usage_{};
6562 std::function<std::string()> usage_callback_{};
6565 std::string footer_{};
6568 std::function<std::string()> footer_callback_{};
6571 Option *help_ptr_{
nullptr};
6574 Option *help_all_ptr_{
nullptr};
6577 Option *version_ptr_{
nullptr};
6583 std::function<std::string(
const App *,
const Error &e)> failure_message_{FailureMessage::simple};
6594 missing_t missing_{};
6625 bool ignore_case_{
false};
6628 bool ignore_underscore_{
false};
6631 bool fallthrough_{
false};
6634 bool allow_windows_style_options_{
6642 bool positionals_at_end_{
false};
6644 enum class startup_mode :
char { stable, enabled, disabled };
6647 startup_mode default_startup{startup_mode::stable};
6650 bool configurable_{
false};
6653 bool validate_positionals_{
false};
6656 bool validate_optional_arguments_{
false};
6660 bool silent_{
false};
6678 App *parent_{
nullptr};
6681 std::string group_{
"Subcommands"};
6684 std::vector<std::string> aliases_{};
6691 Option *config_ptr_{
nullptr};
6700 std::vector<std::string> normalized_argv_{};
6707 App(std::string app_description, std::string app_name, App *parent);
6714 explicit App(std::string app_description =
"", std::string app_name =
"")
6715 : App(app_description, app_name,
nullptr) {
6716 set_help_flag(
"-h,--help",
"Print this help message and exit");
6719 App(
const App &) =
delete;
6720 App &operator=(
const App &) =
delete;
6723 virtual ~App() =
default;
6734 App *callback(std::function<
void()> app_callback) {
6735 if(immediate_callback_) {
6736 parse_complete_callback_ =
std::move(app_callback);
6738 final_callback_ =
std::move(app_callback);
6745 App *final_callback(std::function<
void()> app_callback) {
6746 final_callback_ =
std::move(app_callback);
6752 App *parse_complete_callback(std::function<
void()> pc_callback) {
6753 parse_complete_callback_ =
std::move(pc_callback);
6759 App *preparse_callback(std::function<
void(
std::size_t)> pp_callback) {
6760 pre_parse_callback_ =
std::move(pp_callback);
6765 App *name(std::string app_name =
"");
6768 App *alias(std::string app_name);
6771 App *allow_extras(
bool allow =
true) {
6772 allow_extras_ = allow;
6777 App *required(
bool require =
true) {
6778 required_ = require;
6783 App *disabled(
bool disable =
true) {
6784 disabled_ = disable;
6789 App *silent(
bool silence =
true) {
6795 App *disabled_by_default(
bool disable =
true) {
6797 default_startup = startup_mode::disabled;
6799 default_startup = (default_startup == startup_mode::enabled) ? startup_mode::enabled : startup_mode::stable;
6806 App *enabled_by_default(
bool enable =
true) {
6808 default_startup = startup_mode::enabled;
6811 (default_startup == startup_mode::disabled) ? startup_mode::disabled : startup_mode::stable;
6817 App *immediate_callback(
bool immediate =
true);
6820 App *validate_positionals(
bool validate =
true) {
6821 validate_positionals_ = validate;
6826 App *validate_optional_arguments(
bool validate =
true) {
6827 validate_optional_arguments_ = validate;
6832 App *allow_config_extras(
bool allow =
true) {
6834 allow_config_extras_ = config_extras_mode::capture;
6835 allow_extras_ =
true;
6837 allow_config_extras_ = config_extras_mode::error;
6843 App *allow_config_extras(config_extras_mode mode) {
6844 allow_config_extras_ = mode;
6849 App *prefix_command(
bool allow =
true) {
6850 prefix_command_ = allow;
6855 App *ignore_case(
bool value =
true);
6859 App *allow_windows_style_options(
bool value =
true) {
6860 allow_windows_style_options_ =
value;
6865 App *positionals_at_end(
bool value =
true) {
6866 positionals_at_end_ =
value;
6871 App *configurable(
bool value =
true) {
6872 configurable_ =
value;
6877 App *ignore_underscore(
bool value =
true);
6886 App *formatter_fn(std::function<std::string(
const App *, std::string, AppFormatMode)> fmt) {
6893 config_formatter_ = fmt;
6901 OptionDefaults *option_defaults() {
return &option_defaults_; }
6921 Option *add_option(std::string option_name,
6922 callback_t option_callback,
6923 std::string option_description =
"",
6924 bool defaulted =
false,
6925 std::function<std::string()> func = {});
6928 template <
typename AssignTo,
6929 typename ConvertTo = AssignTo,
6930 enable_if_t<!std::is_const<ConvertTo>::value, detail::enabler> = detail::dummy>
6931 Option *add_option(std::string option_name,
6933 std::string option_description =
"") {
6935 auto fun = [&variable](
const CLI::results_t &res) {
6936 return detail::lexical_conversion<AssignTo, ConvertTo>(res, variable);
6939 Option *opt = add_option(option_name, fun, option_description,
false, [&variable]() {
6940 return CLI::detail::checked_to_string<AssignTo, ConvertTo>(variable);
6942 opt->type_name(detail::type_name<ConvertTo>());
6945 auto Tcount = detail::type_count<AssignTo>::value;
6946 auto XCcount = detail::type_count<ConvertTo>::value;
6947 opt->type_size(detail::type_count_min<ConvertTo>::value, (
std::max)(Tcount, XCcount));
6948 opt->expected(detail::expected_count<ConvertTo>::value);
6949 opt->run_callback_for_default();
6954 template <typename AssignTo, enable_if_t<!std::is_const<AssignTo>::value, detail::enabler> = detail::dummy>
6955 Option *add_option_no_stream(std::string option_name,
6957 std::string option_description =
"") {
6959 auto fun = [&variable](
const CLI::results_t &res) {
6960 return detail::lexical_conversion<AssignTo, AssignTo>(res, variable);
6963 Option *opt = add_option(option_name, fun, option_description,
false, []() {
return std::string{}; });
6964 opt->type_name(detail::type_name<AssignTo>());
6965 opt->type_size(detail::type_count_min<AssignTo>::value, detail::type_count<AssignTo>::value);
6966 opt->expected(detail::expected_count<AssignTo>::value);
6967 opt->run_callback_for_default();
6972 template <
typename ArgType>
6973 Option *add_option_function(std::string option_name,
6974 const std::function<
void(
const ArgType &)> &func,
6975 std::string option_description =
"") {
6977 auto fun = [func](
const CLI::results_t &res) {
6979 bool result = detail::lexical_conversion<ArgType, ArgType>(res, variable);
6986 Option *opt = add_option(option_name,
std::move(fun), option_description,
false);
6987 opt->type_name(detail::type_name<ArgType>());
6988 opt->type_size(detail::type_count_min<ArgType>::value, detail::type_count<ArgType>::value);
6989 opt->expected(detail::expected_count<ArgType>::value);
6994 Option *add_option(std::string option_name) {
6995 return add_option(option_name, CLI::callback_t{}, std::string{},
false);
6999 template <
typename T,
7000 enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value, detail::enabler> =
7002 Option *add_option(std::string option_name, T &option_description) {
7003 return add_option(option_name, CLI::callback_t(), option_description,
false);
7007 Option *set_help_flag(std::string flag_name =
"",
const std::string &help_description =
"");
7010 Option *set_help_all_flag(std::string help_name =
"",
const std::string &help_description =
"");
7013 Option *set_version_flag(std::string flag_name =
"",
7014 const std::string &versionString =
"",
7015 const std::string &version_help =
"Display program version information and exit");
7018 Option *set_version_flag(std::string flag_name,
7019 std::function<std::string()> vfunc,
7020 const std::string &version_help =
"Display program version information and exit");
7024 Option *_add_flag_internal(std::string flag_name, CLI::callback_t fun, std::string flag_description);
7028 Option *add_flag(std::string flag_name) {
return _add_flag_internal(flag_name, CLI::callback_t(), std::string{}); }
7033 template <
typename T,
7034 enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value, detail::enabler> =
7036 Option *add_flag(std::string flag_name, T &flag_description) {
7037 return _add_flag_internal(flag_name, CLI::callback_t(), flag_description);
7042 template <
typename T,
7043 enable_if_t<!detail::is_mutable_container<T>::value && !std::is_const<T>::value &&
7045 detail::enabler> = detail::dummy>
7046 Option *add_flag(std::string flag_name,
7048 std::string flag_description =
"") {
7050 CLI::callback_t fun = [&flag_result](
const CLI::results_t &res) {
7051 using CLI::detail::lexical_cast;
7052 return lexical_cast(res[0], flag_result);
7054 auto *opt = _add_flag_internal(flag_name,
std::move(fun),
std::move(flag_description));
7055 return detail::default_flag_modifiers<T>(opt);
7059 template <
typename T,
7062 Option *add_flag(std::string flag_name,
7064 std::string flag_description =
"") {
7065 CLI::callback_t fun = [&flag_results](
const CLI::results_t &res) {
7067 for(
const auto &elem : res) {
7068 using CLI::detail::lexical_cast;
7069 flag_results.emplace_back();
7070 retval &= lexical_cast(elem, flag_results.back());
7075 ->multi_option_policy(MultiOptionPolicy::TakeAll)
7076 ->run_callback_for_default();
7080 Option *add_flag_callback(std::string flag_name,
7081 std::function<
void(
void)> function,
7082 std::string flag_description =
"");
7085 Option *add_flag_function(std::string flag_name,
7087 std::string flag_description =
"");
7091 Option *add_flag(std::string flag_name,
7093 std::string flag_description =
"") {
7099 Option *set_config(std::string option_name =
"",
7100 std::string default_filename =
"",
7101 const std::string &help_message =
"Read an ini file",
7102 bool config_required =
false);
7105 bool remove_option(Option *opt);
7108 template <
typename T = Option_group>
7109 T *add_option_group(std::string group_name, std::string group_description =
"") {
7110 if(!detail::valid_alias_name_string(group_name)) {
7111 THROW IncorrectConstruction(
"option group names may not contain newlines or null characters");
7114 auto *ptr = option_group.get();
7126 App *add_subcommand(std::string subcommand_name =
"", std::string subcommand_description =
"");
7129 App *add_subcommand(CLI::App_p subcom);
7132 bool remove_subcommand(App *subcom);
7136 App *get_subcommand(
const App *subcom)
const;
7143 CLI11_NODISCARD App *get_subcommand_no_THROW(std::string subcom)
const noexcept;
7149 CLI::App_p get_subcommand_ptr(App *subcom)
const;
7152 CLI11_NODISCARD CLI::App_p get_subcommand_ptr(std::string subcom)
const;
7170 App *group(std::string group_name) {
7171 group_ = group_name;
7176 App *require_subcommand() {
7177 require_subcommand_min_ = 1;
7178 require_subcommand_max_ = 0;
7185 App *require_subcommand(
int value) {
7187 require_subcommand_min_ = 0;
7199 require_subcommand_min_ = min;
7200 require_subcommand_max_ = max;
7205 App *require_option() {
7206 require_option_min_ = 1;
7207 require_option_max_ = 0;
7214 App *require_option(
int value) {
7216 require_option_min_ = 0;
7228 require_option_min_ = min;
7229 require_option_max_ = max;
7235 App *fallthrough(
bool value =
true) {
7236 fallthrough_ =
value;
7242 explicit operator bool()
const {
return parsed_ > 0; }
7251 virtual void pre_callback() {}
7262 void parse(
int argc,
const char *
const *argv);
7263 void parse(
int argc,
const wchar_t *
const *argv);
7266 template <
class CharT>
void parse_char_t(
int argc,
const CharT *
const *argv);
7273 void parse(std::string commandline,
bool program_name_included =
false);
7274 void parse(std::wstring commandline,
bool program_name_included =
false);
7278 void parse(std::vector<std::string> &args);
7281 void parse(std::vector<std::string> &&args);
7283 void parse_from_stream(std::istream &input);
7286 void failure_message(std::function<std::string(
const App *,
const Error &e)> function) {
7287 failure_message_ = function;
7291 int exit(
const Error &e, std::ostream &out =
std::cout, std::ostream &err =
std::cerr)
const;
7313 bool got_subcommand(
const App *subcom)
const {
7315 return get_subcommand(subcom)->parsed_ > 0;
7319 CLI11_NODISCARD bool got_subcommand(std::string subcommand_name)
const noexcept {
7320 App *sub = get_subcommand_no_THROW(subcommand_name);
7321 return (sub !=
nullptr) ? (sub->parsed_ > 0) :
false;
7325 App *excludes(Option *opt) {
7326 if(opt ==
nullptr) {
7327 THROW OptionNotFound(
"nullptr passed");
7329 exclude_options_.insert(opt);
7334 App *excludes(App *app) {
7335 if(app ==
nullptr) {
7336 THROW OptionNotFound(
"nullptr passed");
7339 THROW OptionNotFound(
"cannot self reference in needs");
7341 auto res = exclude_subcommands_.insert(app);
7344 app->exclude_subcommands_.insert(
this);
7349 App *needs(Option *opt) {
7350 if(opt ==
nullptr) {
7351 THROW OptionNotFound(
"nullptr passed");
7353 need_options_.insert(opt);
7357 App *needs(App *app) {
7358 if(app ==
nullptr) {
7359 THROW OptionNotFound(
"nullptr passed");
7362 THROW OptionNotFound(
"cannot self reference in needs");
7364 need_subcommands_.insert(app);
7369 bool remove_excludes(Option *opt);
7372 bool remove_excludes(App *app);
7375 bool remove_needs(Option *opt);
7378 bool remove_needs(App *app);
7384 App *usage(std::string usage_string) {
7389 App *usage(std::function<std::string()> usage_function) {
7390 usage_callback_ =
std::move(usage_function);
7394 App *footer(std::string footer_string) {
7399 App *footer(std::function<std::string()> footer_function) {
7400 footer_callback_ =
std::move(footer_function);
7405 CLI11_NODISCARD std::string config_to_str(
bool default_also =
false,
bool write_description =
false)
const {
7406 return config_formatter_->to_config(
this, default_also, write_description,
"");
7411 CLI11_NODISCARD std::string help(std::string prev =
"", AppFormatMode mode = AppFormatMode::Normal)
const;
7428#if CLI11_USE_STATIC_RTTI == 0
7436 CLI11_NODISCARD std::string get_description()
const {
return description_; }
7439 App *description(std::string app_description) {
7440 description_ =
std::move(app_description);
7451 CLI11_NODISCARD Option *get_option_no_THROW(std::string option_name)
noexcept;
7454 CLI11_NODISCARD const Option *get_option_no_THROW(std::string option_name)
const noexcept;
7457 CLI11_NODISCARD const Option *get_option(std::string option_name)
const {
7458 const auto *opt = get_option_no_THROW(option_name);
7459 if(opt ==
nullptr) {
7460 THROW OptionNotFound(option_name);
7466 Option *get_option(std::string option_name) {
7467 auto *opt = get_option_no_THROW(option_name);
7468 if(opt ==
nullptr) {
7469 THROW OptionNotFound(option_name);
7475 const Option *
operator[](
const std::string &option_name)
const {
return get_option(option_name); }
7478 const Option *
operator[](
const char *option_name)
const {
return get_option(option_name); }
7484 CLI11_NODISCARD bool get_ignore_underscore()
const {
return ignore_underscore_; }
7490 CLI11_NODISCARD bool get_allow_windows_style_options()
const {
return allow_windows_style_options_; }
7493 CLI11_NODISCARD bool get_positionals_at_end()
const {
return positionals_at_end_; }
7496 CLI11_NODISCARD bool get_configurable()
const {
return configurable_; }
7499 CLI11_NODISCARD const std::string &get_group()
const {
return group_; }
7503 return (usage_callback_) ? usage_callback_() +
'\n' + usage_ : usage_;
7508 return (footer_callback_) ? footer_callback_() +
'\n' + footer_ : footer_;
7524 CLI11_NODISCARD bool get_prefix_command()
const {
return prefix_command_; }
7527 CLI11_NODISCARD bool get_allow_extras()
const {
return allow_extras_; }
7539 CLI11_NODISCARD bool get_immediate_callback()
const {
return immediate_callback_; }
7542 CLI11_NODISCARD bool get_disabled_by_default()
const {
return (default_startup == startup_mode::disabled); }
7545 CLI11_NODISCARD bool get_enabled_by_default()
const {
return (default_startup == startup_mode::enabled); }
7547 CLI11_NODISCARD bool get_validate_positionals()
const {
return validate_positionals_; }
7549 CLI11_NODISCARD bool get_validate_optional_arguments()
const {
return validate_optional_arguments_; }
7552 CLI11_NODISCARD config_extras_mode get_allow_config_extras()
const {
return allow_config_extras_; }
7555 Option *get_help_ptr() {
return help_ptr_; }
7558 CLI11_NODISCARD const Option *get_help_ptr()
const {
return help_ptr_; }
7561 CLI11_NODISCARD const Option *get_help_all_ptr()
const {
return help_all_ptr_; }
7564 Option *get_config_ptr() {
return config_ptr_; }
7567 CLI11_NODISCARD const Option *get_config_ptr()
const {
return config_ptr_; }
7570 Option *get_version_ptr() {
return version_ptr_; }
7573 CLI11_NODISCARD const Option *get_version_ptr()
const {
return version_ptr_; }
7576 App *get_parent() {
return parent_; }
7585 CLI11_NODISCARD const std::vector<std::string> &get_aliases()
const {
return aliases_; }
7588 App *clear_aliases() {
7594 CLI11_NODISCARD std::string get_display_name(
bool with_aliases =
false)
const;
7606 CLI11_NODISCARD std::vector<std::string> remaining(
bool recurse =
false)
const;
7609 CLI11_NODISCARD std::vector<std::string> remaining_for_passthrough(
bool recurse =
false)
const;
7621 void _validate()
const;
7629 void run_callback(
bool final_mode =
false,
bool suppress_final_callback =
false);
7632 CLI11_NODISCARD bool _valid_subcommand(
const std::string ¤t,
bool ignore_used =
true)
const;
7635 CLI11_NODISCARD detail::Classifier _recognize(
const std::string ¤t,
7636 bool ignore_used_subcommands =
true)
const;
7641 void _process_config_file();
7644 bool _process_config_file(
const std::string &config_file,
bool throw_error);
7647 void _process_env();
7650 void _process_callbacks();
7655 void _process_help_flags(
bool trigger_help =
false,
bool trigger_all_help =
false)
const;
7658 void _process_requirements();
7664 void _process_extras();
7668 void _process_extras(std::vector<std::string> &args);
7671 void increment_parsed();
7674 void _parse(std::vector<std::string> &args);
7677 void _parse(std::vector<std::string> &&args);
7680 void _parse_stream(std::istream &input);
7689 bool _parse_single_config(
const ConfigItem &item,
std::size_t level = 0);
7693 bool _parse_single(std::vector<std::string> &args,
bool &positional_only);
7704 bool _parse_positional(std::vector<std::string> &args,
bool haltOnSubcommand);
7709 _find_subcommand(
const std::string &subc_name,
bool ignore_disabled,
bool ignore_used)
const noexcept;
7715 bool _parse_subcommand(std::vector<std::string> &args);
7720 bool _parse_arg(std::vector<std::string> &args, detail::Classifier current_type,
bool local_processing_only);
7723 void _trigger_pre_parse(
std::size_t remaining_args);
7726 App *_get_fallthrough_parent();
7729 CLI11_NODISCARD const std::string &_compare_subcommand_names(
const App &subcom,
const App &base)
const;
7732 void _move_to_missing(detail::Classifier val_type,
const std::string &val);
7736 void _move_option(Option *opt, App *app);
7740class Option_group :
public App {
7742 Option_group(std::string group_description, std::string group_name, App *parent)
7743 : App(
std::move(group_description),
"", parent) {
7747 using App::add_option;
7749 Option *add_option(Option *opt) {
7750 if(get_parent() ==
nullptr) {
7751 THROW OptionNotFound(
"Unable to locate the specified option");
7753 get_parent()->_move_option(opt,
this);
7757 void add_options(Option *opt) { add_option(opt); }
7759 template <
typename... Args>
void add_options(Option *opt, Args... args) {
7761 add_options(args...);
7763 using App::add_subcommand;
7765 App *add_subcommand(App *subcom) {
7766 App_p subc = subcom->get_parent()->get_subcommand_ptr(subcom);
7767 subc->get_parent()->remove_subcommand(subcom);
7774CLI11_INLINE void TriggerOn(App *trigger_app, App *app_to_enable);
7780CLI11_INLINE void TriggerOff(App *trigger_app, App *app_to_enable);
7786CLI11_INLINE void deprecate_option(Option *opt,
const std::string &replacement =
"");
7789inline void deprecate_option(App *app,
const std::string &option_name,
const std::string &replacement =
"") {
7790 auto *opt = app->get_option(option_name);
7791 deprecate_option(opt, replacement);
7795inline void deprecate_option(App &app,
const std::string &option_name,
const std::string &replacement =
"") {
7796 auto *opt = app.get_option(option_name);
7797 deprecate_option(opt, replacement);
7807CLI11_INLINE void retire_option(App *app,
const std::string &option_name);
7810CLI11_INLINE void retire_option(App &app,
const std::string &option_name);
7818 template <
typename... Args>
static decltype(
auto) parse_arg(App *app, Args &&...args) {
7823 template <
typename... Args>
static decltype(
auto) parse_subcommand(App *app, Args &&...args) {
7828 template <
typename... Args>
7829 static auto parse_arg(App *app, Args &&...args) ->
7830 typename std::result_of<
decltype (&App::_parse_arg)(App, Args...)>::type {
7835 template <
typename... Args>
7836 static auto parse_subcommand(App *app, Args &&...args) ->
7837 typename std::result_of<
decltype (&App::_parse_subcommand)(App, Args...)>::type {
7842 static App *get_fallthrough_parent(App *app) {
return app->_get_fallthrough_parent(); }
7849CLI11_INLINE App::App(std::string app_description, std::string app_name, App *parent)
7850 : name_(
std::move(app_name)), description_(
std::move(app_description)), parent_(parent) {
7852 if(parent_ !=
nullptr) {
7853 if(parent_->help_ptr_ !=
nullptr)
7854 set_help_flag(parent_->help_ptr_->get_name(
false,
true), parent_->help_ptr_->get_description());
7855 if(parent_->help_all_ptr_ !=
nullptr)
7856 set_help_all_flag(parent_->help_all_ptr_->get_name(
false,
true), parent_->help_all_ptr_->get_description());
7859 option_defaults_ = parent_->option_defaults_;
7862 failure_message_ = parent_->failure_message_;
7863 allow_extras_ = parent_->allow_extras_;
7864 allow_config_extras_ = parent_->allow_config_extras_;
7865 prefix_command_ = parent_->prefix_command_;
7866 immediate_callback_ = parent_->immediate_callback_;
7867 ignore_case_ = parent_->ignore_case_;
7868 ignore_underscore_ = parent_->ignore_underscore_;
7869 fallthrough_ = parent_->fallthrough_;
7870 validate_positionals_ = parent_->validate_positionals_;
7871 validate_optional_arguments_ = parent_->validate_optional_arguments_;
7872 configurable_ = parent_->configurable_;
7873 allow_windows_style_options_ = parent_->allow_windows_style_options_;
7874 group_ = parent_->group_;
7875 usage_ = parent_->usage_;
7876 footer_ = parent_->footer_;
7877 formatter_ = parent_->formatter_;
7878 config_formatter_ = parent_->config_formatter_;
7879 require_subcommand_max_ = parent_->require_subcommand_max_;
7887 normalized_argv_ = detail::compute_win32_argv();
7889 if(!normalized_argv_view_.empty()) {
7890 normalized_argv_view_.clear();
7893 normalized_argv_view_.reserve(normalized_argv_.size());
7894 for(
auto &arg : normalized_argv_) {
7896 normalized_argv_view_.push_back(
const_cast<char *
>(arg.data()));
7899 return normalized_argv_view_.data();
7907 if(parent_ !=
nullptr) {
7908 std::string oname = name_;
7910 const auto &res = _compare_subcommand_names(*
this, *_get_fallthrough_parent());
7913 THROW(OptionAlreadyAdded(app_name +
" conflicts with existing subcommand names"));
7918 has_automatic_name_ =
false;
7923 if(app_name.empty() || !detail::valid_alias_name_string(app_name)) {
7924 THROW IncorrectConstruction(
"Aliases may not be empty or contain newlines or null characters");
7926 if(parent_ !=
nullptr) {
7927 aliases_.push_back(app_name);
7928 const auto &res = _compare_subcommand_names(*
this, *_get_fallthrough_parent());
7930 aliases_.pop_back();
7931 THROW(OptionAlreadyAdded(
"alias already matches an existing subcommand: " + app_name));
7934 aliases_.push_back(app_name);
7940CLI11_INLINE App *App::immediate_callback(
bool immediate) {
7941 immediate_callback_ = immediate;
7942 if(immediate_callback_) {
7943 if(final_callback_ && !(parse_complete_callback_)) {
7944 std::swap(final_callback_, parse_complete_callback_);
7946 }
else if(!(final_callback_) && parse_complete_callback_) {
7947 std::swap(final_callback_, parse_complete_callback_);
7953 if(
value && !ignore_case_) {
7954 ignore_case_ =
true;
7955 auto *p = (parent_ !=
nullptr) ? _get_fallthrough_parent() :
this;
7956 const auto &match = _compare_subcommand_names(*
this, *p);
7957 if(!match.empty()) {
7958 ignore_case_ =
false;
7959 THROW OptionAlreadyAdded(
"ignore case would cause subcommand name conflicts: " + match);
7962 ignore_case_ =
value;
7967 if(
value && !ignore_underscore_) {
7968 ignore_underscore_ =
true;
7969 auto *p = (parent_ !=
nullptr) ? _get_fallthrough_parent() :
this;
7970 const auto &match = _compare_subcommand_names(*
this, *p);
7971 if(!match.empty()) {
7972 ignore_underscore_ =
false;
7973 THROW OptionAlreadyAdded(
"ignore underscore would cause subcommand name conflicts: " + match);
7976 ignore_underscore_ =
value;
7980CLI11_INLINE Option *App::add_option(std::string option_name,
7981 callback_t option_callback,
7982 std::string option_description,
7984 std::function<std::string()> func) {
7985 Option myopt{option_name, option_description, option_callback,
this};
7987 if(
std::find_if(std::begin(options_), std::end(options_), [&myopt](
const Option_p &v) {
return *v == myopt; }) ==
7988 std::end(options_)) {
7989 if(myopt.lnames_.empty() && myopt.snames_.empty()) {
7992 std::string test_name =
"--" + myopt.get_single_name();
7993 if(test_name.size() == 3) {
7994 test_name.erase(0, 1);
7997 auto *op = get_option_no_THROW(test_name);
7999 THROW(OptionAlreadyAdded(
"added option positional name matches existing option: " + test_name));
8001 }
else if(parent_ !=
nullptr) {
8002 for(
auto &ln : myopt.lnames_) {
8003 auto *op = parent_->get_option_no_THROW(ln);
8005 THROW(OptionAlreadyAdded(
"added option matches existing positional option: " + ln));
8008 for(
auto &sn : myopt.snames_) {
8009 auto *op = parent_->get_option_no_THROW(sn);
8011 THROW(OptionAlreadyAdded(
"added option matches existing positional option: " + sn));
8015 options_.emplace_back();
8016 Option_p &option = options_.back();
8017 option.reset(
new Option(option_name, option_description, option_callback,
this));
8020 option->default_function(func);
8024 option->capture_default_str();
8027 option_defaults_.copy_to(option.get());
8030 if(!defaulted && option->get_always_capture_default())
8031 option->capture_default_str();
8033 return option.get();
8036 for(
auto &opt : options_) {
8037 const auto &matchname = opt->matching_name(myopt);
8038 if(!matchname.empty()) {
8039 THROW(OptionAlreadyAdded(
"added option matched existing option name: " + matchname));
8043 THROW(OptionAlreadyAdded(
"added option matched existing option name"));
8046CLI11_INLINE Option *App::set_help_flag(std::string flag_name,
const std::string &help_description) {
8048 if(help_ptr_ !=
nullptr) {
8049 remove_option(help_ptr_);
8050 help_ptr_ =
nullptr;
8054 if(!flag_name.empty()) {
8055 help_ptr_ = add_flag(flag_name, help_description);
8056 help_ptr_->configurable(
false);
8062CLI11_INLINE Option *App::set_help_all_flag(std::string help_name,
const std::string &help_description) {
8064 if(help_all_ptr_ !=
nullptr) {
8065 remove_option(help_all_ptr_);
8066 help_all_ptr_ =
nullptr;
8070 if(!help_name.empty()) {
8071 help_all_ptr_ = add_flag(help_name, help_description);
8072 help_all_ptr_->configurable(
false);
8075 return help_all_ptr_;
8079App::set_version_flag(std::string flag_name,
const std::string &versionString,
const std::string &version_help) {
8081 if(version_ptr_ !=
nullptr) {
8082 remove_option(version_ptr_);
8083 version_ptr_ =
nullptr;
8087 if(!flag_name.empty()) {
8088 version_ptr_ = add_flag_callback(
8089 flag_name, [versionString]() {
THROW(CLI::CallForVersion(versionString, 0)); }, version_help);
8090 version_ptr_->configurable(
false);
8093 return version_ptr_;
8097App::set_version_flag(std::string flag_name, std::function<std::string()> vfunc,
const std::string &version_help) {
8098 if(version_ptr_ !=
nullptr) {
8099 remove_option(version_ptr_);
8100 version_ptr_ =
nullptr;
8104 if(!flag_name.empty()) {
8106 add_flag_callback(flag_name, [vfunc]() {
THROW(CLI::CallForVersion(vfunc(), 0)); }, version_help);
8107 version_ptr_->configurable(
false);
8110 return version_ptr_;
8113CLI11_INLINE Option *App::_add_flag_internal(std::string flag_name, CLI::callback_t fun, std::string flag_description) {
8114 Option *opt =
nullptr;
8115 if(detail::has_default_flag_values(flag_name)) {
8117 auto flag_defaults = detail::get_default_flag_values(flag_name);
8118 detail::remove_default_flag_values(flag_name);
8120 for(
const auto &fname : flag_defaults)
8121 opt->fnames_.push_back(fname.first);
8122 opt->default_flag_values_ =
std::move(flag_defaults);
8127 if(opt->get_positional()) {
8128 auto pos_name = opt->get_name(
true);
8130 THROW IncorrectConstruction::PositionalFlag(pos_name);
8132 opt->multi_option_policy(MultiOptionPolicy::TakeLast);
8134 opt->required(
false);
8138CLI11_INLINE Option *App::add_flag_callback(std::string flag_name,
8139 std::function<
void(
void)> function,
8140 std::string flag_description) {
8142 CLI::callback_t fun = [function](
const CLI::results_t &res) {
8143 using CLI::detail::lexical_cast;
8144 bool trigger{
false};
8145 auto result = lexical_cast(res[0], trigger);
8146 if(result && trigger) {
8155App::add_flag_function(std::string flag_name,
8157 std::string flag_description) {
8159 CLI::callback_t fun = [function](
const CLI::results_t &res) {
8160 using CLI::detail::lexical_cast;
8162 lexical_cast(res[0], flag_count);
8163 function(flag_count);
8167 ->multi_option_policy(MultiOptionPolicy::Sum);
8170CLI11_INLINE Option *App::set_config(std::string option_name,
8171 std::string default_filename,
8172 const std::string &help_message,
8173 bool config_required) {
8176 if(config_ptr_ !=
nullptr) {
8177 remove_option(config_ptr_);
8178 config_ptr_ =
nullptr;
8182 if(!option_name.empty()) {
8183 config_ptr_ = add_option(option_name, help_message);
8184 if(config_required) {
8185 config_ptr_->required();
8187 if(!default_filename.empty()) {
8188 config_ptr_->default_str(
std::move(default_filename));
8189 config_ptr_->force_callback_ =
true;
8191 config_ptr_->configurable(
false);
8193 config_ptr_->multi_option_policy(MultiOptionPolicy::Reverse);
8201 for(Option_p &op : options_) {
8202 op->remove_needs(opt);
8203 op->remove_excludes(opt);
8206 if(help_ptr_ == opt)
8207 help_ptr_ =
nullptr;
8208 if(help_all_ptr_ == opt)
8209 help_all_ptr_ =
nullptr;
8212 std::find_if(std::begin(options_), std::end(options_), [opt](
const Option_p &v) {
return v.get() == opt; });
8213 if(iterator != std::end(options_)) {
8214 options_.erase(iterator);
8220CLI11_INLINE App *App::add_subcommand(std::string subcommand_name, std::string subcommand_description) {
8221 if(!subcommand_name.empty() && !detail::valid_name_string(subcommand_name)) {
8222 if(!detail::valid_first_char(subcommand_name[0])) {
8223 THROW IncorrectConstruction(
8224 "Subcommand name starts with invalid character, '!' and '-' and control characters");
8226 for(
auto c : subcommand_name) {
8227 if(!detail::valid_later_char(c)) {
8228 THROW IncorrectConstruction(std::string(
"Subcommand name contains invalid character ('") + c +
8229 "'), all characters are allowed except"
8230 "'=',':','{','}', ' ', and control characters");
8235 return add_subcommand(
std::move(subcom));
8238CLI11_INLINE App *App::add_subcommand(CLI::App_p subcom) {
8240 THROW IncorrectConstruction(
"passed App is not valid");
8241 auto *ckapp = (name_.empty() && parent_ !=
nullptr) ? _get_fallthrough_parent() :
this;
8242 const auto &mstrg = _compare_subcommand_names(*subcom, *ckapp);
8243 if(!mstrg.empty()) {
8244 THROW(OptionAlreadyAdded(
"subcommand name or alias matches existing subcommand: " + mstrg));
8246 subcom->parent_ =
this;
8247 subcommands_.push_back(
std::move(subcom));
8248 return subcommands_.back().get();
8253 for(App_p &sub : subcommands_) {
8254 sub->remove_excludes(subcom);
8255 sub->remove_needs(subcom);
8259 std::begin(subcommands_), std::end(subcommands_), [subcom](
const App_p &v) {
return v.get() == subcom; });
8260 if(iterator != std::end(subcommands_)) {
8261 subcommands_.erase(iterator);
8267CLI11_INLINE App *App::get_subcommand(
const App *subcom)
const {
8268 if(subcom ==
nullptr)
8269 THROW OptionNotFound(
"nullptr passed");
8270 for(
const App_p &subcomptr : subcommands_)
8271 if(subcomptr.get() == subcom)
8272 return subcomptr.get();
8273 THROW OptionNotFound(subcom->get_name());
8277 auto *subc = _find_subcommand(subcom,
false,
false);
8279 THROW OptionNotFound(subcom);
8284 return _find_subcommand(subcom,
false,
false);
8289 auto uindex =
static_cast<unsigned>(index);
8290 if(uindex < subcommands_.size())
8291 return subcommands_[uindex].get();
8296CLI11_INLINE CLI::App_p App::get_subcommand_ptr(App *subcom)
const {
8297 if(subcom ==
nullptr)
8298 THROW OptionNotFound(
"nullptr passed");
8299 for(
const App_p &subcomptr : subcommands_)
8300 if(subcomptr.get() == subcom)
8302 THROW OptionNotFound(subcom->get_name());
8306 for(
const App_p &subcomptr : subcommands_)
8307 if(subcomptr->check_name(subcom))
8309 THROW OptionNotFound(subcom);
8314 auto uindex =
static_cast<unsigned>(index);
8315 if(uindex < subcommands_.size())
8316 return subcommands_[uindex];
8322 for(
const App_p &app : subcommands_) {
8323 if(app->name_.empty() && app->group_ == group_name) {
8327 THROW OptionNotFound(group_name);
8332 for(
const auto &opt : options_) {
8333 cnt += opt->count();
8335 for(
const auto &sub : subcommands_) {
8336 cnt += sub->count_all();
8338 if(!get_name().empty()) {
8347 pre_parse_called_ =
false;
8350 parsed_subcommands_.clear();
8351 for(
const Option_p &opt : options_) {
8354 for(
const App_p &subc : subcommands_) {
8359CLI11_INLINE void App::parse(
int argc,
const char *
const *argv) { parse_char_t(argc, argv); }
8360CLI11_INLINE void App::parse(
int argc,
const wchar_t *
const *argv) { parse_char_t(argc, argv); }
8365CLI11_INLINE const char *maybe_narrow(
const char *str) {
return str; }
8366CLI11_INLINE std::string maybe_narrow(
const wchar_t *str) {
return narrow(str); }
8370template <
class CharT>
CLI11_INLINE void App::parse_char_t(
int argc,
const CharT *
const *argv) {
8372 if(name_.empty() || has_automatic_name_) {
8373 has_automatic_name_ =
true;
8374 name_ = detail::maybe_narrow(argv[0]);
8377 std::vector<std::string> args;
8378 args.reserve(
static_cast<std::size_t>(argc) - 1U);
8379 for(
auto i =
static_cast<std::size_t>(argc) - 1U; i > 0U; --i)
8380 args.emplace_back(detail::maybe_narrow(argv[i]));
8385CLI11_INLINE void App::parse(std::string commandline,
bool program_name_included) {
8387 if(program_name_included) {
8388 auto nstr = detail::split_program_name(commandline);
8389 if((name_.empty()) || (has_automatic_name_)) {
8390 has_automatic_name_ =
true;
8395 detail::trim(commandline);
8398 if(!commandline.empty()) {
8399 commandline = detail::find_and_modify(commandline,
"=", detail::escape_detect);
8400 if(allow_windows_style_options_)
8401 commandline = detail::find_and_modify(commandline,
":", detail::escape_detect);
8404 auto args = detail::split_up(
std::move(commandline));
8406 args.erase(std::remove(args.begin(), args.end(), std::string{}), args.end());
8408 detail::remove_quotes(args);
8409 }
catch(
const std::invalid_argument &arg) {
8410#ifndef BB_NO_EXCEPTIONS
8411 THROW CLI::ParseError(arg.what(), CLI::ExitCodes::InvalidError);
8414 std::reverse(args.begin(), args.end());
8418CLI11_INLINE void App::parse(std::wstring commandline,
bool program_name_included) {
8419 parse(narrow(commandline), program_name_included);
8422CLI11_INLINE void App::parse(std::vector<std::string> &args) {
8441CLI11_INLINE void App::parse(std::vector<std::string> &&args) {
8460CLI11_INLINE void App::parse_from_stream(std::istream &input) {
8467 _parse_stream(input);
8471CLI11_INLINE int App::exit(
const Error &e, std::ostream &out, std::ostream &err)
const {
8474 if(e.get_name() ==
"RuntimeError")
8475 return e.get_exit_code();
8477 if(e.get_name() ==
"CallForHelp") {
8479 return e.get_exit_code();
8482 if(e.get_name() ==
"CallForAllHelp") {
8483 out << help(
"", AppFormatMode::All);
8484 return e.get_exit_code();
8487 if(e.get_name() ==
"CallForVersion") {
8488 out << e.what() <<
'\n';
8489 return e.get_exit_code();
8492 if(e.get_exit_code() !=
static_cast<int>(ExitCodes::Success)) {
8493 if(failure_message_)
8494 err << failure_message_(
this, e) <<
std::flush;
8497 return e.get_exit_code();
8503 std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](
const App_p &v) {
return v.get(); });
8508 [&filter](
const App *app) {
return !filter(app); }),
8509 std::end(subcomms));
8518 std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](
const App_p &v) {
return v.get(); });
8522 std::remove_if(std::begin(subcomms), std::end(subcomms), [&filter](App *app) {
return !filter(app); }),
8523 std::end(subcomms));
8530 auto iterator =
std::find(std::begin(exclude_options_), std::end(exclude_options_), opt);
8531 if(iterator == std::end(exclude_options_)) {
8534 exclude_options_.erase(iterator);
8539 auto iterator =
std::find(std::begin(exclude_subcommands_), std::end(exclude_subcommands_), app);
8540 if(iterator == std::end(exclude_subcommands_)) {
8543 auto *other_app = *iterator;
8544 exclude_subcommands_.erase(iterator);
8545 other_app->remove_excludes(
this);
8550 auto iterator =
std::find(std::begin(need_options_), std::end(need_options_), opt);
8551 if(iterator == std::end(need_options_)) {
8554 need_options_.erase(iterator);
8559 auto iterator =
std::find(std::begin(need_subcommands_), std::end(need_subcommands_), app);
8560 if(iterator == std::end(need_subcommands_)) {
8563 need_subcommands_.erase(iterator);
8571 prev +=
" " + get_name();
8574 auto selected_subcommands = get_subcommands();
8575 if(!selected_subcommands.empty()) {
8576 return selected_subcommands.back()->help(prev, mode);
8578 return formatter_->make_help(
this, prev, mode);
8583 if(version_ptr_ !=
nullptr) {
8585 results_t rv = version_ptr_->results();
8586 version_ptr_->clear();
8587 version_ptr_->add_result(
"true");
8589 version_ptr_->run_callback();
8590 }
catch(
const CLI::CallForVersion &cfv) {
8591#ifndef BB_NO_EXCEPTIONS
8595 version_ptr_->clear();
8596 version_ptr_->add_result(rv);
8604 std::begin(options_), std::end(options_), std::begin(options), [](
const Option_p &val) {
return val.get(); });
8609 [&filter](
const Option *opt) {
return !filter(opt); }),
8619 std::begin(options_), std::end(options_), std::begin(options), [](
const Option_p &val) {
return val.get(); });
8623 std::remove_if(std::begin(options), std::end(options), [&filter](Option *opt) {
return !filter(opt); }),
8631 for(Option_p &opt : options_) {
8632 if(opt->check_name(option_name)) {
8636 for(
auto &subc : subcommands_) {
8638 if(subc->get_name().empty()) {
8639 auto *opt = subc->get_option_no_THROW(option_name);
8640 if(opt !=
nullptr) {
8649 for(
const Option_p &opt : options_) {
8650 if(opt->check_name(option_name)) {
8654 for(
const auto &subc : subcommands_) {
8656 if(subc->get_name().empty()) {
8657 auto *opt = subc->get_option_no_THROW(option_name);
8658 if(opt !=
nullptr) {
8668 return std::string(
"[Option Group: ") + get_group() +
"]";
8670 if(aliases_.empty() || !with_aliases) {
8673 std::string dispname = name_;
8674 for(
const auto &lalias : aliases_) {
8675 dispname.push_back(
',');
8676 dispname.push_back(
' ');
8677 dispname.append(lalias);
8683 std::string local_name = name_;
8684 if(ignore_underscore_) {
8685 local_name = detail::remove_underscore(name_);
8686 name_to_check = detail::remove_underscore(name_to_check);
8689 local_name = detail::to_lower(name_);
8690 name_to_check = detail::to_lower(name_to_check);
8693 if(local_name == name_to_check) {
8696 for(std::string les : aliases_) {
8697 if(ignore_underscore_) {
8698 les = detail::remove_underscore(les);
8701 les = detail::to_lower(les);
8703 if(les == name_to_check) {
8711 std::vector<std::string> groups;
8713 for(
const Option_p &opt : options_) {
8715 if(
std::find(groups.begin(), groups.end(), opt->get_group()) == groups.end()) {
8716 groups.push_back(opt->get_group());
8724 std::vector<std::string> miss_list;
8730 if(!allow_extras_) {
8731 for(
const auto &sub : subcommands_) {
8732 if(sub->name_.empty() && !sub->missing_.empty()) {
8741 for(
const App *sub : parsed_subcommands_) {
8742 std::vector<std::string> output = sub->remaining(recurse);
8750 std::vector<std::string> miss_list = remaining(recurse);
8751 std::reverse(std::begin(miss_list), std::end(miss_list));
8758 return val.first != detail::Classifier::POSITIONAL_MARK;
8762 for(
const App_p &sub : subcommands_) {
8763 remaining_options += sub->remaining_size(recurse);
8766 return remaining_options;
8771 auto pcount =
std::count_if(std::begin(options_), std::end(options_), [](
const Option_p &opt) {
8772 return opt->get_items_expected_max() >= detail::expected_max_vector_size && !opt->nonpositional();
8775 auto pcount_req =
std::count_if(std::begin(options_), std::end(options_), [](
const Option_p &opt) {
8776 return opt->get_items_expected_max() >= detail::expected_max_vector_size && !opt->nonpositional() &&
8777 opt->get_required();
8779 if(pcount - pcount_req > 1) {
8780 THROW InvalidError(name_);
8785 for(
const App_p &app : subcommands_) {
8787 if(app->get_name().empty())
8791 if(require_option_min_ > 0) {
8792 if(require_option_max_ > 0) {
8793 if(require_option_max_ < require_option_min_) {
8794 THROW(InvalidError(
"Required min options greater than required max options", ExitCodes::InvalidError));
8797 if(require_option_min_ > (options_.size() + nameless_subs)) {
8799 InvalidError(
"Required min options greater than number of available options", ExitCodes::InvalidError));
8805 if(default_startup == startup_mode::enabled) {
8807 }
else if(default_startup == startup_mode::disabled) {
8810 for(
const App_p &app : subcommands_) {
8811 if(app->has_automatic_name_) {
8814 if(app->name_.empty()) {
8815 app->fallthrough_ =
false;
8816 app->prefix_command_ =
false;
8819 app->parent_ =
this;
8824CLI11_INLINE void App::run_callback(
bool final_mode,
bool suppress_final_callback) {
8827 if(!final_mode && parse_complete_callback_) {
8828 parse_complete_callback_();
8831 for(App *subc : get_subcommands()) {
8832 if(subc->parent_ ==
this) {
8833 subc->run_callback(
true, suppress_final_callback);
8837 for(
auto &subc : subcommands_) {
8838 if(subc->name_.empty() && subc->count_all() > 0) {
8839 subc->run_callback(
true, suppress_final_callback);
8844 if(final_callback_ && (parsed_ > 0) && (!suppress_final_callback)) {
8845 if(!name_.empty() || count_all() > 0 || parent_ ==
nullptr) {
8853 if(require_subcommand_max_ != 0 && parsed_subcommands_.size() >= require_subcommand_max_) {
8854 return parent_ !=
nullptr && parent_->_valid_subcommand(current, ignore_used);
8856 auto *com = _find_subcommand(current,
true, ignore_used);
8857 if(com !=
nullptr) {
8861 return parent_ !=
nullptr && parent_->_valid_subcommand(current, ignore_used);
8865 bool ignore_used_subcommands)
const {
8866 std::string dummy1, dummy2;
8869 return detail::Classifier::POSITIONAL_MARK;
8870 if(_valid_subcommand(current, ignore_used_subcommands))
8871 return detail::Classifier::SUBCOMMAND;
8872 if(detail::split_long(current, dummy1, dummy2))
8873 return detail::Classifier::LONG;
8874 if(detail::split_short(current, dummy1, dummy2)) {
8875 if(dummy1[0] >=
'0' && dummy1[0] <=
'9') {
8876 if(get_option_no_THROW(std::string{
'-', dummy1[0]}) ==
nullptr) {
8877 return detail::Classifier::NONE;
8880 return detail::Classifier::SHORT;
8882 if((allow_windows_style_options_) && (detail::split_windows_style(current, dummy1, dummy2)))
8883 return detail::Classifier::WINDOWS_STYLE;
8884 if((current ==
"++") && !name_.empty() && parent_ !=
nullptr)
8885 return detail::Classifier::SUBCOMMAND_TERMINATOR;
8886 auto dotloc = current.find_first_of(
'.');
8887 if(dotloc != std::string::npos) {
8888 auto *cm = _find_subcommand(current.substr(0, dotloc),
true, ignore_used_subcommands);
8890 auto res = cm->_recognize(current.substr(dotloc + 1), ignore_used_subcommands);
8891 if(res == detail::Classifier::SUBCOMMAND) {
8896 return detail::Classifier::NONE;
8899CLI11_INLINE bool App::_process_config_file(
const std::string &config_file,
bool throw_error) {
8900 auto path_result = detail::check_path(config_file.c_str());
8901 if(path_result == detail::path_type::file) {
8904 _parse_config(values);
8906 }
catch(
const FileError &) {
8912 }
else if(throw_error) {
8913 THROW FileError::Missing(config_file);
8920 if(config_ptr_ !=
nullptr) {
8921 bool config_required = config_ptr_->get_required();
8922 auto file_given = config_ptr_->count() > 0;
8923 if(!(file_given || config_ptr_->envname_.empty())) {
8924 std::string ename_string = detail::get_environment_value(config_ptr_->envname_);
8925 if(!ename_string.empty()) {
8926 config_ptr_->add_result(ename_string);
8929 config_ptr_->run_callback();
8931 auto config_files = config_ptr_->as<std::vector<std::string>>();
8932 bool files_used{file_given};
8933 if(config_files.empty() || config_files.front().empty()) {
8934 if(config_required) {
8935 THROW FileError(
"config file is required but none was given");
8939 for(
const auto &config_file : config_files) {
8940 if(_process_config_file(config_file, config_required || file_given)) {
8946 config_ptr_->clear();
8947 bool force = config_ptr_->force_callback_;
8948 config_ptr_->force_callback_ =
false;
8949 config_ptr_->run_callback();
8950 config_ptr_->force_callback_ = force;
8956 for(
const Option_p &opt : options_) {
8957 if(opt->count() == 0 && !opt->envname_.empty()) {
8958 std::string ename_string = detail::get_environment_value(opt->envname_);
8959 if(!ename_string.empty()) {
8960 std::string result = ename_string;
8961 result = opt->_validate(result, 0);
8962 if(result.empty()) {
8963 opt->add_result(ename_string);
8969 for(App_p &sub : subcommands_) {
8970 if(sub->get_name().empty() || (sub->count_all() > 0 && !sub->parse_complete_callback_)) {
8972 sub->_process_env();
8979 for(App_p &sub : subcommands_) {
8981 if(sub->get_name().empty() && sub->parse_complete_callback_) {
8982 if(sub->count_all() > 0) {
8983 sub->_process_callbacks();
8984 sub->run_callback();
8989 for(
const Option_p &opt : options_) {
8990 if((*opt) && !opt->get_callback_run()) {
8991 opt->run_callback();
8994 for(App_p &sub : subcommands_) {
8995 if(!sub->parse_complete_callback_) {
8996 sub->_process_callbacks();
9001CLI11_INLINE void App::_process_help_flags(
bool trigger_help,
bool trigger_all_help)
const {
9002 const Option *help_ptr = get_help_ptr();
9003 const Option *help_all_ptr = get_help_all_ptr();
9005 if(help_ptr !=
nullptr && help_ptr->count() > 0)
9006 trigger_help =
true;
9007 if(help_all_ptr !=
nullptr && help_all_ptr->count() > 0)
9008 trigger_all_help =
true;
9011 if(!parsed_subcommands_.empty()) {
9012 for(
const App *sub : parsed_subcommands_)
9013 sub->_process_help_flags(trigger_help, trigger_all_help);
9016 }
else if(trigger_all_help) {
9017 THROW CallForAllHelp();
9018 }
else if(trigger_help) {
9019 THROW CallForHelp();
9025 bool excluded{
false};
9026 std::string excluder;
9027 for(
const auto &opt : exclude_options_) {
9028 if(opt->count() > 0) {
9030 excluder = opt->get_name();
9033 for(
const auto &subc : exclude_subcommands_) {
9034 if(subc->count_all() > 0) {
9036 excluder = subc->get_display_name();
9040 if(count_all() > 0) {
9041 THROW ExcludesError(get_display_name(), excluder);
9048 bool missing_needed{
false};
9049 std::string missing_need;
9050 for(
const auto &opt : need_options_) {
9051 if(opt->count() == 0) {
9052 missing_needed =
true;
9053 missing_need = opt->get_name();
9056 for(
const auto &subc : need_subcommands_) {
9057 if(subc->count_all() == 0) {
9058 missing_needed =
true;
9059 missing_need = subc->get_display_name();
9062 if(missing_needed) {
9063 if(count_all() > 0) {
9064 THROW RequiresError(get_display_name(), missing_need);
9071 for(
const Option_p &opt : options_) {
9073 if(opt->count() != 0) {
9077 if(opt->get_required() && opt->count() == 0) {
9078 THROW RequiredError(opt->get_name());
9081 for(
const Option *opt_req : opt->needs_)
9082 if(opt->count() > 0 && opt_req->count() == 0)
9083 THROW RequiresError(opt->get_name(), opt_req->get_name());
9085 for(
const Option *opt_ex : opt->excludes_)
9086 if(opt->count() > 0 && opt_ex->count() != 0)
9087 THROW ExcludesError(opt->get_name(), opt_ex->get_name());
9090 if(require_subcommand_min_ > 0) {
9091 auto selected_subcommands = get_subcommands();
9092 if(require_subcommand_min_ > selected_subcommands.size())
9093 THROW RequiredError::Subcommand(require_subcommand_min_);
9100 for(App_p &sub : subcommands_) {
9103 if(sub->name_.empty() && sub->count_all() > 0) {
9108 if(require_option_min_ > used_options || (require_option_max_ > 0 && require_option_max_ < used_options)) {
9109 auto option_list = detail::join(options_, [
this](
const Option_p &ptr) {
9110 if(ptr.get() == help_ptr_ || ptr.get() == help_all_ptr_) {
9111 return std::string{};
9113 return ptr->get_name(
false,
true);
9116 auto subc_list = get_subcommands([](App *app) {
return ((app->get_name().empty()) && (!app->disabled_)); });
9117 if(!subc_list.empty()) {
9118 option_list +=
"," + detail::join(subc_list, [](
const App *app) {
return app->get_display_name(); });
9120 THROW RequiredError::Option(require_option_min_, require_option_max_, used_options, option_list);
9124 for(App_p &sub : subcommands_) {
9127 if(sub->name_.empty() && sub->required_ ==
false) {
9128 if(sub->count_all() == 0) {
9129 if(require_option_min_ > 0 && require_option_min_ <= used_options) {
9134 if(require_option_max_ > 0 && used_options >= require_option_min_) {
9141 if(sub->count() > 0 || sub->name_.empty()) {
9142 sub->_process_requirements();
9145 if(sub->required_ && sub->count_all() == 0) {
9146 THROW(CLI::RequiredError(sub->get_display_name()));
9155 _process_config_file();
9159 }
catch(
const CLI::FileError &) {
9162 _process_callbacks();
9163 _process_help_flags();
9167 _process_callbacks();
9168 _process_help_flags();
9170 _process_requirements();
9174 if(!(allow_extras_ || prefix_command_)) {
9176 if(num_left_over > 0) {
9177 THROW ExtrasError(name_, remaining(
false));
9181 for(App_p &sub : subcommands_) {
9182 if(sub->count() > 0)
9183 sub->_process_extras();
9187CLI11_INLINE void App::_process_extras(std::vector<std::string> &args) {
9188 if(!(allow_extras_ || prefix_command_)) {
9190 if(num_left_over > 0) {
9191 args = remaining(
false);
9192 THROW ExtrasError(name_, args);
9196 for(App_p &sub : subcommands_) {
9197 if(sub->count() > 0)
9198 sub->_process_extras(args);
9204 for(App_p &sub : subcommands_) {
9205 if(sub->get_name().empty())
9206 sub->increment_parsed();
9210CLI11_INLINE void App::_parse(std::vector<std::string> &args) {
9212 _trigger_pre_parse(args.size());
9213 bool positional_only =
false;
9215 while(!args.empty()) {
9216 if(!_parse_single(args, positional_only)) {
9221 if(parent_ ==
nullptr) {
9225 _process_extras(args);
9228 args = remaining_for_passthrough(
false);
9229 }
else if(parse_complete_callback_) {
9231 _process_callbacks();
9232 _process_help_flags();
9233 _process_requirements();
9234 run_callback(
false,
true);
9238CLI11_INLINE void App::_parse(std::vector<std::string> &&args) {
9242 _trigger_pre_parse(args.size());
9243 bool positional_only =
false;
9245 while(!args.empty()) {
9246 _parse_single(args, positional_only);
9254CLI11_INLINE void App::_parse_stream(std::istream &input) {
9255 auto values = config_formatter_->from_config(input);
9256 _parse_config(values);
9258 _trigger_pre_parse(values.size());
9266 for(
const ConfigItem &item : args) {
9267 if(!_parse_single_config(item) && allow_config_extras_ == config_extras_mode::error)
9268 THROW ConfigError::Extras(item.fullname());
9274 if(level < item.parents.size()) {
9275 auto *subcom = get_subcommand_no_THROW(item.parents.at(level));
9276 return (subcom !=
nullptr) ? subcom->_parse_single_config(item, level + 1) :
false;
9279 if(item.name ==
"++") {
9282 _trigger_pre_parse(2);
9283 if(parent_ !=
nullptr) {
9284 parent_->parsed_subcommands_.push_back(
this);
9290 if(item.name ==
"--") {
9291 if(configurable_ && parse_complete_callback_) {
9292 _process_callbacks();
9293 _process_requirements();
9298 Option *op = get_option_no_THROW(
"--" + item.name);
9300 if(item.name.size() == 1) {
9301 op = get_option_no_THROW(
"-" + item.name);
9304 op = get_option_no_THROW(item.name);
9310 if(get_allow_config_extras() == config_extras_mode::capture) {
9312 missing_.emplace_back(detail::Classifier::NONE, item.fullname());
9313 for(
const auto &input : item.inputs) {
9314 missing_.emplace_back(detail::Classifier::NONE, input);
9320 if(!op->get_configurable()) {
9321 if(get_allow_config_extras() == config_extras_mode::ignore_all) {
9324 THROW ConfigError::NotConfigurable(item.fullname());
9329 if(op->get_expected_min() == 0) {
9330 if(item.inputs.size() <= 1) {
9332 auto res = config_formatter_->to_flag(item);
9333 bool converted{
false};
9334 if(op->get_disable_flag_override()) {
9335 auto val = detail::to_flag_value(res);
9337 res = op->get_flag_value(item.name,
"{}");
9344 res = op->get_flag_value(item.name, res);
9347 op->add_result(res);
9350 if(
static_cast<int>(item.inputs.size()) > op->get_items_expected_max() &&
9351 op->get_multi_option_policy() != MultiOptionPolicy::TakeAll) {
9352 if(op->get_items_expected_max() > 1) {
9353 THROW ArgumentMismatch::AtMost(item.fullname(), op->get_items_expected_max(), item.inputs.size());
9356 if(!op->get_disable_flag_override()) {
9357 THROW ConversionError::TooManyInputsFlag(item.fullname());
9361 for(
const auto &res : item.inputs) {
9362 bool valid_value{
false};
9363 if(op->default_flag_values_.empty()) {
9364 if(res ==
"true" || res ==
"false" || res ==
"1" || res ==
"0") {
9368 for(
const auto &valid_res : op->default_flag_values_) {
9369 if(valid_res.second == res) {
9377 op->add_result(res);
9379 THROW InvalidError(
"invalid flag argument given");
9385 op->add_result(item.inputs);
9392CLI11_INLINE bool App::_parse_single(std::vector<std::string> &args,
bool &positional_only) {
9394 detail::Classifier classifier = positional_only ? detail::Classifier::NONE : _recognize(args.back());
9395 switch(classifier) {
9396 case detail::Classifier::POSITIONAL_MARK:
9398 positional_only =
true;
9399 if((!_has_remaining_positionals()) && (parent_ !=
nullptr)) {
9402 _move_to_missing(classifier,
"--");
9405 case detail::Classifier::SUBCOMMAND_TERMINATOR:
9410 case detail::Classifier::SUBCOMMAND:
9411 retval = _parse_subcommand(args);
9413 case detail::Classifier::LONG:
9414 case detail::Classifier::SHORT:
9415 case detail::Classifier::WINDOWS_STYLE:
9417 retval = _parse_arg(args, classifier,
false);
9419 case detail::Classifier::NONE:
9421 retval = _parse_positional(args,
false);
9422 if(retval && positionals_at_end_) {
9423 positional_only =
true;
9428 THROW HorribleError(
"unrecognized classifier (you should not see this!)");
9436 for(
const Option_p &opt : options_) {
9437 if(opt->get_positional() && (!required_only || opt->get_required())) {
9438 if(opt->get_items_expected_min() > 0 &&
static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
9439 retval +=
static_cast<std::size_t>(opt->get_items_expected_min()) - opt->count();
9447 for(
const Option_p &opt : options_) {
9448 if(opt->get_positional() && ((
static_cast<int>(opt->count()) < opt->get_items_expected_min()))) {
9456CLI11_INLINE bool App::_parse_positional(std::vector<std::string> &args,
bool haltOnSubcommand) {
9458 const std::string &positional = args.back();
9459 Option *posOpt{
nullptr};
9461 if(positionals_at_end_) {
9463 auto arg_rem = args.size();
9464 auto remreq = _count_remaining_positionals(
true);
9465 if(arg_rem <= remreq) {
9466 for(
const Option_p &opt : options_) {
9467 if(opt->get_positional() && opt->required_) {
9468 if(
static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
9469 if(validate_positionals_) {
9470 std::string pos = positional;
9471 pos = opt->_validate(pos, 0);
9483 if(posOpt ==
nullptr) {
9484 for(
const Option_p &opt : options_) {
9486 if(opt->get_positional() &&
9487 (
static_cast<int>(opt->count()) < opt->get_items_expected_min() || opt->get_allow_extra_args())) {
9488 if(validate_positionals_) {
9489 std::string pos = positional;
9490 pos = opt->_validate(pos, 0);
9500 if(posOpt !=
nullptr) {
9501 parse_order_.push_back(posOpt);
9502 if(posOpt->get_inject_separator()) {
9503 if(!posOpt->results().empty() && !posOpt->results().back().empty()) {
9504 posOpt->add_result(std::string{});
9507 if(posOpt->get_trigger_on_parse() && posOpt->current_option_state_ == Option::option_state::callback_run) {
9510 posOpt->add_result(positional);
9511 if(posOpt->get_trigger_on_parse()) {
9512 posOpt->run_callback();
9519 for(
auto &subc : subcommands_) {
9520 if((subc->name_.empty()) && (!subc->disabled_)) {
9521 if(subc->_parse_positional(args,
false)) {
9522 if(!subc->pre_parse_called_) {
9523 subc->_trigger_pre_parse(args.size());
9530 if(parent_ !=
nullptr && fallthrough_)
9531 return _get_fallthrough_parent()->_parse_positional(args,
static_cast<bool>(parse_complete_callback_));
9534 auto *com = _find_subcommand(args.back(),
true,
false);
9535 if(com !=
nullptr && (require_subcommand_max_ == 0 || require_subcommand_max_ > parsed_subcommands_.size())) {
9536 if(haltOnSubcommand) {
9545 auto *parent_app = (parent_ !=
nullptr) ? _get_fallthrough_parent() :
this;
9546 com = parent_app->_find_subcommand(args.back(),
true,
false);
9547 if(com !=
nullptr && (com->parent_->require_subcommand_max_ == 0 ||
9548 com->parent_->require_subcommand_max_ > com->parent_->parsed_subcommands_.size())) {
9552 if(positionals_at_end_) {
9553 THROW CLI::ExtrasError(name_, args);
9556 if(parent_ !=
nullptr && name_.empty()) {
9560 _move_to_missing(detail::Classifier::NONE, positional);
9562 if(prefix_command_) {
9563 while(!args.empty()) {
9564 _move_to_missing(detail::Classifier::NONE, args.back());
9573App::_find_subcommand(
const std::string &subc_name,
bool ignore_disabled,
bool ignore_used)
const noexcept {
9574 for(
const App_p &com : subcommands_) {
9575 if(com->disabled_ && ignore_disabled)
9577 if(com->get_name().empty()) {
9578 auto *subc = com->_find_subcommand(subc_name, ignore_disabled, ignore_used);
9579 if(subc !=
nullptr) {
9583 if(com->check_name(subc_name)) {
9584 if((!*com) || !ignore_used)
9591CLI11_INLINE bool App::_parse_subcommand(std::vector<std::string> &args) {
9592 if(_count_remaining_positionals(
true) > 0) {
9593 _parse_positional(args,
false);
9596 auto *com = _find_subcommand(args.back(),
true,
true);
9597 if(com ==
nullptr) {
9599 auto dotloc = args.back().find_first_of(
'.');
9600 if(dotloc != std::string::npos) {
9601 com = _find_subcommand(args.back().substr(0, dotloc),
true,
true);
9602 if(com !=
nullptr) {
9603 args.back() = args.back().substr(dotloc + 1);
9604 args.push_back(com->get_display_name());
9608 if(com !=
nullptr) {
9611 parsed_subcommands_.push_back(com);
9614 auto *parent_app = com->parent_;
9615 while(parent_app !=
this) {
9616 parent_app->_trigger_pre_parse(args.size());
9618 parent_app->parsed_subcommands_.push_back(com);
9620 parent_app = parent_app->parent_;
9625 if(parent_ ==
nullptr)
9626 THROW HorribleError(
"Subcommand " + args.back() +
" missing");
9631App::_parse_arg(std::vector<std::string> &args, detail::Classifier current_type,
bool local_processing_only) {
9633 std::string current = args.back();
9635 std::string arg_name;
9639 switch(current_type) {
9640 case detail::Classifier::LONG:
9641 if(!detail::split_long(current, arg_name,
value))
9642 THROW HorribleError(
"Long parsed but missing (you should not see this):" + args.back());
9644 case detail::Classifier::SHORT:
9645 if(!detail::split_short(current, arg_name, rest))
9646 THROW HorribleError(
"Short parsed but missing! You should not see this");
9648 case detail::Classifier::WINDOWS_STYLE:
9649 if(!detail::split_windows_style(current, arg_name,
value))
9650 THROW HorribleError(
"windows option parsed but missing! You should not see this");
9652 case detail::Classifier::SUBCOMMAND:
9653 case detail::Classifier::SUBCOMMAND_TERMINATOR:
9654 case detail::Classifier::POSITIONAL_MARK:
9655 case detail::Classifier::NONE:
9657 THROW HorribleError(
"parsing got called with invalid option! You should not see this");
9660 auto op_ptr =
std::find_if(std::begin(options_), std::end(options_), [arg_name, current_type](
const Option_p &opt) {
9661 if(current_type == detail::Classifier::LONG)
9662 return opt->check_lname(arg_name);
9663 if(current_type == detail::Classifier::SHORT)
9664 return opt->check_sname(arg_name);
9666 return opt->check_lname(arg_name) || opt->check_sname(arg_name);
9670 if(op_ptr == std::end(options_)) {
9671 for(
auto &subc : subcommands_) {
9672 if(subc->name_.empty() && !subc->disabled_) {
9673 if(subc->_parse_arg(args, current_type, local_processing_only)) {
9674 if(!subc->pre_parse_called_) {
9675 subc->_trigger_pre_parse(args.size());
9683 if(parent_ !=
nullptr && name_.empty()) {
9688 auto dotloc = arg_name.find_first_of(
'.', 1);
9689 if(dotloc != std::string::npos) {
9691 auto *sub = _find_subcommand(arg_name.substr(0, dotloc),
true,
false);
9692 if(sub !=
nullptr) {
9693 auto v = args.back();
9695 arg_name = arg_name.substr(dotloc + 1);
9696 if(arg_name.size() > 1) {
9697 args.push_back(std::string(
"--") + v.substr(dotloc + 3));
9698 current_type = detail::Classifier::LONG;
9700 auto nval = v.substr(dotloc + 2);
9702 if(nval.size() > 2) {
9704 args.push_back(nval.substr(3));
9707 args.push_back(nval);
9708 current_type = detail::Classifier::SHORT;
9710 auto val = sub->_parse_arg(args, current_type,
true);
9713 parsed_subcommands_.push_back(sub);
9717 _trigger_pre_parse(args.size());
9719 if(sub->parse_complete_callback_) {
9720 sub->_process_env();
9721 sub->_process_callbacks();
9722 sub->_process_help_flags();
9723 sub->_process_requirements();
9724 sub->run_callback(
false,
true);
9732 if(local_processing_only) {
9736 if(parent_ !=
nullptr && fallthrough_)
9737 return _get_fallthrough_parent()->_parse_arg(args, current_type,
false);
9741 _move_to_missing(current_type, current);
9748 Option_p &op = *op_ptr;
9750 if(op->get_inject_separator()) {
9751 if(!op->results().empty() && !op->results().back().empty()) {
9752 op->add_result(std::string{});
9755 if(op->get_trigger_on_parse() && op->current_option_state_ == Option::option_state::callback_run) {
9758 int min_num = (std::min)(op->get_type_size_min(), op->get_items_expected_min());
9759 int max_num = op->get_items_expected_max();
9762 if(max_num >= detail::expected_max_vector_size / 16 && !op->get_allow_extra_args()) {
9763 auto tmax = op->get_type_size_max();
9764 max_num = detail::checked_multiply(tmax, op->get_expected_min()) ? tmax : detail::expected_max_vector_size;
9768 int result_count = 0;
9771 auto res = op->get_flag_value(arg_name,
value);
9772 op->add_result(res);
9773 parse_order_.push_back(op.get());
9774 }
else if(!
value.empty()) {
9775 op->add_result(
value, result_count);
9776 parse_order_.push_back(op.get());
9777 collected += result_count;
9779 }
else if(!rest.empty()) {
9780 op->add_result(rest, result_count);
9781 parse_order_.push_back(op.get());
9783 collected += result_count;
9787 while(min_num > collected && !args.empty()) {
9788 std::string current_ = args.back();
9790 op->add_result(current_, result_count);
9791 parse_order_.push_back(op.get());
9792 collected += result_count;
9795 if(min_num > collected) {
9796 THROW ArgumentMismatch::TypedAtLeast(op->get_name(), min_num, op->get_type_name());
9800 if(max_num > collected || op->get_allow_extra_args()) {
9801 auto remreqpos = _count_remaining_positionals(
true);
9803 while((collected < max_num || op->get_allow_extra_args()) && !args.empty() &&
9804 _recognize(args.back(),
false) == detail::Classifier::NONE) {
9806 if(remreqpos >= args.size()) {
9809 if(validate_optional_arguments_) {
9810 std::string arg = args.back();
9811 arg = op->_validate(arg, 0);
9816 op->add_result(args.back(), result_count);
9817 parse_order_.push_back(op.get());
9819 collected += result_count;
9823 if(!args.empty() && _recognize(args.back()) == detail::Classifier::POSITIONAL_MARK)
9826 if(min_num == 0 && max_num > 0 && collected == 0) {
9827 auto res = op->get_flag_value(arg_name, std::string{});
9828 op->add_result(res);
9829 parse_order_.push_back(op.get());
9833 if(min_num > 0 && (collected % op->get_type_size_max()) != 0) {
9834 if(op->get_type_size_max() != op->get_type_size_min()) {
9835 op->add_result(std::string{});
9837 THROW ArgumentMismatch::PartialType(op->get_name(), op->get_type_size_min(), op->get_type_name());
9840 if(op->get_trigger_on_parse()) {
9845 args.push_back(rest);
9851 if(!pre_parse_called_) {
9852 pre_parse_called_ =
true;
9853 if(pre_parse_callback_) {
9854 pre_parse_callback_(remaining_args);
9856 }
else if(immediate_callback_) {
9857 if(!name_.empty()) {
9858 auto pcnt = parsed_;
9862 pre_parse_called_ =
true;
9869 if(parent_ ==
nullptr) {
9870 THROW(HorribleError(
"No Valid parent"));
9872 auto *fallthrough_parent = parent_;
9873 while((fallthrough_parent->parent_ !=
nullptr) && (fallthrough_parent->get_name().empty())) {
9874 fallthrough_parent = fallthrough_parent->parent_;
9876 return fallthrough_parent;
9880 const App &base)
const {
9881 static const std::string estring;
9882 if(subcom.disabled_) {
9885 for(
const auto &subc : base.subcommands_) {
9886 if(subc.get() != &subcom) {
9887 if(subc->disabled_) {
9890 if(!subcom.get_name().empty()) {
9891 if(subc->check_name(subcom.get_name())) {
9892 return subcom.get_name();
9895 if(!subc->get_name().empty()) {
9896 if(subcom.check_name(subc->get_name())) {
9897 return subc->get_name();
9900 for(
const auto &les : subcom.aliases_) {
9901 if(subc->check_name(les)) {
9906 for(
const auto &les : subc->aliases_) {
9907 if(subcom.check_name(les)) {
9912 if(subc->get_name().empty()) {
9913 const auto &cmpres = _compare_subcommand_names(subcom, *subc);
9914 if(!cmpres.empty()) {
9919 if(subcom.get_name().empty()) {
9920 const auto &cmpres = _compare_subcommand_names(*subc, subcom);
9921 if(!cmpres.empty()) {
9930CLI11_INLINE void App::_move_to_missing(detail::Classifier val_type,
const std::string &val) {
9931 if(allow_extras_ || subcommands_.empty()) {
9932 missing_.emplace_back(val_type, val);
9936 for(
auto &subc : subcommands_) {
9937 if(subc->name_.empty() && subc->allow_extras_) {
9938 subc->missing_.emplace_back(val_type, val);
9943 missing_.emplace_back(val_type, val);
9946CLI11_INLINE void App::_move_option(Option *opt, App *app) {
9947 if(opt ==
nullptr) {
9948 THROW OptionNotFound(
"the option is NULL");
9952 for(
auto &subc : subcommands_) {
9953 if(app == subc.get()) {
9958 THROW OptionNotFound(
"The Given app is not a subcommand");
9961 if((help_ptr_ == opt) || (help_all_ptr_ == opt))
9962 THROW OptionAlreadyAdded(
"cannot move help options");
9964 if(config_ptr_ == opt)
9965 THROW OptionAlreadyAdded(
"cannot move config file options");
9968 std::find_if(std::begin(options_), std::end(options_), [opt](
const Option_p &v) {
return v.get() == opt; });
9969 if(iterator != std::end(options_)) {
9970 const auto &opt_p = *iterator;
9971 if(
std::find_if(std::begin(app->options_), std::end(app->options_), [&opt_p](
const Option_p &v) {
9972 return (*v == *opt_p);
9973 }) == std::end(app->options_)) {
9975 app->options_.push_back(
std::move(*iterator));
9976 options_.erase(iterator);
9978 THROW OptionAlreadyAdded(
"option was not located: " + opt->get_name());
9981 THROW OptionNotFound(
"could not locate the given Option");
9985CLI11_INLINE void TriggerOn(App *trigger_app, App *app_to_enable) {
9986 app_to_enable->enabled_by_default(
false);
9987 app_to_enable->disabled_by_default();
9988 trigger_app->preparse_callback([app_to_enable](
std::size_t) { app_to_enable->disabled(
false); });
9992 for(
auto &app : apps_to_enable) {
9993 app->enabled_by_default(
false);
9994 app->disabled_by_default();
9997 trigger_app->preparse_callback([apps_to_enable](
std::size_t) {
9998 for(
const auto &app : apps_to_enable) {
9999 app->disabled(
false);
10004CLI11_INLINE void TriggerOff(App *trigger_app, App *app_to_enable) {
10005 app_to_enable->disabled_by_default(
false);
10006 app_to_enable->enabled_by_default();
10007 trigger_app->preparse_callback([app_to_enable](
std::size_t) { app_to_enable->disabled(); });
10011 for(
auto &app : apps_to_enable) {
10012 app->disabled_by_default(
false);
10013 app->enabled_by_default();
10016 trigger_app->preparse_callback([apps_to_enable](
std::size_t) {
10017 for(
const auto &app : apps_to_enable) {
10023CLI11_INLINE void deprecate_option(Option *opt,
const std::string &replacement) {
10024 Validator deprecate_warning{[opt, replacement](std::string &) {
10025 std::cout << opt->get_name() <<
" is deprecated please use '" << replacement
10027 return std::string();
10030 deprecate_warning.application_index(0);
10031 opt->check(deprecate_warning);
10032 if(!replacement.empty()) {
10033 opt->description(opt->get_description() +
" DEPRECATED: please use '" + replacement +
"' instead");
10037CLI11_INLINE void retire_option(App *app, Option *opt) {
10039 auto *option_copy = temp.add_option(opt->get_name(
false,
true))
10040 ->type_size(opt->get_type_size_min(), opt->get_type_size_max())
10041 ->expected(opt->get_expected_min(), opt->get_expected_max())
10042 ->allow_extra_args(opt->get_allow_extra_args());
10044 app->remove_option(opt);
10045 auto *opt2 = app->add_option(option_copy->get_name(
false,
true),
"option has been retired and has no effect");
10046 opt2->type_name(
"RETIRED")
10047 ->default_str(
"RETIRED")
10048 ->type_size(option_copy->get_type_size_min(), option_copy->get_type_size_max())
10049 ->expected(option_copy->get_expected_min(), option_copy->get_expected_max())
10050 ->allow_extra_args(option_copy->get_allow_extra_args());
10052 Validator retired_warning{[opt2](std::string &) {
10053 std::cout <<
"WARNING " << opt2->get_name() <<
" is retired and has no effect\n";
10054 return std::string();
10057 retired_warning.application_index(0);
10058 opt2->check(retired_warning);
10061CLI11_INLINE void retire_option(App &app, Option *opt) { retire_option(&app, opt); }
10063CLI11_INLINE void retire_option(App *app,
const std::string &option_name) {
10065 auto *opt = app->get_option_no_THROW(option_name);
10066 if(opt !=
nullptr) {
10067 retire_option(app, opt);
10070 auto *opt2 = app->add_option(option_name,
"option has been retired and has no effect")
10071 ->type_name(
"RETIRED")
10073 ->default_str(
"RETIRED");
10074 Validator retired_warning{[opt2](std::string &) {
10075 std::cout <<
"WARNING " << opt2->get_name() <<
" is retired and has no effect\n";
10076 return std::string();
10079 retired_warning.application_index(0);
10080 opt2->check(retired_warning);
10083CLI11_INLINE void retire_option(App &app,
const std::string &option_name) { retire_option(&app, option_name); }
10085namespace FailureMessage {
10087CLI11_INLINE std::string simple(
const App *app,
const Error &e) {
10088 std::string header = std::string(e.what()) +
"\n";
10089 std::vector<std::string> names;
10092 if(app->get_help_ptr() !=
nullptr)
10093 names.push_back(app->get_help_ptr()->get_name());
10095 if(app->get_help_all_ptr() !=
nullptr)
10096 names.push_back(app->get_help_all_ptr()->get_name());
10100 header +=
"Run with " + detail::join(names,
" or ") +
" for more information.\n";
10105CLI11_INLINE std::string help(
const App *app,
const Error &e) {
10106 std::string header = std::string(
"ERROR: ") + e.get_name() +
": " + e.what() +
"\n";
10107 header += app->help();
10118std::string convert_arg_for_ini(
const std::string &arg,
10119 char stringQuote =
'"',
10120 char literalQuote =
'\'',
10121 bool disable_multi_line =
false);
10124std::string ini_join(
const std::vector<std::string> &args,
10125 char sepChar =
',',
10126 char arrayStart =
'[',
10127 char arrayEnd =
']',
10128 char stringQuote =
'"',
10129 char literalQuote =
'\'');
10131void clean_name_string(std::string &name,
const std::string &keyChars);
10133std::vector<std::string> generate_parents(
const std::string §ion, std::string &name,
char parentSeparator);
10136void checkParentSegments(
std::vector<ConfigItem> &output,
const std::string ¤tSection,
char parentSeparator);
10142static constexpr auto multiline_literal_quote = R
"(''')";
10143static constexpr auto multiline_string_quote = R
"(""")";
10147CLI11_INLINE bool is_printable(
const std::string &test_string) {
10148 return std::all_of(test_string.begin(), test_string.end(), [](
char x) {
10149 return (isprint(static_cast<unsigned char>(x)) != 0 || x ==
'\n' || x ==
'\t');
10154convert_arg_for_ini(
const std::string &arg,
char stringQuote,
char literalQuote,
bool disable_multi_line) {
10156 return std::string(2, stringQuote);
10159 if(arg ==
"true" || arg ==
"false" || arg ==
"nan" || arg ==
"inf") {
10163 if(arg.compare(0, 2,
"0x") != 0 && arg.compare(0, 2,
"0X") != 0) {
10164 using CLI::detail::lexical_cast;
10166 if(lexical_cast(arg, val)) {
10167 if(arg.find_first_not_of(
"0123456789.-+eE") == std::string::npos) {
10173 if(arg.size() == 1) {
10174 if(isprint(
static_cast<unsigned char>(arg.front())) == 0) {
10175 return binary_escape_string(arg);
10178 return std::string(1, stringQuote) +
"'" + stringQuote;
10180 return std::string(1, literalQuote) + arg + literalQuote;
10183 if(arg.front() ==
'0') {
10184 if(arg[1] ==
'x') {
10185 if(
std::all_of(arg.begin() + 2, arg.end(), [](
char x) {
10186 return (x >=
'0' && x <=
'9') || (x >=
'A' && x <=
'F') || (x >=
'a' && x <=
'f');
10190 }
else if(arg[1] ==
'o') {
10191 if(
std::all_of(arg.begin() + 2, arg.end(), [](
char x) { return (x >=
'0' && x <=
'7'); })) {
10194 }
else if(arg[1] ==
'b') {
10195 if(
std::all_of(arg.begin() + 2, arg.end(), [](
char x) { return (x ==
'0' || x ==
'1'); })) {
10200 if(!is_printable(arg)) {
10201 return binary_escape_string(arg);
10203 if(detail::has_escapable_character(arg)) {
10204 if(arg.size() > 100 && !disable_multi_line) {
10205 return std::string(multiline_literal_quote) + arg + multiline_literal_quote;
10207 return std::string(1, stringQuote) + detail::add_escaped_characters(arg) + stringQuote;
10209 return std::string(1, stringQuote) + arg + stringQuote;
10212CLI11_INLINE std::string ini_join(
const std::vector<std::string> &args,
10217 char literalQuote) {
10218 bool disable_multi_line{
false};
10219 std::string joined;
10220 if(args.size() > 1 && arrayStart !=
'\0') {
10221 joined.push_back(arrayStart);
10222 disable_multi_line =
true;
10225 for(
const auto &arg : args) {
10227 joined.push_back(sepChar);
10229 joined.push_back(
' ');
10232 joined.append(convert_arg_for_ini(arg, stringQuote, literalQuote, disable_multi_line));
10234 if(args.size() > 1 && arrayEnd !=
'\0') {
10235 joined.push_back(arrayEnd);
10241generate_parents(
const std::string §ion, std::string &name,
char parentSeparator) {
10242 std::vector<std::string> parents;
10243 if(detail::to_lower(section) !=
"default") {
10244 if(section.find(parentSeparator) != std::string::npos) {
10245 parents = detail::split_up(section, parentSeparator);
10247 parents = {section};
10250 if(name.find(parentSeparator) != std::string::npos) {
10251 std::vector<std::string> plist = detail::split_up(name, parentSeparator);
10252 name = plist.back();
10254 parents.insert(parents.end(), plist.begin(), plist.end());
10258 detail::remove_quotes(parents);
10259 }
catch(
const std::invalid_argument &iarg) {
10260#ifndef BB_NO_EXCEPTIONS
10261 THROW CLI::ParseError(iarg.what(), CLI::ExitCodes::InvalidError);
10268checkParentSegments(
std::vector<ConfigItem> &output,
const std::string ¤tSection,
char parentSeparator) {
10270 std::string estring;
10271 auto parents = detail::generate_parents(currentSection, estring, parentSeparator);
10272 if(!output.empty() && output.back().name ==
"--") {
10273 std::size_t msize = (parents.size() > 1U) ? parents.size() : 2;
10274 while(output.back().parents.size() >= msize) {
10275 output.push_back(output.back());
10276 output.back().parents.pop_back();
10279 if(parents.size() > 1) {
10281 std::size_t mpair = (std::min)(output.back().parents.size(), parents.size() - 1);
10283 if(output.back().parents[ii] != parents[ii]) {
10288 if(common == mpair) {
10291 while(output.back().parents.size() > common + 1) {
10292 output.push_back(output.back());
10293 output.back().parents.pop_back();
10296 for(
std::size_t ii = common; ii < parents.size() - 1; ++ii) {
10297 output.emplace_back();
10298 output.back().parents.assign(parents.begin(), parents.begin() +
static_cast<std::ptrdiff_t>(ii) + 1);
10299 output.back().name =
"++";
10302 }
else if(parents.size() > 1) {
10303 for(
std::size_t ii = 0; ii < parents.size() - 1; ++ii) {
10304 output.emplace_back();
10305 output.back().parents.assign(parents.begin(), parents.begin() +
static_cast<std::ptrdiff_t>(ii) + 1);
10306 output.back().name =
"++";
10311 output.emplace_back();
10312 output.back().parents =
std::move(parents);
10313 output.back().name =
"++";
10317CLI11_INLINE bool hasMLString(std::string
const &fullString,
char check) {
10318 if(fullString.length() < 3) {
10321 auto it = fullString.rbegin();
10322 return (*it == check) && (*(it + 1) == check) && (*(it + 2) == check);
10329 std::string currentSection =
"default";
10330 std::string previousSection =
"default";
10332 bool isDefaultArray = (arrayStart ==
'[' && arrayEnd ==
']' && arraySeparator ==
',');
10333 bool isINIArray = (arrayStart ==
'\0' || arrayStart ==
' ') && arrayStart == arrayEnd;
10334 bool inSection{
false};
10335 bool inMLineComment{
false};
10336 bool inMLineValue{
false};
10338 char aStart = (isINIArray) ?
'[' : arrayStart;
10339 char aEnd = (isINIArray) ?
']' : arrayEnd;
10340 char aSep = (isINIArray && arraySeparator ==
' ') ?
',' : arraySeparator;
10341 int currentSectionIndex{0};
10343 std::string line_sep_chars{parentSeparatorChar, commentChar, valueDelimiter};
10344 while(getline(input,
buffer)) {
10345 std::vector<std::string> items_buffer;
10347 line = detail::trim_copy(
buffer);
10353 if(line.compare(0, 3, multiline_string_quote) == 0 || line.compare(0, 3, multiline_literal_quote) == 0) {
10354 inMLineComment =
true;
10355 auto cchar = line.front();
10356 while(inMLineComment) {
10357 if(getline(input, line)) {
10358 detail::trim(line);
10362 if(detail::hasMLString(line, cchar)) {
10363 inMLineComment =
false;
10368 if(line.front() ==
'[' && line.back() ==
']') {
10369 if(currentSection !=
"default") {
10371 output.emplace_back();
10372 output.back().parents = detail::generate_parents(currentSection, name, parentSeparatorChar);
10373 output.back().name =
"--";
10375 currentSection = line.substr(1,
len - 2);
10377 if(currentSection.size() > 1 && currentSection.front() ==
'[' && currentSection.back() ==
']') {
10378 currentSection = currentSection.substr(1, currentSection.size() - 2);
10380 if(detail::to_lower(currentSection) ==
"default") {
10381 currentSection =
"default";
10383 detail::checkParentSegments(output, currentSection, parentSeparatorChar);
10386 if(currentSection == previousSection) {
10387 ++currentSectionIndex;
10389 currentSectionIndex = 0;
10390 previousSection = currentSection;
10396 if(line.front() ==
';' || line.front() ==
'#' || line.front() == commentChar) {
10400 if(line.find_first_of(
"\"'`") != std::string::npos) {
10401 while(search_start < line.size()) {
10402 auto test_char = line[search_start];
10403 if(test_char ==
'\"' || test_char ==
'\'' || test_char ==
'`') {
10404 search_start = detail::close_sequence(line, search_start, line[search_start]);
10406 }
else if(test_char == valueDelimiter || test_char == commentChar) {
10409 }
else if(test_char ==
' ' || test_char ==
'\t' || test_char == parentSeparatorChar) {
10412 search_start = line.find_first_of(line_sep_chars, search_start);
10417 auto delimiter_pos = line.find_first_of(valueDelimiter, search_start + 1);
10418 auto comment_pos = line.find_first_of(commentChar, search_start);
10419 if(comment_pos < delimiter_pos) {
10420 delimiter_pos = std::string::npos;
10422 if(delimiter_pos != std::string::npos) {
10424 name = detail::trim_copy(line.substr(0, delimiter_pos));
10425 std::string item = detail::trim_copy(line.substr(delimiter_pos + 1, std::string::npos));
10427 (item.compare(0, 3, multiline_literal_quote) == 0 || item.compare(0, 3, multiline_string_quote) == 0);
10428 if(!mlquote && comment_pos != std::string::npos) {
10429 auto citems = detail::split_up(item, commentChar);
10430 item = detail::trim_copy(citems.front());
10434 auto keyChar = item.front();
10435 item =
buffer.substr(delimiter_pos + 1, std::string::npos);
10436 detail::ltrim(item);
10438 inMLineValue =
true;
10439 bool lineExtension{
false};
10440 bool firstLine =
true;
10441 if(!item.empty() && item.back() ==
'\\') {
10443 lineExtension =
true;
10445 while(inMLineValue) {
10451 detail::rtrim(line);
10452 if(detail::hasMLString(line, keyChar)) {
10456 if(lineExtension) {
10457 detail::ltrim(line);
10458 }
else if(!(firstLine && item.empty())) {
10459 item.push_back(
'\n');
10463 inMLineValue =
false;
10464 if(!item.empty() && item.back() ==
'\n') {
10467 if(keyChar ==
'\"') {
10469 item = detail::remove_escaped_characters(item);
10470 }
catch(
const std::invalid_argument &iarg) {
10471#ifndef BB_NO_EXCEPTIONS
10472 THROW CLI::ParseError(iarg.what(), CLI::ExitCodes::InvalidError);
10477 if(lineExtension) {
10479 }
else if(!(firstLine && item.empty())) {
10480 item.push_back(
'\n');
10482 lineExtension =
false;
10484 if(!l2.empty() && l2.back() ==
'\\') {
10485 lineExtension =
true;
10491 items_buffer = {item};
10492 }
else if(item.size() > 1 && item.front() == aStart) {
10493 for(std::string multiline; item.back() != aEnd &&
std::getline(input, multiline);) {
10494 detail::trim(multiline);
10497 if(item.back() == aEnd) {
10498 items_buffer = detail::split_up(item.substr(1, item.length() - 2), aSep);
10500 items_buffer = detail::split_up(item.substr(1, std::string::npos), aSep);
10502 }
else if((isDefaultArray || isINIArray) && item.find_first_of(aSep) != std::string::npos) {
10503 items_buffer = detail::split_up(item, aSep);
10504 }
else if((isDefaultArray || isINIArray) && item.find_first_of(
' ') != std::string::npos) {
10505 items_buffer = detail::split_up(item,
'\0');
10507 items_buffer = {item};
10510 name = detail::trim_copy(line.substr(0, comment_pos));
10511 items_buffer = {
"true"};
10513 std::vector<std::string> parents;
10515 parents = detail::generate_parents(currentSection, name, parentSeparatorChar);
10516 detail::process_quoted_string(name);
10518 for(
auto &it : items_buffer) {
10519 detail::process_quoted_string(it, stringQuote, literalQuote);
10521 }
catch(
const std::invalid_argument &ia) {
10522#ifndef BB_NO_EXCEPTIONS
10523 THROW CLI::ParseError(ia.what(), CLI::ExitCodes::InvalidError);
10527 if(parents.size() > maximumLayers) {
10530 if(!configSection.empty() && !inSection) {
10531 if(parents.empty() || parents.front() != configSection) {
10534 if(configIndex >= 0 && currentSectionIndex != configIndex) {
10537 parents.erase(parents.begin());
10540 if(!output.empty() && name == output.back().name && parents == output.back().parents) {
10541 output.back().inputs.insert(output.back().inputs.end(), items_buffer.begin(), items_buffer.end());
10543 output.emplace_back();
10544 output.back().parents =
std::move(parents);
10546 output.back().inputs =
std::move(items_buffer);
10549 if(currentSection !=
"default") {
10552 output.emplace_back();
10553 output.back().parents = detail::generate_parents(currentSection, ename, parentSeparatorChar);
10554 output.back().name =
"--";
10555 while(output.back().parents.size() > 1) {
10556 output.push_back(output.back());
10557 output.back().parents.pop_back();
10563CLI11_INLINE std::string &clean_name_string(std::string &name,
const std::string &keyChars) {
10564 if(name.find_first_of(keyChars) != std::string::npos || (name.front() ==
'[' && name.back() ==
']') ||
10565 (name.find_first_of(
"'`\"\\") != std::string::npos)) {
10566 if(name.find_first_of(
'\'') == std::string::npos) {
10567 name.insert(0, 1,
'\'');
10568 name.push_back(
'\'');
10570 if(detail::has_escapable_character(name)) {
10571 name = detail::add_escaped_characters(name);
10573 name.insert(0, 1,
'\"');
10574 name.push_back(
'\"');
10581ConfigBase::to_config(
const App *app,
bool default_also,
bool write_description, std::string prefix)
const {
10582 std::stringstream out;
10583 std::string commentLead;
10584 commentLead.push_back(commentChar);
10585 commentLead.push_back(
' ');
10587 std::string commentTest =
"#;";
10588 commentTest.push_back(commentChar);
10589 commentTest.push_back(parentSeparatorChar);
10591 std::string keyChars = commentTest;
10592 keyChars.push_back(literalQuote);
10593 keyChars.push_back(stringQuote);
10594 keyChars.push_back(arrayStart);
10595 keyChars.push_back(arrayEnd);
10596 keyChars.push_back(valueDelimiter);
10597 keyChars.push_back(arraySeparator);
10599 std::vector<std::string> groups = app->get_groups();
10600 bool defaultUsed =
false;
10601 groups.insert(groups.begin(), std::string(
"Options"));
10602 if(write_description && (app->get_configurable() || app->get_parent() ==
nullptr || app->get_name().empty())) {
10603 out << commentLead << detail::fix_newlines(commentLead, app->get_description()) <<
'\n';
10605 for(
auto &group : groups) {
10606 if(group ==
"Options" || group.empty()) {
10610 defaultUsed =
true;
10612 if(write_description && group !=
"Options" && !group.empty()) {
10613 out <<
'\n' << commentLead << group <<
" Options\n";
10615 for(
const Option *opt : app->get_options({})) {
10618 if(opt->get_configurable()) {
10619 if(opt->get_group() != group) {
10620 if(!(group ==
"Options" && opt->get_group().empty())) {
10624 std::string single_name = opt->get_single_name();
10625 if(single_name.empty()) {
10629 std::string
value = detail::ini_join(
10630 opt->reduced_results(), arraySeparator, arrayStart, arrayEnd, stringQuote, literalQuote);
10632 if(
value.empty() && default_also) {
10633 if(!opt->get_default_str().empty()) {
10634 value = detail::convert_arg_for_ini(opt->get_default_str(), stringQuote, literalQuote,
false);
10635 }
else if(opt->get_expected_min() == 0) {
10637 }
else if(opt->get_run_callback_for_default()) {
10642 if(!
value.empty()) {
10644 if(!opt->get_fnames().empty()) {
10646 value = opt->get_flag_value(single_name,
value);
10647 }
catch(
const CLI::ArgumentMismatch &) {
10649 for(
const auto &test_name : opt->get_fnames()) {
10651 value = opt->get_flag_value(test_name,
value);
10652 single_name = test_name;
10654 }
catch(
const CLI::ArgumentMismatch &) {
10659 value = detail::ini_join(
10660 opt->results(), arraySeparator, arrayStart, arrayEnd, stringQuote, literalQuote);
10664 if(write_description && opt->has_description()) {
10666 out << commentLead << detail::fix_newlines(commentLead, opt->get_description()) <<
'\n';
10668 clean_name_string(single_name, keyChars);
10670 std::string name = prefix + single_name;
10672 out << name << valueDelimiter <<
value <<
'\n';
10677 auto subcommands = app->get_subcommands({});
10678 for(
const App *subcom : subcommands) {
10679 if(subcom->get_name().empty()) {
10680 if(!default_also && (subcom->count_all() == 0)) {
10683 if(write_description && !subcom->get_group().empty()) {
10684 out <<
'\n' << commentLead << subcom->get_group() <<
" Options\n";
10698 out << to_config(subcom, default_also, write_description, prefix);
10702 for(
const App *subcom : subcommands) {
10703 if(!subcom->get_name().empty()) {
10704 if(!default_also && (subcom->count_all() == 0)) {
10707 std::string subname = subcom->get_name();
10708 clean_name_string(subname, keyChars);
10710 if(subcom->get_configurable() && app->got_subcommand(subcom)) {
10711 if(!prefix.empty() || app->get_parent() ==
nullptr) {
10713 out <<
'[' << prefix << subname <<
"]\n";
10715 std::string appname = app->get_name();
10716 clean_name_string(appname, keyChars);
10717 subname = appname + parentSeparatorChar + subname;
10718 const auto *p = app->get_parent();
10719 while(p->get_parent() !=
nullptr) {
10720 std::string pname = p->get_name();
10721 clean_name_string(pname, keyChars);
10722 subname = pname + parentSeparatorChar + subname;
10723 p = p->get_parent();
10725 out <<
'[' << subname <<
"]\n";
10727 out << to_config(subcom, default_also, write_description,
"");
10729 out << to_config(subcom, default_also, write_description, prefix + subname + parentSeparatorChar);
10744 std::stringstream out;
10746 out <<
"\n" << group <<
":\n";
10747 for(
const Option *opt : opts) {
10748 out << make_option(opt, is_positional);
10754CLI11_INLINE std::string Formatter::make_positionals(
const App *app)
const {
10756 app->get_options([](
const Option *opt) {
return !opt->get_group().empty() && opt->get_positional(); });
10761 return make_group(get_label(
"Positionals"),
true, opts);
10764CLI11_INLINE std::string Formatter::make_groups(
const App *app, AppFormatMode mode)
const {
10765 std::stringstream out;
10766 std::vector<std::string> groups = app->get_groups();
10769 for(
const std::string &group : groups) {
10771 return opt->get_group() == group
10772 && opt->nonpositional()
10773 && (mode != AppFormatMode::Sub
10774 || (app->get_help_ptr() != opt
10775 && app->get_help_all_ptr() != opt));
10777 if(!group.empty() && !opts.empty()) {
10778 out << make_group(group,
false, opts);
10780 if(group != groups.back())
10788CLI11_INLINE std::string Formatter::make_description(
const App *app)
const {
10789 std::string desc = app->get_description();
10790 auto min_options = app->get_require_option_min();
10791 auto max_options = app->get_require_option_max();
10792 if(app->get_required()) {
10793 desc +=
" " + get_label(
"REQUIRED") +
" ";
10795 if((max_options == min_options) && (min_options > 0)) {
10796 if(min_options == 1) {
10797 desc +=
" \n[Exactly 1 of the following options is required]";
10799 desc +=
" \n[Exactly " +
std::to_string(min_options) +
" options from the following list are required]";
10801 }
else if(max_options > 0) {
10802 if(min_options > 0) {
10804 " of the follow options are required]";
10806 desc +=
" \n[At most " +
std::to_string(max_options) +
" of the following options are allowed]";
10808 }
else if(min_options > 0) {
10809 desc +=
" \n[At least " +
std::to_string(min_options) +
" of the following options are required]";
10811 return (!desc.empty()) ? desc +
"\n" : std::string{};
10814CLI11_INLINE std::string Formatter::make_usage(
const App *app, std::string name)
const {
10815 std::string usage = app->get_usage();
10816 if(!usage.empty()) {
10817 return usage +
"\n";
10820 std::stringstream out;
10822 out << get_label(
"Usage") <<
":" << (name.empty() ?
"" :
" ") << name;
10824 std::vector<std::string> groups = app->get_groups();
10828 app->get_options([](
const Option *opt) {
return opt->nonpositional(); });
10829 if(!non_pos_options.empty())
10830 out <<
" [" << get_label(
"OPTIONS") <<
"]";
10836 if(!positionals.empty()) {
10838 std::vector<std::string> positional_names(positionals.size());
10839 std::transform(positionals.begin(), positionals.end(), positional_names.begin(), [
this](
const Option *opt) {
10840 return make_option_usage(opt);
10843 out <<
" " << detail::join(positional_names,
" ");
10847 if(!app->get_subcommands(
10848 [](
const CLI::App *subc) { return ((!subc->get_disabled()) && (!subc->get_name().empty())); })
10850 out <<
" " << (app->get_require_subcommand_min() == 0 ?
"[" :
"")
10851 << get_label(app->get_require_subcommand_max() < 2 || app->get_require_subcommand_min() > 1 ?
"SUBCOMMAND"
10853 << (app->get_require_subcommand_min() == 0 ?
"]" :
"");
10861CLI11_INLINE std::string Formatter::make_footer(
const App *app)
const {
10862 std::string footer = app->get_footer();
10863 if(footer.empty()) {
10864 return std::string{};
10866 return "\n" + footer +
"\n";
10869CLI11_INLINE std::string Formatter::make_help(
const App *app, std::string name, AppFormatMode mode)
const {
10873 if(mode == AppFormatMode::Sub)
10874 return make_expanded(app);
10876 std::stringstream out;
10877 if((app->get_name().empty()) && (app->get_parent() !=
nullptr)) {
10878 if(app->get_group() !=
"Subcommands") {
10879 out << app->get_group() <<
':';
10883 out << make_description(app);
10884 out << make_usage(app, name);
10885 out << make_positionals(app);
10886 out << make_groups(app, mode);
10887 out << make_subcommands(app, mode);
10888 out << make_footer(app);
10893CLI11_INLINE std::string Formatter::make_subcommands(
const App *app, AppFormatMode mode)
const {
10894 std::stringstream out;
10899 std::vector<std::string> subcmd_groups_seen;
10900 for(
const App *com : subcommands) {
10901 if(com->get_name().empty()) {
10902 if(!com->get_group().empty()) {
10903 out << make_expanded(com);
10907 std::string group_key = com->get_group();
10908 if(!group_key.empty() &&
10909 std::find_if(subcmd_groups_seen.begin(), subcmd_groups_seen.end(), [&group_key](std::string
a) {
10910 return detail::to_lower(a) == detail::to_lower(group_key);
10911 }) == subcmd_groups_seen.end())
10912 subcmd_groups_seen.push_back(group_key);
10916 for(
const std::string &group : subcmd_groups_seen) {
10917 out <<
"\n" << group <<
":\n";
10919 [&group](
const App *sub_app) {
return detail::to_lower(sub_app->get_group()) == detail::to_lower(group); });
10920 for(
const App *new_com : subcommands_group) {
10921 if(new_com->get_name().empty())
10923 if(mode != AppFormatMode::All) {
10924 out << make_subcommand(new_com);
10926 out << new_com->help(new_com->get_name(), AppFormatMode::Sub);
10935CLI11_INLINE std::string Formatter::make_subcommand(
const App *sub)
const {
10936 std::stringstream out;
10937 detail::format_help(out,
10938 sub->get_display_name(
true) + (sub->get_required() ?
" " + get_label(
"REQUIRED") :
""),
10939 sub->get_description(),
10944CLI11_INLINE std::string Formatter::make_expanded(
const App *sub)
const {
10945 std::stringstream out;
10946 out << sub->get_display_name(
true) <<
"\n";
10948 out << make_description(sub);
10949 if(sub->get_name().empty() && !sub->get_aliases().empty()) {
10950 detail::format_aliases(out, sub->get_aliases(), column_width_ + 2);
10952 out << make_positionals(sub);
10953 out << make_groups(sub, AppFormatMode::Sub);
10954 out << make_subcommands(sub, AppFormatMode::Sub);
10957 std::string tmp = detail::find_and_replace(out.str(),
"\n\n",
"\n");
10958 tmp = tmp.substr(0, tmp.size() - 1);
10961 return detail::find_and_replace(tmp,
"\n",
"\n ") +
"\n";
10964CLI11_INLINE std::string Formatter::make_option_name(
const Option *opt,
bool is_positional)
const {
10966 return opt->get_name(
true,
false);
10968 return opt->get_name(
false,
true);
10971CLI11_INLINE std::string Formatter::make_option_opts(
const Option *opt)
const {
10972 std::stringstream out;
10974 if(!opt->get_option_text().empty()) {
10975 out <<
" " << opt->get_option_text();
10977 if(opt->get_type_size() != 0) {
10978 if(!opt->get_type_name().empty())
10979 out <<
" " << get_label(opt->get_type_name());
10980 if(!opt->get_default_str().empty())
10981 out <<
" [" << opt->get_default_str() <<
"] ";
10982 if(opt->get_expected_max() == detail::expected_max_vector_size)
10984 else if(opt->get_expected_min() > 1)
10985 out <<
" x " << opt->get_expected();
10987 if(opt->get_required())
10988 out <<
" " << get_label(
"REQUIRED");
10990 if(!opt->get_envname().empty())
10991 out <<
" (" << get_label(
"Env") <<
":" << opt->get_envname() <<
")";
10992 if(!opt->get_needs().empty()) {
10993 out <<
" " << get_label(
"Needs") <<
":";
10994 for(
const Option *op : opt->get_needs())
10995 out <<
" " << op->get_name();
10997 if(!opt->get_excludes().empty()) {
10998 out <<
" " << get_label(
"Excludes") <<
":";
10999 for(
const Option *op : opt->get_excludes())
11000 out <<
" " << op->get_name();
11006CLI11_INLINE std::string Formatter::make_option_desc(
const Option *opt)
const {
return opt->get_description(); }
11008CLI11_INLINE std::string Formatter::make_option_usage(
const Option *opt)
const {
11010 std::stringstream out;
11011 out << make_option_name(opt,
true);
11012 if(opt->get_expected_max() >= detail::expected_max_vector_size)
11014 else if(opt->get_expected_max() > 1)
11015 out <<
"(" << opt->get_expected() <<
"x)";
11017 return opt->get_required() ? out.str() :
"[" + out.str() +
"]";
#define CLI11_ERROR_SIMPLE(name)
#define CLI11_DIAGNOSTIC_IGNORE_DEPRECATED
#define CLI11_DIAGNOSTIC_PUSH
#define CLI11_DIAGNOSTIC_POP
#define CLI11_ERROR_DEF(parent, name)
uint8_t buffer[RANDOM_BUFFER_SIZE]
FF const & operator[](size_t idx) const
Retruns the element in beta_products at place #idx.
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
std::string to_string(bb::avm2::ValueTag tag)