60#define CLI11_VERSION_MAJOR 2
61#define CLI11_VERSION_MINOR 3
62#define CLI11_VERSION_PATCH 1
63#define CLI11_VERSION "2.3.1"
66#if !(defined(_MSC_VER) && __cplusplus == 199711L) && !defined(__INTEL_COMPILER)
67#if __cplusplus >= 201402L
69#if __cplusplus >= 201703L
71#if __cplusplus > 201703L
76#elif defined(_MSC_VER) && __cplusplus == 199711L
79#if _MSVC_LANG >= 201402L
81#if _MSVC_LANG > 201402L && _MSC_VER >= 1910
83#if _MSVC_LANG > 201703L && _MSC_VER >= 1910
90#if defined(CLI11_CPP14)
91#define CLI11_DEPRECATED(reason) [[deprecated(reason)]]
92#elif defined(_MSC_VER)
93#define CLI11_DEPRECATED(reason) __declspec(deprecated(reason))
95#define CLI11_DEPRECATED(reason) __attribute__((deprecated(reason)))
99#if !defined(CLI11_CPP17) || (defined(__GNUC__) && !defined(__llvm__) && \
100 !defined(__INTEL_COMPILER) && __GNUC__ < 10 && __GNUC__ > 4)
101#define CLI11_NODISCARD
103#define CLI11_NODISCARD [[nodiscard]]
107#ifndef CLI11_USE_STATIC_RTTI
108#if (defined(_HAS_STATIC_RTTI) && _HAS_STATIC_RTTI)
109#define CLI11_USE_STATIC_RTTI 1
110#elif defined(__cpp_rtti)
111#if (defined(_CPPRTTI) && _CPPRTTI == 0)
112#define CLI11_USE_STATIC_RTTI 1
114#define CLI11_USE_STATIC_RTTI 0
116#elif (defined(__GCC_RTTI) && __GXX_RTTI)
117#define CLI11_USE_STATIC_RTTI 0
119#define CLI11_USE_STATIC_RTTI 1
127#define CLI11_INLINE inline
132#if defined CLI11_CPP17 && defined __has_include && !defined CLI11_HAS_FILESYSTEM
133#if __has_include(<filesystem>)
135#if defined __MAC_OS_X_VERSION_MIN_REQUIRED && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500
136#define CLI11_HAS_FILESYSTEM 0
137#elif defined(__wasi__)
139#define CLI11_HAS_FILESYSTEM 0
142#if defined __cpp_lib_filesystem && __cpp_lib_filesystem >= 201703
143#if defined _GLIBCXX_RELEASE && _GLIBCXX_RELEASE >= 9
144#define CLI11_HAS_FILESYSTEM 1
145#elif defined(__GLIBCXX__)
147#define CLI11_HAS_FILESYSTEM 0
149#define CLI11_HAS_FILESYSTEM 1
152#define CLI11_HAS_FILESYSTEM 0
158#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
162#include <sys/types.h>
172template <typename T, typename = typename std::enable_if<std::is_enum<T>::value>::type>
175 return in << static_cast<typename std::underlying_type<T>::type>(item);
181using enums::operator<<;
186constexpr int expected_max_vector_size{1 << 29};
189CLI11_INLINE std::vector<std::string> split(
const std::string &s,
char delim);
193std::string join(
const T &v, std::string delim =
",") {
194 std::ostringstream s;
195 auto beg = std::begin(v);
196 auto end = std::end(v);
197 if (beg != end) s << *beg++;
199 s << delim << *beg++;
208 typename =
typename std::enable_if<!std::is_constructible<std::string, Callable>::value>::type>
209std::string join(
const T &v, Callable func, std::string delim =
",") {
210 std::ostringstream s;
211 auto beg = std::begin(v);
212 auto end = std::end(v);
213 auto loc = s.tellp();
215 auto nloc = s.tellp();
227std::string rjoin(
const T &v, std::string delim =
",") {
228 std::ostringstream s;
229 for (std::size_t start = 0; start < v.size(); start++) {
230 if (start > 0) s << delim;
231 s << v[v.size() - start - 1];
239CLI11_INLINE std::string <rim(std::string &str);
242CLI11_INLINE std::string <rim(std::string &str,
const std::string &filter);
245CLI11_INLINE std::string &rtrim(std::string &str);
248CLI11_INLINE std::string &rtrim(std::string &str,
const std::string &filter);
251inline std::string &trim(std::string &str) {
return ltrim(rtrim(str)); }
254inline std::string &trim(std::string &str,
const std::string filter) {
255 return ltrim(rtrim(str, filter), filter);
259inline std::string trim_copy(
const std::string &str) {
265CLI11_INLINE std::string &remove_quotes(std::string &str);
271CLI11_INLINE std::string fix_newlines(
const std::string &leader, std::string input);
275inline std::string trim_copy(
const std::string &str,
const std::string &filter) {
277 return trim(s, filter);
280CLI11_INLINE std::ostream &format_help(std::ostream &out,
282 const std::string &description,
286CLI11_INLINE std::ostream &format_aliases(std::ostream &out,
287 const std::vector<std::string> &aliases,
294bool valid_first_char(T c) {
295 return ((c !=
'-') && (c !=
'!') && (c !=
' ') && c !=
'\n');
300bool valid_later_char(T c) {
304 return ((c !=
'=') && (c !=
':') && (c !=
'{') && (c !=
' ') && c !=
'\n');
308CLI11_INLINE
bool valid_name_string(
const std::string &str);
311inline bool valid_alias_name_string(
const std::string &str) {
312 static const std::string badChars(std::string(
"\n") +
'\0');
313 return (str.find_first_of(badChars) == std::string::npos);
317inline bool is_separator(
const std::string &str) {
318 static const std::string sep(
"%%");
319 return (str.empty() || str == sep);
323inline bool isalpha(
const std::string &str) {
324 return std::all_of(str.begin(), str.end(),
325 [](
char c) { return std::isalpha(c, std::locale()); });
329inline std::string to_lower(std::string str) {
330 std::transform(std::begin(str), std::end(str), std::begin(str),
331 [](
const std::string::value_type &x) {
return std::tolower(x, std::locale()); });
336inline std::string remove_underscore(std::string str) {
337 str.erase(std::remove(std::begin(str), std::end(str),
'_'), std::end(str));
342CLI11_INLINE std::string find_and_replace(std::string str, std::string from, std::string to);
345inline bool has_default_flag_values(
const std::string &flags) {
346 return (flags.find_first_of(
"{!") != std::string::npos);
349CLI11_INLINE
void remove_default_flag_values(std::string &flags);
353CLI11_INLINE std::ptrdiff_t find_member(std::string name,
354 const std::vector<std::string> names,
355 bool ignore_case =
false,
356 bool ignore_underscore =
false);
361template <
typename Callable>
362inline std::string find_and_modify(std::string str, std::string trigger, Callable modify) {
363 std::size_t start_pos = 0;
364 while ((start_pos = str.find(trigger, start_pos)) != std::string::npos) {
365 start_pos = modify(str, start_pos);
372CLI11_INLINE std::vector<std::string> split_up(std::string str,
char delimiter =
'\0');
379CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset);
382CLI11_INLINE std::string &add_quotes_if_needed(std::string &str);
387CLI11_INLINE std::vector<std::string> split(
const std::string &s,
char delim) {
388 std::vector<std::string> elems;
391 elems.emplace_back();
393 std::stringstream ss;
396 while (std::getline(ss, item, delim)) {
397 elems.push_back(item);
403CLI11_INLINE std::string <rim(std::string &str) {
404 auto it = std::find_if(str.begin(), str.end(),
405 [](
char ch) { return !std::isspace<char>(ch, std::locale()); });
406 str.erase(str.begin(), it);
410CLI11_INLINE std::string <rim(std::string &str,
const std::string &filter) {
411 auto it = std::find_if(str.begin(), str.end(),
412 [&filter](
char ch) { return filter.find(ch) == std::string::npos; });
413 str.erase(str.begin(), it);
417CLI11_INLINE std::string &rtrim(std::string &str) {
418 auto it = std::find_if(str.rbegin(), str.rend(),
419 [](
char ch) { return !std::isspace<char>(ch, std::locale()); });
420 str.erase(it.base(), str.end());
424CLI11_INLINE std::string &rtrim(std::string &str,
const std::string &filter) {
425 auto it = std::find_if(str.rbegin(), str.rend(),
426 [&filter](
char ch) { return filter.find(ch) == std::string::npos; });
427 str.erase(it.base(), str.end());
431CLI11_INLINE std::string &remove_quotes(std::string &str) {
432 if (str.length() > 1 && (str.front() ==
'"' || str.front() ==
'\'')) {
433 if (str.front() == str.back()) {
435 str.erase(str.begin(), str.begin() + 1);
441CLI11_INLINE std::string fix_newlines(
const std::string &leader, std::string input) {
442 std::string::size_type n = 0;
443 while (n != std::string::npos && n < input.size()) {
444 n = input.find(
'\n', n);
445 if (n != std::string::npos) {
446 input = input.substr(0, n + 1) + leader + input.substr(n + 1);
453CLI11_INLINE std::ostream &format_help(std::ostream &out,
455 const std::string &description,
458 out << std::setw(static_cast<int>(wid)) << std::left << name;
459 if (!description.empty()) {
460 if (name.length() >= wid) out <<
"\n" << std::setw(
static_cast<int>(wid)) <<
"";
461 for (
const char c : description) {
464 out << std::setw(static_cast<int>(wid)) <<
"";
472CLI11_INLINE std::ostream &format_aliases(std::ostream &out,
473 const std::vector<std::string> &aliases,
475 if (!aliases.empty()) {
476 out << std::setw(static_cast<int>(wid)) <<
" aliases: ";
478 for (
const auto &alias : aliases) {
484 out << detail::fix_newlines(
" ", alias);
491CLI11_INLINE
bool valid_name_string(
const std::string &str) {
492 if (str.empty() || !valid_first_char(str[0])) {
496 for (
auto c = str.begin() + 1; c != e; ++c)
497 if (!valid_later_char(*c))
return false;
501CLI11_INLINE std::string find_and_replace(std::string str, std::string from, std::string to) {
502 std::size_t start_pos = 0;
504 while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
505 str.replace(start_pos, from.length(), to);
506 start_pos += to.length();
512CLI11_INLINE
void remove_default_flag_values(std::string &flags) {
513 auto loc = flags.find_first_of(
'{', 2);
514 while (loc != std::string::npos) {
515 auto finish = flags.find_first_of(
"},", loc + 1);
516 if ((finish != std::string::npos) && (flags[finish] ==
'}')) {
517 flags.erase(flags.begin() +
static_cast<std::ptrdiff_t
>(loc),
518 flags.begin() +
static_cast<std::ptrdiff_t
>(finish) + 1);
520 loc = flags.find_first_of(
'{', loc + 1);
522 flags.erase(std::remove(flags.begin(), flags.end(),
'!'), flags.end());
525CLI11_INLINE std::ptrdiff_t find_member(std::string name,
526 const std::vector<std::string> names,
528 bool ignore_underscore) {
529 auto it = std::end(names);
531 if (ignore_underscore) {
532 name = detail::to_lower(detail::remove_underscore(name));
533 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
534 return detail::to_lower(detail::remove_underscore(local_name)) == name;
537 name = detail::to_lower(name);
538 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
539 return detail::to_lower(local_name) == name;
543 }
else if (ignore_underscore) {
544 name = detail::remove_underscore(name);
545 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
546 return detail::remove_underscore(local_name) == name;
549 it = std::find(std::begin(names), std::end(names), name);
552 return (it != std::end(names)) ? (it - std::begin(names)) : (-1);
555CLI11_INLINE std::vector<std::string> split_up(std::string str,
char delimiter) {
556 const std::string delims(
"\'\"`");
557 auto find_ws = [delimiter](
char ch) {
558 return (delimiter ==
'\0') ? std::isspace<char>(ch, std::locale()) : (ch == delimiter);
562 std::vector<std::string> output;
563 bool embeddedQuote =
false;
565 while (!str.empty()) {
566 if (delims.find_first_of(str[0]) != std::string::npos) {
568 auto end = str.find_first_of(keyChar, 1);
569 while ((end != std::string::npos) &&
570 (str[end - 1] ==
'\\')) {
571 end = str.find_first_of(keyChar, end + 1);
572 embeddedQuote =
true;
574 if (end != std::string::npos) {
575 output.push_back(str.substr(1, end - 1));
576 if (end + 2 < str.size()) {
577 str = str.substr(end + 2);
583 output.push_back(str.substr(1));
587 auto it = std::find_if(std::begin(str), std::end(str), find_ws);
588 if (it != std::end(str)) {
589 std::string value = std::string(str.begin(), it);
590 output.push_back(value);
591 str = std::string(it + 1, str.end());
593 output.push_back(str);
599 output.back() = find_and_replace(output.back(), std::string(
"\\") + keyChar,
600 std::string(1, keyChar));
601 embeddedQuote =
false;
608CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset) {
609 auto next = str[offset + 1];
610 if ((next ==
'\"') || (next ==
'\'') || (next ==
'`')) {
611 auto astart = str.find_last_of(
"-/ \"\'`", offset - 1);
612 if (astart != std::string::npos) {
613 if (str[astart] == ((str[offset] ==
'=') ?
'-' :
'/'))
620CLI11_INLINE std::string &add_quotes_if_needed(std::string &str) {
621 if ((str.front() !=
'"' && str.front() !=
'\'') || str.front() != str.back()) {
622 char quote = str.find(
'"') < str.find(
'\'') ?
'\'' :
'"';
623 if (str.find(
' ') != std::string::npos) {
624 str.insert(0, 1, quote);
625 str.append(1, quote);
635#define CLI11_ERROR_DEF(parent, name) \
637 name(std::string ename, std::string msg, int exit_code) \
638 : parent(std::move(ename), std::move(msg), exit_code) {} \
639 name(std::string ename, std::string msg, ExitCodes exit_code) \
640 : parent(std::move(ename), std::move(msg), exit_code) {} \
643 name(std::string msg, ExitCodes exit_code) : parent(#name, std::move(msg), exit_code) {} \
644 name(std::string msg, int exit_code) : parent(#name, std::move(msg), exit_code) {}
647#define CLI11_ERROR_SIMPLE(name) \
648 explicit name(std::string msg) : name(#name, msg, ExitCodes::name) {}
652enum class ExitCodes {
681class Error :
public std::runtime_error {
682 int actual_exit_code;
683 std::string error_name{
"Error"};
686 CLI11_NODISCARD
int get_exit_code()
const {
return actual_exit_code; }
688 CLI11_NODISCARD std::string get_name()
const {
return error_name; }
690 Error(std::string name, std::string msg,
int exit_code =
static_cast<int>(ExitCodes::BaseClass))
691 : runtime_error(msg), actual_exit_code(exit_code), error_name(std::move(name)) {}
693 Error(std::string name, std::string msg, ExitCodes exit_code)
694 : Error(name, msg,
static_cast<int>(exit_code)) {}
719 ": You can only change the expected arguments for vectors");
724 ": You can't change expected arguments after you've changed the multi option policy!");
731 name +
": multi_option_policy only works for flags and exact value options");
746 return BadNameString(
"Must have a name, not just dashes: " + name);
748 static BadNameString MultiPositionalNames(std::string name) {
749 return BadNameString(
"Only one positional name allowed, remove: " + name);
756 explicit OptionAlreadyAdded(std::string name)
757 : OptionAlreadyAdded(name +
" is already added", ExitCodes::OptionAlreadyAdded) {}
758 static OptionAlreadyAdded Requires(std::string name, std::string other) {
759 return {name +
" requires " + other, ExitCodes::OptionAlreadyAdded};
761 static OptionAlreadyAdded Excludes(std::string name, std::string other) {
762 return {name +
" excludes " + other, ExitCodes::OptionAlreadyAdded};
778 Success() : Success(
"Successfully completed, should be caught and quit", ExitCodes::Success) {}
782class CallForHelp :
public Success {
783 CLI11_ERROR_DEF(Success, CallForHelp)
785 : CallForHelp(
"This should be caught in your main function, see examples",
786 ExitCodes::Success) {}
790class CallForAllHelp :
public Success {
791 CLI11_ERROR_DEF(Success, CallForAllHelp)
793 : CallForAllHelp(
"This should be caught in your main function, see examples",
794 ExitCodes::Success) {}
798class CallForVersion :
public Success {
799 CLI11_ERROR_DEF(Success, CallForVersion)
801 : CallForVersion(
"This should be caught in your main function, see examples",
802 ExitCodes::Success) {}
809 explicit RuntimeError(
int exit_code = 1) : RuntimeError(
"Runtime error", exit_code) {}
816 static FileError Missing(std::string name) {
817 return FileError(name +
" was not readable (missing?)");
824 CLI11_ERROR_SIMPLE(ConversionError)
825 ConversionError(std::string member, std::string name)
826 : ConversionError(
"The value " + member +
" is not an allowed value for " + name) {}
827 ConversionError(std::string name, std::vector<std::string> results)
828 : ConversionError(
"Could not convert: " + name +
" = " + detail::join(results)) {}
829 static ConversionError TooManyInputsFlag(std::string name) {
830 return ConversionError(name +
": too many inputs for a flag");
832 static ConversionError TrueFalse(std::string name) {
833 return ConversionError(name +
": Should be true/false or a number");
840 CLI11_ERROR_SIMPLE(ValidationError)
841 explicit ValidationError(std::string name, std::string msg)
842 : ValidationError(name +
": " + msg) {}
848 explicit RequiredError(std::string name)
849 : RequiredError(name +
" is required", ExitCodes::RequiredError) {}
850 static RequiredError Subcommand(std::size_t min_subcom) {
851 if (min_subcom == 1) {
852 return RequiredError(
"A subcommand");
854 return {
"Requires at least " + std::to_string(min_subcom) +
" subcommands",
855 ExitCodes::RequiredError};
857 static RequiredError Option(std::size_t min_option,
858 std::size_t max_option,
860 const std::string &option_list) {
861 if ((min_option == 1) && (max_option == 1) && (used == 0))
862 return RequiredError(
"Exactly 1 option from [" + option_list +
"]");
863 if ((min_option == 1) && (max_option == 1) && (used > 1)) {
864 return {
"Exactly 1 option from [" + option_list +
"] is required and " +
865 std::to_string(used) +
" were given",
866 ExitCodes::RequiredError};
868 if ((min_option == 1) && (used == 0))
869 return RequiredError(
"At least 1 option from [" + option_list +
"]");
870 if (used < min_option) {
871 return {
"Requires at least " + std::to_string(min_option) +
" options used and only " +
872 std::to_string(used) +
"were given from [" + option_list +
"]",
873 ExitCodes::RequiredError};
876 return {
"Requires at most 1 options be given from [" + option_list +
"]",
877 ExitCodes::RequiredError};
879 return {
"Requires at most " + std::to_string(max_option) +
" options be used and " +
880 std::to_string(used) +
"were given from [" + option_list +
"]",
881 ExitCodes::RequiredError};
888 CLI11_ERROR_SIMPLE(ArgumentMismatch)
889 ArgumentMismatch(std::string name,
int expected, std::size_t received)
890 : ArgumentMismatch(expected > 0
891 ? (
"Expected exactly " + std::to_string(expected) +
892 " arguments to " + name +
", got " + std::to_string(received))
893 : (
"Expected at least " + std::to_string(-expected) +
894 " arguments to " + name +
", got " + std::to_string(received)),
895 ExitCodes::ArgumentMismatch) {}
897 static ArgumentMismatch AtLeast(std::string name,
int num, std::size_t received) {
898 return ArgumentMismatch(name +
": At least " + std::to_string(num) +
899 " required but received " + std::to_string(received));
901 static ArgumentMismatch AtMost(std::string name,
int num, std::size_t received) {
902 return ArgumentMismatch(name +
": At Most " + std::to_string(num) +
903 " required but received " + std::to_string(received));
905 static ArgumentMismatch TypedAtLeast(std::string name,
int num, std::string type) {
906 return ArgumentMismatch(name +
": " + std::to_string(num) +
" required " + type +
909 static ArgumentMismatch FlagOverride(std::string name) {
910 return ArgumentMismatch(name +
" was given a disallowed flag override");
912 static ArgumentMismatch PartialType(std::string name,
int num, std::string type) {
913 return ArgumentMismatch(name +
": " + type +
" only partially specified: " +
914 std::to_string(num) +
" required for each element");
921 RequiresError(std::string curname, std::string subname)
922 : RequiresError(curname +
" requires " + subname, ExitCodes::RequiresError) {}
928 ExcludesError(std::string curname, std::string subname)
929 : ExcludesError(curname +
" excludes " + subname, ExitCodes::ExcludesError) {}
935 explicit ExtrasError(std::vector<std::string> args)
936 : ExtrasError((args.size() > 1 ?
"The following arguments were not expected: "
937 :
"The following argument was not expected: ") +
938 detail::rjoin(args,
" "),
939 ExitCodes::ExtrasError) {}
940 ExtrasError(
const std::string &name, std::vector<std::string> args)
942 (args.size() > 1 ?
"The following arguments were not expected: "
943 :
"The following argument was not expected: ") +
944 detail::rjoin(args,
" "),
945 ExitCodes::ExtrasError) {}
953 return ConfigError(
"INI was not able to parse " + item);
955 static ConfigError NotConfigurable(std::string item) {
956 return ConfigError(item +
": This option is not allowed in a configuration file");
963 explicit InvalidError(std::string name)
964 : InvalidError(name +
": Too many positional arguments with unlimited expected args",
965 ExitCodes::InvalidError) {}
978class OptionNotFound :
public Error {
979 CLI11_ERROR_DEF(Error, OptionNotFound)
980 explicit OptionNotFound(std::string name)
981 : OptionNotFound(name +
" not found", ExitCodes::OptionNotFound) {}
984#undef CLI11_ERROR_DEF
985#undef CLI11_ERROR_SIMPLE
995enum class enabler {};
998constexpr enabler dummy = {};
1006template <
bool B,
class T =
void>
1007using enable_if_t =
typename std::enable_if<B, T>::type;
1010template <
typename... Ts>
1016template <
typename... Ts>
1017using void_t =
typename make_void<Ts...>::type;
1021template <
bool B,
class T,
class F>
1022using conditional_t =
typename std::conditional<B, T, F>::type;
1025template <
typename T>
1033template <
typename T>
1037template <
typename T>
1041template <
typename T>
1045template <
typename T>
1051template <
typename T>
1059 using type = std::string;
1070template <
typename T,
typename Enable =
void>
1075template <
typename T>
1076struct element_type<T, typename std::enable_if<is_copyable_ptr<T>::value>::type> {
1077 using type =
typename std::pointer_traits<T>::element_type;
1082template <
typename T>
1089template <
typename T,
typename _ =
void>
1091 using value_type =
typename T::value_type;
1092 using first_type =
typename std::remove_const<value_type>::type;
1093 using second_type =
typename std::remove_const<value_type>::type;
1096 template <
typename Q>
1097 static auto first(Q &&pair_value) ->
decltype(std::forward<Q>(pair_value)) {
1098 return std::forward<Q>(pair_value);
1101 template <
typename Q>
1102 static auto second(Q &&pair_value) ->
decltype(std::forward<Q>(pair_value)) {
1103 return std::forward<Q>(pair_value);
1109template <
typename T>
1112 conditional_t<false,
1113 void_t<typename T::value_type::first_type, typename T::value_type::second_type>,
1114 void>> : std::true_type {
1115 using value_type =
typename T::value_type;
1116 using first_type =
typename std::remove_const<typename value_type::first_type>::type;
1117 using second_type =
typename std::remove_const<typename value_type::second_type>::type;
1120 template <
typename Q>
1121 static auto first(Q &&pair_value) ->
decltype(std::get<0>(std::forward<Q>(pair_value))) {
1122 return std::get<0>(std::forward<Q>(pair_value));
1125 template <
typename Q>
1126 static auto second(Q &&pair_value) ->
decltype(std::get<1>(std::forward<Q>(pair_value))) {
1127 return std::get<1>(std::forward<Q>(pair_value));
1139#pragma GCC diagnostic push
1140#pragma GCC diagnostic ignored "-Wnarrowing"
1143template <
typename T,
typename C>
1145 template <
typename TT,
typename CC>
1146 static auto test(
int, std::true_type) ->
decltype(
1149#pragma diag_suppress 2361
1151 TT{std::declval<CC>()}
1153#pragma diag_default 2361
1156 std::is_move_assignable<TT>());
1158 template <
typename TT,
typename CC>
1159 static auto test(
int, std::false_type) -> std::false_type;
1161 template <
typename,
typename>
1162 static auto test(...) -> std::false_type;
1165 static constexpr bool value =
1166 decltype(test<T, C>(0,
typename std::is_constructible<T, C>::type()))::value;
1169#pragma GCC diagnostic pop
1176template <
typename T,
typename S = std::o
stringstream>
1178 template <
typename TT,
typename SS>
1179 static auto test(
int) ->
decltype(std::declval<SS &>() << std::declval<TT>(), std::true_type());
1181 template <
typename,
typename>
1182 static auto test(...) -> std::false_type;
1185 static constexpr bool value =
decltype(test<T, S>(0))::value;
1189template <
typename T,
typename S = std::i
stringstream>
1191 template <
typename TT,
typename SS>
1192 static auto test(
int)
1193 ->
decltype(std::declval<SS &>() >> std::declval<TT &>(), std::true_type());
1195 template <
typename,
typename>
1196 static auto test(...) -> std::false_type;
1199 static constexpr bool value =
decltype(test<T, S>(0))::value;
1203template <
typename T>
1205 template <
typename TT>
1206 static auto test(
int)
1207 ->
decltype(std::declval<TT>().real(), std::declval<TT>().imag(), std::true_type());
1210 static auto test(...) -> std::false_type;
1213 static constexpr bool value =
decltype(test<T>(0))::value;
1217template <typename T, enable_if_t<is_istreamable<T>::value, detail::enabler> = detail::dummy>
1218bool from_stream(
const std::string &istring, T &obj) {
1219 std::istringstream is;
1222 return !is.fail() && !is.rdbuf()->in_avail();
1225template <typename T, enable_if_t<!is_istreamable<T>::value, detail::enabler> = detail::dummy>
1226bool from_stream(
const std::string & , T & ) {
1231template <
typename T,
typename _ =
void>
1237template <
typename T>
1242 void_t<typename T::value_type,
1243 decltype(std::declval<T>().end()),
1244 decltype(std::declval<T>().clear()),
1245 decltype(std::declval<T>().insert(std::declval<decltype(std::declval<T>().end())>(),
1246 std::declval<const typename T::value_type &>()))>,
1247 void>> :
public conditional_t<std::is_constructible<T, std::string>::value,
1252template <
typename T,
typename _ =
void>
1258template <
typename T>
1261 conditional_t<false,
1262 void_t<decltype(std::declval<T>().end()), decltype(std::declval<T>().begin())>,
1263 void>> :
public std::true_type {};
1266template <
typename T,
typename _ =
void>
1270template <
typename T>
1271struct is_wrapper<T, conditional_t<false, void_t<typename T::value_type>, void>>
1272 :
public std::true_type {};
1275template <
typename S>
1277 template <
typename SS>
1281 static auto test(
int)
1282 ->
decltype(std::tuple_size<typename std::decay<SS>::type>::value, std::true_type{});
1284 static auto test(...) -> std::false_type;
1287 static constexpr bool value =
decltype(test<S>(0))::value;
1291template <
typename T,
1292 enable_if_t<std::is_convertible<T, std::string>::value, detail::enabler> = detail::dummy>
1293auto to_string(T &&value) ->
decltype(std::forward<T>(value)) {
1294 return std::forward<T>(value);
1298template <
typename T,
1299 enable_if_t<std::is_constructible<std::string, T>::value &&
1300 !std::is_convertible<T, std::string>::value,
1301 detail::enabler> = detail::dummy>
1302std::string to_string(
const T &value) {
1303 return std::string(value);
1307template <
typename T,
1308 enable_if_t<!std::is_convertible<std::string, T>::value &&
1309 !std::is_constructible<std::string, T>::value && is_ostreamable<T>::value,
1310 detail::enabler> = detail::dummy>
1311std::string to_string(T &&value) {
1312 std::stringstream stream;
1314 return stream.str();
1319template <
typename T,
1320 enable_if_t<!std::is_constructible<std::string, T>::value && !is_ostreamable<T>::value &&
1322 detail::enabler> = detail::dummy>
1323std::string to_string(T &&) {
1328template <
typename T,
1329 enable_if_t<!std::is_constructible<std::string, T>::value && !is_ostreamable<T>::value &&
1331 detail::enabler> = detail::dummy>
1332std::string to_string(T &&variable) {
1333 auto cval = variable.begin();
1334 auto end = variable.end();
1338 std::vector<std::string> defaults;
1339 while (cval != end) {
1340 defaults.emplace_back(CLI::detail::to_string(*cval));
1343 return {
"[" + detail::join(defaults) +
"]"};
1347template <
typename T1,
1350 enable_if_t<std::is_same<T1, T2>::value, detail::enabler> = detail::dummy>
1351auto checked_to_string(T &&value) ->
decltype(to_string(std::forward<T>(value))) {
1352 return to_string(std::forward<T>(value));
1356template <
typename T1,
1359 enable_if_t<!std::is_same<T1, T2>::value, detail::enabler> = detail::dummy>
1360std::string checked_to_string(T &&) {
1361 return std::string{};
1364template <typename T, enable_if_t<std::is_arithmetic<T>::value, detail::enabler> = detail::dummy>
1365std::string value_string(
const T &value) {
1366 return std::to_string(value);
1369template <typename T, enable_if_t<std::is_enum<T>::value, detail::enabler> = detail::dummy>
1370std::string value_string(
const T &value) {
1371 return std::to_string(
static_cast<typename std::underlying_type<T>::type
>(value));
1374template <
typename T,
1375 enable_if_t<!std::is_enum<T>::value && !std::is_arithmetic<T>::value, detail::enabler> =
1377auto value_string(
const T &value) ->
decltype(to_string(value)) {
1378 return to_string(value);
1382template <
typename T,
typename def,
typename Enable =
void>
1388template <
typename T,
typename def>
1389struct wrapped_type<T, def, typename std::enable_if<is_wrapper<T>::value>::type> {
1390 using type =
typename T::value_type;
1394template <
typename T,
typename Enable =
void>
1396 static const int value{0};
1400template <
typename T>
1403 typename std::enable_if<!is_tuple_like<T>::value && !is_mutable_container<T>::value &&
1404 !std::is_void<T>::value>::type> {
1405 static constexpr int value{1};
1409template <
typename T>
1412 typename std::enable_if<is_tuple_like<T>::value && !is_mutable_container<T>::value>::type> {
1413 static constexpr int value{std::tuple_size<T>::value};
1417template <
typename T>
1419 static constexpr int value{type_count_base<typename T::value_type>::value};
1425template <
typename T>
1429template <
typename T>
1433template <
typename T,
typename Enable =
void>
1435 static const int value{0};
1439template <
typename T>
1441 typename std::enable_if<!is_wrapper<T>::value && !is_tuple_like<T>::value &&
1442 !is_complex<T>::value && !std::is_void<T>::value>::type> {
1443 static constexpr int value{1};
1447template <
typename T>
1448struct type_count<T, typename std::enable_if<is_complex<T>::value>::type> {
1449 static constexpr int value{2};
1454template <
typename T>
1455struct type_count<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1461template <
typename T>
1464 typename std::enable_if<is_wrapper<T>::value && !is_complex<T>::value &&
1465 !is_tuple_like<T>::value && !is_mutable_container<T>::value>::type> {
1466 static constexpr int value{type_count<typename T::value_type>::value};
1470template <
typename T, std::
size_t I>
1471constexpr typename std::enable_if<I == type_count_base<T>::value,
int>::type tuple_type_size() {
1476template <
typename T, std::
size_t I>
1477 constexpr typename std::enable_if < I<type_count_base<T>::value,
int>::type tuple_type_size() {
1478 return subtype_count<typename std::tuple_element<I, T>::type>::value +
1479 tuple_type_size<T, I + 1>();
1483template <
typename T>
1484struct type_count<T, typename std::enable_if<is_tuple_like<T>::value>::type> {
1485 static constexpr int value{tuple_type_size<T, 0>()};
1489template <
typename T>
1491 static constexpr int value{is_mutable_container<T>::value ? expected_max_vector_size
1492 : type_count<T>::value};
1496template <
typename T,
typename Enable =
void>
1497struct type_count_min {
1498 static const int value{0};
1502template <
typename T>
1503struct type_count_min<
1505 typename std::enable_if<!is_mutable_container<T>::value && !is_tuple_like<T>::value &&
1506 !is_wrapper<T>::value && !is_complex<T>::value &&
1507 !std::is_void<T>::value>::type> {
1508 static constexpr int value{type_count<T>::value};
1512template <
typename T>
1513struct type_count_min<T, typename std::enable_if<is_complex<T>::value>::type> {
1514 static constexpr int value{1};
1519template <
typename T>
1520struct type_count_min<T,
1521 typename std::enable_if<is_wrapper<T>::value && !is_complex<T>::value &&
1522 !is_tuple_like<T>::value>::type> {
1523 static constexpr int value{subtype_count_min<typename T::value_type>::value};
1527template <
typename T, std::
size_t I>
1528constexpr typename std::enable_if<I == type_count_base<T>::value,
int>::type tuple_type_size_min() {
1533template <
typename T, std::
size_t I>
1534 constexpr typename std::enable_if <
1535 I<type_count_base<T>::value,
int>::type tuple_type_size_min() {
1537 tuple_type_size_min<T, I + 1>();
1541template <
typename T>
1542struct type_count_min<T, typename std::enable_if<is_tuple_like<T>::value>::type> {
1543 static constexpr int value{tuple_type_size_min<T, 0>()};
1547template <
typename T>
1549 static constexpr int value{
1550 is_mutable_container<T>::value
1551 ? ((type_count<T>::value < expected_max_vector_size) ? type_count<T>::value : 0)
1552 : type_count_min<T>::value};
1556template <
typename T,
typename Enable =
void>
1557struct expected_count {
1558 static const int value{0};
1562template <
typename T>
1563struct expected_count<
1565 typename std::enable_if<!is_mutable_container<T>::value && !is_wrapper<T>::value &&
1566 !std::is_void<T>::value>::type> {
1567 static constexpr int value{1};
1570template <
typename T>
1571struct expected_count<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1572 static constexpr int value{expected_max_vector_size};
1576template <
typename T>
1577struct expected_count<
1579 typename std::enable_if<!is_mutable_container<T>::value && is_wrapper<T>::value>::type> {
1580 static constexpr int value{expected_count<typename T::value_type>::value};
1584enum class object_category :
int {
1587 unsigned_integral = 4,
1590 floating_point = 10,
1591 number_constructible = 12,
1592 double_constructible = 14,
1593 integer_constructible = 16,
1595 string_assignable = 23,
1596 string_constructible = 24,
1600 complex_number = 60,
1602 container_value = 80,
1609template <
typename T,
typename Enable =
void>
1610struct classify_object {
1611 static constexpr object_category value{object_category::other};
1615template <
typename T>
1616struct classify_object<
1618 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, char>::value &&
1619 std::is_signed<T>::value && !is_bool<T>::value &&
1620 !std::is_enum<T>::value>::type> {
1621 static constexpr object_category value{object_category::integral_value};
1625template <
typename T>
1626struct classify_object<
1628 typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value &&
1629 !std::is_same<T, char>::value && !is_bool<T>::value>::type> {
1630 static constexpr object_category value{object_category::unsigned_integral};
1634template <
typename T>
1635struct classify_object<
1637 typename std::enable_if<std::is_same<T, char>::value && !std::is_enum<T>::value>::type> {
1638 static constexpr object_category value{object_category::char_value};
1642template <
typename T>
1643struct classify_object<T, typename std::enable_if<is_bool<T>::value>::type> {
1644 static constexpr object_category value{object_category::boolean_value};
1648template <
typename T>
1649struct classify_object<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
1650 static constexpr object_category value{object_category::floating_point};
1654template <
typename T>
1655struct classify_object<
1657 typename std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1658 std::is_assignable<T &, std::string>::value>::type> {
1659 static constexpr object_category value{object_category::string_assignable};
1663template <
typename T>
1664struct classify_object<
1666 typename std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1667 !std::is_assignable<T &, std::string>::value &&
1668 (type_count<T>::value == 1) &&
1669 std::is_constructible<T, std::string>::value>::type> {
1670 static constexpr object_category value{object_category::string_constructible};
1674template <
typename T>
1675struct classify_object<T, typename std::enable_if<std::is_enum<T>::value>::type> {
1676 static constexpr object_category value{object_category::enumeration};
1679template <
typename T>
1680struct classify_object<T, typename std::enable_if<is_complex<T>::value>::type> {
1681 static constexpr object_category value{object_category::complex_number};
1686template <
typename T>
1687struct uncommon_type {
1688 using type =
typename std::conditional<
1689 !std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1690 !std::is_assignable<T &, std::string>::value &&
1691 !std::is_constructible<T, std::string>::value && !is_complex<T>::value &&
1692 !is_mutable_container<T>::value && !std::is_enum<T>::value,
1694 std::false_type>::type;
1695 static constexpr bool value = type::value;
1699template <
typename T>
1700struct classify_object<
1702 typename std::enable_if<(!is_mutable_container<T>::value && is_wrapper<T>::value &&
1703 !is_tuple_like<T>::value && uncommon_type<T>::value)>::type> {
1704 static constexpr object_category value{object_category::wrapper_value};
1708template <
typename T>
1709struct classify_object<
1711 typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1712 !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
1713 is_direct_constructible<T, int>::value>::type> {
1714 static constexpr object_category value{object_category::number_constructible};
1718template <
typename T>
1719struct classify_object<
1721 typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1722 !is_wrapper<T>::value && !is_direct_constructible<T, double>::value &&
1723 is_direct_constructible<T, int>::value>::type> {
1724 static constexpr object_category value{object_category::integer_constructible};
1728template <
typename T>
1729struct classify_object<
1731 typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1732 !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
1733 !is_direct_constructible<T, int>::value>::type> {
1734 static constexpr object_category value{object_category::double_constructible};
1738template <
typename T>
1739struct classify_object<
1741 typename std::enable_if<is_tuple_like<T>::value &&
1742 ((type_count<T>::value >= 2 && !is_wrapper<T>::value) ||
1743 (uncommon_type<T>::value &&
1744 !is_direct_constructible<T, double>::value &&
1745 !is_direct_constructible<T, int>::value) ||
1746 (uncommon_type<T>::value && type_count<T>::value >= 2))>::type> {
1747 static constexpr object_category value{object_category::tuple_value};
1757template <
typename T>
1758struct classify_object<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1759 static constexpr object_category value{object_category::container_value};
1768template <
typename T,
1769 enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> =
1771constexpr const char *type_name() {
1775template <
typename T,
1776 enable_if_t<classify_object<T>::value == object_category::integral_value ||
1777 classify_object<T>::value == object_category::integer_constructible,
1778 detail::enabler> = detail::dummy>
1779constexpr const char *type_name() {
1783template <
typename T,
1784 enable_if_t<classify_object<T>::value == object_category::unsigned_integral,
1785 detail::enabler> = detail::dummy>
1786constexpr const char *type_name() {
1790template <
typename T,
1791 enable_if_t<classify_object<T>::value == object_category::floating_point ||
1792 classify_object<T>::value == object_category::number_constructible ||
1793 classify_object<T>::value == object_category::double_constructible,
1794 detail::enabler> = detail::dummy>
1795constexpr const char *type_name() {
1800template <
typename T,
1801 enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> =
1803constexpr const char *type_name() {
1808template <
typename T,
1809 enable_if_t<classify_object<T>::value == object_category::boolean_value,
1810 detail::enabler> = detail::dummy>
1811constexpr const char *type_name() {
1816template <
typename T,
1817 enable_if_t<classify_object<T>::value == object_category::complex_number,
1818 detail::enabler> = detail::dummy>
1819constexpr const char *type_name() {
1824template <
typename T,
1825 enable_if_t<classify_object<T>::value >= object_category::string_assignable &&
1826 classify_object<T>::value <= object_category::other,
1827 detail::enabler> = detail::dummy>
1828constexpr const char *type_name() {
1832template <
typename T,
1833 enable_if_t<classify_object<T>::value == object_category::tuple_value &&
1834 type_count_base<T>::value >= 2,
1835 detail::enabler> = detail::dummy>
1836std::string type_name();
1839template <
typename T,
1840 enable_if_t<classify_object<T>::value == object_category::container_value ||
1841 classify_object<T>::value == object_category::wrapper_value,
1842 detail::enabler> = detail::dummy>
1843std::string type_name();
1846template <
typename T,
1847 enable_if_t<classify_object<T>::value == object_category::tuple_value &&
1848 type_count_base<T>::value == 1,
1849 detail::enabler> = detail::dummy>
1850inline std::string type_name() {
1851 return type_name<typename std::decay<typename std::tuple_element<0, T>::type>::type>();
1855template <
typename T, std::
size_t I>
1856inline typename std::enable_if<I == type_count_base<T>::value, std::string>::type tuple_name() {
1857 return std::string{};
1861template <
typename T, std::
size_t I>
1862inline typename std::enable_if<(I < type_count_base<T>::value), std::string>::type tuple_name() {
1865 type_name<typename std::decay<typename std::tuple_element<I, T>::type>::type>()} +
1866 ',' + tuple_name<T, I + 1>();
1867 if (str.back() ==
',') str.pop_back();
1872template <
typename T,
1873 enable_if_t<classify_object<T>::value == object_category::tuple_value &&
1874 type_count_base<T>::value >= 2,
1876inline std::string type_name() {
1877 auto tname = std::string(1,
'[') + tuple_name<T, 0>();
1878 tname.push_back(
']');
1883template <
typename T,
1884 enable_if_t<classify_object<T>::value == object_category::container_value ||
1885 classify_object<T>::value == object_category::wrapper_value,
1887inline std::string type_name() {
1888 return type_name<typename T::value_type>();
1894template <typename T, enable_if_t<std::is_unsigned<T>::value, detail::enabler> = detail::dummy>
1895bool integral_conversion(
const std::string &input, T &output)
noexcept {
1896 if (input.empty()) {
1899 char *val =
nullptr;
1900 std::uint64_t output_ll = std::strtoull(input.c_str(), &val, 0);
1901 output =
static_cast<T
>(output_ll);
1902 if (val == (input.c_str() + input.size()) &&
static_cast<std::uint64_t
>(output) == output_ll) {
1906 std::int64_t output_sll = std::strtoll(input.c_str(), &val, 0);
1907 if (val == (input.c_str() + input.size())) {
1908 output = (output_sll < 0) ? static_cast<T>(0) : static_cast<T>(output_sll);
1909 return (
static_cast<std::int64_t
>(output) == output_sll);
1915template <typename T, enable_if_t<std::is_signed<T>::value, detail::enabler> = detail::dummy>
1916bool integral_conversion(
const std::string &input, T &output)
noexcept {
1917 if (input.empty()) {
1920 char *val =
nullptr;
1921 std::int64_t output_ll = std::strtoll(input.c_str(), &val, 0);
1922 output =
static_cast<T
>(output_ll);
1923 if (val == (input.c_str() + input.size()) &&
static_cast<std::int64_t
>(output) == output_ll) {
1926 if (input ==
"true") {
1928 output =
static_cast<T
>(1);
1935inline std::int64_t to_flag_value(std::string val) {
1936 static const std::string trueString(
"true");
1937 static const std::string falseString(
"false");
1938 if (val == trueString) {
1941 if (val == falseString) {
1944 val = detail::to_lower(val);
1945 std::int64_t ret = 0;
1946 if (val.size() == 1) {
1947 if (val[0] >=
'1' && val[0] <=
'9') {
1948 return (
static_cast<std::int64_t
>(val[0]) -
'0');
1963 throw std::invalid_argument(
"unrecognized character");
1967 if (val == trueString || val ==
"on" || val ==
"yes" || val ==
"enable") {
1969 }
else if (val == falseString || val ==
"off" || val ==
"no" || val ==
"disable") {
1972 ret = std::stoll(val);
1978template <
typename T,
1979 enable_if_t<classify_object<T>::value == object_category::integral_value ||
1980 classify_object<T>::value == object_category::unsigned_integral,
1981 detail::enabler> = detail::dummy>
1982bool lexical_cast(
const std::string &input, T &output) {
1983 return integral_conversion(input, output);
1987template <
typename T,
1988 enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> =
1990bool lexical_cast(
const std::string &input, T &output) {
1991 if (input.size() == 1) {
1992 output =
static_cast<T
>(input[0]);
1995 return integral_conversion(input, output);
1999template <
typename T,
2000 enable_if_t<classify_object<T>::value == object_category::boolean_value,
2001 detail::enabler> = detail::dummy>
2002bool lexical_cast(
const std::string &input, T &output) {
2004 auto out = to_flag_value(input);
2007 }
catch (
const std::invalid_argument &) {
2009 }
catch (
const std::out_of_range &) {
2012 output = (input[0] !=
'-');
2018template <
typename T,
2019 enable_if_t<classify_object<T>::value == object_category::floating_point,
2020 detail::enabler> = detail::dummy>
2021bool lexical_cast(
const std::string &input, T &output) {
2022 if (input.empty()) {
2025 char *val =
nullptr;
2026 auto output_ld = std::strtold(input.c_str(), &val);
2027 output =
static_cast<T
>(output_ld);
2028 return val == (input.c_str() + input.size());
2032template <
typename T,
2033 enable_if_t<classify_object<T>::value == object_category::complex_number,
2034 detail::enabler> = detail::dummy>
2035bool lexical_cast(
const std::string &input, T &output) {
2036 using XC =
typename wrapped_type<T, double>::type;
2039 bool worked =
false;
2040 auto nloc = str1.find_last_of(
"+-");
2041 if (nloc != std::string::npos && nloc > 0) {
2042 worked = detail::lexical_cast(str1.substr(0, nloc), x);
2043 str1 = str1.substr(nloc);
2044 if (str1.back() ==
'i' || str1.back() ==
'j') str1.pop_back();
2045 worked = worked && detail::lexical_cast(str1, y);
2047 if (str1.back() ==
'i' || str1.back() ==
'j') {
2049 worked = detail::lexical_cast(str1, y);
2052 worked = detail::lexical_cast(str1, x);
2060 return from_stream(input, output);
2064template <
typename T,
2065 enable_if_t<classify_object<T>::value == object_category::string_assignable,
2066 detail::enabler> = detail::dummy>
2067bool lexical_cast(
const std::string &input, T &output) {
2073template <
typename T,
2074 enable_if_t<classify_object<T>::value == object_category::string_constructible,
2075 detail::enabler> = detail::dummy>
2076bool lexical_cast(
const std::string &input, T &output) {
2082template <
typename T,
2083 enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> =
2085bool lexical_cast(
const std::string &input, T &output) {
2086 typename std::underlying_type<T>::type val;
2087 if (!integral_conversion(input, val)) {
2090 output =
static_cast<T
>(val);
2095template <
typename T,
2096 enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
2097 std::is_assignable<T &, typename T::value_type>::value,
2098 detail::enabler> = detail::dummy>
2099bool lexical_cast(
const std::string &input, T &output) {
2100 typename T::value_type val;
2101 if (lexical_cast(input, val)) {
2105 return from_stream(input, output);
2108template <
typename T,
2109 enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
2110 !std::is_assignable<T &, typename T::value_type>::value &&
2111 std::is_assignable<T &, T>::value,
2112 detail::enabler> = detail::dummy>
2113bool lexical_cast(
const std::string &input, T &output) {
2114 typename T::value_type val;
2115 if (lexical_cast(input, val)) {
2119 return from_stream(input, output);
2123template <
typename T,
2124 enable_if_t<classify_object<T>::value == object_category::number_constructible,
2125 detail::enabler> = detail::dummy>
2126bool lexical_cast(
const std::string &input, T &output) {
2128 if (integral_conversion(input, val)) {
2134 if (lexical_cast(input, dval)) {
2139 return from_stream(input, output);
2143template <
typename T,
2144 enable_if_t<classify_object<T>::value == object_category::integer_constructible,
2145 detail::enabler> = detail::dummy>
2146bool lexical_cast(
const std::string &input, T &output) {
2148 if (integral_conversion(input, val)) {
2152 return from_stream(input, output);
2156template <
typename T,
2157 enable_if_t<classify_object<T>::value == object_category::double_constructible,
2158 detail::enabler> = detail::dummy>
2159bool lexical_cast(
const std::string &input, T &output) {
2161 if (lexical_cast(input, val)) {
2165 return from_stream(input, output);
2169template <
typename T,
2170 enable_if_t<classify_object<T>::value == object_category::other &&
2171 std::is_assignable<T &, int>::value,
2172 detail::enabler> = detail::dummy>
2173bool lexical_cast(
const std::string &input, T &output) {
2175 if (integral_conversion(input, val)) {
2177#pragma warning(push)
2178#pragma warning(disable : 4800)
2191 return from_stream(input, output);
2196template <
typename T,
2197 enable_if_t<classify_object<T>::value == object_category::other &&
2198 !std::is_assignable<T &, int>::value,
2199 detail::enabler> = detail::dummy>
2200bool lexical_cast(
const std::string &input, T &output) {
2201 static_assert(is_istreamable<T>::value,
2202 "option object type must have a lexical cast overload or streaming input "
2203 "operator(>>) defined, if it "
2204 "is convertible from another type use the add_option<T, XC>(...) with XC being "
2206 return from_stream(input, output);
2214 enable_if_t<std::is_same<AssignTo, ConvertTo>::value &&
2215 (classify_object<AssignTo>::value == object_category::string_assignable ||
2216 classify_object<AssignTo>::value == object_category::string_constructible),
2217 detail::enabler> = detail::dummy>
2218bool lexical_assign(
const std::string &input, AssignTo &output) {
2219 return lexical_cast(input, output);
2223template <
typename AssignTo,
2225 enable_if_t<std::is_same<AssignTo, ConvertTo>::value &&
2226 std::is_assignable<AssignTo &, AssignTo>::value &&
2227 classify_object<AssignTo>::value != object_category::string_assignable &&
2228 classify_object<AssignTo>::value != object_category::string_constructible,
2229 detail::enabler> = detail::dummy>
2230bool lexical_assign(
const std::string &input, AssignTo &output) {
2231 if (input.empty()) {
2232 output = AssignTo{};
2236 return lexical_cast(input, output);
2240template <
typename AssignTo,
2242 enable_if_t<std::is_same<AssignTo, ConvertTo>::value &&
2243 !std::is_assignable<AssignTo &, AssignTo>::value &&
2244 classify_object<AssignTo>::value == object_category::wrapper_value,
2245 detail::enabler> = detail::dummy>
2246bool lexical_assign(
const std::string &input, AssignTo &output) {
2247 if (input.empty()) {
2248 typename AssignTo::value_type emptyVal{};
2252 return lexical_cast(input, output);
2257template <
typename AssignTo,
2259 enable_if_t<std::is_same<AssignTo, ConvertTo>::value &&
2260 !std::is_assignable<AssignTo &, AssignTo>::value &&
2261 classify_object<AssignTo>::value != object_category::wrapper_value &&
2262 std::is_assignable<AssignTo &, int>::value,
2263 detail::enabler> = detail::dummy>
2264bool lexical_assign(
const std::string &input, AssignTo &output) {
2265 if (input.empty()) {
2270 if (lexical_cast(input, val)) {
2278template <
typename AssignTo,
2280 enable_if_t<!std::is_same<AssignTo, ConvertTo>::value &&
2281 std::is_assignable<AssignTo &, ConvertTo &>::value,
2282 detail::enabler> = detail::dummy>
2283bool lexical_assign(
const std::string &input, AssignTo &output) {
2285 bool parse_result = (!input.empty()) ? lexical_cast<ConvertTo>(input, val) : true;
2289 return parse_result;
2293template <
typename AssignTo,
2295 enable_if_t<!std::is_same<AssignTo, ConvertTo>::value &&
2296 !std::is_assignable<AssignTo &, ConvertTo &>::value &&
2297 std::is_move_assignable<AssignTo>::value,
2298 detail::enabler> = detail::dummy>
2299bool lexical_assign(
const std::string &input, AssignTo &output) {
2301 bool parse_result = input.empty() ? true : lexical_cast<ConvertTo>(input, val);
2303 output = AssignTo(val);
2305 return parse_result;
2309template <
typename AssignTo,
2311 enable_if_t<classify_object<ConvertTo>::value <= object_category::other &&
2312 classify_object<AssignTo>::value <= object_category::wrapper_value,
2313 detail::enabler> = detail::dummy>
2314bool lexical_conversion(
const std::vector<std ::string> &strings, AssignTo &output) {
2315 return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2320template <
typename AssignTo,
2322 enable_if_t<(type_count<AssignTo>::value <= 2) && expected_count<AssignTo>::value == 1 &&
2323 is_tuple_like<ConvertTo>::value && type_count_base<ConvertTo>::value == 2,
2324 detail::enabler> = detail::dummy>
2325bool lexical_conversion(
const std::vector<std ::string> &strings, AssignTo &output) {
2327 typename std::remove_const<typename std::tuple_element<0, ConvertTo>::type>::type v1;
2328 typename std::tuple_element<1, ConvertTo>::type v2;
2329 bool retval = lexical_assign<decltype(v1), decltype(v1)>(strings[0], v1);
2330 if (strings.size() > 1) {
2331 retval = retval && lexical_assign<decltype(v2), decltype(v2)>(strings[1], v2);
2334 output = AssignTo{v1, v2};
2343 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2344 type_count<ConvertTo>::value == 1,
2345 detail::enabler> = detail::dummy>
2346bool lexical_conversion(
const std::vector<std ::string> &strings, AssignTo &output) {
2347 output.erase(output.begin(), output.end());
2348 if (strings.size() == 1 && strings[0] ==
"{}") {
2351 bool skip_remaining =
false;
2352 if (strings.size() == 2 && strings[0] ==
"{}" && is_separator(strings[1])) {
2353 skip_remaining =
true;
2355 for (
const auto &elem : strings) {
2356 typename AssignTo::value_type out;
2357 bool retval = lexical_assign<typename AssignTo::value_type, typename ConvertTo::value_type>(
2362 output.insert(output.end(), std::move(out));
2363 if (skip_remaining) {
2367 return (!output.empty());
2371template <
class AssignTo,
2373 enable_if_t<is_complex<ConvertTo>::value, detail::enabler> = detail::dummy>
2374bool lexical_conversion(
const std::vector<std::string> &strings, AssignTo &output) {
2375 if (strings.size() >= 2 && !strings[1].empty()) {
2376 using XC2 =
typename wrapped_type<ConvertTo, double>::type;
2378 auto str1 = strings[1];
2379 if (str1.back() ==
'i' || str1.back() ==
'j') {
2382 auto worked = detail::lexical_cast(strings[0], x) && detail::lexical_cast(str1, y);
2384 output = ConvertTo{x, y};
2388 return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2395 enable_if_t<is_mutable_container<AssignTo>::value && (expected_count<ConvertTo>::value == 1) &&
2396 (type_count<ConvertTo>::value == 1),
2397 detail::enabler> = detail::dummy>
2398bool lexical_conversion(
const std::vector<std ::string> &strings, AssignTo &output) {
2401 output.reserve(strings.size());
2402 for (
const auto &elem : strings) {
2403 output.emplace_back();
2405 retval && lexical_assign<typename AssignTo::value_type, ConvertTo>(elem, output.back());
2407 return (!output.empty()) && retval;
2416 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2417 type_count_base<ConvertTo>::value == 2,
2418 detail::enabler> = detail::dummy>
2419bool lexical_conversion(std::vector<std::string> strings, AssignTo &output);
2425 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2426 type_count_base<ConvertTo>::value != 2 &&
2427 ((type_count<ConvertTo>::value > 2) ||
2428 (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
2429 detail::enabler> = detail::dummy>
2430bool lexical_conversion(
const std::vector<std::string> &strings, AssignTo &output);
2433template <
class AssignTo,
2435 enable_if_t<is_tuple_like<AssignTo>::value && is_tuple_like<ConvertTo>::value &&
2436 (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2437 type_count<ConvertTo>::value > 2),
2438 detail::enabler> = detail::dummy>
2439bool lexical_conversion(
const std::vector<std::string> &strings,
2447 enable_if_t<!is_tuple_like<AssignTo>::value && !is_mutable_container<AssignTo>::value &&
2448 classify_object<ConvertTo>::value != object_category::wrapper_value &&
2449 (is_mutable_container<ConvertTo>::value || type_count<ConvertTo>::value > 2),
2450 detail::enabler> = detail::dummy>
2451bool lexical_conversion(
const std::vector<std ::string> &strings, AssignTo &output) {
2452 if (strings.size() > 1 || (!strings.empty() && !(strings.front().empty()))) {
2454 auto retval = lexical_conversion<ConvertTo, ConvertTo>(strings, val);
2455 output = AssignTo{val};
2458 output = AssignTo{};
2463template <
class AssignTo,
class ConvertTo, std::
size_t I>
2464inline typename std::enable_if<(I >= type_count_base<AssignTo>::value),
bool>::type
2465tuple_conversion(
const std::vector<std::string> &, AssignTo &) {
2470template <
class AssignTo,
class ConvertTo>
2471inline typename std::enable_if<!is_mutable_container<ConvertTo>::value &&
2472 type_count<ConvertTo>::value == 1,
2474tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2475 auto retval = lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2476 strings.erase(strings.begin());
2482template <
class AssignTo,
class ConvertTo>
2483inline typename std::enable_if<!is_mutable_container<ConvertTo>::value &&
2484 (type_count<ConvertTo>::value > 1) &&
2485 type_count<ConvertTo>::value == type_count_min<ConvertTo>::value,
2487tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2488 auto retval = lexical_conversion<AssignTo, ConvertTo>(strings, output);
2489 strings.erase(strings.begin(), strings.begin() + type_count<ConvertTo>::value);
2495template <
class AssignTo,
class ConvertTo>
2496inline typename std::enable_if<is_mutable_container<ConvertTo>::value ||
2497 type_count<ConvertTo>::value != type_count_min<ConvertTo>::value,
2499tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2500 std::size_t index{subtype_count_min<ConvertTo>::value};
2501 const std::size_t mx_count{subtype_count<ConvertTo>::value};
2502 const std::size_t mx{(std::max)(mx_count, strings.size())};
2504 while (index < mx) {
2505 if (is_separator(strings[index])) {
2510 bool retval = lexical_conversion<AssignTo, ConvertTo>(
2511 std::vector<std::string>(strings.begin(),
2512 strings.begin() +
static_cast<std::ptrdiff_t
>(index)),
2514 strings.erase(strings.begin(), strings.begin() +
static_cast<std::ptrdiff_t
>(index) + 1);
2519template <
class AssignTo,
class ConvertTo, std::
size_t I>
2520inline typename std::enable_if<(I < type_count_base<AssignTo>::value),
bool>::type tuple_conversion(
2521 std::vector<std::string> strings, AssignTo &output) {
2523 using ConvertToElement =
2524 typename std::conditional<is_tuple_like<ConvertTo>::value,
2525 typename std::tuple_element<I, ConvertTo>::type, ConvertTo>::type;
2526 if (!strings.empty()) {
2529 tuple_type_conversion<typename std::tuple_element<I, AssignTo>::type, ConvertToElement>(
2530 strings, std::get<I>(output));
2532 retval = retval && tuple_conversion<AssignTo, ConvertTo, I + 1>(std::move(strings), output);
2540 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2541 type_count_base<ConvertTo>::value == 2,
2543bool lexical_conversion(std::vector<std::string> strings, AssignTo &output) {
2545 while (!strings.empty()) {
2546 typename std::remove_const<
2547 typename std::tuple_element<0, typename ConvertTo::value_type>::type>::type v1;
2548 typename std::tuple_element<1, typename ConvertTo::value_type>::type v2;
2549 bool retval = tuple_type_conversion<decltype(v1), decltype(v1)>(strings, v1);
2550 if (!strings.empty()) {
2551 retval = retval && tuple_type_conversion<decltype(v2), decltype(v2)>(strings, v2);
2554 output.insert(output.end(),
typename AssignTo::value_type{v1, v2});
2559 return (!output.empty());
2564template <
class AssignTo,
2566 enable_if_t<is_tuple_like<AssignTo>::value && is_tuple_like<ConvertTo>::value &&
2567 (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2568 type_count<ConvertTo>::value > 2),
2570bool lexical_conversion(
const std::vector<std ::string> &strings, AssignTo &output) {
2571 static_assert(!is_tuple_like<ConvertTo>::value ||
2572 type_count_base<AssignTo>::value == type_count_base<ConvertTo>::value,
2573 "if the conversion type is defined as a tuple it must be the same size as the "
2574 "type you are converting to");
2575 return tuple_conversion<AssignTo, ConvertTo, 0>(strings, output);
2583 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2584 type_count_base<ConvertTo>::value != 2 &&
2585 ((type_count<ConvertTo>::value > 2) ||
2586 (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
2588bool lexical_conversion(
const std::vector<std ::string> &strings, AssignTo &output) {
2591 std::vector<std::string> temp;
2593 std::size_t icount{0};
2594 std::size_t xcm{type_count<ConvertTo>::value};
2595 auto ii_max = strings.size();
2596 while (ii < ii_max) {
2597 temp.push_back(strings[ii]);
2600 if (icount == xcm || is_separator(temp.back()) || ii == ii_max) {
2601 if (
static_cast<int>(xcm) > type_count_min<ConvertTo>::value &&
2602 is_separator(temp.back())) {
2605 typename AssignTo::value_type temp_out;
2608 lexical_conversion<typename AssignTo::value_type, typename ConvertTo::value_type>(
2614 output.insert(output.end(), std::move(temp_out));
2622template <
typename AssignTo,
2624 enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2625 std::is_assignable<ConvertTo &, ConvertTo>::value,
2626 detail::enabler> = detail::dummy>
2627bool lexical_conversion(
const std::vector<std::string> &strings, AssignTo &output) {
2628 if (strings.empty() || strings.front().empty()) {
2629 output = ConvertTo{};
2632 typename ConvertTo::value_type val;
2633 if (lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings,
2635 output = ConvertTo{val};
2642template <
typename AssignTo,
2644 enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2645 !std::is_assignable<AssignTo &, ConvertTo>::value,
2646 detail::enabler> = detail::dummy>
2647bool lexical_conversion(
const std::vector<std::string> &strings, AssignTo &output) {
2648 using ConvertType =
typename ConvertTo::value_type;
2649 if (strings.empty() || strings.front().empty()) {
2650 output = ConvertType{};
2654 if (lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings,
2663inline std::string sum_string_vector(
const std::vector<std::string> &values) {
2667 for (
const auto &arg : values) {
2669 auto comp = detail::lexical_cast<double>(arg, tv);
2672 tv =
static_cast<double>(detail::to_flag_value(arg));
2673 }
catch (
const std::exception &) {
2681 for (
const auto &arg : values) {
2685 if (val <=
static_cast<double>((std::numeric_limits<std::int64_t>::min)()) ||
2686 val >=
static_cast<double>((std::numeric_limits<std::int64_t>::max)()) ||
2688 val ==
static_cast<std::int64_t
>(val)) {
2689 output = detail::value_string(
static_cast<int64_t
>(val));
2691 output = detail::value_string(val);
2702CLI11_INLINE
bool split_short(
const std::string ¤t, std::string &name, std::string &rest);
2705CLI11_INLINE
bool split_long(
const std::string ¤t, std::string &name, std::string &value);
2708CLI11_INLINE
bool split_windows_style(
const std::string ¤t,
2710 std::string &value);
2713CLI11_INLINE std::vector<std::string> split_names(std::string current);
2716CLI11_INLINE std::vector<std::pair<std::string, std::string>> get_default_flag_values(
2717 const std::string &str);
2720CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string> get_names(
2721 const std::vector<std::string> &input);
2727CLI11_INLINE
bool split_short(
const std::string ¤t, std::string &name, std::string &rest) {
2728 if (current.size() > 1 && current[0] ==
'-' && valid_first_char(current[1])) {
2729 name = current.substr(1, 1);
2730 rest = current.substr(2);
2736CLI11_INLINE
bool split_long(
const std::string ¤t, std::string &name, std::string &value) {
2737 if (current.size() > 2 && current.substr(0, 2) ==
"--" && valid_first_char(current[2])) {
2738 auto loc = current.find_first_of(
'=');
2739 if (loc != std::string::npos) {
2740 name = current.substr(2, loc - 2);
2741 value = current.substr(loc + 1);
2743 name = current.substr(2);
2751CLI11_INLINE
bool split_windows_style(
const std::string ¤t,
2753 std::string &value) {
2754 if (current.size() > 1 && current[0] ==
'/' && valid_first_char(current[1])) {
2755 auto loc = current.find_first_of(
':');
2756 if (loc != std::string::npos) {
2757 name = current.substr(1, loc - 1);
2758 value = current.substr(loc + 1);
2760 name = current.substr(1);
2768CLI11_INLINE std::vector<std::string> split_names(std::string current) {
2769 std::vector<std::string> output;
2770 std::size_t val = 0;
2771 while ((val = current.find(
',')) != std::string::npos) {
2772 output.push_back(trim_copy(current.substr(0, val)));
2773 current = current.substr(val + 1);
2775 output.push_back(trim_copy(current));
2779CLI11_INLINE std::vector<std::pair<std::string, std::string>> get_default_flag_values(
2780 const std::string &str) {
2781 std::vector<std::string> flags = split_names(str);
2782 flags.erase(std::remove_if(flags.begin(), flags.end(),
2783 [](
const std::string &name) {
2784 return ((name.empty()) ||
2785 (!(((name.find_first_of(
'{') != std::string::npos) &&
2786 (name.back() ==
'}')) ||
2787 (name[0] ==
'!'))));
2790 std::vector<std::pair<std::string, std::string>> output;
2791 output.reserve(flags.size());
2792 for (
auto &flag : flags) {
2793 auto def_start = flag.find_first_of(
'{');
2794 std::string defval =
"false";
2795 if ((def_start != std::string::npos) && (flag.back() ==
'}')) {
2796 defval = flag.substr(def_start + 1);
2798 flag.erase(def_start,
2801 flag.erase(0, flag.find_first_not_of(
"-!"));
2802 output.emplace_back(flag, defval);
2807CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string> get_names(
2808 const std::vector<std::string> &input) {
2809 std::vector<std::string> short_names;
2810 std::vector<std::string> long_names;
2811 std::string pos_name;
2813 for (std::string name : input) {
2814 if (name.length() == 0) {
2817 if (name.length() > 1 && name[0] ==
'-' && name[1] !=
'-') {
2818 if (name.length() == 2 && valid_first_char(name[1]))
2819 short_names.emplace_back(1, name[1]);
2821 throw BadNameString::OneCharName(name);
2822 }
else if (name.length() > 2 && name.substr(0, 2) ==
"--") {
2823 name = name.substr(2);
2824 if (valid_name_string(name))
2825 long_names.push_back(name);
2827 throw BadNameString::BadLongName(name);
2828 }
else if (name ==
"-" || name ==
"--") {
2829 throw BadNameString::DashesOnly(name);
2831 if (pos_name.length() > 0)
throw BadNameString::MultiPositionalNames(name);
2836 return std::make_tuple(short_names, long_names, pos_name);
2856 std::vector<std::string> tmp =
parents;
2857 tmp.emplace_back(
name);
2858 return detail::join(tmp,
".");
2865 std::vector<ConfigItem> items{};
2869 virtual std::string
to_config(
const App *,
bool,
bool, std::string)
const = 0;
2872 virtual std::vector<ConfigItem>
from_config(std::istream &)
const = 0;
2876 if (item.
inputs.size() == 1) {
2877 return item.
inputs.at(0);
2879 if (item.
inputs.empty()) {
2882 throw ConversionError::TooManyInputsFlag(item.
fullname());
2886 CLI11_NODISCARD std::vector<ConfigItem>
from_file(
const std::string &name)
const {
2887 std::ifstream input{name};
2888 if (!input.good())
throw FileError::Missing(name);
2924 std::string to_config(
const App * ,
2926 bool write_description,
2927 std::string prefix)
const override;
2929 std::vector<ConfigItem> from_config(std::istream &input)
const override;
2989using ConfigTOML = ConfigBase;
2992class ConfigINI :
public ConfigTOML {
3022 std::function<std::string(std::string &)>
func_{[](std::string &) {
return std::string{}; }};
3032 Validator(std::string validator_desc, std::function<std::string(std::string &)> func)
3033 : desc_function_([validator_desc]() {
return validator_desc; }), func_(std::move(func)) {}
3036 Validator() =
default;
3039 :
desc_function_([validator_desc]() {
return validator_desc; }) {}
3042 std::string validator_desc,
3043 std::string validator_name =
"")
3045 func_(std::move(op)),
3046 name_(std::move(validator_name)) {}
3048 Validator &
operation(std::function<std::string(std::string &)> op) {
3049 func_ = std::move(op);
3054 std::string operator()(std::string &str)
const;
3059 std::string value = str;
3069 CLI11_NODISCARD
Validator description(std::string validator_desc)
const;
3076 return std::string{};
3079 Validator &
name(std::string validator_name) {
3080 name_ = std::move(validator_name);
3084 CLI11_NODISCARD Validator
name(std::string validator_name)
const {
3085 Validator newval(*
this);
3086 newval.
name_ = std::move(validator_name);
3097 CLI11_NODISCARD Validator
active(
bool active_val =
true)
const {
3098 Validator newval(*
this);
3115 Validator newval(*
this);
3140 void _merge_description(
const Validator &val1,
3142 const std::string &merger);
3155enum class path_type { nonexistent, file, directory };
3158CLI11_INLINE path_type check_path(
const char *file)
noexcept;
3161class ExistingFileValidator :
public Validator {
3163 ExistingFileValidator();
3167class ExistingDirectoryValidator :
public Validator {
3169 ExistingDirectoryValidator();
3173class ExistingPathValidator :
public Validator {
3175 ExistingPathValidator();
3179class NonexistentPathValidator :
public Validator {
3181 NonexistentPathValidator();
3185class IPV4Validator :
public Validator {
3210template <
typename DesiredType>
3211class TypeValidator :
public Validator {
3213 explicit TypeValidator(
const std::string &validator_name)
3214 : Validator(validator_name, [](std::string &input_string) {
3215 auto val = DesiredType();
3216 if (!detail::lexical_cast(input_string, val)) {
3217 return std::string(
"Failed parsing ") + input_string +
" as a " +
3218 detail::type_name<DesiredType>();
3220 return std::string();
3222 TypeValidator() : TypeValidator(detail::type_name<DesiredType>()) {}
3230class FileOnDefaultPath :
public Validator {
3232 explicit FileOnDefaultPath(std::string default_path,
bool enableErrorReturn =
true);
3242 template <
typename T>
3243 Range(T min_val, T max_val,
const std::string &validator_name = std::string{})
3245 if (validator_name.empty()) {
3246 std::stringstream out;
3247 out << detail::type_name<T>() <<
" in [" << min_val <<
" - " << max_val <<
"]";
3248 description(out.str());
3251 func_ = [min_val, max_val](std::string &input) {
3253 bool converted = detail::lexical_cast(input, val);
3254 if ((!converted) || (val < min_val || val > max_val)) {
3255 std::stringstream out;
3256 out <<
"Value " << input <<
" not in range [";
3257 out << min_val <<
" - " << max_val <<
"]";
3260 return std::string{};
3265 template <
typename T>
3266 explicit Range(T max_val,
const std::string &validator_name = std::string{})
3267 :
Range(static_cast<T>(0), max_val, validator_name) {}
3271const Range NonNegativeNumber((std::numeric_limits<double>::max)(),
"NONNEGATIVE");
3275const Range PositiveNumber((std::numeric_limits<double>::min)(),
3276 (std::numeric_limits<double>::max)(),
3286 template <
typename T>
3288 std::stringstream out;
3289 out << detail::type_name<T>() <<
" bounded to [" << min_val <<
" - " << max_val <<
"]";
3292 func_ = [min_val, max_val](std::string &input) {
3294 bool converted = detail::lexical_cast(input, val);
3296 return std::string(
"Value ") + input +
" could not be converted";
3299 input = detail::to_string(min_val);
3300 else if (val > max_val)
3301 input = detail::to_string(max_val);
3303 return std::string{};
3308 template <
typename T>
3313template <
typename T,
3314 enable_if_t<is_copyable_ptr<typename std::remove_reference<T>::type>::value,
3315 detail::enabler> = detail::dummy>
3316auto smart_deref(T value) ->
decltype(*value) {
3320template <
typename T,
3321 enable_if_t<!is_copyable_ptr<typename std::remove_reference<T>::type>::value,
3322 detail::enabler> = detail::dummy>
3323typename std::remove_reference<T>::type &smart_deref(T &value) {
3327template <
typename T>
3328std::string generate_set(
const T &set) {
3329 using element_t =
typename detail::element_type<T>::type;
3330 using iteration_type_t =
3331 typename detail::pair_adaptor<element_t>::value_type;
3332 std::string out(1,
'{');
3333 out.append(detail::join(
3334 detail::smart_deref(set),
3341template <
typename T>
3342std::string generate_map(
const T &map,
bool key_only =
false) {
3343 using element_t =
typename detail::element_type<T>::type;
3344 using iteration_type_t =
3345 typename detail::pair_adaptor<element_t>::value_type;
3346 std::string out(1,
'{');
3347 out.append(detail::join(
3348 detail::smart_deref(map),
3349 [key_only](
const iteration_type_t &v) {
3363template <
typename C,
typename V>
3365 template <
typename CC,
typename VV>
3366 static auto test(
int)
3367 ->
decltype(std::declval<CC>().find(std::declval<VV>()), std::true_type());
3368 template <
typename,
typename>
3369 static auto test(...) ->
decltype(std::false_type());
3371 static const auto value =
decltype(test<C, V>(0))::value;
3372 using type = std::integral_constant<bool, value>;
3376template <
typename T,
3378 enable_if_t<!has_find<T, V>::value, detail::enabler> = detail::dummy>
3379auto search(
const T &set,
const V &val)
3380 -> std::pair<bool,
decltype(std::begin(detail::smart_deref(set)))> {
3381 using element_t =
typename detail::element_type<T>::type;
3382 auto &setref = detail::smart_deref(set);
3384 std::find_if(std::begin(setref), std::end(setref), [&val](
decltype(*std::begin(setref)) v) {
3387 return {(it != std::end(setref)), it};
3391template <
typename T,
3393 enable_if_t<has_find<T, V>::value, detail::enabler> = detail::dummy>
3394auto search(
const T &set,
const V &val)
3395 -> std::pair<bool,
decltype(std::begin(detail::smart_deref(set)))> {
3396 auto &setref = detail::smart_deref(set);
3397 auto it = setref.find(val);
3398 return {(it != std::end(setref)), it};
3402template <
typename T,
typename V>
3403auto search(
const T &set,
const V &val,
const std::function<V(V)> &filter_function)
3404 -> std::pair<bool,
decltype(std::begin(detail::smart_deref(set)))> {
3405 using element_t =
typename detail::element_type<T>::type;
3407 auto res = search(set, val);
3408 if ((res.first) || (!(filter_function))) {
3412 auto &setref = detail::smart_deref(set);
3414 std::find_if(std::begin(setref), std::end(setref), [&](
decltype(*std::begin(setref)) v) {
3416 a = filter_function(a);
3419 return {(it != std::end(setref)), it};
3426template <
typename T>
3427inline typename std::enable_if<std::is_signed<T>::value, T>::type overflowCheck(
const T &a,
3429 if ((a > 0) == (b > 0)) {
3430 return ((std::numeric_limits<T>::max)() / (std::abs)(a) < (std::abs)(b));
3432 return ((std::numeric_limits<T>::min)() / (std::abs)(a) > -(std::abs)(b));
3435template <
typename T>
3436inline typename std::enable_if<!std::is_signed<T>::value, T>::type overflowCheck(
const T &a,
3438 return ((std::numeric_limits<T>::max)() / a < b);
3442template <
typename T>
3443typename std::enable_if<std::is_integral<T>::value,
bool>::type checked_multiply(T &a, T b) {
3444 if (a == 0 || b == 0 || a == 1 || b == 1) {
3448 if (a == (std::numeric_limits<T>::min)() || b == (std::numeric_limits<T>::min)()) {
3451 if (overflowCheck(a, b)) {
3459template <
typename T>
3460typename std::enable_if<std::is_floating_point<T>::value,
bool>::type checked_multiply(T &a, T b) {
3462 if (std::isinf(c) && !std::isinf(a) && !std::isinf(b)) {
3473 using filter_fn_t = std::function<std::string(std::string)>;
3476 template <
typename T,
typename... Args>
3477 IsMember(std::initializer_list<T> values, Args &&...args)
3478 :
IsMember(std::vector<T>(values), std::forward<Args>(args)...) {}
3481 template <
typename T>
3486 template <
typename T,
typename F>
3491 typename detail::element_type<T>::type;
3493 typename detail::pair_adaptor<element_t>::first_type;
3495 using local_item_t =
3496 typename IsMemberType<item_t>::type;
3500 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3503 desc_function_ = [set]() {
return detail::generate_set(detail::smart_deref(set)); };
3507 func_ = [set, filter_fn](std::string &input) {
3509 if (!detail::lexical_cast(input, b)) {
3515 auto res = detail::search(set, b, filter_fn);
3524 return std::string{};
3528 return input +
" not in " + detail::generate_set(detail::smart_deref(set));
3533 template <
typename T,
typename... Args>
3534 IsMember(T &&set, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3536 std::forward<T>(set),
3537 [filter_fn_1, filter_fn_2](std::string a) {
return filter_fn_2(filter_fn_1(a)); },
3542template <
typename T>
3543using TransformPairs = std::vector<std::pair<std::string, T>>;
3548 using filter_fn_t = std::function<std::string(std::string)>;
3551 template <
typename... Args>
3552 Transformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
3553 :
Transformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
3556 template <
typename T>
3561 template <
typename T,
typename F>
3564 "mapping must produce value pairs");
3568 typename detail::element_type<T>::type;
3570 typename detail::pair_adaptor<element_t>::first_type;
3571 using local_item_t =
3572 typename IsMemberType<item_t>::type;
3576 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3579 desc_function_ = [mapping]() {
return detail::generate_map(detail::smart_deref(mapping)); };
3581 func_ = [mapping, filter_fn](std::string &input) {
3583 if (!detail::lexical_cast(input, b)) {
3584 return std::string();
3591 auto res = detail::search(mapping, b, filter_fn);
3595 return std::string{};
3600 template <
typename T,
typename... Args>
3601 Transformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3603 std::forward<T>(mapping),
3604 [filter_fn_1, filter_fn_2](std::string a) {
return filter_fn_2(filter_fn_1(a)); },
3611 using filter_fn_t = std::function<std::string(std::string)>;
3614 template <
typename... Args>
3617 :
CheckedTransformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
3620 template <
typename T>
3625 template <
typename T,
typename F>
3628 "mapping must produce value pairs");
3632 typename detail::element_type<T>::type;
3634 typename detail::pair_adaptor<element_t>::first_type;
3635 using local_item_t =
3636 typename IsMemberType<item_t>::type;
3638 using iteration_type_t =
3639 typename detail::pair_adaptor<element_t>::value_type;
3642 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3644 auto tfunc = [mapping]() {
3645 std::string out(
"value in ");
3646 out += detail::generate_map(detail::smart_deref(mapping)) +
" OR {";
3647 out += detail::join(
3648 detail::smart_deref(mapping),
3649 [](
const iteration_type_t &v) {
3659 func_ = [mapping, tfunc, filter_fn](std::string &input) {
3661 bool converted = detail::lexical_cast(input, b);
3666 auto res = detail::search(mapping, b, filter_fn);
3670 return std::string{};
3673 for (
const auto &v : detail::smart_deref(mapping)) {
3674 auto output_string =
3676 if (output_string == input) {
3677 return std::string();
3681 return "Check " + input +
" " + tfunc() +
" FAILED";
3686 template <
typename T,
typename... Args>
3688 filter_fn_t filter_fn_1,
3689 filter_fn_t filter_fn_2,
3692 std::forward<T>(mapping),
3693 [filter_fn_1, filter_fn_2](std::string a) {
return filter_fn_2(filter_fn_1(a)); },
3698inline std::string ignore_case(std::string item) {
return detail::to_lower(item); }
3701inline std::string ignore_underscore(std::string item) {
return detail::remove_underscore(item); }
3704inline std::string ignore_space(std::string item) {
3705 item.erase(std::remove(std::begin(item), std::end(item),
' '), std::end(item));
3706 item.erase(std::remove(std::begin(item), std::end(item),
'\t'), std::end(item));
3721class AsNumberWithUnit :
public Validator {
3729 CASE_INSENSITIVE = 1,
3732 DEFAULT = CASE_INSENSITIVE | UNIT_OPTIONAL
3735 template <
typename Number>
3738 const std::string &unit_name =
"UNIT") {
3739 description(generate_description<Number>(unit_name, opts));
3740 validate_mapping(mapping, opts);
3743 func_ = [mapping, opts](std::string &input) -> std::string {
3746 detail::rtrim(input);
3747 if (input.empty()) {
3748 throw ValidationError(
"Input is empty");
3752 auto unit_begin = input.end();
3753 while (unit_begin > input.begin() && std::isalpha(*(unit_begin - 1), std::locale())) {
3757 std::string unit{unit_begin, input.end()};
3758 input.resize(
static_cast<std::size_t
>(std::distance(input.begin(), unit_begin)));
3759 detail::trim(input);
3761 if (opts & UNIT_REQUIRED && unit.empty()) {
3762 throw ValidationError(
"Missing mandatory unit");
3764 if (opts & CASE_INSENSITIVE) {
3765 unit = detail::to_lower(unit);
3768 if (!detail::lexical_cast(input, num)) {
3769 throw ValidationError(std::string(
"Value ") + input +
3770 " could not be converted to " +
3771 detail::type_name<Number>());
3778 auto it = mapping.find(unit);
3779 if (it == mapping.end()) {
3780 throw ValidationError(unit +
3781 " unit not recognized. "
3782 "Allowed values: " +
3783 detail::generate_map(mapping,
true));
3786 if (!input.empty()) {
3787 bool converted = detail::lexical_cast(input, num);
3789 throw ValidationError(std::string(
"Value ") + input +
3790 " could not be converted to " +
3791 detail::type_name<Number>());
3794 bool ok = detail::checked_multiply(num, it->second);
3796 throw ValidationError(
3797 detail::to_string(num) +
" multiplied by " + unit +
3798 " factor would cause number overflow. Use smaller value.");
3801 num =
static_cast<Number
>(it->second);
3804 input = detail::to_string(num);
3813 template <
typename Number>
3814 static void validate_mapping(std::map<std::string, Number> &mapping,
Options opts) {
3815 for (
auto &kv : mapping) {
3816 if (kv.first.empty()) {
3817 throw ValidationError(
"Unit must not be empty.");
3819 if (!detail::isalpha(kv.first)) {
3820 throw ValidationError(
"Unit must contain only letters.");
3825 if (opts & CASE_INSENSITIVE) {
3826 std::map<std::string, Number> lower_mapping;
3827 for (
auto &kv : mapping) {
3828 auto s = detail::to_lower(kv.first);
3829 if (lower_mapping.count(s)) {
3830 throw ValidationError(
3831 std::string(
"Several matching lowercase unit representations are found: ") +
3834 lower_mapping[detail::to_lower(kv.first)] = kv.second;
3836 mapping = std::move(lower_mapping);
3841 template <
typename Number>
3842 static std::string generate_description(
const std::string &
name,
Options opts) {
3843 std::stringstream out;
3844 out << detail::type_name<Number>() <<
' ';
3845 if (opts & UNIT_REQUIRED) {
3848 out <<
'[' <<
name <<
']';
3869 using result_t = std::uint64_t;
3882 static std::map<std::string, result_t> init_mapping(
bool kb_is_1000);
3885 static std::map<std::string, result_t> get_mapping(
bool kb_is_1000);
3893CLI11_INLINE std::pair<std::string, std::string> split_program_name(std::string commandline);
3899 std::string retstring;
3902 std::string value = str;
3903 retstring =
func_(value);
3905 retstring =
func_(str);
3912 Validator newval(*
this);
3913 newval.
desc_function_ = [validator_desc]() {
return validator_desc; };
3920 newval._merge_description(*
this, other,
" AND ");
3923 const std::function<std::string(std::string & filename)> &f1 =
func_;
3924 const std::function<std::string(std::string & filename)> &f2 = other.
func_;
3926 newval.
func_ = [f1, f2](std::string &input) {
3927 std::string s1 = f1(input);
3928 std::string s2 = f2(input);
3929 if (!s1.empty() && !s2.empty())
return std::string(
"(") + s1 +
") AND (" + s2 +
")";
3941 newval._merge_description(*
this, other,
" OR ");
3944 const std::function<std::string(std::string &)> &f1 =
func_;
3945 const std::function<std::string(std::string &)> &f2 = other.
func_;
3947 newval.
func_ = [f1, f2](std::string &input) {
3948 std::string s1 = f1(input);
3949 std::string s2 = f2(input);
3950 if (s1.empty() || s2.empty())
return std::string();
3952 return std::string(
"(") + s1 +
") OR (" + s2 +
")";
3963 auto str = dfunc1();
3964 return (!str.empty()) ? std::string(
"NOT ") + str : std::string{};
3967 const std::function<std::string(std::string & res)> &f1 =
func_;
3969 newval.
func_ = [f1, dfunc1](std::string &test) -> std::string {
3970 std::string s1 = f1(test);
3972 return std::string(
"check ") + dfunc1() +
" succeeded improperly";
3974 return std::string{};
3981CLI11_INLINE
void Validator::_merge_description(
const Validator &val1,
3983 const std::string &merger) {
3984 const std::function<std::string()> &dfunc1 = val1.
desc_function_;
3985 const std::function<std::string()> &dfunc2 = val2.
desc_function_;
3988 std::string f1 = dfunc1();
3989 std::string f2 = dfunc2();
3990 if ((f1.empty()) || (f2.empty())) {
3993 return std::string(1,
'(') + f1 +
')' + merger +
'(' + f2 +
')';
3999#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
4000CLI11_INLINE path_type check_path(
const char *file)
noexcept {
4002 auto stat = std::filesystem::status(file, ec);
4004 return path_type::nonexistent;
4006 switch (stat.type()) {
4007 case std::filesystem::file_type::none:
4008 case std::filesystem::file_type::not_found:
4009 return path_type::nonexistent;
4010 case std::filesystem::file_type::directory:
4011 return path_type::directory;
4012 case std::filesystem::file_type::symlink:
4013 case std::filesystem::file_type::block:
4014 case std::filesystem::file_type::character:
4015 case std::filesystem::file_type::fifo:
4016 case std::filesystem::file_type::socket:
4017 case std::filesystem::file_type::regular:
4018 case std::filesystem::file_type::unknown:
4020 return path_type::file;
4024CLI11_INLINE path_type check_path(
const char *file)
noexcept {
4025#if defined(_MSC_VER)
4026 struct __stat64 buffer;
4027 if (_stat64(file, &buffer) == 0) {
4028 return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
4032 if (stat(file, &buffer) == 0) {
4033 return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
4036 return path_type::nonexistent;
4040CLI11_INLINE ExistingFileValidator::ExistingFileValidator() : Validator(
"FILE") {
4041 func_ = [](std::string &filename) {
4042 auto path_result = check_path(filename.c_str());
4043 if (path_result == path_type::nonexistent) {
4044 return "File does not exist: " + filename;
4046 if (path_result == path_type::directory) {
4047 return "File is actually a directory: " + filename;
4049 return std::string();
4053CLI11_INLINE ExistingDirectoryValidator::ExistingDirectoryValidator() :
Validator(
"DIR") {
4054 func_ = [](std::string &filename) {
4055 auto path_result = check_path(filename.c_str());
4056 if (path_result == path_type::nonexistent) {
4057 return "Directory does not exist: " + filename;
4059 if (path_result == path_type::file) {
4060 return "Directory is actually a file: " + filename;
4062 return std::string();
4066CLI11_INLINE ExistingPathValidator::ExistingPathValidator() :
Validator(
"PATH(existing)") {
4067 func_ = [](std::string &filename) {
4068 auto path_result = check_path(filename.c_str());
4069 if (path_result == path_type::nonexistent) {
4070 return "Path does not exist: " + filename;
4072 return std::string();
4076CLI11_INLINE NonexistentPathValidator::NonexistentPathValidator()
4078 func_ = [](std::string &filename) {
4079 auto path_result = check_path(filename.c_str());
4080 if (path_result != path_type::nonexistent) {
4081 return "Path already exists: " + filename;
4083 return std::string();
4087CLI11_INLINE IPV4Validator::IPV4Validator() :
Validator(
"IPV4") {
4088 func_ = [](std::string &ip_addr) {
4089 auto result = CLI::detail::split(ip_addr,
'.');
4090 if (result.size() != 4) {
4091 return std::string(
"Invalid IPV4 address must have four parts (") + ip_addr +
')';
4094 for (
const auto &var : result) {
4095 bool retval = detail::lexical_cast(var, num);
4097 return std::string(
"Failed parsing number (") + var +
')';
4099 if (num < 0 || num > 255) {
4100 return std::string(
"Each IP number must be between 0 and 255 ") + var;
4103 return std::string();
4109CLI11_INLINE FileOnDefaultPath::FileOnDefaultPath(std::string default_path,
bool enableErrorReturn)
4110 : Validator(
"FILE") {
4111 func_ = [default_path, enableErrorReturn](std::string &filename) {
4112 auto path_result = detail::check_path(filename.c_str());
4113 if (path_result == detail::path_type::nonexistent) {
4114 std::string test_file_path = default_path;
4115 if (default_path.back() !=
'/' && default_path.back() !=
'\\') {
4117 test_file_path +=
'/';
4119 test_file_path.append(filename);
4120 path_result = detail::check_path(test_file_path.c_str());
4121 if (path_result == detail::path_type::file) {
4122 filename = test_file_path;
4124 if (enableErrorReturn) {
4125 return "File does not exist: " + filename;
4129 return std::string{};
4135 description(
"SIZE [b, kb(=1000b), kib(=1024b), ...]");
4141CLI11_INLINE std::map<std::string, AsSizeValue::result_t> AsSizeValue::init_mapping(
4143 std::map<std::string, result_t> m;
4144 result_t k_factor = kb_is_1000 ? 1000 : 1024;
4145 result_t ki_factor = 1024;
4149 for (std::string p : {
"k",
"m",
"g",
"t",
"p",
"e"}) {
4160CLI11_INLINE std::map<std::string, AsSizeValue::result_t> AsSizeValue::get_mapping(
4163 static auto m = init_mapping(
true);
4166 static auto m = init_mapping(
false);
4172CLI11_INLINE std::pair<std::string, std::string> split_program_name(std::string commandline) {
4174 std::pair<std::string, std::string> vals;
4176 auto esp = commandline.find_first_of(
' ', 1);
4177 while (detail::check_path(commandline.substr(0, esp).c_str()) != path_type::file) {
4178 esp = commandline.find_first_of(
' ', esp + 1);
4179 if (esp == std::string::npos) {
4182 if (commandline[0] ==
'"' || commandline[0] ==
'\'' || commandline[0] ==
'`') {
4183 bool embeddedQuote =
false;
4184 auto keyChar = commandline[0];
4185 auto end = commandline.find_first_of(keyChar, 1);
4186 while ((end != std::string::npos) &&
4187 (commandline[end - 1] ==
'\\')) {
4188 end = commandline.find_first_of(keyChar, end + 1);
4189 embeddedQuote =
true;
4191 if (end != std::string::npos) {
4192 vals.first = commandline.substr(1, end - 1);
4194 if (embeddedQuote) {
4195 vals.first = find_and_replace(vals.first, std::string(
"\\") + keyChar,
4196 std::string(1, keyChar));
4199 esp = commandline.find_first_of(
' ', 1);
4202 esp = commandline.find_first_of(
' ', 1);
4208 if (vals.first.empty()) {
4209 vals.first = commandline.substr(0, esp);
4214 vals.second = (esp < commandline.length() - 1) ? commandline.substr(esp + 1) : std::string{};
4230enum class AppFormatMode {
4240class FormatterBase {
4267 virtual std::string
make_help(
const App *, std::string, AppFormatMode)
const = 0;
4284 CLI11_NODISCARD std::string
get_label(std::string key)
const {
4297 using funct_t = std::function<std::string(
const App *, std::string, AppFormatMode)>;
4310 std::string
make_help(
const App *app, std::string name, AppFormatMode mode)
const override {
4311 return lambda_(app, name, mode);
4317class Formatter :
public FormatterBase {
4319 Formatter() =
default;
4320 Formatter(
const Formatter &) =
default;
4321 Formatter(Formatter &&) =
default;
4322 Formatter &operator=(
const Formatter &) =
default;
4323 Formatter &operator=(Formatter &&) =
default;
4330 CLI11_NODISCARD
virtual std::string
make_group(std::string group,
4332 std::vector<const Option *> opts)
const;
4338 std::string
make_groups(
const App *app, AppFormatMode mode)
const;
4356 virtual std::string
make_usage(
const App *app, std::string name)
const;
4359 std::string
make_help(
const App * , std::string, AppFormatMode)
const override;
4367 std::stringstream out;
4388using results_t = std::vector<std::string>;
4390using callback_t = std::function<bool(
const results_t &)>;
4395using Option_p = std::unique_ptr<Option>;
4397enum class MultiOptionPolicy :
char {
4409template <
typename CRTP>
4442 template <
typename T>
4450 if (!detail::valid_alias_name_string(name)) {
4454 return static_cast<CRTP *
>(
this);
4460 return static_cast<CRTP *
>(
this);
4466 CRTP *always_capture_default(
bool value =
true) {
4468 return static_cast<CRTP *
>(
this);
4506 auto *self =
static_cast<CRTP *
>(
this);
4507 self->multi_option_policy(MultiOptionPolicy::TakeLast);
4513 auto *self =
static_cast<CRTP *
>(
this);
4514 self->multi_option_policy(MultiOptionPolicy::TakeFirst);
4520 auto self =
static_cast<CRTP *
>(
this);
4521 self->multi_option_policy(MultiOptionPolicy::TakeAll);
4527 auto *self =
static_cast<CRTP *
>(
this);
4528 self->multi_option_policy(MultiOptionPolicy::Join);
4534 auto self =
static_cast<CRTP *
>(
this);
4535 self->delimiter_ = delim;
4536 self->multi_option_policy(MultiOptionPolicy::Join);
4543 return static_cast<CRTP *
>(
this);
4549 return static_cast<CRTP *
>(
this);
4557 OptionDefaults() =
default;
4635 std::function<std::string()>
type_name_{[]() {
return std::string(); }};
4708 std::string option_description,
4709 callback_t callback,
4791 std::string Validator_description =
"",
4792 std::string Validator_name =
"");
4798 Option *
transform(
const std::function<std::string(std::string)> &func,
4799 std::string transform_description =
"",
4800 std::string transform_name =
"");
4804 Option *
each(
const std::function<
void(std::string)> &func);
4821 template <
typename T = App>
4823 auto opt =
static_cast<T *
>(
parent_)->get_option_no_throw(opt_name);
4824 if (opt ==
nullptr) {
4825 throw IncorrectConstruction::MissingOption(opt_name);
4831 template <
typename A,
typename B,
typename... ARG>
4834 return needs(opt1, args...);
4844 template <
typename T = App>
4846 auto opt =
static_cast<T *
>(
parent_)->get_option_no_throw(opt_name);
4847 if (opt ==
nullptr) {
4848 throw IncorrectConstruction::MissingOption(opt_name);
4854 template <
typename A,
typename B,
typename... ARG>
4873 template <
typename T = App>
4880 template <
typename T = App>
4956 return detail::checked_multiply(t,
expected_max_) ? t : detail::expected_max_vector_size;
4979 Option *option_text(std::string text) {
4984 CLI11_NODISCARD
const std::string &get_option_text()
const {
return option_text_; }
4994 CLI11_NODISCARD std::string
get_name(
bool positional =
false,
4995 bool all_options =
false
5012 CLI11_NODISCARD
bool check_name(
const std::string &name)
const;
5036 CLI11_NODISCARD std::string
get_flag_value(
const std::string &name,
5037 std::string input_value)
const;
5055 template <
typename T>
5057 bool retval =
false;
5061 retval = detail::lexical_conversion<T, T>(res, output);
5068 _validate_results(res);
5070 _reduce_results(extra, res);
5071 if (!extra.empty()) {
5072 res = std::move(extra);
5080 retval = detail::lexical_conversion<T, T>(res, output);
5088 template <
typename T>
5089 CLI11_NODISCARD T
as()
const {
5120 Option *
type_size(
int option_type_size_min,
int option_type_size_max);
5147 template <
typename X>
5149 std::string val_str = detail::to_string(val);
5151 results_t old_results{std::move(
results_)};
5179 void _validate_results(results_t &res)
const;
5184 void _reduce_results(results_t &out,
const results_t &original)
const;
5187 std::string _validate(std::string &result,
int index)
const;
5190 int _add_result(std::string &&result, std::vector<std::string> &res)
const;
5193template <
typename CRTP>
5194template <
typename T>
5215 }
else if (value == detail::expected_max_vector_size) {
5229 if (value_min < 0) {
5230 value_min = -value_min;
5233 if (value_max < 0) {
5234 value_max = detail::expected_max_vector_size;
5236 if (value_max < value_min) {
5250 if (!validator_name.empty())
validators_.back().name(validator_name);
5255 std::string Validator_description,
5256 std::string Validator_name) {
5258 std::move(Validator_name));
5265 if (!Validator_name.empty())
validators_.front().name(Validator_name);
5270 std::string transform_description,
5271 std::string transform_name) {
5274 [func](std::string &val) {
5276 return std::string{};
5278 std::move(transform_description), std::move(transform_name)));
5285 [func](std::string &inout) {
5287 return std::string{};
5299 if ((Validator_name.empty()) && (!
validators_.empty())) {
5302 throw OptionNotFound(std::string{
"Validator "} + Validator_name +
" Not Found");
5307 if (index >= 0 && index <
static_cast<int>(
validators_.size())) {
5314 auto iterator = std::find(std::begin(
needs_), std::end(
needs_), opt);
5316 if (iterator == std::end(
needs_)) {
5349template <
typename T>
5353 auto *parent =
static_cast<T *
>(
parent_);
5354 for (
const Option_p &opt : parent->options_) {
5355 if (opt.get() ==
this) {
5358 const auto &omatch = opt->matching_name(*
this);
5359 if (!omatch.empty()) {
5371template <
typename T>
5375 auto *parent =
static_cast<T *
>(
parent_);
5376 for (
const Option_p &opt : parent->options_) {
5377 if (opt.get() ==
this) {
5380 const auto &omatch = opt->matching_name(*
this);
5381 if (!omatch.empty()) {
5407CLI11_NODISCARD CLI11_INLINE std::string
Option::get_name(
bool positional,
bool all_options)
const {
5411 std::vector<std::string> name_list;
5415 name_list.push_back(
pname_);
5418 for (
const std::string &sname :
snames_) {
5419 name_list.push_back(
"-" + sname);
5425 for (
const std::string &lname :
lnames_) {
5426 name_list.push_back(
"--" + lname);
5432 for (
const std::string &sname :
snames_) name_list.push_back(
"-" + sname);
5434 for (
const std::string &lname :
lnames_) name_list.push_back(
"--" + lname);
5437 return detail::join(name_list);
5441 if (positional)
return pname_;
5472 bool local_result =
callback_(send_results);
5479 static const std::string estring;
5480 for (
const std::string &sname :
snames_)
5482 for (
const std::string &lname :
lnames_)
5487 for (
const std::string &sname : other.
snames_)
5489 for (
const std::string &lname : other.
lnames_)
5496 if (name.length() > 2 && name[0] ==
'-' && name[1] ==
'-')
return check_lname(name.substr(2));
5497 if (name.length() > 1 && name.front() ==
'-')
return check_sname(name.substr(1));
5499 std::string local_pname =
pname_;
5500 std::string local_name = name;
5502 local_pname = detail::remove_underscore(local_pname);
5503 local_name = detail::remove_underscore(local_name);
5506 local_pname = detail::to_lower(local_pname);
5507 local_name = detail::to_lower(local_name);
5509 if (local_name == local_pname) {
5522 std::string input_value)
const {
5523 static const std::string trueString{
"true"};
5524 static const std::string falseString{
"false"};
5525 static const std::string emptyString{
"{}"};
5528 if (!((input_value.empty()) || (input_value == emptyString))) {
5530 if (default_ind >= 0) {
5534 throw(ArgumentMismatch::FlagOverride(name));
5537 if (input_value != trueString) {
5538 throw(ArgumentMismatch::FlagOverride(name));
5544 if ((input_value.empty()) || (input_value == emptyString)) {
5546 return (ind < 0) ? trueString
5557 auto val = detail::to_flag_value(input_value);
5558 return (val == 1) ? falseString : (val == (-1) ? trueString : std::to_string(-val));
5559 }
catch (
const std::invalid_argument &) {
5568 _add_result(std::move(s),
results_);
5574 results_added = _add_result(std::move(s),
results_);
5581 for (
auto &str : s) {
5582 _add_result(std::move(str),
results_);
5592 _validate_results(res);
5596 _reduce_results(extra, res);
5597 if (!extra.empty()) {
5598 res = std::move(extra);
5606 if (option_type_size < 0) {
5624 if (option_type_size_min < 0 || option_type_size_max < 0) {
5627 option_type_size_min = (std::abs)(option_type_size_min);
5628 option_type_size_max = (std::abs)(option_type_size_max);
5631 if (option_type_size_min > option_type_size_max) {
5652 if (!vtype.empty()) {
5653 full_type_name +=
":" + vtype;
5657 return full_type_name;
5660CLI11_INLINE
void Option::_validate_results(results_t &res)
const {
5671 for (std::string &result : res) {
5677 auto err_msg = _validate(result, (index >= 0) ? (index %
type_size_max_) : index);
5678 if (!err_msg.empty())
throw ValidationError(
get_name(), err_msg);
5688 for (std::string &result : res) {
5689 auto err_msg = _validate(result, index);
5691 if (!err_msg.empty())
throw ValidationError(
get_name(), err_msg);
5697CLI11_INLINE
void Option::_reduce_results(results_t &out,
const results_t &original)
const {
5704 case MultiOptionPolicy::TakeAll:
5706 case MultiOptionPolicy::TakeLast: {
5708 std::size_t trim_size = std::min<std::size_t>(
5711 if (original.size() != trim_size) {
5712 out.assign(original.end() -
static_cast<results_t::difference_type
>(trim_size),
5716 case MultiOptionPolicy::TakeFirst: {
5717 std::size_t trim_size = std::min<std::size_t>(
5720 if (original.size() != trim_size) {
5721 out.assign(original.begin(),
5722 original.begin() +
static_cast<results_t::difference_type
>(trim_size));
5725 case MultiOptionPolicy::Join:
5727 out.push_back(detail::join(
5731 case MultiOptionPolicy::Sum:
5732 out.push_back(detail::sum_string_vector(original));
5734 case MultiOptionPolicy::Throw:
5744 if (original.size() < num_min) {
5745 throw ArgumentMismatch::AtLeast(
get_name(),
static_cast<int>(num_min),
5748 if (original.size() > num_max) {
5749 throw ArgumentMismatch::AtMost(
get_name(),
static_cast<int>(num_max),
5760 out.push_back(
"{}");
5761 out.push_back(
"%%");
5764 out.push_back(
"%%");
5768CLI11_INLINE std::string Option::_validate(std::string &result,
int index)
const {
5769 std::string err_msg;
5775 auto v = vali.get_application_index();
5776 if (v == -1 || v == index) {
5778 err_msg = vali(result);
5779 }
catch (
const ValidationError &err) {
5780 err_msg = err.what();
5782 if (!err_msg.empty())
break;
5789CLI11_INLINE
int Option::_add_result(std::string &&result, std::vector<std::string> &res)
const {
5790 int result_count = 0;
5796 for (
auto &var : CLI::detail::split(result.substr(1),
',')) {
5798 result_count += _add_result(std::move(var), res);
5801 return result_count;
5804 res.push_back(std::move(result));
5807 if ((result.find_first_of(
delimiter_) != std::string::npos)) {
5808 for (
const auto &var : CLI::detail::split(result,
delimiter_)) {
5815 res.push_back(std::move(result));
5819 return result_count;
5823#define CLI11_PARSE(app, argc, argv) \
5825 (app).parse((argc), (argv)); \
5826 } catch (const CLI::ParseError &e) { \
5827 return (app).exit(e); \
5832enum class Classifier {
5839 SUBCOMMAND_TERMINATOR
5844namespace FailureMessage {
5845std::string simple(
const App *app,
const Error &e);
5846std::string help(
const App *app,
const Error &e);
5851enum class config_extras_mode :
char { error = 0, ignore, ignore_all, capture };
5855using App_p = std::shared_ptr<App>;
5862 enable_if_t<!std::is_integral<T>::value || (
sizeof(T) <= 1U), detail::enabler> = detail::dummy>
5863Option *default_flag_modifiers(Option *opt) {
5864 return opt->always_capture_default();
5870 enable_if_t<std::is_integral<T>::value && (
sizeof(T) > 1U), detail::enabler> = detail::dummy>
5871Option *default_flag_modifiers(Option *opt) {
5872 return opt->multi_option_policy(MultiOptionPolicy::Sum)->default_str(
"0")->force_callback();
5968 FailureMessage::simple};
5974 using missing_t = std::vector<std::pair<detail::Classifier, std::string>>;
6033 enum class startup_mode :
char { stable, enabled,
disabled };
6089 App(std::string app_description, std::string app_name,
App *parent);
6096 explicit App(std::string app_description =
"", std::string app_name =
"")
6097 :
App(app_description, app_name, nullptr) {
6098 set_help_flag(
"-h,--help",
"Print this help message and exit");
6101 App(
const App &) =
delete;
6102 App &operator=(
const App &) =
delete;
6144 App *
name(std::string app_name =
"");
6180 : startup_mode::stable;
6192 : startup_mode::stable;
6268 formatter_ = std::make_shared<FormatterLambda>(fmt);
6303 callback_t option_callback,
6304 std::string option_description =
"",
6305 bool defaulted =
false,
6306 std::function<std::string()> func = {});
6309 template <
typename AssignTo,
6310 typename ConvertTo = AssignTo,
6311 enable_if_t<!std::is_const<ConvertTo>::value, detail::enabler> = detail::dummy>
6314 std::string option_description =
"") {
6315 auto fun = [&variable](
const CLI::results_t &res) {
6316 return detail::lexical_conversion<AssignTo, ConvertTo>(res, variable);
6319 Option *opt =
add_option(option_name, fun, option_description,
false, [&variable]() {
6320 return CLI::detail::checked_to_string<AssignTo, ConvertTo>(variable);
6322 opt->
type_name(detail::type_name<ConvertTo>());
6326 auto Tcount = detail::type_count<AssignTo>::value;
6327 auto XCcount = detail::type_count<ConvertTo>::value;
6328 opt->
type_size(detail::type_count_min<ConvertTo>::value, (std::max)(Tcount, XCcount));
6329 opt->
expected(detail::expected_count<ConvertTo>::value);
6335 template <
typename AssignTo,
6336 enable_if_t<!std::is_const<AssignTo>::value, detail::enabler> = detail::dummy>
6339 std::string option_description =
"") {
6340 auto fun = [&variable](
const CLI::results_t &res) {
6341 return detail::lexical_conversion<AssignTo, AssignTo>(res, variable);
6345 add_option(option_name, fun, option_description,
false, []() {
return std::string{}; });
6346 opt->
type_name(detail::type_name<AssignTo>());
6347 opt->
type_size(detail::type_count_min<AssignTo>::value,
6348 detail::type_count<AssignTo>::value);
6349 opt->
expected(detail::expected_count<AssignTo>::value);
6355 template <
typename ArgType>
6357 std::string option_name,
6358 const std::function<
void(
const ArgType &)> &func,
6359 std::string option_description =
"") {
6360 auto fun = [func](
const CLI::results_t &res) {
6362 bool result = detail::lexical_conversion<ArgType, ArgType>(res, variable);
6369 Option *opt =
add_option(option_name, std::move(fun), option_description,
false);
6370 opt->
type_name(detail::type_name<ArgType>());
6371 opt->
type_size(detail::type_count_min<ArgType>::value, detail::type_count<ArgType>::value);
6372 opt->
expected(detail::expected_count<ArgType>::value);
6378 return add_option(option_name, CLI::callback_t{}, std::string{},
false);
6382 template <
typename T,
6383 enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value,
6384 detail::enabler> = detail::dummy>
6385 Option *
add_option(std::string option_name, T &option_description) {
6386 return add_option(option_name, CLI::callback_t(), option_description,
false);
6390 Option *
set_help_flag(std::string flag_name =
"",
const std::string &help_description =
"");
6397 std::string flag_name =
"",
6398 const std::string &versionString =
"",
6399 const std::string &version_help =
"Display program version information and exit");
6403 std::string flag_name,
6404 std::function<std::string()> vfunc,
6405 const std::string &version_help =
"Display program version information and exit");
6409 Option *_add_flag_internal(std::string flag_name,
6410 CLI::callback_t fun,
6411 std::string flag_description);
6416 return _add_flag_internal(flag_name, CLI::callback_t(), std::string{});
6422 template <
typename T,
6423 enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value,
6424 detail::enabler> = detail::dummy>
6425 Option *
add_flag(std::string flag_name, T &flag_description) {
6426 return _add_flag_internal(flag_name, CLI::callback_t(), flag_description);
6431 template <
typename T,
6432 enable_if_t<!detail::is_mutable_container<T>::value && !std::is_const<T>::value &&
6433 !std::is_constructible<std::function<void(
int)>, T>::value,
6434 detail::enabler> = detail::dummy>
6437 std::string flag_description =
"") {
6438 CLI::callback_t fun = [&flag_result](
const CLI::results_t &res) {
6439 return CLI::detail::lexical_cast(res[0], flag_result);
6441 auto *opt = _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
6442 return detail::default_flag_modifiers<T>(opt);
6446 template <
typename T,
6447 enable_if_t<!std::is_assignable<std::function<void(std::int64_t)> &, T>::value,
6448 detail::enabler> = detail::dummy>
6450 std::vector<T> &flag_results,
6451 std::string flag_description =
"") {
6452 CLI::callback_t fun = [&flag_results](
const CLI::results_t &res) {
6454 for (
const auto &elem : res) {
6455 flag_results.emplace_back();
6456 retval &= detail::lexical_cast(elem, flag_results.back());
6460 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
6467 std::string flag_name,
6468 std::function<
void(
void)> function,
6469 std::string flag_description =
"");
6473 std::string flag_name,
6474 std::function<
void(std::int64_t)> function,
6475 std::string flag_description =
"");
6480 std::string flag_name,
6481 std::function<
void(std::int64_t)> function,
6482 std::string flag_description =
"") {
6484 std::move(flag_description));
6489 Option *
set_config(std::string option_name =
"",
6490 std::string default_filename =
"",
6491 const std::string &help_message =
"Read an ini file",
6492 bool config_required =
false);
6498 template <
typename T = Option_group>
6500 if (!detail::valid_alias_name_string(group_name)) {
6502 "option group names may not contain newlines or null characters");
6504 auto option_group = std::make_shared<T>(std::move(group_description), group_name,
this);
6505 auto *ptr = option_group.get();
6507 App_p app_ptr = std::dynamic_pointer_cast<App>(option_group);
6555 CLI11_NODISCARD std::size_t
count_all()
const;
6630 explicit operator bool()
const {
return parsed_ > 0; }
6650 void parse(
int argc,
const char *
const *argv);
6656 void parse(std::string commandline,
bool program_name_included =
false);
6660 void parse(std::vector<std::string> &args);
6663 void parse(std::vector<std::string> &&args);
6665 void parse_from_stream(std::istream &input);
6674 int exit(
const Error &e, std::ostream &out = std::cout, std::ostream &err = std::cerr)
const;
6681 CLI11_NODISCARD std::size_t
count(std::string option_name)
const {
6691 std::vector<const App *>
get_subcommands(
const std::function<
bool(
const App *)> &filter)
const;
6710 if (opt ==
nullptr) {
6719 if (app ==
nullptr) {
6734 if (opt ==
nullptr) {
6742 if (app ==
nullptr) {
6743 throw OptionNotFound(
"nullptr passed");
6746 throw OptionNotFound(
"cannot self reference in needs");
6769 footer_ = std::move(footer_string);
6781 bool write_description =
false)
const {
6787 CLI11_NODISCARD std::string
help(std::string prev =
"",
6788 AppFormatMode mode = AppFormatMode::Normal)
const;
6791 CLI11_NODISCARD std::string
version()
const;
6807#if CLI11_USE_STATIC_RTTI == 0
6826 const std::function<
bool(
const Option *)> filter = {})
const;
6829 std::vector<Option *>
get_options(
const std::function<
bool(Option *)> filter = {});
6835 CLI11_NODISCARD
const Option *
get_option_no_throw(std::string option_name)
const noexcept;
6838 CLI11_NODISCARD
const Option *
get_option(std::string option_name)
const {
6840 if (opt ==
nullptr) {
6849 if (opt ==
nullptr) {
6986 CLI11_NODISCARD std::string
get_display_name(
bool with_aliases =
false)
const;
6989 CLI11_NODISCARD
bool check_name(std::string name_to_check)
const;
6992 CLI11_NODISCARD std::vector<std::string>
get_groups()
const;
6998 CLI11_NODISCARD std::vector<std::string>
remaining(
bool recurse =
false)
const;
7005 CLI11_NODISCARD std::size_t
remaining_size(
bool recurse =
false)
const;
7022 void run_callback(
bool final_mode =
false,
bool suppress_final_callback =
false);
7027 bool ignore_used =
true)
const;
7030 CLI11_NODISCARD detail::Classifier
_recognize(
const std::string ¤t,
7031 bool ignore_used_subcommands =
true)
const;
7067 void _parse(std::vector<std::string> &args);
7070 void _parse(std::vector<std::string> &&args);
7088 bool _parse_single(std::vector<std::string> &args,
bool &positional_only);
7104 bool ignore_disabled,
7105 bool ignore_used)
const noexcept;
7115 bool _parse_arg(std::vector<std::string> &args, detail::Classifier current_type);
7127 const App &base)
const;
7130 void _move_to_missing(detail::Classifier val_type,
const std::string &val);
7138class Option_group :
public App {
7140 Option_group(std::string group_description, std::string group_name,
App *parent)
7141 :
App(std::move(group_description),
"", parent) {
7157 template <
typename... Args>
7166 subc->get_parent()->remove_subcommand(subcom);
7173CLI11_INLINE
void TriggerOn(App *trigger_app, App *app_to_enable);
7176CLI11_INLINE
void TriggerOn(App *trigger_app, std::vector<App *> apps_to_enable);
7179CLI11_INLINE
void TriggerOff(App *trigger_app, App *app_to_enable);
7182CLI11_INLINE
void TriggerOff(App *trigger_app, std::vector<App *> apps_to_enable);
7185CLI11_INLINE
void deprecate_option(Option *opt,
const std::string &replacement =
"");
7188inline void deprecate_option(App *app,
7189 const std::string &option_name,
7190 const std::string &replacement =
"") {
7191 auto *opt = app->get_option(option_name);
7192 deprecate_option(opt, replacement);
7196inline void deprecate_option(
App &app,
7197 const std::string &option_name,
7198 const std::string &replacement =
"") {
7199 auto *opt = app.get_option(option_name);
7200 deprecate_option(opt, replacement);
7204CLI11_INLINE
void retire_option(
App *app,
Option *opt);
7207CLI11_INLINE
void retire_option(
App &app,
Option *opt);
7210CLI11_INLINE
void retire_option(
App *app,
const std::string &option_name);
7213CLI11_INLINE
void retire_option(
App &app,
const std::string &option_name);
7215namespace FailureMessage {
7218CLI11_INLINE std::string simple(
const App *app,
const Error &e);
7221CLI11_INLINE std::string help(
const App *app,
const Error &e);
7231 template <
typename... Args>
7232 static decltype(
auto)
parse_arg(
App *app, Args &&...args) {
7233 return app->
_parse_arg(std::forward<Args>(args)...);
7237 template <
typename... Args>
7243 template <
typename... Args>
7246 return app->
_parse_arg(std::forward<Args>(args)...);
7250 template <
typename... Args>
7261CLI11_INLINE
App::App(std::string app_description, std::string app_name,
App *parent)
7265 if (
parent_->help_ptr_ !=
nullptr)
7267 parent_->help_ptr_->get_description());
7268 if (
parent_->help_all_ptr_ !=
nullptr)
7270 parent_->help_all_ptr_->get_description());
7313 if (app_name.empty() || !detail::valid_alias_name_string(app_name)) {
7315 "Aliases may not be empty or contain newlines or null characters");
7322 throw(
OptionAlreadyAdded(
"alias already matches an existing subcommand: " + app_name));
7348 if (!match.empty()) {
7350 throw OptionAlreadyAdded(
"ignore case would cause subcommand name conflicts: " + match);
7362 if (!match.empty()) {
7364 throw OptionAlreadyAdded(
"ignore underscore would cause subcommand name conflicts: " +
7373 callback_t option_callback,
7374 std::string option_description,
7376 std::function<std::string()> func) {
7377 Option myopt{option_name, option_description, option_callback,
this};
7380 [&myopt](
const Option_p &v) {
return *v == myopt; }) == std::end(
options_)) {
7382 Option_p &option =
options_.back();
7383 option.reset(
new Option(option_name, option_description, option_callback,
this));
7386 option->default_function(func);
7389 if (defaulted) option->capture_default_str();
7395 if (!defaulted && option->get_always_capture_default()) option->capture_default_str();
7397 return option.get();
7402 if (!matchname.empty()) {
7403 throw(
OptionAlreadyAdded(
"added option matched existing option name: " + matchname));
7411 const std::string &help_description) {
7420 if (!flag_name.empty()) {
7429 const std::string &help_description) {
7438 if (!help_name.empty()) {
7447 const std::string &versionString,
7448 const std::string &version_help) {
7457 if (!flag_name.empty()) {
7468 std::function<std::string()> vfunc,
7469 const std::string &version_help) {
7476 if (!flag_name.empty()) {
7485CLI11_INLINE
Option *App::_add_flag_internal(std::string flag_name,
7486 CLI::callback_t fun,
7487 std::string flag_description) {
7489 if (detail::has_default_flag_values(flag_name)) {
7491 auto flag_defaults = detail::get_default_flag_values(flag_name);
7492 detail::remove_default_flag_values(flag_name);
7493 opt =
add_option(std::move(flag_name), std::move(fun), std::move(flag_description),
false);
7494 for (
const auto &fname : flag_defaults) opt->
fnames_.push_back(fname.first);
7497 opt =
add_option(std::move(flag_name), std::move(fun), std::move(flag_description),
false);
7501 auto pos_name = opt->
get_name(
true);
7503 throw IncorrectConstruction::PositionalFlag(pos_name);
7512 std::string flag_name,
7513 std::function<
void(
void)> function,
7514 std::string flag_description) {
7515 CLI::callback_t fun = [function](
const CLI::results_t &res) {
7516 bool trigger{
false};
7517 auto result = CLI::detail::lexical_cast(res[0], trigger);
7518 if (result && trigger) {
7523 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
7527 std::string flag_name,
7528 std::function<
void(std::int64_t)> function,
7529 std::string flag_description) {
7530 CLI::callback_t fun = [function](
const CLI::results_t &res) {
7531 std::int64_t flag_count{0};
7532 CLI::detail::lexical_cast(res[0], flag_count);
7533 function(flag_count);
7536 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
7541 std::string default_filename,
7542 const std::string &help_message,
7543 bool config_required) {
7551 if (!option_name.empty()) {
7553 if (config_required) {
7556 if (!default_filename.empty()) {
7557 config_ptr_->default_str(std::move(default_filename));
7568 op->remove_needs(opt);
7569 op->remove_excludes(opt);
7576 [opt](
const Option_p &v) {
return v.get() == opt; });
7577 if (iterator != std::end(
options_)) {
7585 std::string subcommand_description) {
7586 if (!subcommand_name.empty() && !detail::valid_name_string(subcommand_name)) {
7587 if (!detail::valid_first_char(subcommand_name[0])) {
7589 "Subcommand name starts with invalid character, '!' and '-' are not allowed");
7591 for (
auto c : subcommand_name) {
7592 if (!detail::valid_later_char(c)) {
7594 std::string(
"Subcommand name contains invalid character ('") + c +
7595 "'), all characters are allowed except"
7596 "'=',':','{','}', and ' '");
7601 std::shared_ptr<App>(
new App(std::move(subcommand_description), subcommand_name,
this));
7609 if (!mstrg.empty()) {
7610 throw(
OptionAlreadyAdded(
"subcommand name or alias matches existing subcommand: " + mstrg));
7612 subcom->parent_ =
this;
7620 sub->remove_excludes(subcom);
7621 sub->remove_needs(subcom);
7625 [subcom](
const App_p &v) {
return v.get() == subcom; });
7636 if (subcomptr.get() == subcom)
return subcomptr.get();
7648 auto uindex =
static_cast<unsigned>(index);
7657 if (subcomptr.get() == subcom)
return subcomptr;
7663 if (subcomptr->check_name(subcom))
return subcomptr;
7669 auto uindex =
static_cast<unsigned>(index);
7677 if (app->
name_.empty() && app->
group_ == group_name) {
7687 cnt += opt->
count();
7690 cnt += sub->count_all();
7705 for (
const Option_p &opt :
options_) {
7720 std::vector<std::string> args;
7721 args.reserve(
static_cast<std::size_t
>(argc) - 1U);
7722 for (
auto i =
static_cast<std::size_t
>(argc) - 1U; i > 0U; --i) args.emplace_back(argv[i]);
7723 parse(std::move(args));
7726CLI11_INLINE
void App::parse(std::string commandline,
bool program_name_included) {
7727 if (program_name_included) {
7728 auto nstr = detail::split_program_name(commandline);
7733 commandline = std::move(nstr.second);
7735 detail::trim(commandline);
7739 if (!commandline.empty()) {
7740 commandline = detail::find_and_modify(commandline,
"=", detail::escape_detect);
7742 commandline = detail::find_and_modify(commandline,
":", detail::escape_detect);
7745 auto args = detail::split_up(std::move(commandline));
7747 args.erase(std::remove(args.begin(), args.end(), std::string{}), args.end());
7748 std::reverse(args.begin(), args.end());
7750 parse(std::move(args));
7789CLI11_INLINE
void App::parse_from_stream(std::istream &input) {
7800CLI11_INLINE
int App::exit(
const Error &e, std::ostream &out, std::ostream &err)
const {
7802 if (e.get_name() ==
"RuntimeError")
return e.get_exit_code();
7804 if (e.get_name() ==
"CallForHelp") {
7806 return e.get_exit_code();
7809 if (e.get_name() ==
"CallForAllHelp") {
7810 out <<
help(
"", AppFormatMode::All);
7811 return e.get_exit_code();
7814 if (e.get_name() ==
"CallForVersion") {
7815 out << e.what() << std::endl;
7816 return e.get_exit_code();
7819 if (e.get_exit_code() !=
static_cast<int>(ExitCodes::Success)) {
7823 return e.get_exit_code();
7827 const std::function<
bool(
const App *)> &filter)
const {
7828 std::vector<const App *> subcomms(
subcommands_.size());
7830 [](
const App_p &v) {
return v.get(); });
7833 subcomms.erase(std::remove_if(std::begin(subcomms), std::end(subcomms),
7834 [&filter](
const App *app) {
return !filter(app); }),
7835 std::end(subcomms));
7844 [](
const App_p &v) {
return v.get(); });
7847 subcomms.erase(std::remove_if(std::begin(subcomms), std::end(subcomms),
7848 [&filter](
App *app) {
return !filter(app); }),
7849 std::end(subcomms));
7870 auto *other_app = *iterator;
7872 other_app->remove_excludes(
this);
7894CLI11_NODISCARD CLI11_INLINE std::string
App::help(std::string prev, AppFormatMode mode)
const {
7902 if (!selected_subcommands.empty()) {
7903 return selected_subcommands.at(0)->help(prev, mode);
7905 return formatter_->make_help(
this, prev, mode);
7926 const std::function<
bool(
const Option *)> filter)
const {
7927 std::vector<const Option *> options(
options_.size());
7928 std::transform(std::begin(
options_), std::end(
options_), std::begin(options),
7929 [](
const Option_p &val) {
return val.get(); });
7932 options.erase(std::remove_if(std::begin(options), std::end(options),
7933 [&filter](
const Option *opt) {
return !filter(opt); }),
7940CLI11_INLINE std::vector<Option *>
App::get_options(
const std::function<
bool(Option *)> filter) {
7941 std::vector<Option *> options(
options_.size());
7942 std::transform(std::begin(
options_), std::end(
options_), std::begin(options),
7943 [](
const Option_p &val) {
return val.get(); });
7946 options.erase(std::remove_if(std::begin(options), std::end(options),
7947 [&filter](Option *opt) {
return !filter(opt); }),
7962 if (subc->get_name().empty()) {
7963 auto *opt = subc->get_option_no_throw(option_name);
7964 if (opt !=
nullptr) {
7973 std::string option_name)
const noexcept {
7974 for (
const Option_p &opt :
options_) {
7981 if (subc->get_name().empty()) {
7982 auto *opt = subc->get_option_no_throw(option_name);
7983 if (opt !=
nullptr) {
7992 if (
name_.empty()) {
7993 return std::string(
"[Option Group: ") +
get_group() +
"]";
7995 if (
aliases_.empty() || !with_aliases) {
7998 std::string dispname =
name_;
7999 for (
const auto &lalias :
aliases_) {
8000 dispname.push_back(
',');
8001 dispname.push_back(
' ');
8002 dispname.append(lalias);
8008 std::string local_name =
name_;
8010 local_name = detail::remove_underscore(
name_);
8011 name_to_check = detail::remove_underscore(name_to_check);
8014 local_name = detail::to_lower(
name_);
8015 name_to_check = detail::to_lower(name_to_check);
8018 if (local_name == name_to_check) {
8023 les = detail::remove_underscore(les);
8026 les = detail::to_lower(les);
8028 if (les == name_to_check) {
8036 std::vector<std::string> groups;
8038 for (
const Option_p &opt :
options_) {
8040 if (std::find(groups.begin(), groups.end(), opt->
get_group()) == groups.end()) {
8048CLI11_NODISCARD CLI11_INLINE std::vector<std::string>
App::remaining(
bool recurse)
const {
8049 std::vector<std::string> miss_list;
8050 for (
const std::pair<detail::Classifier, std::string> &miss :
missing_) {
8051 miss_list.push_back(std::get<1>(miss));
8057 if (sub->name_.empty() && !sub->missing_.empty()) {
8058 for (
const std::pair<detail::Classifier, std::string> &miss : sub->missing_) {
8059 miss_list.push_back(std::get<1>(miss));
8067 std::vector<std::string> output = sub->remaining(recurse);
8068 std::copy(std::begin(output), std::end(output), std::back_inserter(miss_list));
8075 bool recurse)
const {
8076 std::vector<std::string> miss_list =
remaining(recurse);
8077 std::reverse(std::begin(miss_list), std::end(miss_list));
8082 auto remaining_options =
static_cast<std::size_t
>(
8084 [](
const std::pair<detail::Classifier, std::string> &val) {
8085 return val.first != detail::Classifier::POSITIONAL_MARK;
8090 remaining_options += sub->remaining_size(recurse);
8093 return remaining_options;
8098 auto pcount = std::count_if(std::begin(
options_), std::end(
options_), [](
const Option_p &opt) {
8099 return opt->get_items_expected_max() >= detail::expected_max_vector_size &&
8100 !opt->nonpositional();
8104 std::count_if(std::begin(
options_), std::end(
options_), [](
const Option_p &opt) {
8105 return opt->get_items_expected_max() >= detail::expected_max_vector_size &&
8106 !opt->nonpositional() && opt->get_required();
8108 if (pcount - pcount_req > 1) {
8113 std::size_t nameless_subs{0};
8116 if (app->
get_name().empty()) ++nameless_subs;
8122 throw(
InvalidError(
"Required min options greater than required max options",
8123 ExitCodes::InvalidError));
8127 throw(
InvalidError(
"Required min options greater than number of available options",
8128 ExitCodes::InvalidError));
8143 if (app->
name_.empty()) {
8162 if (subc->parent_ ==
this) {
8163 subc->run_callback(
true, suppress_final_callback);
8168 if (subc->name_.empty() && subc->count_all() > 0) {
8169 subc->run_callback(
true, suppress_final_callback);
8182 bool ignore_used)
const {
8185 return parent_ !=
nullptr &&
parent_->_valid_subcommand(current, ignore_used);
8188 if (com !=
nullptr) {
8192 return parent_ !=
nullptr &&
parent_->_valid_subcommand(current, ignore_used);
8196 const std::string ¤t,
bool ignore_used_subcommands)
const {
8197 std::string dummy1, dummy2;
8199 if (current ==
"--")
return detail::Classifier::POSITIONAL_MARK;
8200 if (
_valid_subcommand(current, ignore_used_subcommands))
return detail::Classifier::SUBCOMMAND;
8201 if (detail::split_long(current, dummy1, dummy2))
return detail::Classifier::LONG;
8202 if (detail::split_short(current, dummy1, dummy2)) {
8203 if (dummy1[0] >=
'0' && dummy1[0] <=
'9') {
8205 return detail::Classifier::NONE;
8208 return detail::Classifier::SHORT;
8211 return detail::Classifier::WINDOWS_STYLE;
8212 if ((current ==
"++") && !
name_.empty() &&
parent_ !=
nullptr)
8213 return detail::Classifier::SUBCOMMAND_TERMINATOR;
8214 return detail::Classifier::NONE;
8219 bool config_required =
config_ptr_->get_required();
8221 auto config_files =
config_ptr_->as<std::vector<std::string>>();
8222 if (config_files.empty() || config_files.front().empty()) {
8223 if (config_required) {
8224 throw FileError::Missing(
"no specified config file");
8228 for (
auto rit = config_files.rbegin(); rit != config_files.rend(); ++rit) {
8229 const auto &config_file = *rit;
8230 auto path_result = detail::check_path(config_file.c_str());
8231 if (path_result == detail::path_type::file) {
8239 if (config_required || file_given)
throw;
8241 }
else if (config_required || file_given) {
8242 throw FileError::Missing(config_file);
8249 for (
const Option_p &opt :
options_) {
8251 char *buffer =
nullptr;
8252 std::string ename_string;
8257 if (_dupenv_s(&buffer, &sz, opt->
envname_.c_str()) == 0 && buffer !=
nullptr) {
8258 ename_string = std::string(buffer);
8263 buffer = std::getenv(opt->
envname_.c_str());
8264 if (buffer !=
nullptr) ename_string = std::string(buffer);
8267 if (!ename_string.empty()) {
8274 if (sub->get_name().empty() || !sub->parse_complete_callback_) sub->_process_env();
8281 if (sub->get_name().empty() && sub->parse_complete_callback_) {
8282 if (sub->count_all() > 0) {
8283 sub->_process_callbacks();
8284 sub->run_callback();
8289 for (
const Option_p &opt :
options_) {
8295 if (!sub->parse_complete_callback_) {
8296 sub->_process_callbacks();
8305 if (help_ptr !=
nullptr && help_ptr->
count() > 0) trigger_help =
true;
8306 if (help_all_ptr !=
nullptr && help_all_ptr->
count() > 0) trigger_all_help =
true;
8312 sub->_process_help_flags(trigger_help, trigger_all_help);
8315 }
else if (trigger_all_help) {
8317 }
else if (trigger_help) {
8324 bool excluded{
false};
8325 std::string excluder;
8327 if (opt->
count() > 0) {
8333 if (subc->count_all() > 0) {
8335 excluder = subc->get_display_name();
8347 bool missing_needed{
false};
8348 std::string missing_need;
8350 if (opt->
count() == 0) {
8351 missing_needed =
true;
8356 if (subc->count_all() == 0) {
8357 missing_needed =
true;
8358 missing_need = subc->get_display_name();
8361 if (missing_needed) {
8369 std::size_t used_options = 0;
8370 for (
const Option_p &opt :
options_) {
8371 if (opt->
count() != 0) {
8379 for (
const Option *opt_req : opt->
needs_)
8380 if (opt->
count() > 0 && opt_req->
count() == 0)
8383 for (
const Option *opt_ex : opt->
excludes_)
8384 if (opt->
count() > 0 && opt_ex->
count() != 0)
8400 if (sub->disabled_)
continue;
8401 if (sub->name_.empty() && sub->count_all() > 0) {
8408 auto option_list = detail::join(
options_, [
this](
const Option_p &ptr) {
8410 return std::string{};
8412 return ptr->get_name(
false,
true);
8417 if (!subc_list.empty()) {
8418 option_list +=
"," + detail::join(subc_list, [](
const App *app) {
8428 if (sub->disabled_)
continue;
8429 if (sub->name_.empty() && sub->required_ ==
false) {
8430 if (sub->count_all() == 0) {
8443 if (sub->count() > 0 || sub->name_.empty()) {
8444 sub->_process_requirements();
8447 if (sub->required_ && sub->count_all() == 0) {
8478 if (num_left_over > 0) {
8484 if (sub->count() > 0) sub->_process_extras();
8491 if (num_left_over > 0) {
8498 if (sub->count() > 0) sub->_process_extras(args);
8505 if (sub->get_name().empty()) sub->increment_parsed();
8512 bool positional_only =
false;
8514 while (!args.empty()) {
8542 bool positional_only =
false;
8544 while (!args.empty()) {
8567 throw ConfigError::Extras(item.fullname());
8572 if (level < item.
parents.size()) {
8575 auto result = subcom->_parse_single_config(item, level + 1);
8583 if (item.
name ==
"++") {
8588 parent_->parsed_subcommands_.push_back(
this);
8594 if (item.
name ==
"--") {
8603 if (op ==
nullptr) {
8604 if (item.
name.size() == 1) {
8608 if (op ==
nullptr) {
8611 if (op ==
nullptr) {
8623 throw ConfigError::NotConfigurable(item.
fullname());
8628 if (item.
inputs.size() <= 1) {
8641 throw ConversionError::TooManyInputsFlag(item.
fullname());
8653 detail::Classifier classifier =
8654 positional_only ? detail::Classifier::NONE :
_recognize(args.back());
8655 switch (classifier) {
8656 case detail::Classifier::POSITIONAL_MARK:
8658 positional_only =
true;
8665 case detail::Classifier::SUBCOMMAND_TERMINATOR:
8670 case detail::Classifier::SUBCOMMAND:
8673 case detail::Classifier::LONG:
8674 case detail::Classifier::SHORT:
8675 case detail::Classifier::WINDOWS_STYLE:
8679 case detail::Classifier::NONE:
8683 positional_only =
true;
8688 throw HorribleError(
"unrecognized classifier (you should not see this!)");
8695 bool required_only)
const {
8696 std::size_t retval = 0;
8697 for (
const Option_p &opt :
options_) {
8709 for (
const Option_p &opt :
options_) {
8720 const std::string &positional = args.back();
8725 auto arg_rem = args.size();
8727 if (arg_rem <= remreq) {
8728 for (
const Option_p &opt :
options_) {
8732 std::string pos = positional;
8733 pos = opt->_validate(pos, 0);
8761 for (
const Option_p &opt :
options_) {
8767 std::string pos = positional;
8768 pos = opt->_validate(pos, 0);
8793 if ((subc->name_.empty()) && (!subc->disabled_)) {
8794 if (subc->_parse_positional(args,
false)) {
8795 if (!subc->pre_parse_called_) {
8796 subc->_trigger_pre_parse(args.size());
8809 if (com !=
nullptr &&
8811 if (haltOnSubcommand) {
8822 if (com !=
nullptr &&
8823 (com->parent_->require_subcommand_max_ == 0 ||
8824 com->parent_->require_subcommand_max_ > com->parent_->parsed_subcommands_.size())) {
8839 while (!args.empty()) {
8849 bool ignore_disabled,
8850 bool ignore_used)
const noexcept {
8852 if (com->disabled_ && ignore_disabled)
continue;
8853 if (com->get_name().empty()) {
8854 auto *subc = com->_find_subcommand(subc_name, ignore_disabled, ignore_used);
8855 if (subc !=
nullptr) {
8859 if (com->check_name(subc_name)) {
8860 if ((!*com) || !ignore_used)
return com.get();
8872 if (com !=
nullptr) {
8874 if (!com->silent_) {
8878 auto *parent_app = com->parent_;
8879 while (parent_app !=
this) {
8880 parent_app->_trigger_pre_parse(args.size());
8881 if (!com->silent_) {
8882 parent_app->parsed_subcommands_.push_back(com);
8884 parent_app = parent_app->parent_;
8893CLI11_INLINE
bool App::_parse_arg(std::vector<std::string> &args, detail::Classifier current_type) {
8894 std::string current = args.back();
8896 std::string arg_name;
8900 switch (current_type) {
8901 case detail::Classifier::LONG:
8902 if (!detail::split_long(current, arg_name, value))
8903 throw HorribleError(
"Long parsed but missing (you should not see this):" +
8906 case detail::Classifier::SHORT:
8907 if (!detail::split_short(current, arg_name, rest))
8908 throw HorribleError(
"Short parsed but missing! You should not see this");
8910 case detail::Classifier::WINDOWS_STYLE:
8911 if (!detail::split_windows_style(current, arg_name, value))
8912 throw HorribleError(
"windows option parsed but missing! You should not see this");
8914 case detail::Classifier::SUBCOMMAND:
8915 case detail::Classifier::SUBCOMMAND_TERMINATOR:
8916 case detail::Classifier::POSITIONAL_MARK:
8917 case detail::Classifier::NONE:
8919 throw HorribleError(
"parsing got called with invalid option! You should not see this");
8923 [arg_name, current_type](
const Option_p &opt) {
8924 if (current_type == detail::Classifier::LONG)
8925 return opt->check_lname(arg_name);
8926 if (current_type == detail::Classifier::SHORT)
8927 return opt->check_sname(arg_name);
8930 return opt->check_lname(arg_name) || opt->check_sname(arg_name);
8934 if (op_ptr == std::end(
options_)) {
8936 if (subc->name_.empty() && !subc->disabled_) {
8937 if (subc->_parse_arg(args, current_type)) {
8938 if (!subc->pre_parse_called_) {
8939 subc->_trigger_pre_parse(args.size());
8965 Option_p &op = *op_ptr;
8967 if (op->get_inject_separator()) {
8968 if (!op->results().empty() && !op->results().back().empty()) {
8969 op->add_result(std::string{});
8972 if (op->get_trigger_on_parse() &&
8976 int min_num = (std::min)(op->get_type_size_min(), op->get_items_expected_min());
8977 int max_num = op->get_items_expected_max();
8980 if (max_num >= detail::expected_max_vector_size / 16 && !op->get_allow_extra_args()) {
8981 auto tmax = op->get_type_size_max();
8982 max_num = detail::checked_multiply(tmax, op->get_expected_min())
8984 : detail::expected_max_vector_size;
8988 int result_count = 0;
8991 auto res = op->get_flag_value(arg_name, value);
8992 op->add_result(res);
8994 }
else if (!value.empty()) {
8995 op->add_result(value, result_count);
8997 collected += result_count;
8999 }
else if (!rest.empty()) {
9000 op->add_result(rest, result_count);
9003 collected += result_count;
9007 while (min_num > collected && !args.empty()) {
9008 std::string current_ = args.back();
9010 op->add_result(current_, result_count);
9012 collected += result_count;
9015 if (min_num > collected) {
9016 throw ArgumentMismatch::TypedAtLeast(op->get_name(), min_num, op->get_type_name());
9020 if (max_num > collected || op->get_allow_extra_args()) {
9023 while ((collected < max_num || op->get_allow_extra_args()) && !args.empty() &&
9024 _recognize(args.back(),
false) == detail::Classifier::NONE) {
9026 if (remreqpos >= args.size()) {
9030 std::string arg = args.back();
9031 arg = op->_validate(arg, 0);
9036 op->add_result(args.back(), result_count);
9039 collected += result_count;
9043 if (!args.empty() &&
_recognize(args.back()) == detail::Classifier::POSITIONAL_MARK)
9046 if (min_num == 0 && max_num > 0 && collected == 0) {
9047 auto res = op->get_flag_value(arg_name, std::string{});
9048 op->add_result(res);
9054 if (min_num > 0 && (collected % op->get_type_size_max()) != 0) {
9055 if (op->get_type_size_max() != op->get_type_size_min()) {
9056 op->add_result(std::string{});
9058 throw ArgumentMismatch::PartialType(op->get_name(), op->get_type_size_min(),
9059 op->get_type_name());
9062 if (op->get_trigger_on_parse()) {
9065 if (!rest.empty()) {
9067 args.push_back(rest);
9079 if (!
name_.empty()) {
9094 auto *fallthrough_parent =
parent_;
9095 while ((fallthrough_parent->parent_ !=
nullptr) && (fallthrough_parent->get_name().empty())) {
9096 fallthrough_parent = fallthrough_parent->parent_;
9098 return fallthrough_parent;
9102 const App &subcom,
const App &base)
const {
9103 static const std::string estring;
9108 if (subc.get() != &subcom) {
9109 if (subc->disabled_) {
9113 if (subc->check_name(subcom.
get_name())) {
9117 if (!subc->get_name().empty()) {
9119 return subc->get_name();
9122 for (
const auto &les : subcom.
aliases_) {
9123 if (subc->check_name(les)) {
9129 for (
const auto &les : subc->aliases_) {
9135 if (subc->get_name().empty()) {
9137 if (!cmpres.empty()) {
9144 if (!cmpres.empty()) {
9155 missing_.emplace_back(val_type, val);
9160 if (subc->name_.empty() && subc->allow_extras_) {
9161 subc->missing_.emplace_back(val_type, val);
9166 missing_.emplace_back(val_type, val);
9170 if (opt ==
nullptr) {
9176 if (app == subc.get()) {
9190 [opt](
const Option_p &v) {
return v.get() == opt; });
9191 if (iterator != std::end(
options_)) {
9192 const auto &opt_p = *iterator;
9194 [&opt_p](
const Option_p &v) { return (*v == *opt_p); }) ==
9197 app->
options_.push_back(std::move(*iterator));
9207CLI11_INLINE
void TriggerOn(
App *trigger_app,
App *app_to_enable) {
9211 [app_to_enable](std::size_t) { app_to_enable->
disabled(
false); });
9214CLI11_INLINE
void TriggerOn(
App *trigger_app, std::vector<App *> apps_to_enable) {
9215 for (
auto &app : apps_to_enable) {
9220 trigger_app->preparse_callback([apps_to_enable](std::size_t) {
9221 for (
const auto &app : apps_to_enable) {
9227CLI11_INLINE
void TriggerOff(
App *trigger_app,
App *app_to_enable) {
9228 app_to_enable->disabled_by_default(
false);
9229 app_to_enable->enabled_by_default();
9230 trigger_app->preparse_callback([app_to_enable](std::size_t) { app_to_enable->disabled(); });
9233CLI11_INLINE
void TriggerOff(
App *trigger_app, std::vector<App *> apps_to_enable) {
9234 for (
auto &app : apps_to_enable) {
9239 trigger_app->preparse_callback([apps_to_enable](std::size_t) {
9240 for (
const auto &app : apps_to_enable) {
9246CLI11_INLINE
void deprecate_option(
Option *opt,
const std::string &replacement) {
9247 Validator deprecate_warning{[opt, replacement](std::string &) {
9248 std::cout << opt->get_name() <<
" is deprecated please use '"
9249 << replacement <<
"' instead\n";
9250 return std::string();
9254 opt->check(deprecate_warning);
9255 if (!replacement.empty()) {
9256 opt->description(opt->get_description() +
" DEPRECATED: please use '" + replacement +
9261CLI11_INLINE
void retire_option(
App *app,
Option *opt) {
9263 auto *option_copy = temp.
add_option(opt->get_name(
false,
true))
9264 ->
type_size(opt->get_type_size_min(), opt->get_type_size_max())
9265 ->
expected(opt->get_expected_min(), opt->get_expected_max())
9268 app->remove_option(opt);
9269 auto *opt2 = app->add_option(option_copy->get_name(
false,
true),
9270 "option has been retired and has no effect")
9273 ->
type_size(option_copy->get_type_size_min(), option_copy->get_type_size_max())
9274 ->
expected(option_copy->get_expected_min(), option_copy->get_expected_max())
9277 Validator retired_warning{[opt2](std::string &) {
9278 std::cout <<
"WARNING " << opt2->get_name()
9279 <<
" is retired and has no effect\n";
9280 return std::string();
9284 opt2->check(retired_warning);
9287CLI11_INLINE
void retire_option(
App &app,
Option *opt) { retire_option(&app, opt); }
9289CLI11_INLINE
void retire_option(
App *app,
const std::string &option_name) {
9290 auto *opt = app->get_option_no_throw(option_name);
9291 if (opt !=
nullptr) {
9292 retire_option(app, opt);
9295 auto *opt2 = app->add_option(option_name,
"option has been retired and has no effect")
9296 ->type_name(
"RETIRED")
9298 ->default_str(
"RETIRED");
9299 Validator retired_warning{[opt2](std::string &) {
9300 std::cout <<
"WARNING " << opt2->get_name()
9301 <<
" is retired and has no effect\n";
9302 return std::string();
9306 opt2->check(retired_warning);
9309CLI11_INLINE
void retire_option(
App &app,
const std::string &option_name) {
9310 retire_option(&app, option_name);
9313namespace FailureMessage {
9315CLI11_INLINE std::string simple(
const App *app,
const Error &e) {
9316 std::string header = std::string(e.what()) +
"\n";
9317 std::vector<std::string> names;
9320 if (app->get_help_ptr() !=
nullptr) names.push_back(app->get_help_ptr()->get_name());
9322 if (app->get_help_all_ptr() !=
nullptr) names.push_back(app->get_help_all_ptr()->get_name());
9326 header +=
"Run with " + detail::join(names,
" or ") +
" for more information.\n";
9331CLI11_INLINE std::string help(
const App *app,
const Error &e) {
9332 std::string header = std::string(
"ERROR: ") + e.get_name() +
": " + e.what() +
"\n";
9333 header += app->help();
9341std::string convert_arg_for_ini(
const std::string &arg,
9342 char stringQuote =
'"',
9343 char characterQuote =
'\'');
9346std::string ini_join(
const std::vector<std::string> &args,
9348 char arrayStart =
'[',
9349 char arrayEnd =
']',
9350 char stringQuote =
'"',
9351 char characterQuote =
'\'');
9353std::vector<std::string> generate_parents(
const std::string §ion,
9355 char parentSeparator);
9359void checkParentSegments(std::vector<ConfigItem> &output,
9360 const std::string ¤tSection,
9361 char parentSeparator);
9366CLI11_INLINE std::string convert_arg_for_ini(
const std::string &arg,
9368 char characterQuote) {
9370 return std::string(2, stringQuote);
9373 if (arg ==
"true" || arg ==
"false" || arg ==
"nan" || arg ==
"inf") {
9377 if (arg.compare(0, 2,
"0x") != 0 && arg.compare(0, 2,
"0X") != 0) {
9379 if (detail::lexical_cast(arg, val)) {
9384 if (arg.size() == 1) {
9385 return std::string(1, characterQuote) + arg + characterQuote;
9388 if (arg.front() ==
'0') {
9389 if (arg[1] ==
'x') {
9390 if (std::all_of(arg.begin() + 2, arg.end(), [](
char x) {
9391 return (x >=
'0' && x <=
'9') || (x >=
'A' && x <=
'F') ||
9392 (x >=
'a' && x <=
'f');
9396 }
else if (arg[1] ==
'o') {
9397 if (std::all_of(arg.begin() + 2, arg.end(),
9398 [](
char x) { return (x >=
'0' && x <=
'7'); })) {
9401 }
else if (arg[1] ==
'b') {
9402 if (std::all_of(arg.begin() + 2, arg.end(),
9403 [](
char x) { return (x ==
'0' || x ==
'1'); })) {
9408 if (arg.find_first_of(stringQuote) == std::string::npos) {
9409 return std::string(1, stringQuote) + arg + stringQuote;
9411 return characterQuote + arg + characterQuote;
9414CLI11_INLINE std::string ini_join(
const std::vector<std::string> &args,
9419 char characterQuote) {
9421 if (args.size() > 1 && arrayStart !=
'\0') {
9422 joined.push_back(arrayStart);
9424 std::size_t start = 0;
9425 for (
const auto &arg : args) {
9427 joined.push_back(sepChar);
9428 if (!std::isspace<char>(sepChar, std::locale())) {
9429 joined.push_back(
' ');
9432 joined.append(convert_arg_for_ini(arg, stringQuote, characterQuote));
9434 if (args.size() > 1 && arrayEnd !=
'\0') {
9435 joined.push_back(arrayEnd);
9440CLI11_INLINE std::vector<std::string> generate_parents(
const std::string §ion,
9442 char parentSeparator) {
9443 std::vector<std::string> parents;
9444 if (detail::to_lower(section) !=
"default") {
9445 if (section.find(parentSeparator) != std::string::npos) {
9446 parents = detail::split(section, parentSeparator);
9448 parents = {section};
9451 if (name.find(parentSeparator) != std::string::npos) {
9452 std::vector<std::string> plist = detail::split(name, parentSeparator);
9453 name = plist.back();
9454 detail::remove_quotes(name);
9456 parents.insert(parents.end(), plist.begin(), plist.end());
9460 for (
auto &parent : parents) {
9461 detail::remove_quotes(parent);
9466CLI11_INLINE
void checkParentSegments(std::vector<ConfigItem> &output,
9467 const std::string ¤tSection,
9468 char parentSeparator) {
9469 std::string estring;
9470 auto parents = detail::generate_parents(currentSection, estring, parentSeparator);
9471 if (!output.empty() && output.back().name ==
"--") {
9472 std::size_t msize = (parents.size() > 1U) ? parents.size() : 2;
9473 while (output.back().parents.size() >= msize) {
9474 output.push_back(output.back());
9475 output.back().parents.pop_back();
9478 if (parents.size() > 1) {
9479 std::size_t common = 0;
9480 std::size_t mpair = (std::min)(output.back().parents.size(), parents.size() - 1);
9481 for (std::size_t ii = 0; ii < mpair; ++ii) {
9482 if (output.back().parents[ii] != parents[ii]) {
9487 if (common == mpair) {
9490 while (output.back().parents.size() > common + 1) {
9491 output.push_back(output.back());
9492 output.back().parents.pop_back();
9495 for (std::size_t ii = common; ii < parents.size() - 1; ++ii) {
9496 output.emplace_back();
9497 output.back().parents.assign(parents.begin(),
9498 parents.begin() +
static_cast<std::ptrdiff_t
>(ii) + 1);
9499 output.back().name =
"++";
9502 }
else if (parents.size() > 1) {
9503 for (std::size_t ii = 0; ii < parents.size() - 1; ++ii) {
9504 output.emplace_back();
9505 output.back().parents.assign(parents.begin(),
9506 parents.begin() +
static_cast<std::ptrdiff_t
>(ii) + 1);
9507 output.back().name =
"++";
9512 output.emplace_back();
9513 output.back().parents = std::move(parents);
9514 output.back().name =
"++";
9520 std::string currentSection =
"default";
9521 std::string previousSection =
"default";
9522 std::vector<ConfigItem> output;
9525 bool inSection{
false};
9526 char aStart = (isINIArray) ?
'[' :
arrayStart;
9527 char aEnd = (isINIArray) ?
']' :
arrayEnd;
9529 int currentSectionIndex{0};
9530 while (getline(input, line)) {
9531 std::vector<std::string> items_buffer;
9535 std::size_t len = line.length();
9540 if (line.front() ==
'[' && line.back() ==
']') {
9541 if (currentSection !=
"default") {
9543 output.emplace_back();
9544 output.back().parents =
9546 output.back().name =
"--";
9548 currentSection = line.substr(1, len - 2);
9550 if (currentSection.size() > 1 && currentSection.front() ==
'[' &&
9551 currentSection.back() ==
']') {
9552 currentSection = currentSection.substr(1, currentSection.size() - 2);
9554 if (detail::to_lower(currentSection) ==
"default") {
9555 currentSection =
"default";
9560 if (currentSection == previousSection) {
9561 ++currentSectionIndex;
9563 currentSectionIndex = 0;
9564 previousSection = currentSection;
9570 if (line.front() ==
';' || line.front() ==
'#' || line.front() ==
commentChar) {
9576 if (pos != std::string::npos) {
9577 name = detail::trim_copy(line.substr(0, pos));
9578 std::string item = detail::trim_copy(line.substr(pos + 1));
9580 if (cloc != std::string::npos) {
9585 if (item.size() > 1 && item.front() == aStart) {
9586 for (std::string multiline;
9587 item.back() != aEnd && std::getline(input, multiline);) {
9588 detail::trim(multiline);
9591 items_buffer = detail::split_up(item.substr(1, item.length() - 2), aSep);
9592 }
else if ((isDefaultArray || isINIArray) &&
9593 item.find_first_of(aSep) != std::string::npos) {
9594 items_buffer = detail::split_up(item, aSep);
9595 }
else if ((isDefaultArray || isINIArray) &&
9596 item.find_first_of(
' ') != std::string::npos) {
9597 items_buffer = detail::split_up(item);
9599 items_buffer = {item};
9602 name = detail::trim_copy(line);
9604 if (cloc != std::string::npos) {
9610 items_buffer = {
"true"};
9613 detail::remove_quotes(name);
9616 for (
auto &it : items_buffer) {
9617 detail::remove_quotes(it);
9620 std::vector<std::string> parents =
9632 parents.erase(parents.begin());
9635 if (!output.empty() && name == output.back().name && parents == output.back().parents) {
9636 output.back().inputs.insert(output.back().inputs.end(), items_buffer.begin(),
9637 items_buffer.end());
9639 output.emplace_back();
9640 output.back().parents = std::move(parents);
9641 output.back().name = std::move(name);
9642 output.back().inputs = std::move(items_buffer);
9645 if (currentSection !=
"default") {
9648 output.emplace_back();
9649 output.back().parents =
9651 output.back().name =
"--";
9652 while (output.back().parents.size() > 1) {
9653 output.push_back(output.back());
9654 output.back().parents.pop_back();
9662 bool write_description,
9663 std::string prefix)
const {
9664 std::stringstream out;
9665 std::string commentLead;
9667 commentLead.push_back(
' ');
9669 std::vector<std::string> groups = app->
get_groups();
9670 bool defaultUsed =
false;
9671 groups.insert(groups.begin(), std::string(
"Options"));
9672 if (write_description &&
9674 out << commentLead << detail::fix_newlines(commentLead, app->
get_description()) <<
'\n';
9676 for (
auto &group : groups) {
9677 if (group ==
"Options" || group.empty()) {
9683 if (write_description && group !=
"Options" && !group.empty()) {
9684 out <<
'\n' << commentLead << group <<
" Options\n";
9688 if (opt->get_configurable()) {
9689 if (opt->get_group() != group) {
9690 if (!(group ==
"Options" && opt->get_group().empty())) {
9694 std::string name = prefix + opt->get_single_name();
9699 if (value.empty() && default_also) {
9700 if (!opt->get_default_str().empty()) {
9701 value = detail::convert_arg_for_ini(opt->get_default_str(),
stringQuote,
9703 }
else if (opt->get_expected_min() == 0) {
9705 }
else if (opt->get_run_callback_for_default()) {
9710 if (!value.empty()) {
9711 if (!opt->get_fnames().empty()) {
9712 value = opt->get_flag_value(name, value);
9714 if (write_description && opt->has_description()) {
9717 << detail::fix_newlines(commentLead, opt->get_description()) <<
'\n';
9725 for (
const App *subcom : subcommands) {
9726 if (subcom->get_name().empty()) {
9727 if (write_description && !subcom->get_group().empty()) {
9728 out <<
'\n' << commentLead << subcom->get_group() <<
" Options\n";
9730 out <<
to_config(subcom, default_also, write_description, prefix);
9734 for (
const App *subcom : subcommands) {
9735 if (!subcom->get_name().empty()) {
9737 if (!prefix.empty() || app->
get_parent() ==
nullptr) {
9738 out <<
'[' << prefix << subcom->get_name() <<
"]\n";
9740 std::string subname =
9743 while (p->get_parent() !=
nullptr) {
9745 p = p->get_parent();
9747 out <<
'[' << subname <<
"]\n";
9749 out <<
to_config(subcom, default_also, write_description,
"");
9751 out <<
to_config(subcom, default_also, write_description,
9762 std::vector<const Option *> opts)
const {
9763 std::stringstream out;
9765 out <<
"\n" << group <<
":\n";
9766 for (
const Option *opt : opts) {
9774 std::vector<const Option *> opts = app->
get_options(
9777 if (opts.empty())
return {};
9783 std::stringstream out;
9784 std::vector<std::string> groups = app->
get_groups();
9787 for (
const std::string &group : groups) {
9788 std::vector<const Option *> opts = app->
get_options([app, mode, &group](
const Option *opt) {
9791 && (mode != AppFormatMode::Sub
9795 if (!group.empty() && !opts.empty()) {
9798 if (group != groups.back()) out <<
"\n";
9810 desc +=
" REQUIRED ";
9812 if ((max_options == min_options) && (min_options > 0)) {
9813 if (min_options == 1) {
9814 desc +=
" \n[Exactly 1 of the following options is required]";
9816 desc +=
" \n[Exactly " + std::to_string(min_options) +
9817 "options from the following list are required]";
9819 }
else if (max_options > 0) {
9820 if (min_options > 0) {
9821 desc +=
" \n[Between " + std::to_string(min_options) +
" and " +
9822 std::to_string(max_options) +
" of the follow options are required]";
9824 desc +=
" \n[At most " + std::to_string(max_options) +
9825 " of the following options are allowed]";
9827 }
else if (min_options > 0) {
9828 desc +=
" \n[At least " + std::to_string(min_options) +
9829 " of the following options are required]";
9831 return (!desc.empty()) ? desc +
"\n" : std::string{};
9835 std::stringstream out;
9837 out <<
get_label(
"Usage") <<
":" << (name.empty() ?
"" :
" ") << name;
9839 std::vector<std::string> groups = app->
get_groups();
9842 std::vector<const Option *> non_pos_options =
9844 if (!non_pos_options.empty()) out <<
" [" <<
get_label(
"OPTIONS") <<
"]";
9847 std::vector<const Option *> positionals =
9851 if (!positionals.empty()) {
9853 std::vector<std::string> positional_names(positionals.size());
9854 std::transform(positionals.begin(), positionals.end(), positional_names.begin(),
9855 [
this](
const Option *opt) { return make_option_usage(opt); });
9857 out <<
" " << detail::join(positional_names,
" ");
9862 return ((!subc->get_disabled()) && (!subc->get_name().empty()));
9880 if (footer.empty()) {
9881 return std::string{};
9883 return "\n" + footer +
"\n";
9888 AppFormatMode mode)
const {
9893 std::stringstream out;
9895 if (app->
get_group() !=
"Subcommands") {
9915 std::stringstream out;
9920 std::vector<std::string> subcmd_groups_seen;
9921 for (
const App *com : subcommands) {
9922 if (com->get_name().empty()) {
9923 if (!com->get_group().empty()) {
9928 std::string group_key = com->get_group();
9929 if (!group_key.empty() && std::find_if(subcmd_groups_seen.begin(), subcmd_groups_seen.end(),
9930 [&group_key](std::string a) {
9931 return detail::to_lower(a) ==
9932 detail::to_lower(group_key);
9933 }) == subcmd_groups_seen.end())
9934 subcmd_groups_seen.push_back(group_key);
9938 for (
const std::string &group : subcmd_groups_seen) {
9939 out <<
"\n" << group <<
":\n";
9940 std::vector<const App *> subcommands_group =
9942 return detail::to_lower(sub_app->
get_group()) == detail::to_lower(group);
9944 for (
const App *new_com : subcommands_group) {
9945 if (new_com->get_name().empty())
continue;
9946 if (mode != AppFormatMode::All) {
9949 out << new_com->help(new_com->get_name(), AppFormatMode::Sub);
9959 std::stringstream out;
9965 std::stringstream out;
9977 std::string tmp = detail::find_and_replace(out.str(),
"\n\n",
"\n");
9978 tmp = tmp.substr(0, tmp.size() - 1);
9981 return detail::find_and_replace(tmp,
"\n",
"\n ") +
"\n";
9985 if (is_positional)
return opt->
get_name(
true,
false);
9991 std::stringstream out;
9993 if (!opt->get_option_text().empty()) {
9994 out <<
" " << opt->get_option_text();
10009 out <<
" " <<
get_label(
"Needs") <<
":";
10010 for (
const Option *op : opt->
get_needs()) out <<
" " << op->get_name();
10013 out <<
" " <<
get_label(
"Excludes") <<
":";
10026 std::stringstream out;
10033 return opt->
get_required() ? out.str() :
"[" + out.str() +
"]";
Creates a command line program, with very few defaults.
Definition CLI11.hpp:5883
int exit(const Error &e, std::ostream &out=std::cout, std::ostream &err=std::cerr) const
Print a nice error message and return the exit code.
Definition CLI11.hpp:7800
CLI11_NODISCARD std::string help(std::string prev="", AppFormatMode mode=AppFormatMode::Normal) const
Definition CLI11.hpp:7894
CLI11_NODISCARD std::size_t remaining_size(bool recurse=false) const
This returns the number of remaining options, minus the – separator.
Definition CLI11.hpp:8081
const Option * operator[](const std::string &option_name) const
Shortcut bracket operator for getting a pointer to an option.
Definition CLI11.hpp:6856
CLI11_NODISCARD bool _has_remaining_positionals() const
Count the required remaining positional arguments.
Definition CLI11.hpp:8708
App * configurable(bool value=true)
Specify that the subcommand can be triggered by a config file.
Definition CLI11.hpp:6252
CLI11_NODISCARD detail::Classifier _recognize(const std::string ¤t, bool ignore_used_subcommands=true) const
Selects a Classifier enum based on the type of the current argument.
Definition CLI11.hpp:8195
App * immediate_callback(bool immediate=true)
Set the subcommand callback to be executed immediately on subcommand completion.
Definition CLI11.hpp:7331
Option * get_option_no_throw(std::string option_name) noexcept
Get an option by name (noexcept non-const version).
Definition CLI11.hpp:7954
Option * set_help_flag(std::string flag_name="", const std::string &help_description="")
Set a help flag, replace the existing one if present.
Definition CLI11.hpp:7410
App * _get_fallthrough_parent()
Definition CLI11.hpp:9090
CLI11_NODISCARD std::string config_to_str(bool default_also=false, bool write_description=false) const
Definition CLI11.hpp:6780
CLI11_NODISCARD bool get_enabled_by_default() const
Get the status of disabled by default.
Definition CLI11.hpp:6931
Option * config_ptr_
Pointer to the config option.
Definition CLI11.hpp:6081
CLI11_NODISCARD bool got_subcommand(std::string subcommand_name) const
Check with name instead of pointer to see if subcommand was selected.
Definition CLI11.hpp:6704
CLI11_NODISCARD bool get_configurable() const
Check the status of the allow windows style options.
Definition CLI11.hpp:6881
Option * add_option_no_stream(std::string option_name, AssignTo &variable, std::string option_description="")
Add option for assigning to a variable.
Definition CLI11.hpp:6337
CLI11_NODISCARD std::shared_ptr< FormatterBase > get_formatter() const
Access the formatter.
Definition CLI11.hpp:6797
Option * add_option(std::string option_name)
Add option with no description or variable assignment.
Definition CLI11.hpp:6377
App * config_formatter(std::shared_ptr< Config > fmt)
Set the config formatter.
Definition CLI11.hpp:6273
App * allow_config_extras(bool allow=true)
ignore extras in config files
Definition CLI11.hpp:6213
App * disabled_by_default(bool disable=true)
Definition CLI11.hpp:6175
void _move_to_missing(detail::Classifier val_type, const std::string &val)
Helper function to place extra values in the most appropriate position.
Definition CLI11.hpp:9153
std::size_t require_option_min_
Minimum required options (not inheritable!).
Definition CLI11.hpp:6062
App * silent(bool silence=true)
silence the subcommand from showing up in the processed list
Definition CLI11.hpp:6168
App * clear_aliases()
clear all the aliases of the current App
Definition CLI11.hpp:6980
CLI11_NODISCARD bool get_ignore_underscore() const
Check the status of ignore_underscore.
Definition CLI11.hpp:6867
App * ignore_underscore(bool value=true)
Ignore underscore. Subcommands inherit value.
Definition CLI11.hpp:7357
App * allow_extras(bool allow=true)
Remove the error when extras are left over on the command line.
Definition CLI11.hpp:6150
App * fallthrough(bool value=true)
Definition CLI11.hpp:6623
std::size_t require_subcommand_max_
Definition CLI11.hpp:6059
Option * get_config_ptr()
Get a pointer to the config option.
Definition CLI11.hpp:6956
std::vector< App_p > subcommands_
Storage for subcommand list.
Definition CLI11.hpp:6009
CLI11_NODISCARD std::vector< std::string > remaining(bool recurse=false) const
This returns the missing options from the current subcommand.
Definition CLI11.hpp:8048
CLI11_NODISCARD bool get_allow_extras() const
Get the status of allow extras.
Definition CLI11.hpp:6911
CLI11_NODISCARD std::vector< std::string > remaining_for_passthrough(bool recurse=false) const
Definition CLI11.hpp:8074
std::uint32_t parsed_
Counts the number of times this command/subcommand was parsed.
Definition CLI11.hpp:6052
CLI11_NODISCARD App * get_option_group(std::string group_name) const
Check to see if an option group is part of this App.
Definition CLI11.hpp:7675
App * require_subcommand()
The argumentless form of require subcommand requires 1 or more subcommands.
Definition CLI11.hpp:6564
Option * get_option(std::string option_name)
Get an option by name (non-const version).
Definition CLI11.hpp:6847
OptionDefaults option_defaults_
The default values for options, customizable and changeable INHERITABLE.
Definition CLI11.hpp:5939
void _process_help_flags(bool trigger_help=false, bool trigger_all_help=false) const
Definition CLI11.hpp:8301
CLI11_NODISCARD const Option * get_version_ptr() const
Get a pointer to the version option. (const).
Definition CLI11.hpp:6965
void _process_requirements()
Verify required options and cross requirements. Subcommands too (only if selected).
Definition CLI11.hpp:8322
CLI11_NODISCARD std::size_t count_all() const
Definition CLI11.hpp:7684
CLI11_NODISCARD bool get_fallthrough() const
Check the status of fallthrough.
Definition CLI11.hpp:6870
bool disabled_
If set to true the subcommand is disabled and cannot be used, ignored for main app.
Definition CLI11.hpp:5916
CLI11_NODISCARD bool get_prefix_command() const
Get the prefix command status.
Definition CLI11.hpp:6908
Option * add_option(std::string option_name, AssignTo &variable, std::string option_description="")
Add option for assigning to a variable.
Definition CLI11.hpp:6312
CLI11_NODISCARD std::size_t get_require_subcommand_max() const
Get the required max subcommand value.
Definition CLI11.hpp:6897
Option * set_version_flag(std::string flag_name="", const std::string &versionString="", const std::string &version_help="Display program version information and exit")
Set a version flag and version display string, replace the existing one if present.
Definition CLI11.hpp:7446
bool required_
If set to true the subcommand is required to be processed and used, ignored for main app.
Definition CLI11.hpp:5913
bool remove_needs(Option *opt)
Removes an option from the needs list of this subcommand.
Definition CLI11.hpp:7876
bool _parse_arg(std::vector< std::string > &args, detail::Classifier current_type)
Definition CLI11.hpp:8893
const Option * operator[](const char *option_name) const
Shortcut bracket operator for getting a pointer to an option.
Definition CLI11.hpp:6861
CLI11_NODISCARD bool get_immediate_callback() const
Get the status of disabled.
Definition CLI11.hpp:6923
Option * get_help_ptr()
Get a pointer to the help flag.
Definition CLI11.hpp:6947
App * require_subcommand(int value)
Definition CLI11.hpp:6573
void _configure()
Definition CLI11.hpp:8133
CLI11_NODISCARD std::size_t _count_remaining_positionals(bool required_only=false) const
Count the required remaining positional arguments.
Definition CLI11.hpp:8694
Option * add_flag_function(std::string flag_name, std::function< void(std::int64_t)> function, std::string flag_description="")
Add option for callback with an integer value.
Definition CLI11.hpp:7526
OptionDefaults * option_defaults()
Get the OptionDefault object, to set option defaults.
Definition CLI11.hpp:6282
void parse(int argc, const char *const *argv)
Definition CLI11.hpp:7713
void _process_config_file()
Read and process a configuration file (main app only).
Definition CLI11.hpp:8217
std::string footer_
Footer to put after all options in the help output INHERITABLE.
Definition CLI11.hpp:5949
void increment_parsed()
Definition CLI11.hpp:8502
config_extras_mode allow_config_extras_
Definition CLI11.hpp:5904
CLI11_NODISCARD bool check_name(std::string name_to_check) const
Check the name, case insensitive and underscore insensitive if set.
Definition CLI11.hpp:8007
CLI11_NODISCARD std::string get_footer() const
Generate and return the footer.
Definition CLI11.hpp:6887
App * required(bool require=true)
Remove the error when extras are left over on the command line.
Definition CLI11.hpp:6156
Option * version_ptr_
A pointer to a version flag if there is one.
Definition CLI11.hpp:5961
CLI11_NODISCARD const Option * get_help_all_ptr() const
Get a pointer to the help all flag. (const).
Definition CLI11.hpp:6953
bool remove_subcommand(App *subcom)
Definition CLI11.hpp:7617
App * parent_
A pointer to the parent if this is a subcommand.
Definition CLI11.hpp:6068
std::set< Option * > exclude_options_
Definition CLI11.hpp:5994
void _trigger_pre_parse(std::size_t remaining_args)
Trigger the pre_parse callback if needed.
Definition CLI11.hpp:9072
App * prefix_command(bool allow=true)
Do not parse anything after the first unrecognized option and return.
Definition CLI11.hpp:6230
App * group(std::string group_name)
Changes the group membership.
Definition CLI11.hpp:6558
CLI::App_p get_subcommand_ptr(App *subcom) const
Check to see if a subcommand is part of this command and get a shared_ptr to it.
Definition CLI11.hpp:7654
std::function< std::string()> footer_callback_
This is a function that generates a footer to put after all other options in help output.
Definition CLI11.hpp:5952
std::function< void()> parse_complete_callback_
This is a function that runs when parsing has finished.
Definition CLI11.hpp:5929
virtual void pre_callback()
Definition CLI11.hpp:6639
T * add_option_group(std::string group_name, std::string group_description="")
creates an option group as part of the given app
Definition CLI11.hpp:6499
App * get_parent()
Get the parent of this subcommand (or nullptr if main app).
Definition CLI11.hpp:6968
Option * add_flag(std::string flag_name)
Add a flag with no description or variable assignment.
Definition CLI11.hpp:6415
void _validate() const
Definition CLI11.hpp:8096
std::string name_
Subcommand name or program name (from parser if name is empty).
Definition CLI11.hpp:5894
std::vector< App * > parsed_subcommands_
This is a list of the subcommands collected, in order.
Definition CLI11.hpp:5987
App(std::string app_description="", std::string app_name="")
Create a new program. Pass in the same arguments as main(), along with a help string.
Definition CLI11.hpp:6096
CLI11_NODISCARD const Option * get_help_ptr() const
Get a pointer to the help flag. (const).
Definition CLI11.hpp:6950
bool ignore_underscore_
If true, the program should ignore underscores INHERITABLE.
Definition CLI11.hpp:6015
App * allow_windows_style_options(bool value=true)
Definition CLI11.hpp:6240
missing_t missing_
Definition CLI11.hpp:5981
CLI11_NODISCARD bool get_validate_positionals() const
Get the status of validating positionals.
Definition CLI11.hpp:6935
Option * add_option_function(std::string option_name, const std::function< void(const ArgType &)> &func, std::string option_description="")
Add option for a callback of a specific type.
Definition CLI11.hpp:6356
void run_callback(bool final_mode=false, bool suppress_final_callback=false)
Internal function to run (App) callback, bottom up.
Definition CLI11.hpp:8153
std::size_t require_subcommand_min_
Minimum required subcommands (not inheritable!).
Definition CLI11.hpp:6055
void _process_env()
Get envname options if not yet passed. Runs on all subcommands.
Definition CLI11.hpp:8248
std::function< std::string(const App *, const Error &e)> failure_message_
The error message printing function INHERITABLE.
Definition CLI11.hpp:5967
void _parse_stream(std::istream &input)
Internal function to parse a stream.
Definition CLI11.hpp:8553
CLI11_NODISCARD std::string get_display_name(bool with_aliases=false) const
Get a display name for an app.
Definition CLI11.hpp:7991
void failure_message(std::function< std::string(const App *, const Error &e)> function)
Definition CLI11.hpp:6669
bool has_automatic_name_
If set to true the name was automatically generated from the command line vs a user set name.
Definition CLI11.hpp:5910
CLI11_NODISCARD const std::string & _compare_subcommand_names(const App &subcom, const App &base) const
Definition CLI11.hpp:9101
void clear()
Reset the parsed data.
Definition CLI11.hpp:7699
CLI11_NODISCARD std::size_t get_require_option_max() const
Get the required max option value.
Definition CLI11.hpp:6905
App * enabled_by_default(bool enable=true)
Definition CLI11.hpp:6187
App * footer(std::string footer_string)
Set footer.
Definition CLI11.hpp:6768
App * get_subcommand(const App *subcom) const
Definition CLI11.hpp:7633
App * require_option(int value)
Definition CLI11.hpp:6602
CLI11_NODISCARD std::string version() const
Displays a version string.
Definition CLI11.hpp:7908
virtual ~App()=default
virtual destructor
CLI11_NODISCARD std::size_t count(std::string option_name) const
Counts the number of times the given option was passed.
Definition CLI11.hpp:6681
std::vector< Option_p > options_
The list of options, stored locally.
Definition CLI11.hpp:5942
Option * help_all_ptr_
A pointer to the help all flag if there is one INHERITABLE.
Definition CLI11.hpp:5958
bool validate_optional_arguments_
If set to true optional vector arguments are validated before assigning INHERITABLE.
Definition CLI11.hpp:6045
std::function< void()> final_callback_
This is a function that runs when all processing has completed.
Definition CLI11.hpp:5932
bool remove_option(Option *opt)
Removes an option from the App. Takes an option pointer. Returns true if found and removed.
Definition CLI11.hpp:7565
App * require_option()
The argumentless form of require option requires 1 or more options be used.
Definition CLI11.hpp:6593
App(std::string app_description, std::string app_name, App *parent)
Special private constructor for subcommand.
Definition CLI11.hpp:7261
App * add_subcommand(std::string subcommand_name="", std::string subcommand_description="")
Add a subcommand. Inherits INHERITABLE and OptionDefaults, and help flag.
Definition CLI11.hpp:7584
App * preparse_callback(std::function< void(std::size_t)> pp_callback)
Definition CLI11.hpp:6138
Option * add_flag_callback(std::string flag_name, std::function< void(void)> function, std::string flag_description="")
Add option for callback that is triggered with a true flag and takes no arguments.
Definition CLI11.hpp:7511
bool positionals_at_end_
specify that positional arguments come at the end of the argument sequence not inheritable
Definition CLI11.hpp:6031
void _process()
Process callbacks and such.
Definition CLI11.hpp:8453
bool immediate_callback_
Definition CLI11.hpp:5923
bool _parse_single(std::vector< std::string > &args, bool &positional_only)
Definition CLI11.hpp:8651
App * name(std::string app_name="")
Set a name for the app (empty will use parser to set the name).
Definition CLI11.hpp:7296
void _move_option(Option *opt, App *app)
function that could be used by subclasses of App to shift options around into subcommands
Definition CLI11.hpp:9169
CLI11_NODISCARD bool get_required() const
Get the status of required.
Definition CLI11.hpp:6914
void _process_extras()
Throw an error if anything is left over and should not be.
Definition CLI11.hpp:8475
CLI11_NODISCARD bool _valid_subcommand(const std::string ¤t, bool ignore_used=true) const
Definition CLI11.hpp:8181
Option * add_flag(std::string flag_name, T &flag_description)
Definition CLI11.hpp:6425
CLI11_NODISCARD bool get_ignore_case() const
Check the status of ignore_case.
Definition CLI11.hpp:6864
App * parse_complete_callback(std::function< void()> pc_callback)
Definition CLI11.hpp:6131
bool configurable_
if set to true the subcommand can be triggered via configuration files INHERITABLE
Definition CLI11.hpp:6039
CLI11_NODISCARD std::vector< std::string > get_groups() const
Get the groups available directly from this option (in order).
Definition CLI11.hpp:8035
App * formatter_fn(std::function< std::string(const App *, std::string, AppFormatMode)> fmt)
Set the help formatter.
Definition CLI11.hpp:6267
CLI11_NODISCARD const std::vector< std::string > & get_aliases() const
Get the aliases of the current app.
Definition CLI11.hpp:6977
void _parse_config(const std::vector< ConfigItem > &args)
Definition CLI11.hpp:8564
App * description(std::string app_description)
Set the description of the app.
Definition CLI11.hpp:6818
CLI11_NODISCARD std::shared_ptr< ConfigBase > get_config_formatter_base() const
Access the config formatter as a configBase pointer.
Definition CLI11.hpp:6805
std::string description_
Description of the current program/subcommand.
Definition CLI11.hpp:5897
App * excludes(App *app)
Sets excluded subcommands for the subcommand.
Definition CLI11.hpp:6718
CLI11_NODISCARD bool get_positionals_at_end() const
Check the status of the allow windows style options.
Definition CLI11.hpp:6878
Option * get_version_ptr()
Get a pointer to the version option.
Definition CLI11.hpp:6962
CLI11_NODISCARD std::size_t get_require_option_min() const
Get the required min option value.
Definition CLI11.hpp:6902
std::size_t require_option_max_
Max number of options allowed. 0 is unlimited (not inheritable).
Definition CLI11.hpp:6065
CLI11_NODISCARD bool get_disabled() const
Get the status of disabled.
Definition CLI11.hpp:6917
CLI11_NODISCARD bool get_allow_windows_style_options() const
Check the status of the allow windows style options.
Definition CLI11.hpp:6873
std::vector< std::string > aliases_
Alias names for the subcommand.
Definition CLI11.hpp:6074
CLI11_NODISCARD bool parsed() const
Check to see if this subcommand was parsed, true only if received on command line.
Definition CLI11.hpp:6279
std::set< App * > exclude_subcommands_
this is a list of subcommands that are exclusionary to this one
Definition CLI11.hpp:5990
CLI11_NODISCARD bool get_disabled_by_default() const
Get the status of disabled by default.
Definition CLI11.hpp:6926
Option * add_flag(std::string flag_name, std::vector< T > &flag_results, std::string flag_description="")
Vector version to capture multiple flags.
Definition CLI11.hpp:6449
CLI11_NODISCARD std::size_t count() const
Definition CLI11.hpp:6551
bool _parse_positional(std::vector< std::string > &args, bool haltOnSubcommand)
Definition CLI11.hpp:8719
bool ignore_case_
If true, the program name is not case sensitive INHERITABLE.
Definition CLI11.hpp:6012
CLI11_NODISCARD const std::string & get_group() const
Get the group of this subcommand.
Definition CLI11.hpp:6884
bool silent_
Definition CLI11.hpp:6049
CLI11_NODISCARD const App * get_parent() const
Get the parent of this subcommand (or nullptr if main app) (const version).
Definition CLI11.hpp:6971
std::function< void(std::size_t)> pre_parse_callback_
This is a function that runs prior to the start of parsing.
Definition CLI11.hpp:5926
App * final_callback(std::function< void()> app_callback)
Definition CLI11.hpp:6124
std::string group_
The group membership INHERITABLE.
Definition CLI11.hpp:6071
App * alias(std::string app_name)
Set an alias for the app.
Definition CLI11.hpp:7312
bool pre_parse_called_
Flag indicating that the pre_parse_callback has been triggered.
Definition CLI11.hpp:5919
void _process_callbacks()
Process callbacks. Runs on all subcommands.
Definition CLI11.hpp:8278
App * validate_positionals(bool validate=true)
Set the subcommand to validate positional arguments before assigning.
Definition CLI11.hpp:6201
Option * help_ptr_
A pointer to the help flag if there is one INHERITABLE.
Definition CLI11.hpp:5955
Option * set_config(std::string option_name="", std::string default_filename="", const std::string &help_message="Read an ini file", bool config_required=false)
Set a configuration ini file option, or clear it if no name passed.
Definition CLI11.hpp:7540
App * footer(std::function< std::string()> footer_function)
Set footer.
Definition CLI11.hpp:6773
App * ignore_case(bool value=true)
Ignore case. Subcommands inherit value.
Definition CLI11.hpp:7343
App * excludes(Option *opt)
Sets excluded options for the subcommand.
Definition CLI11.hpp:6709
CLI11_NODISCARD std::shared_ptr< Config > get_config_formatter() const
Access the config formatter.
Definition CLI11.hpp:6800
bool remove_excludes(Option *opt)
Removes an option from the excludes list of this subcommand.
Definition CLI11.hpp:7855
CLI11_NODISCARD std::vector< App * > get_subcommands() const
Definition CLI11.hpp:6687
bool got_subcommand(const App *subcom) const
Check to see if given subcommand was selected.
Definition CLI11.hpp:6698
CLI11_NODISCARD config_extras_mode get_allow_config_extras() const
Get the status of allow extras.
Definition CLI11.hpp:6942
bool _parse_subcommand(std::vector< std::string > &args)
Definition CLI11.hpp:8866
App * positionals_at_end(bool value=true)
Specify that the positional arguments are only at the end of the sequence.
Definition CLI11.hpp:6246
bool fallthrough_
Definition CLI11.hpp:6019
std::set< Option * > need_options_
Definition CLI11.hpp:6002
CLI11_NODISCARD bool get_validate_optional_arguments() const
Get the status of validating optional vector arguments.
Definition CLI11.hpp:6937
CLI11_NODISCARD bool get_silent() const
Get the status of silence.
Definition CLI11.hpp:6920
std::vector< const Option * > get_options(const std::function< bool(const Option *)> filter={}) const
Definition CLI11.hpp:7925
std::set< App * > need_subcommands_
Definition CLI11.hpp:5998
App * validate_optional_arguments(bool validate=true)
Set the subcommand to validate optional vector arguments before assigning.
Definition CLI11.hpp:6207
bool prefix_command_
If true, return immediately on an unrecognized option (implies allow_extras) INHERITABLE.
Definition CLI11.hpp:5907
Option * add_option(std::string option_name, callback_t option_callback, std::string option_description="", bool defaulted=false, std::function< std::string()> func={})
Definition CLI11.hpp:7372
App * formatter(std::shared_ptr< FormatterBase > fmt)
Set the help formatter.
Definition CLI11.hpp:6261
std::vector< Option * > parse_order_
This is a list of pointers to options with the original parse order.
Definition CLI11.hpp:5984
Option * add_option(std::string option_name, T &option_description)
Add option with description but with no variable assignment or callback.
Definition CLI11.hpp:6385
CLI11_NODISCARD const std::vector< Option * > & parse_order() const
This gets a vector of pointers with the original parse order.
Definition CLI11.hpp:6995
void _parse(std::vector< std::string > &args)
Internal parse function.
Definition CLI11.hpp:8509
bool validate_positionals_
If set to true positional options are validated before assigning INHERITABLE.
Definition CLI11.hpp:6042
bool _parse_single_config(const ConfigItem &item, std::size_t level=0)
Fill in a single config option.
Definition CLI11.hpp:8571
startup_mode default_startup
Definition CLI11.hpp:6036
App * allow_config_extras(config_extras_mode mode)
ignore extras in config files
Definition CLI11.hpp:6224
Option * add_flag(std::string flag_name, T &flag_result, std::string flag_description="")
Definition CLI11.hpp:6435
bool allow_extras_
If true, allow extra arguments (ie, don't throw an error). INHERITABLE.
Definition CLI11.hpp:5900
CLI11_NODISCARD std::string get_description() const
Get the app or subcommand description.
Definition CLI11.hpp:6815
App * require_option(std::size_t min, std::size_t max)
Definition CLI11.hpp:6615
CLI11_NODISCARD App * _find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept
Definition CLI11.hpp:8848
CLI11_NODISCARD std::size_t get_require_subcommand_min() const
Get the required min subcommand value.
Definition CLI11.hpp:6892
CLI11_NODISCARD const Option * get_config_ptr() const
Get a pointer to the config option. (const).
Definition CLI11.hpp:6959
CLI11_NODISCARD const std::string & get_name() const
Get the name of the current app.
Definition CLI11.hpp:6974
App * disabled(bool disable=true)
Disable the subcommand or option group.
Definition CLI11.hpp:6162
App * callback(std::function< void()> app_callback)
Definition CLI11.hpp:6113
std::shared_ptr< FormatterBase > formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer).
Definition CLI11.hpp:5964
Option * set_help_all_flag(std::string help_name="", const std::string &help_description="")
Set a help all flag, replaced the existing one if present.
Definition CLI11.hpp:7428
App * require_subcommand(std::size_t min, std::size_t max)
Definition CLI11.hpp:6586
CLI11_NODISCARD const Option * get_option(std::string option_name) const
Get an option by name.
Definition CLI11.hpp:6838
bool allow_windows_style_options_
Definition CLI11.hpp:6023
std::shared_ptr< Config > config_formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer).
Definition CLI11.hpp:6084
Thrown when the wrong number of arguments has been received.
Definition CLI11.hpp:886
Definition CLI11.hpp:3721
Options
Definition CLI11.hpp:3727
AsSizeValue(bool kb_is_1000)
Definition CLI11.hpp:4133
Thrown on construction of a bad name.
Definition CLI11.hpp:736
Bound(T min_val, T max_val)
Definition CLI11.hpp:3287
Bound(T max_val)
Range of one value is 0 to value.
Definition CLI11.hpp:3309
Usually something like –help-all on command line.
Definition CLI11.hpp:790
-h or –help on command line
Definition CLI11.hpp:782
-v or –version on command line
Definition CLI11.hpp:798
This converter works with INI/TOML files; to write INI files use ConfigINI.
Definition CLI11.hpp:2898
std::vector< ConfigItem > from_config(std::istream &input) const override
Convert a configuration into an app.
Definition CLI11.hpp:9518
std::string configSection
Specify the configuration section that should be used.
Definition CLI11.hpp:2921
ConfigBase * comment(char cchar)
Specify the configuration for comment characters.
Definition CLI11.hpp:2931
ConfigBase * arrayDelimiter(char aSep)
Specify the delimiter character for an array.
Definition CLI11.hpp:2942
char arraySeparator
the character used to separate elements in an array
Definition CLI11.hpp:2907
ConfigBase * quoteCharacter(char qString, char qChar)
Specify the quote characters used around strings and characters.
Definition CLI11.hpp:2952
std::string & sectionRef()
get a reference to the configuration section
Definition CLI11.hpp:2968
ConfigBase * arrayBounds(char aStart, char aEnd)
Specify the start and end characters for an array.
Definition CLI11.hpp:2936
ConfigBase * maxLayers(uint8_t layers)
Specify the maximum number of parents.
Definition CLI11.hpp:2958
char characterQuote
the character to use around single characters
Definition CLI11.hpp:2913
CLI11_NODISCARD const std::string & section() const
get the section
Definition CLI11.hpp:2970
char stringQuote
the character to use around strings
Definition CLI11.hpp:2911
ConfigBase * section(const std::string §ionName)
specify a particular section of the configuration file to use
Definition CLI11.hpp:2972
ConfigBase * valueSeparator(char vSep)
Specify the delimiter between a name and value.
Definition CLI11.hpp:2947
uint8_t maximumLayers
the maximum number of layers to allow
Definition CLI11.hpp:2915
char valueDelimiter
the character used separate the name from the value
Definition CLI11.hpp:2909
char arrayStart
the character used to start an array '\0' is a default to not use
Definition CLI11.hpp:2903
char parentSeparatorChar
the separator used to separator parent layers
Definition CLI11.hpp:2917
CLI11_NODISCARD int16_t index() const
get the section index
Definition CLI11.hpp:2980
ConfigBase * index(int16_t sectionIndex)
specify a particular index in the section to use (-1) for all sections to use
Definition CLI11.hpp:2982
int16_t & indexRef()
get a reference to the configuration index
Definition CLI11.hpp:2978
char arrayEnd
the character used to end an array '\0' is a default to not use
Definition CLI11.hpp:2905
ConfigBase * parentSeparator(char sep)
Specify the separator to use for parent layers.
Definition CLI11.hpp:2963
int16_t configIndex
Specify the configuration index to use for arrayed sections.
Definition CLI11.hpp:2919
std::string to_config(const App *, bool default_also, bool write_description, std::string prefix) const override
Convert an app into a configuration.
Definition CLI11.hpp:9660
char commentChar
the character used for comments
Definition CLI11.hpp:2901
Thrown when extra values are found in an INI file.
Definition CLI11.hpp:949
This class provides a converter for configuration files.
Definition CLI11.hpp:2863
virtual CLI11_NODISCARD std::string to_flag(const ConfigItem &item) const
Get a flag value.
Definition CLI11.hpp:2875
virtual std::string to_config(const App *, bool, bool, std::string) const =0
Convert an app into a configuration.
CLI11_NODISCARD std::vector< ConfigItem > from_file(const std::string &name) const
Parse a config file, throw an error (ParseError:ConfigParseError or FileError) on failure.
Definition CLI11.hpp:2886
virtual ~Config()=default
Virtual destructor.
virtual std::vector< ConfigItem > from_config(std::istream &) const =0
Convert a configuration into an app.
Construction errors (not in parsing).
Definition CLI11.hpp:700
Thrown when conversion call back fails, such as when an int fails to coerce to a string.
Definition CLI11.hpp:822
Class wrapping some of the accessors of Validator.
Definition CLI11.hpp:3146
All errors derive from this one.
Definition CLI11.hpp:681
Thrown when an excludes option is present.
Definition CLI11.hpp:926
Thrown when parsing an INI file and it is missing.
Definition CLI11.hpp:813
Thrown when an option is set to conflicting values (non-vector and multi args, for example).
Definition CLI11.hpp:705
Thrown when validation fails before parsing.
Definition CLI11.hpp:961
IsMember(T &&set)
This checks to see if an item is in a set (empty function).
Definition CLI11.hpp:3482
IsMember(T set, F filter_function)
Definition CLI11.hpp:3487
IsMember(T &&set, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
You can pass in as many filter functions as you like, they nest (string only currently).
Definition CLI11.hpp:3534
IsMember(std::initializer_list< T > values, Args &&...args)
This allows in-place construction using an initializer list.
Definition CLI11.hpp:3477
Thrown when an option already exists.
Definition CLI11.hpp:754
Definition CLI11.hpp:4410
CRTP * mandatory(bool value=true)
Support Plumbum term.
Definition CLI11.hpp:4464
CRTP * take_all()
Set the multi option policy to take all arguments.
Definition CLI11.hpp:4519
CRTP * group(const std::string &name)
Changes the group membership.
Definition CLI11.hpp:4449
CRTP * join()
Set the multi option policy to join.
Definition CLI11.hpp:4526
bool always_capture_default_
Automatically capture default value.
Definition CLI11.hpp:4436
MultiOptionPolicy multi_option_policy_
Policy for handling multiple arguments beyond the expected Max.
Definition CLI11.hpp:4439
CRTP * join(char delim)
Set the multi option policy to join with a specific delimiter.
Definition CLI11.hpp:4533
CLI11_NODISCARD bool get_always_capture_default() const
Return true if this will automatically capture the default value for help printing.
Definition CLI11.hpp:4495
CLI11_NODISCARD char get_delimiter() const
Get the current delimiter char.
Definition CLI11.hpp:4492
CLI11_NODISCARD bool get_required() const
True if this is a required option.
Definition CLI11.hpp:4477
CRTP * take_first()
Set the multi option policy to take last.
Definition CLI11.hpp:4512
CLI11_NODISCARD bool get_ignore_case() const
The status of ignore case.
Definition CLI11.hpp:4480
bool ignore_case_
Ignore the case when matching (option, not value).
Definition CLI11.hpp:4421
CRTP * configurable(bool value=true)
Allow in a configuration file.
Definition CLI11.hpp:4541
CRTP * delimiter(char value='\0')
Allow in a configuration file.
Definition CLI11.hpp:4547
CLI11_NODISCARD MultiOptionPolicy get_multi_option_policy() const
The status of the multi option policy.
Definition CLI11.hpp:4498
CLI11_NODISCARD bool get_configurable() const
The status of configurable.
Definition CLI11.hpp:4486
bool configurable_
Allow this option to be given in a configuration file.
Definition CLI11.hpp:4427
bool disable_flag_override_
Disable overriding flag values with '=value'.
Definition CLI11.hpp:4430
bool required_
True if this is a required option.
Definition CLI11.hpp:4418
CRTP * take_last()
Set the multi option policy to take last.
Definition CLI11.hpp:4505
char delimiter_
Specify a delimiter character for vector arguments.
Definition CLI11.hpp:4433
std::string group_
The group membership.
Definition CLI11.hpp:4415
CLI11_NODISCARD bool get_ignore_underscore() const
The status of ignore_underscore.
Definition CLI11.hpp:4483
bool ignore_underscore_
Ignore underscores when matching (option, not value).
Definition CLI11.hpp:4424
CLI11_NODISCARD bool get_disable_flag_override() const
The status of configurable.
Definition CLI11.hpp:4489
CLI11_NODISCARD const std::string & get_group() const
Get the group of this option.
Definition CLI11.hpp:4474
void copy_to(T *other) const
Copy the contents to another similar class (one based on OptionBase).
Definition CLI11.hpp:5195
CRTP * required(bool value=true)
Set the option as required.
Definition CLI11.hpp:4458
Definition CLI11.hpp:4555
OptionDefaults * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times.
Definition CLI11.hpp:4562
OptionDefaults * ignore_case(bool value=true)
Ignore the case of the option name.
Definition CLI11.hpp:4568
OptionDefaults * ignore_underscore(bool value=true)
Ignore underscores in the option name.
Definition CLI11.hpp:4574
OptionDefaults * delimiter(char value='\0')
set a delimiter character to split up single arguments to treat as multiple inputs
Definition CLI11.hpp:4586
OptionDefaults * disable_flag_override(bool value=true)
Disable overriding flag values with an '=' segment.
Definition CLI11.hpp:4580
Thrown when counting a non-existent option.
Definition CLI11.hpp:978
Extension of App to better manage groups of options.
Definition CLI11.hpp:7138
App * add_subcommand(App *subcom)
Add an existing subcommand to be a member of an option_group.
Definition CLI11.hpp:7164
Option * add_option(Option *opt)
Add an existing option to the Option_group.
Definition CLI11.hpp:7147
void add_options(Option *opt, Args... args)
Add a bunch of options to the group.
Definition CLI11.hpp:7158
void add_options(Option *opt)
Add an existing option to the Option_group.
Definition CLI11.hpp:7155
Definition CLI11.hpp:4592
Option * type_size(int option_type_size)
Set a custom option size.
Definition CLI11.hpp:5605
Option * expected(int value)
Set the number of expected arguments.
Definition CLI11.hpp:5207
CLI11_NODISCARD bool get_positional() const
True if the argument can be given directly.
Definition CLI11.hpp:4962
std::string default_str_
A human readable default value, either manually set, captured, or captured by default.
Definition CLI11.hpp:4627
bool run_callback_for_default_
Control option to run the callback to set the default.
Definition CLI11.hpp:4696
CLI11_NODISCARD std::string get_envname() const
The environment variable associated to this value.
Definition CLI11.hpp:4907
CLI11_NODISCARD bool check_name(const std::string &name) const
Check a name. Requires "-" or "--" for short / long, supports positional name.
Definition CLI11.hpp:5495
Option * type_name(std::string typeval)
Set a custom option typestring.
Definition CLI11.hpp:5111
std::function< std::string()> type_name_
Definition CLI11.hpp:4635
option_state
enumeration for the option state machine
Definition CLI11.hpp:4683
@ reduced
a subset of results has been generated
Definition CLI11.hpp:4686
@ callback_run
the callback has been executed
Definition CLI11.hpp:4687
@ validated
the results have been validated
Definition CLI11.hpp:4685
@ parsing
The option is currently collecting parsed results.
Definition CLI11.hpp:4684
option_state current_option_state_
Whether the callback has run (needed for INI parsing).
Definition CLI11.hpp:4690
std::string option_text_
If given, replace the text that describes the option type and usage in the help text.
Definition CLI11.hpp:4630
int type_size_min_
The minimum number of arguments an option should be expecting.
Definition CLI11.hpp:4648
CLI11_NODISCARD results_t reduced_results() const
Get a copy of the results.
Definition CLI11.hpp:5587
CLI11_NODISCARD std::string get_type_name() const
Get the full typename for this option.
Definition CLI11.hpp:5647
CLI11_NODISCARD bool check_fname(std::string name) const
Requires "--" to be removed from string.
Definition CLI11.hpp:5026
std::string pname_
A positional name.
Definition CLI11.hpp:4614
int expected_min_
The minimum number of expected values.
Definition CLI11.hpp:4651
Option(std::string option_name, std::string option_description, callback_t callback, App *parent)
Making an option by hand is not defined, it must be made by the App class.
Definition CLI11.hpp:4707
Option * ignore_case(bool value=true)
Definition CLI11.hpp:5350
std::set< Option * > needs_
A list of options that are required with this option.
Definition CLI11.hpp:4659
Option * default_function(const std::function< std::string()> &func)
Set a capture function for the default. Mostly used by App.
Definition CLI11.hpp:5126
CLI11_NODISCARD int get_type_size_min() const
The minimum number of arguments the option expects.
Definition CLI11.hpp:4899
void run_callback()
Process the callback.
Definition CLI11.hpp:5453
CLI11_NODISCARD bool check_sname(std::string name) const
Requires "-" to be removed from string.
Definition CLI11.hpp:5015
bool trigger_on_result_
Definition CLI11.hpp:4701
bool flag_like_
Specify that the option should act like a flag vs regular option.
Definition CLI11.hpp:4694
CLI11_NODISCARD std::string get_name(bool positional=false, bool all_options=false) const
Gets a comma separated list of names. Will include / prefer the positional name if positional is true...
Definition CLI11.hpp:5407
std::set< Option * > excludes_
A list of options that are excluded with this option.
Definition CLI11.hpp:4662
bool force_callback_
flag indicating that the option should force the callback regardless if any results present
Definition CLI11.hpp:4703
CLI11_NODISCARD bool get_callback_run() const
See if the callback has been run already.
Definition CLI11.hpp:5096
CLI11_NODISCARD bool get_force_callback() const
The status of force_callback.
Definition CLI11.hpp:4773
std::vector< std::string > fnames_
a list of flag names with specified default values;
Definition CLI11.hpp:4611
CLI11_NODISCARD bool get_run_callback_for_default() const
Get the current value of run_callback_for_default.
Definition CLI11.hpp:4783
CLI11_NODISCARD std::string get_default_str() const
The default value (for help printing).
Definition CLI11.hpp:4916
CLI11_NODISCARD bool nonpositional() const
True if option has at least one non-positional name.
Definition CLI11.hpp:4965
CLI11_NODISCARD int get_items_expected_min() const
The total min number of expected string values to be used.
Definition CLI11.hpp:4951
CLI11_NODISCARD const std::string & matching_name(const Option &other) const
If options share any of the same names, find it.
Definition CLI11.hpp:5478
CLI11_NODISCARD bool check_lname(std::string name) const
Requires "--" to be removed from string.
Definition CLI11.hpp:5020
CLI11_NODISCARD const results_t & results() const
Get the current complete results set.
Definition CLI11.hpp:5049
Option * disable_flag_override(bool value=true)
Disable flag overrides values, e.g. –flag=is not allowed.
Definition CLI11.hpp:4887
CLI11_NODISCARD int get_items_expected_max() const
Get the maximum number of items expected to be returned and used for the callback.
Definition CLI11.hpp:4954
std::vector< std::string > snames_
A list of the short names (-a) without the leading dashes.
Definition CLI11.hpp:4600
results_t proc_results_
results after reduction
Definition CLI11.hpp:4681
bool remove_excludes(Option *opt)
Remove needs link from an option. Returns true if the option really was in the needs list.
Definition CLI11.hpp:5339
CLI11_NODISCARD std::size_t count() const
Count the total number of times an option was passed.
Definition CLI11.hpp:4725
Option * run_callback_for_default(bool value=true)
Definition CLI11.hpp:4778
void inject_separator(bool value=true)
Set the value of the separator injection flag.
Definition CLI11.hpp:5123
Option * allow_extra_args(bool value=true)
Definition CLI11.hpp:4752
Option * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times (or another policy).
Definition CLI11.hpp:5393
Option * trigger_on_parse(bool value=true)
Definition CLI11.hpp:4760
CLI11_NODISCARD callback_t get_callback() const
Get the callback function.
Definition CLI11.hpp:4919
CLI11_NODISCARD bool get_inject_separator() const
Return the inject_separator flag.
Definition CLI11.hpp:4904
Option * excludes(Option *opt)
Sets excluded options.
Definition CLI11.hpp:5323
App * parent_
link back up to the parent App for fallthrough
Definition CLI11.hpp:4669
CLI11_NODISCARD bool get_trigger_on_parse() const
The status of trigger on parse.
Definition CLI11.hpp:4765
CLI11_NODISCARD const std::vector< std::string > & get_lnames() const
Get the long names.
Definition CLI11.hpp:4922
int expected_max_
The maximum number of expected values.
Definition CLI11.hpp:4653
CLI11_NODISCARD std::set< Option * > get_excludes() const
The set of options excluded.
Definition CLI11.hpp:4913
CLI11_NODISCARD std::string get_flag_value(const std::string &name, std::string input_value) const
Definition CLI11.hpp:5521
Option * excludes(std::string opt_name)
Can find a string if needed.
Definition CLI11.hpp:4845
CLI11_NODISCARD int get_items_expected() const
The total min number of expected string values to be used.
Definition CLI11.hpp:4959
Validator * get_validator(const std::string &Validator_name="")
Get a named Validator.
Definition CLI11.hpp:5293
CLI11_NODISCARD std::set< Option * > get_needs() const
The set of options needed.
Definition CLI11.hpp:4910
std::string description_
The description for help strings.
Definition CLI11.hpp:4624
CLI11_NODISCARD const std::vector< std::string > & get_snames() const
Get the short names.
Definition CLI11.hpp:4925
CLI11_NODISCARD int get_type_size_max() const
The maximum number of arguments the option expects.
Definition CLI11.hpp:4901
bool inject_separator_
flag indicating a separator needs to be injected after each argument call
Definition CLI11.hpp:4698
Option * check(Validator validator, const std::string &validator_name="")
Adds a Validator with a built in type name.
Definition CLI11.hpp:5247
CLI11_NODISCARD const std::string & get_description() const
Get the description.
Definition CLI11.hpp:4971
CLI11_NODISCARD const std::string & get_single_name() const
Get a single name for the option, first of lname, pname, sname, envname.
Definition CLI11.hpp:4930
CLI11_NODISCARD int get_expected() const
The number of times the option expects to be included.
Definition CLI11.hpp:4943
callback_t callback_
Options store a callback to do all the work.
Definition CLI11.hpp:4672
CLI11_NODISCARD bool empty() const
True if the option was not passed.
Definition CLI11.hpp:4728
CLI11_NODISCARD int get_expected_min() const
The number of times the option expects to be included.
Definition CLI11.hpp:4946
void clear()
Clear the parsed results (mostly for testing).
Definition CLI11.hpp:4735
CLI11_NODISCARD int get_expected_max() const
The max number of times the option expects to be included.
Definition CLI11.hpp:4948
Option * capture_default_str()
Capture the default value from the original value (if it can be captured).
Definition CLI11.hpp:5132
void results(T &output) const
Get the results as a specified type.
Definition CLI11.hpp:5056
Option * default_str(std::string val)
Set the default value string representation (does not change the contained value).
Definition CLI11.hpp:5140
CLI11_NODISCARD int get_type_size() const
The number of arguments the option expects.
Definition CLI11.hpp:4896
std::string envname_
If given, check the environment for this option.
Definition CLI11.hpp:4617
std::function< std::string()> default_function_
Run this function to capture a default (ignore if empty).
Definition CLI11.hpp:4638
CLI11_NODISCARD bool get_allow_extra_args() const
Get the current value of allow extra args.
Definition CLI11.hpp:4757
Option * ignore_underscore(bool value=true)
Definition CLI11.hpp:5372
std::vector< std::pair< std::string, std::string > > default_flag_values_
Definition CLI11.hpp:4608
std::vector< Validator > validators_
A list of Validators to run on each value parsed.
Definition CLI11.hpp:4656
Option * envname(std::string name)
Sets environment variable to read if no option given.
Definition CLI11.hpp:4864
Option * type_name_fn(std::function< std::string()> typefun)
Set the type function to run when displayed on this option.
Definition CLI11.hpp:5105
Option * default_val(const X &val)
Definition CLI11.hpp:5148
Option * needs(Option *opt)
Sets required options.
Definition CLI11.hpp:4813
int type_size_max_
Definition CLI11.hpp:4646
Option * needs(A opt, B opt1, ARG... args)
Any number supported, any mix of string and Opt.
Definition CLI11.hpp:4832
bool allow_extra_args_
Specify that extra args beyond type_size_max should be allowed.
Definition CLI11.hpp:4692
Option * description(std::string option_description)
Set the description.
Definition CLI11.hpp:4974
Option * transform(Validator Validator, const std::string &Validator_name="")
Adds a transforming Validator with a built in type name.
Definition CLI11.hpp:5263
std::vector< std::string > lnames_
A list of the long names (--long) without the leading dashes.
Definition CLI11.hpp:4603
Option * force_callback(bool value=true)
Set the value of force_callback.
Definition CLI11.hpp:4768
Option * add_result(std::string s)
Puts a result at the end.
Definition CLI11.hpp:5567
bool remove_needs(Option *opt)
Remove needs link from an option. Returns true if the option really was in the needs list.
Definition CLI11.hpp:5313
bool operator==(const Option &other) const
If options share any of the same names, they are equal (not counting positional).
Definition CLI11.hpp:5009
Option * each(const std::function< void(std::string)> &func)
Definition CLI11.hpp:5283
Option * needs(std::string opt_name)
Can find a string if needed.
Definition CLI11.hpp:4822
CLI11_NODISCARD const std::vector< std::string > & get_fnames() const
Get the flag names with specified default values.
Definition CLI11.hpp:4928
CLI11_NODISCARD bool has_description() const
True if option has description.
Definition CLI11.hpp:4968
results_t results_
complete Results of parsing
Definition CLI11.hpp:4679
CLI11_NODISCARD T as() const
Return the results as the specified type.
Definition CLI11.hpp:5089
Option * excludes(A opt, B opt1, ARG... args)
Any number supported, any mix of string and Opt.
Definition CLI11.hpp:4855
Anything that can error in Parse.
Definition CLI11.hpp:769
Produce a range (factory). Min and max are inclusive.
Definition CLI11.hpp:3236
Range(T min_val, T max_val, const std::string &validator_name=std::string{})
Definition CLI11.hpp:3243
Range(T max_val, const std::string &validator_name=std::string{})
Range of one value is 0 to value.
Definition CLI11.hpp:3266
Thrown when a required option is missing.
Definition CLI11.hpp:846
Thrown when a requires option is missing.
Definition CLI11.hpp:919
This is a successful completion on parsing, supposed to exit.
Definition CLI11.hpp:776
Validate the input as a particular type.
Definition CLI11.hpp:3211
Thrown when validation of results fails.
Definition CLI11.hpp:838
Some validators that are provided.
Definition CLI11.hpp:3015
Validator operator&(const Validator &other) const
Definition CLI11.hpp:3917
CLI11_NODISCARD int get_application_index() const
Get the current value of the application index.
Definition CLI11.hpp:3120
int application_index_
A Validator will only apply to an indexed value (-1 is all elements).
Definition CLI11.hpp:3026
Validator & non_modifying(bool no_modify=true)
Specify whether the Validator can be modifying or not.
Definition CLI11.hpp:3104
Validator & description(std::string validator_desc)
Specify the type string.
Definition CLI11.hpp:3064
std::string operator()(const std::string &str) const
Definition CLI11.hpp:3058
CLI11_NODISCARD Validator application_index(int app_index) const
Specify the application index of a validator.
Definition CLI11.hpp:3114
Validator operator|(const Validator &other) const
Definition CLI11.hpp:3938
CLI11_NODISCARD bool get_active() const
Get a boolean if the validator is active.
Definition CLI11.hpp:3122
bool active_
Enable for Validator to allow it to be disabled if need be.
Definition CLI11.hpp:3028
bool non_modifying_
specify that a validator should not modify the input
Definition CLI11.hpp:3030
Validator(std::string validator_desc)
Construct a Validator with just the description string.
Definition CLI11.hpp:3038
Validator & name(std::string validator_name)
Specify the type string.
Definition CLI11.hpp:3079
std::function< std::string()> desc_function_
This is the description function, if empty the description_ will be used.
Definition CLI11.hpp:3018
std::function< std::string(std::string &)> func_
Definition CLI11.hpp:3022
CLI11_NODISCARD std::string get_description() const
Generate type description information for the Validator.
Definition CLI11.hpp:3072
CLI11_NODISCARD Validator active(bool active_val=true) const
Specify whether the Validator is active or not.
Definition CLI11.hpp:3097
CLI11_NODISCARD const std::string & get_name() const
Get the name of the Validator.
Definition CLI11.hpp:3090
Validator & active(bool active_val=true)
Specify whether the Validator is active or not.
Definition CLI11.hpp:3092
std::string name_
The name for search purposes of the Validator.
Definition CLI11.hpp:3024
CLI11_NODISCARD bool get_modifying() const
Definition CLI11.hpp:3126
CLI11_NODISCARD Validator name(std::string validator_name) const
Specify the type string.
Definition CLI11.hpp:3084
Validator operator!() const
Create a validator that fails when a given validator succeeds.
Definition CLI11.hpp:3959
std::string operator()(std::string &str) const
Definition CLI11.hpp:3898
Validator & application_index(int app_index)
Specify the application index of a validator.
Definition CLI11.hpp:3109
Validator(std::function< std::string(std::string &)> op, std::string validator_desc, std::string validator_name="")
Construct Validator from basic information.
Definition CLI11.hpp:3041
Validator & operation(std::function< std::string(std::string &)> op)
Set the Validator operation function.
Definition CLI11.hpp:3048
Check for an existing directory (returns error message if check fails).
Definition CLI11.hpp:3167
Check for an existing file (returns error message if check fails).
Definition CLI11.hpp:3161
Check for an existing path.
Definition CLI11.hpp:3173
Validate the given string is a legal ipv4 address.
Definition CLI11.hpp:3185
Check for an non-existing path.
Definition CLI11.hpp:3179
Check for complex.
Definition CLI11.hpp:1204
Definition CLI11.hpp:1144
Check for input streamability.
Definition CLI11.hpp:1190
Definition CLI11.hpp:1177
Definition CLI11.hpp:1276
std::ostream & operator<<(std::ostream &in, const T &item)
output streaming for enumerations
Definition CLI11.hpp:173
Holds values to load into Options.
Definition CLI11.hpp:2844
std::vector< std::string > inputs
Listing of inputs.
Definition CLI11.hpp:2852
std::string name
This is the name.
Definition CLI11.hpp:2849
CLI11_NODISCARD std::string fullname() const
The list of parents and name joined by ".".
Definition CLI11.hpp:2855
std::vector< std::string > parents
This is the list of parents.
Definition CLI11.hpp:2846
This can be specialized to override the type deduction for IsMember.
Definition CLI11.hpp:1052
This class is simply to allow tests access to App's protected functions.
Definition CLI11.hpp:7227
static auto parse_subcommand(App *app, Args &&...args) -> typename std::result_of< decltype(&App::_parse_subcommand)(App, Args...)>::type
Wrap _parse_subcommand, perfectly forward arguments and return.
Definition CLI11.hpp:7251
static App * get_fallthrough_parent(App *app)
Wrap the fallthrough parent function to make sure that is working correctly.
Definition CLI11.hpp:7257
static auto parse_arg(App *app, Args &&...args) -> typename std::result_of< decltype(&App::_parse_arg)(App, Args...)>::type
Wrap _parse_short, perfectly forward arguments and return.
Definition CLI11.hpp:7244
not a pointer
Definition CLI11.hpp:1071
Definition CLI11.hpp:1083
Definition CLI11.hpp:3364
Definition CLI11.hpp:1232
Definition CLI11.hpp:1253
Definition CLI11.hpp:1267
static auto first(Q &&pair_value) -> decltype(std::get< 0 >(std::forward< Q >(pair_value)))
Get the first value (really just the underlying value).
Definition CLI11.hpp:1121
static auto second(Q &&pair_value) -> decltype(std::get< 1 >(std::forward< Q >(pair_value)))
Get the second value (really just the underlying value).
Definition CLI11.hpp:1126
Definition CLI11.hpp:1090
static auto second(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the second value (really just the underlying value).
Definition CLI11.hpp:1102
static auto first(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the first value (really just the underlying value).
Definition CLI11.hpp:1097
forward declare the subtype_count_min structure
Definition CLI11.hpp:1430
Set of overloads to get the type size of an object.
Definition CLI11.hpp:1426
This will only trigger for actual void type.
Definition CLI11.hpp:1395
This will only trigger for actual void type.
Definition CLI11.hpp:1434
template to get the underlying value type if it exists or use a default
Definition CLI11.hpp:1383
Check to see if something is bool (fail check by default).
Definition CLI11.hpp:1026
Check to see if something is copyable pointer.
Definition CLI11.hpp:1046
Check to see if something is a shared pointer.
Definition CLI11.hpp:1034
A copy of std::void_t from C++17 (helper for C++11 and C++14).
Definition CLI11.hpp:1011