60 #include <sys/types.h> 62 #include <type_traits> 70 #define CLI11_VERSION_MAJOR 1 71 #define CLI11_VERSION_MINOR 8 72 #define CLI11_VERSION_PATCH 0 73 #define CLI11_VERSION "1.8.0" 82 #if !(defined(_MSC_VER) && __cplusplus == 199711L) && !defined(__INTEL_COMPILER) 83 #if __cplusplus >= 201402L 85 #if __cplusplus >= 201703L 87 #if __cplusplus > 201703L 92 #elif defined(_MSC_VER) && __cplusplus == 199711L 95 #if _MSVC_LANG >= 201402L 97 #if _MSVC_LANG > 201402L && _MSC_VER >= 1910 99 #if __MSVC_LANG > 201703L && _MSC_VER >= 1910 106 #if defined(CLI11_CPP14) 107 #define CLI11_DEPRECATED(reason) [[deprecated(reason)]] 108 #elif defined(_MSC_VER) 109 #define CLI11_DEPRECATED(reason) __declspec(deprecated(reason)) 111 #define CLI11_DEPRECATED(reason) __attribute__((deprecated(reason))) 123 #ifndef CLI11_STD_OPTIONAL 125 #if defined(CLI11_CPP17) && __has_include(<optional>) 126 #define CLI11_STD_OPTIONAL 1 128 #define CLI11_STD_OPTIONAL 0 131 #define CLI11_STD_OPTIONAL 0 135 #ifndef CLI11_EXPERIMENTAL_OPTIONAL 136 #define CLI11_EXPERIMENTAL_OPTIONAL 0 139 #ifndef CLI11_BOOST_OPTIONAL 140 #define CLI11_BOOST_OPTIONAL 0 143 #if CLI11_BOOST_OPTIONAL 144 #include <boost/version.hpp> 145 #if BOOST_VERSION < 106100 146 #error "This boost::optional version is not supported, use 1.61 or better" 150 #if CLI11_STD_OPTIONAL 153 #if CLI11_EXPERIMENTAL_OPTIONAL 154 #include <experimental/optional> 156 #if CLI11_BOOST_OPTIONAL 157 #include <boost/optional.hpp> 158 #include <boost/optional/optional_io.hpp> 174 #if CLI11_STD_OPTIONAL 175 template <
typename T> std::istream &
operator>>(std::istream &in, std::optional<T> &val) {
183 #if CLI11_EXPERIMENTAL_OPTIONAL 184 template <
typename T> std::istream &
operator>>(std::istream &in, std::experimental::optional<T> &val) {
192 #if CLI11_BOOST_OPTIONAL 193 template <
typename T> std::istream &
operator>>(std::istream &in, boost::optional<T> &val) {
202 #if CLI11_STD_OPTIONAL 204 #elif CLI11_EXPERIMENTAL_OPTIONAL 205 using std::experimental::optional;
206 #elif CLI11_BOOST_OPTIONAL 207 using boost::optional;
211 #if CLI11_STD_OPTIONAL || CLI11_EXPERIMENTAL_OPTIONAL || CLI11_BOOST_OPTIONAL 212 #define CLI11_OPTIONAL 1 226 template <typename T, typename = typename std::enable_if<std::is_enum<T>::value>
::type>
233 template <typename T, typename = typename std::enable_if<std::is_enum<T>::value>
::type>
237 item =
static_cast<T
>(i);
243 using namespace enums;
249 inline std::vector<std::string>
split(
const std::string &s,
char delim) {
250 std::vector<std::string> elems;
253 elems.emplace_back();
255 std::stringstream ss;
258 while(std::getline(ss, item, delim)) {
259 elems.push_back(item);
265 template <
typename T>
inline std::string
as_string(
const T &v) {
266 std::ostringstream s;
271 template <typename T, typename = typename std::enable_if<std::is_constructible<std::string, T>::value>
::type>
272 inline auto as_string(T &&v) -> decltype(std::forward<T>(v)) {
273 return std::forward<T>(v);
277 template <
typename T> std::string
join(
const T &v, std::string delim =
",") {
278 std::ostringstream s;
279 auto beg = std::begin(v);
280 auto end = std::end(v);
284 s << delim << *beg++;
290 template <
typename T,
292 typename =
typename std::enable_if<!std::is_constructible<std::string, Callable>::value>
::type>
293 std::string
join(
const T &v, Callable func, std::string delim =
",") {
294 std::ostringstream s;
295 auto beg = std::begin(v);
296 auto end = std::end(v);
300 s << delim << func(*beg++);
306 template <
typename T> std::string
rjoin(
const T &v, std::string delim =
",") {
307 std::ostringstream s;
308 for(
size_t start = 0; start < v.size(); start++) {
311 s << v[v.size() - start - 1];
320 auto it = std::find_if(str.begin(), str.end(), [](
char ch) {
return !std::isspace<char>(ch, std::locale()); });
321 str.erase(str.begin(), it);
326 inline std::string &
ltrim(std::string &
str,
const std::string &filter) {
327 auto it = std::find_if(str.begin(), str.end(), [&filter](
char ch) {
return filter.find(ch) == std::string::npos; });
328 str.erase(str.begin(), it);
334 auto it = std::find_if(str.rbegin(), str.rend(), [](
char ch) {
return !std::isspace<char>(ch, std::locale()); });
335 str.erase(it.base(), str.end());
340 inline std::string &
rtrim(std::string &
str,
const std::string &filter) {
342 std::find_if(str.rbegin(), str.rend(), [&filter](
char ch) {
return filter.find(ch) == std::string::npos; });
343 str.erase(it.base(), str.end());
351 inline std::string &
trim(std::string &
str,
const std::string filter) {
return ltrim(
rtrim(str, filter), filter); }
360 inline std::string
trim_copy(
const std::string &
str,
const std::string &filter) {
362 return trim(s, filter);
365 inline std::ostream &
format_help(std::ostream &out, std::string name, std::string description,
size_t wid) {
367 out << std::setw(static_cast<int>(wid)) << std::left << name;
368 if(!description.empty()) {
369 if(name.length() >= wid)
370 out <<
"\n" << std::setw(static_cast<int>(wid)) <<
"";
371 for(
const char c : description) {
374 out << std::setw(static_cast<int>(wid)) <<
"";
384 return std::isalnum(c, std::locale()) || c ==
'_' || c ==
'?' || c ==
'@';
394 for(
auto c : str.substr(1))
402 return std::all_of(str.begin(), str.end(), [](
char c) {
return std::isalpha(c, std::locale()); });
407 std::transform(std::begin(str), std::end(str), std::begin(str), [](
const std::string::value_type &x) {
408 return std::tolower(x, std::locale());
415 str.erase(std::remove(std::begin(str), std::end(str),
'_'), std::end(str));
422 size_t start_pos = 0;
424 while((start_pos = str.find(from, start_pos)) != std::string::npos) {
425 str.replace(start_pos, from.length(), to);
426 start_pos += to.length();
434 return (flags.find_first_of(
"{!") != std::string::npos);
438 auto loc = flags.find_first_of(
'{');
439 while(loc != std::string::npos) {
440 auto finish = flags.find_first_of(
"},", loc + 1);
441 if((finish != std::string::npos) && (flags[finish] ==
'}')) {
442 flags.erase(flags.begin() +
static_cast<std::ptrdiff_t
>(loc),
443 flags.begin() +
static_cast<std::ptrdiff_t
>(finish) + 1);
445 loc = flags.find_first_of(
'{', loc + 1);
447 flags.erase(std::remove(flags.begin(), flags.end(),
'!'), flags.end());
452 const std::vector<std::string> names,
455 auto it = std::end(names);
459 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
464 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
471 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
475 it = std::find(std::begin(names), std::end(names), name);
477 return (it != std::end(names)) ? (it - std::begin(names)) : (-1);
482 template <
typename Callable>
inline std::string
find_and_modify(std::string
str, std::string trigger, Callable modify) {
483 size_t start_pos = 0;
484 while((start_pos = str.find(trigger, start_pos)) != std::string::npos) {
485 start_pos = modify(str, start_pos);
494 const std::string delims(
"\'\"`");
495 auto find_ws = [](
char ch) {
return std::isspace<char>(ch, std::locale()); };
498 std::vector<std::string> output;
499 bool embeddedQuote =
false;
501 while(!str.empty()) {
502 if(delims.find_first_of(str[0]) != std::string::npos) {
504 auto end = str.find_first_of(keyChar, 1);
505 while((end != std::string::npos) && (str[end - 1] ==
'\\')) {
506 end = str.find_first_of(keyChar, end + 1);
507 embeddedQuote =
true;
509 if(end != std::string::npos) {
510 output.push_back(str.substr(1, end - 1));
511 str = str.substr(end + 1);
513 output.push_back(str.substr(1));
517 auto it = std::find_if(std::begin(str), std::end(str), find_ws);
518 if(it != std::end(str)) {
519 std::string value = std::string(str.begin(), it);
520 output.push_back(value);
521 str = std::string(it, str.end());
523 output.push_back(str);
529 output.back() =
find_and_replace(output.back(), std::string(
"\\") + keyChar, std::string(1, keyChar));
530 embeddedQuote =
false;
541 inline std::string
fix_newlines(std::string leader, std::string input) {
542 std::string::size_type n = 0;
543 while(n != std::string::npos && n < input.size()) {
544 n = input.find(
'\n', n);
545 if(n != std::string::npos) {
546 input = input.substr(0, n + 1) + leader + input.substr(n + 1);
558 auto next = str[offset + 1];
559 if((next ==
'\"') || (next ==
'\'') || (next ==
'`')) {
560 auto astart = str.find_last_of(
"-/ \"\'`", offset - 1);
561 if(astart != std::string::npos) {
562 if(str[astart] == ((str[offset] ==
'=') ?
'-' :
'/'))
571 if((str.front() !=
'"' && str.front() !=
'\'') || str.front() != str.back()) {
572 char quote = str.find(
'"') < str.find(
'\'') ?
'\'' :
'"';
573 if(str.find(
' ') != std::string::npos) {
574 str.insert(0, 1, quote);
575 str.append(1, quote);
591 #define CLI11_ERROR_DEF(parent, name) \ 593 name(std::string ename, std::string msg, int exit_code) : parent(std::move(ename), std::move(msg), exit_code) {} \ 594 name(std::string ename, std::string msg, ExitCodes exit_code) \ 595 : parent(std::move(ename), std::move(msg), exit_code) {} \ 598 name(std::string msg, ExitCodes exit_code) : parent(#name, std::move(msg), exit_code) {} \ 599 name(std::string msg, int exit_code) : parent(#name, std::move(msg), exit_code) {} 602 #define CLI11_ERROR_SIMPLE(name) \ 603 explicit name(std::string msg) : name(#name, msg, ExitCodes::name) {} 636 class Error :
public std::runtime_error {
638 std::string error_name{
"Error"};
643 std::string
get_name()
const {
return error_name; }
646 : runtime_error(msg), actual_exit_code(exit_code), error_name(
std::move(name)) {}
648 Error(std::string name, std::string msg,
ExitCodes exit_code) :
Error(name, msg, static_cast<int>(exit_code)) {}
676 name +
": You can't change expected arguments after you've changed the multi option policy!");
682 return IncorrectConstruction(name +
": multi_option_policy only works for flags and exact value options");
693 return BadNameString(
"Must have a name, not just dashes: " + name);
696 return BadNameString(
"Only one positional name allowed, remove: " + name);
759 :
ConversionError("The value " + member + " is not an allowed value for " + name) {}
788 static RequiredError Option(
size_t min_option,
size_t max_option,
size_t used,
const std::string &option_list) {
789 if((min_option == 1) && (max_option == 1) && (used == 0))
790 return RequiredError(
"Exactly 1 option from [" + option_list +
"]");
791 else if((min_option == 1) && (max_option == 1) && (used > 1))
795 else if((min_option == 1) && (used == 0))
796 return RequiredError(
"At least 1 option from [" + option_list +
"]");
797 else if(used < min_option)
801 else if(max_option == 1)
802 return RequiredError(
"Requires at most 1 options be given from [" + option_list +
"]",
818 : ("Expected
at least " +
std::
to_string(-expected) + " arguments to " + name +
851 :
ExtrasError((args.size() > 1 ? "The following arguments were not expected: "
852 : "The following argument was not expected: ") +
853 detail::
rjoin(args, " "),
863 return ConfigError(item +
": This option is not allowed in a configuration file");
890 #undef CLI11_ERROR_DEF 891 #undef CLI11_ERROR_SIMPLE 930 template <
typename T>
struct is_vector : std::false_type {};
933 template <
class T,
class A>
struct is_vector<
std::vector<T, A>> : std::true_type {};
936 template <
typename T>
struct is_bool : std::false_type {};
939 template <>
struct is_bool<bool> : std::true_type {};
945 template <
typename T>
struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
948 template <
typename T>
struct is_shared_ptr<const std::shared_ptr<T>> : std::true_type {};
969 typename std::conditional<is_copyable_ptr<T>::value,
typename std::pointer_traits<T>::element_type, T>
::type;
977 template <
typename T,
typename _ =
void>
struct pair_adaptor : std::false_type {
983 template <
typename Q>
static auto first(Q &&pair_value) -> decltype(std::forward<Q>(pair_value)) {
984 return std::forward<Q>(pair_value);
987 template <
typename Q>
static auto second(Q &&pair_value) -> decltype(std::forward<Q>(pair_value)) {
988 return std::forward<Q>(pair_value);
994 template <
typename T>
997 conditional_t<false, void_t<typename T::value_type::first_type, typename T::value_type::second_type>, void>>
1004 template <
typename Q>
static auto first(Q &&pair_value) -> decltype(std::get<0>(std::forward<Q>(pair_value))) {
1005 return std::get<0>(std::forward<Q>(pair_value));
1008 template <
typename Q>
static auto second(Q &&pair_value) -> decltype(std::get<1>(std::forward<Q>(pair_value))) {
1009 return std::get<1>(std::forward<Q>(pair_value));
1017 template <
typename SS,
typename TT>
1018 static auto test(
int) -> decltype(std::declval<SS &>() << std::declval<TT>(), std::true_type());
1020 template <
typename,
typename>
static auto test(...) -> std::false_type;
1023 static const bool value = decltype(test<S, T>(0))::value;
1028 auto to_string(T &&value) -> decltype(std::forward<T>(value)) {
1029 return std::forward<T>(value);
1033 template <
typename T,
1037 std::stringstream stream;
1039 return stream.str();
1043 template <
typename T,
1047 return std::string{};
1056 template <
typename T,
1062 template <
typename T,
1068 template <typename T, enable_if_t<std::is_floating_point<T>::value, detail::enabler> =
detail::dummy>
1074 template <typename T, enable_if_t<is_vector<T>::value, detail::enabler> =
detail::dummy>
1079 template <typename T, enable_if_t<std::is_enum<T>::value, detail::enabler> =
detail::dummy>
1085 template <
typename T,
1087 !std::is_enum<T>::value,
1097 static const std::string trueString(
"true");
1098 static const std::string falseString(
"false");
1099 if(val == trueString) {
1102 if(val == falseString) {
1107 if(val.size() == 1) {
1132 throw std::invalid_argument(
"unrecognized character");
1136 if(val == trueString || val ==
"on" || val ==
"yes" || val ==
"enable") {
1138 }
else if(val == falseString || val ==
"off" || val ==
"no" || val ==
"disable") {
1141 ret = std::stoll(val);
1154 long long output_ll = std::stoll(input, &n, 0);
1155 output =
static_cast<T
>(output_ll);
1156 return n == input.size() &&
static_cast<long long>(output) == output_ll;
1157 }
catch(
const std::invalid_argument &) {
1159 }
catch(
const std::out_of_range &) {
1165 template <
typename T,
1169 if(!input.empty() && input.front() ==
'-')
1174 unsigned long long output_ll = std::stoull(input, &n, 0);
1175 output =
static_cast<T
>(output_ll);
1176 return n == input.size() &&
static_cast<unsigned long long>(output) == output_ll;
1177 }
catch(
const std::invalid_argument &) {
1179 }
catch(
const std::out_of_range &) {
1185 template <typename T, enable_if_t<is_bool<T>::value, detail::enabler> =
detail::dummy>
1191 }
catch(
const std::invalid_argument &) {
1197 template <typename T, enable_if_t<std::is_floating_point<T>::value, detail::enabler> =
detail::dummy>
1201 output =
static_cast<T
>(std::stold(input, &n));
1202 return n == input.size();
1203 }
catch(
const std::invalid_argument &) {
1205 }
catch(
const std::out_of_range &) {
1211 template <
typename T,
1213 std::is_assignable<T &, std::string>::value,
1221 template <typename T, enable_if_t<std::is_enum<T>::value, detail::enabler> =
detail::dummy>
1228 output =
static_cast<T
>(val);
1233 template <
typename T,
1235 !std::is_assignable<T &, std::string>::value && !std::is_enum<T>::value,
1238 std::istringstream is;
1242 return !is.fail() && !is.rdbuf()->in_avail();
1249 template <
typename T,
1253 for(
auto &flag : flags) {
1256 output = (count > 0) ? static_cast<T>(count) : T{0};
1263 template <
typename T,
1265 void sum_flag_vector(
const std::vector<std::string> &flags, T &output) {
1267 for(
auto &flag : flags) {
1270 output =
static_cast<T
>(count);
1282 inline bool split_short(
const std::string ¤t, std::string &name, std::string &rest) {
1283 if(current.size() > 1 && current[0] ==
'-' &&
valid_first_char(current[1])) {
1284 name = current.substr(1, 1);
1285 rest = current.substr(2);
1292 inline bool split_long(
const std::string ¤t, std::string &name, std::string &value) {
1293 if(current.size() > 2 && current.substr(0, 2) ==
"--" &&
valid_first_char(current[2])) {
1294 auto loc = current.find_first_of(
'=');
1295 if(loc != std::string::npos) {
1296 name = current.substr(2, loc - 2);
1297 value = current.substr(loc + 1);
1299 name = current.substr(2);
1309 if(current.size() > 1 && current[0] ==
'/' &&
valid_first_char(current[1])) {
1310 auto loc = current.find_first_of(
':');
1311 if(loc != std::string::npos) {
1312 name = current.substr(1, loc - 1);
1313 value = current.substr(loc + 1);
1315 name = current.substr(1);
1325 std::vector<std::string> output;
1327 while((val = current.find(
",")) != std::string::npos) {
1328 output.push_back(
trim_copy(current.substr(0, val)));
1329 current = current.substr(val + 1);
1337 std::vector<std::string> flags =
split_names(str);
1338 flags.erase(std::remove_if(flags.begin(),
1340 [](
const std::string &name) {
1341 return ((name.empty()) || (!(((name.find_first_of(
'{') != std::string::npos) &&
1342 (name.back() ==
'}')) ||
1343 (name[0] ==
'!'))));
1346 std::vector<std::pair<std::string, std::string>> output;
1347 output.reserve(flags.size());
1348 for(
auto &flag : flags) {
1349 auto def_start = flag.find_first_of(
'{');
1350 std::string defval =
"false";
1351 if((def_start != std::string::npos) && (flag.back() ==
'}')) {
1352 defval = flag.substr(def_start + 1);
1354 flag.erase(def_start, std::string::npos);
1356 flag.erase(0, flag.find_first_not_of(
"-!"));
1357 output.emplace_back(flag, defval);
1363 inline std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>
1366 std::vector<std::string> short_names;
1367 std::vector<std::string> long_names;
1368 std::string pos_name;
1370 for(std::string name : input) {
1371 if(name.length() == 0)
1373 else if(name.length() > 1 && name[0] ==
'-' && name[1] !=
'-') {
1375 short_names.emplace_back(1, name[1]);
1378 }
else if(name.length() > 2 && name.substr(0, 2) ==
"--") {
1379 name = name.substr(2);
1381 long_names.push_back(name);
1384 }
else if(name ==
"-" || name ==
"--") {
1387 if(pos_name.length() > 0)
1393 return std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>(
1394 short_names, long_names, pos_name);
1409 inline std::string
ini_join(std::vector<std::string> args) {
1410 std::ostringstream s;
1412 for(
const auto &arg : args) {
1416 auto it = std::find_if(arg.begin(), arg.end(), [](
char ch) {
return std::isspace<char>(ch, std::locale()); });
1419 else if(arg.find_first_of(
'\"') == std::string::npos)
1420 s <<
'\"' << arg <<
'\"';
1422 s <<
'\'' << arg <<
'\'';
1443 std::vector<std::string> tmp = parents;
1444 tmp.emplace_back(name);
1456 virtual std::string to_config(
const App *,
bool,
bool, std::string)
const = 0;
1459 virtual std::vector<ConfigItem> from_config(std::istream &)
const = 0;
1463 if(item.
inputs.size() == 1) {
1464 return item.
inputs.at(0);
1470 std::vector<ConfigItem>
from_file(
const std::string &name) {
1471 std::ifstream input{name};
1475 return from_config(input);
1479 virtual ~
Config() =
default;
1485 std::string to_config(
const App *,
bool default_also,
bool write_description, std::string prefix)
const override;
1487 std::vector<ConfigItem>
from_config(std::istream &input)
const override {
1489 std::string section =
"default";
1491 std::vector<ConfigItem> output;
1493 while(getline(input, line)) {
1494 std::vector<std::string> items_buffer;
1497 size_t len = line.length();
1498 if(len > 1 && line[0] ==
'[' && line[len - 1] ==
']') {
1499 section = line.substr(1, len - 2);
1500 }
else if(len > 0 && line[0] !=
';') {
1501 output.emplace_back();
1505 auto pos = line.find(
'=');
1506 if(pos != std::string::npos) {
1512 items_buffer = {
"ON"};
1519 if(out.
name.find(
'.') != std::string::npos) {
1521 out.
name = plist.back();
1523 out.
parents.insert(out.
parents.end(), plist.begin(), plist.end());
1526 out.
inputs.insert(std::end(out.
inputs), std::begin(items_buffer), std::end(items_buffer));
1554 std::function<std::string()> desc_function_{[]() {
return std::string{}; }};
1558 std::function<std::string(std::string &)> func_{[](std::string &) {
return std::string{}; }};
1564 bool non_modifying_{
false};
1569 explicit Validator(std::string validator_desc) : desc_function_([validator_desc]() {
return validator_desc; }) {}
1571 Validator(std::function<std::string(std::string &)> op, std::string validator_desc, std::string validator_name =
"")
1572 : desc_function_([validator_desc]() {
return validator_desc; }), func_(std::move(op)),
1573 name_(std::move(validator_name)) {}
1576 func_ = std::move(op);
1582 std::string retstring;
1584 if(non_modifying_) {
1585 std::string value =
str;
1586 retstring = func_(value);
1588 retstring = func_(str);
1597 std::string value =
str;
1598 return (active_) ? func_(value) : std::string{};
1603 desc_function_ = [validator_desc]() {
return validator_desc; };
1609 return desc_function_();
1611 return std::string{};
1615 name_ = std::move(validator_name);
1622 active_ = active_val;
1628 non_modifying_ = no_modify;
1646 const std::function<std::string(std::string & filename)> &f1 = func_;
1647 const std::function<std::string(std::string & filename)> &f2 = other.
func_;
1649 newval.
func_ = [f1, f2](std::string &input) {
1650 std::string s1 = f1(input);
1651 std::string s2 = f2(input);
1652 if(!s1.empty() && !s2.empty())
1653 return std::string(
"(") + s1 +
") AND (" + s2 +
")";
1670 const std::function<std::string(std::string &)> &f1 = func_;
1671 const std::function<std::string(std::string &)> &f2 = other.
func_;
1673 newval.
func_ = [f1, f2](std::string &input) {
1674 std::string s1 = f1(input);
1675 std::string s2 = f2(input);
1676 if(s1.empty() || s2.empty())
1677 return std::string();
1679 return std::string(
"(") + s1 +
") OR (" + s2 +
")";
1688 const std::function<std::string()> &dfunc1 = desc_function_;
1690 auto str = dfunc1();
1691 return (!
str.empty()) ? std::string(
"NOT ") +
str : std::string{};
1694 const std::function<std::string(std::string & res)> &f1 = func_;
1696 newval.
func_ = [f1, dfunc1](std::string &test) -> std::string {
1697 std::string s1 = f1(test);
1699 return std::string(
"check ") + dfunc1() +
" succeeded improperly";
1701 return std::string{};
1710 const std::function<std::string()> &dfunc1 = val1.
desc_function_;
1711 const std::function<std::string()> &dfunc2 = val2.
desc_function_;
1713 desc_function_ = [=]() {
1714 std::string f1 = dfunc1();
1715 std::string f2 = dfunc2();
1716 if((f1.empty()) || (f2.empty())) {
1719 return std::string(
"(") + f1 +
")" + merger +
"(" + f2 +
")";
1737 func_ = [](std::string &filename) {
1739 bool exist = stat(filename.c_str(), &buffer) == 0;
1740 bool is_dir = (buffer.st_mode & S_IFDIR) != 0;
1742 return "File does not exist: " + filename;
1744 return "File is actually a directory: " + filename;
1746 return std::string();
1755 func_ = [](std::string &filename) {
1757 bool exist = stat(filename.c_str(), &buffer) == 0;
1758 bool is_dir = (buffer.st_mode & S_IFDIR) != 0;
1760 return "Directory does not exist: " + filename;
1761 }
else if(!is_dir) {
1762 return "Directory is actually a file: " + filename;
1764 return std::string();
1773 func_ = [](std::string &filename) {
1775 bool const exist = stat(filename.c_str(), &buffer) == 0;
1777 return "Path does not exist: " + filename;
1779 return std::string();
1788 func_ = [](std::string &filename) {
1790 bool exist = stat(filename.c_str(), &buffer) == 0;
1792 return "Path already exists: " + filename;
1794 return std::string();
1803 func_ = [](std::string &ip_addr) {
1805 if(result.size() != 4) {
1806 return "Invalid IPV4 address must have four parts " + ip_addr;
1810 for(
const auto &var : result) {
1813 return "Failed parsing number " + var;
1815 if(num < 0 || num > 255) {
1816 return "Each IP number must be between 0 and 255 " + var;
1819 return std::string();
1828 func_ = [](std::string &number_str) {
1831 return "Failed parsing number " + number_str;
1834 return "Number less then 0 " + number_str;
1836 return std::string();
1845 func_ = [](std::string &number_str) {
1848 return "Failed parsing as a number " + number_str;
1850 return std::string();
1887 template <
typename T>
Range(T min, T max) {
1888 std::stringstream out;
1889 out << detail::type_name<T>() <<
" in [" << min <<
" - " << max <<
"]";
1890 description(out.str());
1892 func_ = [min, max](std::string &input) {
1895 if((!converted) || (val < min || val > max))
1898 return std::string();
1903 template <
typename T>
explicit Range(T max) :
Range(static_cast<T>(0), max) {}
1913 template <
typename T>
Bound(T min, T max) {
1914 std::stringstream out;
1915 out << detail::type_name<T>() <<
" bounded to [" << min <<
" - " << max <<
"]";
1916 description(out.str());
1918 func_ = [min, max](std::string &input) {
1922 return "Value " + input +
" could not be converted";
1929 return std::string();
1934 template <
typename T>
explicit Bound(T max) :
Bound(static_cast<T>(0), max) {}
1938 template <
typename T,
1954 std::string out(1,
'{');
1963 template <
typename T> std::string
generate_map(
const T &map,
bool key_only =
false) {
1966 std::string out(1,
'{');
1968 [key_only](
const iteration_type_t &v) {
1983 template <
typename T,
typename V>
1985 template <
typename,
typename V>
static auto test_find(
long) -> std::false_type;
1987 template <
typename T,
typename V>
struct has_find : decltype(test_find<T, V>(0)) {};
1990 template <typename T, typename V, enable_if_t<!has_find<T, V>::value, detail::enabler> =
detail::dummy>
1991 auto search(
const T &
set,
const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
1994 auto it = std::find_if(std::begin(setref), std::end(setref), [&val](decltype(*std::begin(setref)) v) {
1997 return {(it != std::end(setref)), it};
2001 template <typename T, typename V, enable_if_t<has_find<T, V>::value, detail::enabler> =
detail::dummy>
2002 auto search(
const T &
set,
const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
2004 auto it = setref.find(val);
2005 return {(it != std::end(setref)), it};
2009 template <
typename T,
typename V>
2010 auto search(
const T &
set,
const V &val,
const std::function<V(V)> &filter_function)
2011 -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
2014 auto res =
search(
set, val);
2015 if((res.first) || (!(filter_function))) {
2020 auto it = std::find_if(std::begin(setref), std::end(setref), [&](decltype(*std::begin(setref)) v) {
2022 a = filter_function(a);
2025 return {(it != std::end(setref)), it};
2030 if(a == 0 || b == 0) {
2043 template <
typename T>
2046 if(std::isinf(c) && !std::isinf(a) && !std::isinf(b)) {
2060 template <
typename T,
typename... Args>
2061 explicit IsMember(std::initializer_list<T> values, Args &&... args)
2062 :
IsMember(std::vector<T>(values), std::forward<Args>(args)...) {}
2069 template <
typename T,
typename F>
explicit IsMember(T
set, F filter_function) {
2080 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
2087 func_ = [
set, filter_fn](std::string &input) {
2103 return std::string{};
2107 std::string out(
" not in ");
2114 template <
typename T,
typename... Args>
2117 [filter_fn_1, filter_fn_2](std::string a) {
return filter_fn_2(filter_fn_1(a)); },
2130 template <
typename... Args>
2131 explicit Transformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&... args)
2139 template <
typename T,
typename F>
explicit Transformer(T mapping, F filter_function) {
2142 "mapping must produce value pairs");
2151 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
2156 func_ = [mapping, filter_fn](std::string &input) {
2159 return std::string();
2169 return std::string{};
2174 template <
typename T,
typename... Args>
2177 [filter_fn_1, filter_fn_2](std::string a) {
return filter_fn_2(filter_fn_1(a)); },
2187 template <
typename... Args>
2188 explicit CheckedTransformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&... args)
2199 "mapping must produce value pairs");
2210 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
2212 auto tfunc = [mapping]() {
2213 std::string out(
"value in ");
2223 desc_function_ = tfunc;
2225 func_ = [mapping, tfunc, filter_fn](std::string &input) {
2235 return std::string{};
2240 if(output_string == input) {
2241 return std::string();
2245 return "Check " + input +
" " + tfunc() +
" FAILED";
2250 template <
typename T,
typename... Args>
2253 [filter_fn_1, filter_fn_2](std::string a) {
return filter_fn_2(filter_fn_1(a)); },
2265 item.erase(std::remove(std::begin(item), std::end(item),
' '), std::end(item));
2266 item.erase(std::remove(std::begin(item), std::end(item),
'\t'), std::end(item));
2289 CASE_INSENSITIVE = 1,
2292 DEFAULT = CASE_INSENSITIVE | UNIT_OPTIONAL
2295 template <
typename Number>
2298 const std::string &unit_name =
"UNIT") {
2299 description(generate_description<Number>(unit_name, opts));
2300 validate_mapping(mapping, opts);
2303 func_ = [mapping, opts](std::string &input) -> std::string {
2312 auto unit_begin = input.end();
2313 while(unit_begin > input.begin() &&
std::isalpha(*(unit_begin - 1), std::locale())) {
2317 std::string unit{unit_begin, input.end()};
2318 input.resize(static_cast<size_t>(std::distance(input.begin(), unit_begin)));
2321 if(opts & UNIT_REQUIRED && unit.empty()) {
2324 if(opts & CASE_INSENSITIVE) {
2330 throw ValidationError(
"Value " + input +
" could not be converted to " + detail::type_name<Number>());
2339 auto it = mapping.find(unit);
2340 if(it == mapping.end()) {
2342 " unit not recognized. " 2343 "Allowed values: " +
2351 " factor would cause number overflow. Use smaller value.");
2363 for(
auto &kv : mapping) {
2364 if(kv.first.empty()) {
2373 if(opts & CASE_INSENSITIVE) {
2374 std::map<std::string, Number> lower_mapping;
2375 for(
auto &kv : mapping) {
2377 if(lower_mapping.count(s)) {
2378 throw ValidationError(
"Several matching lowercase unit representations are found: " + s);
2382 mapping = std::move(lower_mapping);
2388 std::stringstream out;
2389 out << detail::type_name<Number>() <<
' ';
2390 if(opts & UNIT_REQUIRED) {
2393 out <<
'[' << name <<
']';
2423 description(
"SIZE [b, kb(=1000b), kib(=1024b), ...]");
2425 description(
"SIZE [b, kb(=1024b), ...]");
2432 std::map<std::string, result_t> m;
2433 result_t k_factor = kb_is_1000 ? 1000 : 1024;
2438 for(std::string p : {
"k",
"m",
"g",
"t",
"p",
"e"}) {
2452 static auto m = init_mapping(
true);
2455 static auto m = init_mapping(
false);
2468 std::pair<std::string, std::string> vals;
2470 auto esp = commandline.find_first_of(
' ', 1);
2471 while(!
ExistingFile(commandline.substr(0, esp)).empty()) {
2472 esp = commandline.find_first_of(
' ', esp + 1);
2473 if(esp == std::string::npos) {
2476 esp = commandline.find_first_of(
' ', 1);
2480 vals.first = commandline.substr(0, esp);
2483 vals.second = (esp != std::string::npos) ? commandline.substr(esp + 1) : std::string{};
2521 size_t column_width_{30};
2540 virtual std::string make_help(
const App *, std::string,
AppFormatMode)
const = 0;
2547 void label(std::string key, std::string val) { labels_[key] = val; }
2558 if(labels_.find(key) == labels_.end())
2561 return labels_.at(key);
2572 using funct_t = std::function<std::string(const App *, std::string, AppFormatMode)>;
2586 return lambda_(app, name, mode);
2603 virtual std::string make_group(std::string group,
bool is_positional, std::vector<const Option *> opts)
const;
2606 virtual std::string make_positionals(
const App *
app)
const;
2612 virtual std::string make_subcommands(
const App *app,
AppFormatMode mode)
const;
2615 virtual std::string make_subcommand(
const App *sub)
const;
2618 virtual std::string make_expanded(
const App *sub)
const;
2621 virtual std::string make_footer(
const App *app)
const;
2624 virtual std::string make_description(
const App *app)
const;
2627 virtual std::string make_usage(
const App *app, std::string name)
const;
2630 std::string make_help(
const App *, std::string,
AppFormatMode)
const override;
2638 std::stringstream out;
2640 out, make_option_name(opt, is_positional) + make_option_opts(opt), make_option_desc(opt), column_width_);
2645 virtual std::string make_option_name(
const Option *,
bool)
const;
2648 virtual std::string make_option_opts(
const Option *)
const;
2651 virtual std::string make_option_desc(
const Option *)
const;
2654 virtual std::string make_option_usage(
const Option *opt)
const;
2682 std::string group_ = std::string(
"Options");
2685 bool required_{
false};
2688 bool ignore_case_{
false};
2691 bool ignore_underscore_{
false};
2694 bool configurable_{
true};
2697 bool disable_flag_override_{
false};
2700 char delimiter_{
'\0'};
2703 bool always_capture_default_{
false};
2709 template <
typename T>
void copy_to(T *other)
const {
2710 other->group(group_);
2711 other->required(required_);
2712 other->ignore_case(ignore_case_);
2713 other->ignore_underscore(ignore_underscore_);
2714 other->configurable(configurable_);
2715 other->disable_flag_override(disable_flag_override_);
2716 other->delimiter(delimiter_);
2717 other->always_capture_default(always_capture_default_);
2718 other->multi_option_policy(multi_option_policy_);
2727 return static_cast<CRTP *
>(
this);
2733 return static_cast<CRTP *
>(
this);
2737 CRTP *
mandatory(
bool value =
true) {
return required(value); }
2740 always_capture_default_ = value;
2741 return static_cast<CRTP *
>(
this);
2777 auto self =
static_cast<CRTP *
>(
this);
2784 auto self =
static_cast<CRTP *
>(
this);
2791 auto self =
static_cast<CRTP *
>(
this);
2798 configurable_ = value;
2799 return static_cast<CRTP *
>(
this);
2805 return static_cast<CRTP *
>(
this);
2819 multi_option_policy_ = value;
2825 ignore_case_ = value;
2831 ignore_underscore_ = value;
2837 disable_flag_override_ = value;
2887 std::function<std::string()> type_name_{[]() {
return std::string(); }};
2931 bool callback_run_{
false};
2937 std::string option_description,
2938 std::function<
bool(
results_t)> callback,
2940 : description_(std::move(option_description)), parent_(parent), callback_(std::move(callback)) {
2949 size_t count()
const {
return results_.size(); }
2952 size_t empty()
const {
return results_.empty(); }
2955 operator bool()
const {
return !empty(); }
2976 else if(expected_ == value)
2980 else if(type_size_ >= 0)
2994 validators_.push_back(std::move(validator));
2995 if(!validator_name.empty())
2996 validators_.front().name(validator_name);
3001 Option *
check(std::function<std::string(
const std::string &)> validator,
3002 std::string validator_description =
"",
3003 std::string validator_name =
"") {
3004 validators_.emplace_back(validator, std::move(validator_description), std::move(validator_name));
3005 validators_.back().non_modifying();
3011 validators_.insert(validators_.begin(), std::move(validator));
3012 if(!validator_name.empty())
3013 validators_.front().name(validator_name);
3019 std::string transform_description =
"",
3020 std::string transform_name =
"") {
3021 validators_.insert(validators_.begin(),
3023 [func](std::string &val) {
3025 return std::string{};
3027 std::move(transform_description),
3028 std::move(transform_name)));
3035 validators_.emplace_back(
3036 [func](std::string &inout) {
3038 return std::string{};
3045 for(
auto &validator : validators_) {
3046 if(validator_name == validator.get_name()) {
3050 if((validator_name.empty()) && (!validators_.empty())) {
3051 return &(validators_.front());
3053 throw OptionNotFound(std::string(
"Validator ") + validator_name +
" Not Found");
3057 auto tup = needs_.insert(opt);
3065 for(
const Option_p &opt : dynamic_cast<T *>(parent_)->options_)
3066 if(opt.get() !=
this && opt->check_name(opt_name))
3067 return needs(opt.get());
3072 template <
typename A,
typename B,
typename... ARG>
Option *
needs(A opt, B opt1, ARG... args) {
3074 return needs(opt1, args...);
3079 auto iterator = std::find(std::begin(needs_), std::end(needs_), opt);
3081 if(iterator != std::end(needs_)) {
3082 needs_.erase(iterator);
3091 excludes_.insert(opt);
3104 for(
const Option_p &opt : dynamic_cast<T *>(parent_)->options_)
3105 if(opt.get() !=
this && opt->check_name(opt_name))
3106 return excludes(opt.get());
3111 template <
typename A,
typename B,
typename... ARG>
Option *
excludes(A opt, B opt1, ARG... args) {
3113 return excludes(opt1, args...);
3118 auto iterator = std::find(std::begin(excludes_), std::end(excludes_), opt);
3120 if(iterator != std::end(excludes_)) {
3121 excludes_.erase(iterator);
3139 ignore_case_ = value;
3140 auto *parent =
dynamic_cast<T *
>(parent_);
3142 for(
const Option_p &opt : parent->options_)
3143 if(opt.get() !=
this && *opt == *
this)
3154 ignore_underscore_ = value;
3155 auto *parent =
dynamic_cast<T *
>(parent_);
3156 for(
const Option_p &opt : parent->options_)
3157 if(opt.get() !=
this && *opt == *
this)
3166 if(get_items_expected() < 0)
3168 multi_option_policy_ = value;
3174 disable_flag_override_ = value;
3195 std::
string get_defaultval()
const {
return default_str_; }
3198 std::string get_default_str()
const {
return default_str_; }
3201 callback_t get_callback()
const {
return callback_; }
3204 const std::vector<std::string> get_lnames()
const {
return lnames_; }
3207 const std::vector<std::string> get_snames()
const {
return snames_; }
3210 const std::vector<std::string> get_fnames()
const {
return fnames_; }
3213 int get_expected()
const {
return expected_; }
3231 int get_items_expected()
const {
3232 return std::abs(type_size_ * expected_) *
3237 bool get_positional()
const {
return pname_.length() > 0; }
3240 bool nonpositional()
const {
return (snames_.size() + lnames_.size()) > 0; }
3243 bool has_description()
const {
return description_.length() > 0; }
3246 const std::string &get_description()
const {
return description_; }
3249 Option *description(std::string option_description) {
3250 description_ = std::move(option_description);
3263 bool all_options =
false 3268 std::vector<std::string> name_list;
3271 if((positional && pname_.length()) || (snames_.empty() && lnames_.empty()))
3272 name_list.push_back(pname_);
3273 if((get_items_expected() == 0) && (!fnames_.empty())) {
3274 for(
const std::string &sname : snames_) {
3275 name_list.push_back(
"-" + sname);
3276 if(check_fname(sname)) {
3277 name_list.back() +=
"{" + get_flag_value(sname,
"") +
"}";
3281 for(
const std::string &lname : lnames_) {
3282 name_list.push_back(
"--" + lname);
3283 if(check_fname(lname)) {
3284 name_list.back() +=
"{" + get_flag_value(lname,
"") +
"}";
3288 for(
const std::string &sname : snames_)
3289 name_list.push_back(
"-" + sname);
3291 for(
const std::string &lname : lnames_)
3292 name_list.push_back(
"--" + lname);
3304 else if(!lnames_.empty())
3305 return std::string(
"--") + lnames_[0];
3308 else if(!snames_.empty())
3309 return std::string(
"-") + snames_[0];
3324 callback_run_ =
true;
3327 if(!validators_.empty()) {
3328 for(std::string &result : results_) {
3329 auto err_msg = _validate(result);
3330 if(!err_msg.empty())
3342 std::min<int>(std::max<int>(
std::abs(get_items_expected()), 1), static_cast<int>(results_.size()));
3347 results_t partial_result{results_.end() - trim_size, results_.end()};
3348 local_result = !callback_(partial_result);
3351 results_t partial_result{results_.begin(), results_.begin() + trim_size};
3352 local_result = !callback_(partial_result);
3356 local_result = !callback_(partial_result);
3360 if(get_items_expected() > 0) {
3361 if(results_.size() !=
static_cast<size_t>(get_items_expected()))
3364 }
else if(get_items_expected() < 0) {
3366 if(results_.size() <
static_cast<size_t>(-get_items_expected()) ||
3367 results_.size() %
static_cast<size_t>(
std::abs(get_type_size())) != 0u)
3370 local_result = !callback_(results_);
3379 for(
const std::string &sname : snames_)
3382 for(
const std::string &lname : lnames_)
3387 ignore_underscore_) {
3388 for(
const std::string &sname : other.
snames_)
3389 if(check_sname(sname))
3391 for(
const std::string &lname : other.
lnames_)
3392 if(check_lname(lname))
3401 if(name.length() > 2 && name[0] ==
'-' && name[1] ==
'-')
3402 return check_lname(name.substr(2));
3403 else if(name.length() > 1 && name.front() ==
'-')
3404 return check_sname(name.substr(1));
3406 std::string local_pname = pname_;
3407 if(ignore_underscore_) {
3415 return name == local_pname;
3429 if(fnames_.empty()) {
3436 static const std::string trueString{
"true"};
3437 static const std::string falseString{
"false"};
3438 static const std::string emptyString{
"{}"};
3440 if(disable_flag_override_) {
3441 if(!((input_value.empty()) || (input_value == emptyString))) {
3443 if(default_ind >= 0) {
3445 if(default_flag_values_[static_cast<size_t>(default_ind)].second != input_value) {
3449 if(input_value != trueString) {
3456 if((input_value.empty()) || (input_value == emptyString)) {
3457 return (ind < 0) ? trueString : default_flag_values_[
static_cast<size_t>(ind)].second;
3462 if(default_flag_values_[static_cast<size_t>(ind)].second == falseString) {
3465 return (val == 1) ? falseString : (val == (-1) ? trueString :
std::to_string(-val));
3466 }
catch(
const std::invalid_argument &) {
3476 _add_result(std::move(s));
3477 callback_run_ =
false;
3483 results_added = _add_result(std::move(s));
3484 callback_run_ =
false;
3490 for(
auto &
str : s) {
3491 _add_result(std::move(
str));
3493 callback_run_ =
false;
3498 std::vector<std::string>
results()
const {
return results_; }
3501 template <
typename T,
3505 if(results_.empty()) {
3507 }
else if(results_.size() == 1) {
3510 switch(multi_option_policy_) {
3530 template <
typename T>
void results(std::vector<T> &output)
const {
3534 for(
const auto &elem : results_) {
3535 output.emplace_back();
3545 template <
typename T> T
as()
const {
3560 type_name_ = typefun;
3566 type_name_fn([typeval]() {
return typeval; });
3572 type_size_ = option_type_size;
3575 if(option_type_size < 0)
3582 default_function_ = func;
3588 if(default_function_) {
3589 default_str_ = default_function_();
3603 auto old_results = results_;
3606 results_ = std::move(old_results);
3612 std::string full_type_name = type_name_();
3613 if(!validators_.empty()) {
3614 for(
auto &validator : validators_) {
3615 std::string vtype = validator.get_description();
3616 if(!vtype.empty()) {
3617 full_type_name +=
":" + vtype;
3621 return full_type_name;
3627 std::string err_msg;
3628 for(
const auto &vali : validators_) {
3630 err_msg = vali(result);
3632 err_msg = err.what();
3634 if(!err_msg.empty())
3641 int result_count = 0;
3642 if(delimiter_ ==
'\0') {
3643 results_.push_back(std::move(result));
3646 if((result.find_first_of(delimiter_) != std::string::npos)) {
3649 results_.push_back(var);
3654 results_.push_back(std::move(result));
3658 return result_count;
3669 #define CLI11_PARSE(app, argc, argv) \ 3671 (app).parse((argc), (argv)); \ 3672 } catch(const CLI::ParseError &e) { \ 3673 return (app).exit(e); \ 3682 namespace FailureMessage {
3713 bool allow_extras_{
false};
3716 bool allow_config_extras_{
false};
3719 bool prefix_command_{
false};
3722 bool has_automatic_name_{
false};
3725 bool required_{
false};
3728 bool disabled_{
false};
3731 bool pre_parse_called_{
false};
3735 bool immediate_callback_{
false};
3776 using missing_t = std::vector<std::pair<detail::Classifier, std::string>>;
3804 bool ignore_case_{
false};
3807 bool ignore_underscore_{
false};
3810 bool fallthrough_{
false};
3813 bool allow_windows_style_options_{
3821 bool positionals_at_end_{
false};
3824 bool disabled_by_default_{
false};
3826 bool enabled_by_default_{
false};
3828 bool validate_positionals_{
false};
3836 size_t require_subcommand_min_ = 0;
3839 size_t require_subcommand_max_ = 0;
3842 size_t require_option_min_ = 0;
3845 size_t require_option_max_ = 0;
3848 std::string group_{
"Subcommands"};
3858 bool config_required_{
false};
3869 App(std::string app_description, std::string app_name,
App *parent)
3870 : name_(std::move(app_name)), description_(std::move(app_description)), parent_(parent) {
3872 if(parent_ !=
nullptr) {
3893 group_ = parent_->
group_;
3906 explicit App(std::string app_description =
"", std::string app_name =
"")
3907 :
App(app_description, app_name, nullptr) {
3908 set_help_flag(
"-h,--help",
"Print this help message and exit");
3912 virtual ~
App() =
default;
3921 callback_ = std::move(app_callback);
3928 pre_parse_callback_ = std::move(pp_callback);
3935 has_automatic_name_ =
false;
3941 allow_extras_ = allow;
3947 required_ = require;
3953 disabled_ = disable;
3959 disabled_by_default_ = disable;
3966 enabled_by_default_ = enable;
3972 immediate_callback_ = immediate;
3978 validate_positionals_ = validate;
3985 allow_extras(allow);
3986 allow_config_extras_ = allow;
3992 prefix_command_ = allow;
3998 ignore_case_ = value;
3999 if(parent_ !=
nullptr && !name_.empty()) {
4001 if(subc.get() !=
this && (this->check_name(subc->name_) || subc->check_name(this->name_)))
4010 allow_windows_style_options_ = value;
4016 positionals_at_end_ = value;
4022 ignore_underscore_ = value;
4023 if(parent_ !=
nullptr && !name_.empty()) {
4025 if(subc.get() !=
this && (this->check_name(subc->name_) || subc->check_name(this->name_)))
4040 formatter_ = std::make_shared<FormatterLambda>(fmt);
4046 config_formatter_ = fmt;
4076 std::string option_description =
"",
4077 bool defaulted =
false,
4078 std::function<std::string()> func = {}) {
4079 Option myopt{option_name, option_description, option_callback,
this};
4081 if(std::find_if(std::begin(options_), std::end(options_), [&myopt](
const Option_p &v) {
4083 }) == std::end(options_)) {
4084 options_.emplace_back();
4085 Option_p &option = options_.back();
4086 option.reset(
new Option(option_name, option_description, option_callback,
this));
4089 option->default_function(func);
4093 option->capture_default_str();
4096 option_defaults_.
copy_to(option.get());
4099 if(!defaulted && option->get_always_capture_default())
4100 option->capture_default_str();
4102 return option.get();
4109 template <typename T, enable_if_t<!is_vector<T>::value & !std::is_const<T>::value, detail::enabler> =
detail::dummy>
4112 std::string option_description =
"",
4113 bool defaulted =
false) {
4117 Option *opt = add_option(option_name, fun, option_description, defaulted, [&variable]() {
4126 template <typename T, enable_if_t<!is_vector<T>::value, detail::enabler> =
detail::dummy>
4128 const std::function<
void(
const T &)> &func,
4129 std::string option_description =
"") {
4140 Option *opt = add_option(option_name, std::move(fun), option_description,
false);
4147 return add_option(option_name,
CLI::callback_t(), std::string{},
false);
4151 template <
typename T,
4155 return add_option(option_name,
CLI::callback_t(), option_description,
false);
4159 template <
typename T>
4161 std::vector<T> &variable,
4162 std::string option_description =
"",
4163 bool defaulted =
false) {
4168 variable.reserve(res.size());
4169 for(
const auto &elem : res) {
4171 variable.emplace_back();
4174 return (!variable.empty()) && retval;
4177 auto default_function = [&variable]() {
4178 std::vector<std::string> defaults;
4179 defaults.resize(variable.size());
4180 std::transform(variable.begin(), variable.end(), defaults.begin(), [](T &val) {
4183 return std::string(
"[" +
detail::join(defaults) +
"]");
4186 Option *opt = add_option(option_name, fun, option_description, defaulted, default_function);
4193 template <typename T, enable_if_t<is_vector<T>::value, detail::enabler> =
detail::dummy>
4195 const std::function<
void(
const T &)> &func,
4196 std::string option_description =
"") {
4201 values.reserve(res.size());
4202 for(
const auto &elem : res) {
4203 values.emplace_back();
4212 Option *opt = add_option(option_name, std::move(fun), std::move(option_description),
false);
4220 if(help_ptr_ !=
nullptr) {
4221 remove_option(help_ptr_);
4222 help_ptr_ =
nullptr;
4226 if(!flag_name.empty()) {
4227 help_ptr_ = add_flag(flag_name, help_description);
4228 help_ptr_->configurable(
false);
4237 if(help_all_ptr_ !=
nullptr) {
4238 remove_option(help_all_ptr_);
4239 help_all_ptr_ =
nullptr;
4243 if(!help_name.empty()) {
4244 help_all_ptr_ = add_flag(help_name, help_description);
4245 help_all_ptr_->configurable(
false);
4248 return help_all_ptr_;
4259 opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description),
false);
4260 for(
const auto &fname : flag_defaults)
4261 opt->
fnames_.push_back(fname.first);
4264 opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description),
false);
4267 if(opt->get_positional()) {
4268 auto pos_name = opt->
get_name(
true);
4284 template <
typename T,
4288 return _add_flag_internal(flag_name,
CLI::callback_t(), flag_description);
4293 template <
typename T,
4297 std::string flag_description =
"") {
4302 }
catch(
const std::invalid_argument &) {
4307 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
4312 template <
typename T,
4315 !std::is_constructible<std::function<
void(
int)>, T>::value,
4319 std::string flag_description =
"") {
4322 if(res.size() != 1) {
4327 Option *opt = _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
4333 template <
typename T,
4336 std::vector<T> &flag_results,
4337 std::string flag_description =
"") {
4340 for(
const auto &elem : res) {
4341 flag_results.emplace_back();
4346 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
4351 std::function<
void(
void)>
function,
4352 std::string flag_description =
"") {
4355 if(res.size() != 1) {
4364 Option *opt = _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
4371 std::function<
void(int64_t)>
function,
4372 std::string flag_description =
"") {
4375 int64_t flag_count = 0;
4377 function(flag_count);
4380 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
4384 Option *add_flag(std::string flag_name,
4386 std::function<
void(int64_t)>
function,
4387 std::string flag_description =
"") {
4388 return add_flag_function(std::move(flag_name), std::move(
function), std::move(flag_description));
4393 template <
typename T>
4396 std::set<T> options,
4397 std::string option_description =
"") {
4399 Option *opt = add_option(option_name, member, std::move(option_description));
4405 template <
typename T>
4408 const std::set<T> &options,
4409 std::string option_description =
"") {
4411 Option *opt = add_option(option_name, member, std::move(option_description));
4417 template <
typename T>
4420 std::set<T> options,
4421 std::string option_description,
4424 Option *opt = add_option(option_name, member, std::move(option_description), defaulted);
4430 template <
typename T>
4433 const std::set<T> &options,
4434 std::string option_description,
4437 Option *opt = add_option(option_name, member, std::move(option_description), defaulted);
4444 Option *add_set_ignore_case(std::
string option_name,
4445 std::
string &member,
4446 std::set<std::
string> options,
4447 std::
string option_description = "") {
4449 Option *opt = add_option(option_name, member, std::move(option_description));
4456 CLI11_DEPRECATED(
"Use ->transform(CLI::IsMember(..., CLI::ignore_case)) with a (shared) pointer instead")
4457 Option *add_mutable_set_ignore_case(std::
string option_name,
4458 std::
string &member,
4459 const std::set<std::
string> &options,
4460 std::
string option_description = "") {
4462 Option *opt = add_option(option_name, member, std::move(option_description));
4469 Option *add_set_ignore_case(std::
string option_name,
4470 std::
string &member,
4471 std::set<std::
string> options,
4472 std::
string option_description,
4475 Option *opt = add_option(option_name, member, std::move(option_description), defaulted);
4483 Option *add_mutable_set_ignore_case(std::
string option_name,
4484 std::
string &member,
4485 const std::set<std::
string> &options,
4486 std::
string option_description,
4489 Option *opt = add_option(option_name, member, std::move(option_description), defaulted);
4496 Option *add_set_ignore_underscore(std::
string option_name,
4497 std::
string &member,
4498 std::set<std::
string> options,
4499 std::
string option_description = "") {
4501 Option *opt = add_option(option_name, member, std::move(option_description));
4508 CLI11_DEPRECATED(
"Use ->transform(CLI::IsMember(..., CLI::ignore_underscore)) with a (shared) pointer instead")
4509 Option *add_mutable_set_ignore_underscore(std::
string option_name,
4510 std::
string &member,
4511 const std::set<std::
string> &options,
4512 std::
string option_description = "") {
4514 Option *opt = add_option(option_name, member, std::move(option_description));
4521 Option *add_set_ignore_underscore(std::
string option_name,
4522 std::
string &member,
4523 std::set<std::
string> options,
4524 std::
string option_description,
4527 Option *opt = add_option(option_name, member, std::move(option_description), defaulted);
4534 CLI11_DEPRECATED(
"Use ->transform(CLI::IsMember(..., CLI::ignore_underscore)) with a (shared) pointer instead")
4535 Option *add_mutable_set_ignore_underscore(std::
string option_name,
4536 std::
string &member,
4537 const std::set<std::
string> &options,
4538 std::
string option_description,
4541 Option *opt = add_option(option_name, member, std::move(option_description), defaulted);
4547 CLI11_DEPRECATED(
"Use ->transform(CLI::IsMember(..., CLI::ignore_case, CLI::ignore_underscore)) instead")
4548 Option *add_set_ignore_case_underscore(std::
string option_name,
4549 std::
string &member,
4550 std::set<std::
string> options,
4551 std::
string option_description = "") {
4553 Option *opt = add_option(option_name, member, std::move(option_description));
4561 "Use ->transform(CLI::IsMember(..., CLI::ignore_case, CLI::ignore_underscore)) with a (shared) pointer instead")
4562 Option *add_mutable_set_ignore_case_underscore(std::
string option_name,
4563 std::
string &member,
4564 const std::set<std::
string> &options,
4565 std::
string option_description = "") {
4567 Option *opt = add_option(option_name, member, std::move(option_description));
4573 CLI11_DEPRECATED(
"Use ->transform(CLI::IsMember(..., CLI::ignore_case, CLI::ignore_underscore)) instead")
4574 Option *add_set_ignore_case_underscore(std::
string option_name,
4575 std::
string &member,
4576 std::set<std::
string> options,
4577 std::
string option_description,
4580 Option *opt = add_option(option_name, member, std::move(option_description), defaulted);
4588 "Use ->transform(CLI::IsMember(..., CLI::ignore_case, CLI::ignore_underscore)) with a (shared) pointer instead")
4589 Option *add_mutable_set_ignore_case_underscore(std::
string option_name,
4590 std::
string &member,
4591 const std::set<std::
string> &options,
4592 std::
string option_description,
4595 Option *opt = add_option(option_name, member, std::move(option_description), defaulted);
4601 template <
typename T>
4604 std::string option_description =
"",
4605 bool defaulted =
false,
4606 std::string label =
"COMPLEX") {
4610 if(res[1].back() ==
'i')
4619 auto default_function = [&variable]() {
4620 std::stringstream out;
4626 add_option(option_name, std::move(fun), std::move(option_description), defaulted, default_function);
4634 std::string default_filename =
"",
4635 std::string help_message =
"Read an ini file",
4636 bool config_required =
false) {
4639 if(config_ptr_ !=
nullptr)
4640 remove_option(config_ptr_);
4643 if(!option_name.empty()) {
4644 config_name_ = default_filename;
4645 config_required_ = config_required;
4646 config_ptr_ = add_option(option_name, config_name_, help_message, !default_filename.empty());
4647 config_ptr_->configurable(
false);
4657 op->remove_needs(opt);
4658 op->remove_excludes(opt);
4661 if(help_ptr_ == opt)
4662 help_ptr_ =
nullptr;
4663 if(help_all_ptr_ == opt)
4664 help_all_ptr_ =
nullptr;
4667 std::find_if(std::begin(options_), std::end(options_), [opt](
const Option_p &v) {
return v.get() == opt; });
4668 if(iterator != std::end(options_)) {
4669 options_.erase(iterator);
4676 template <
typename T = Option_group>
4678 auto option_group = std::make_shared<T>(std::move(group_description), group_name,
nullptr);
4679 auto ptr = option_group.get();
4681 App_p app_ptr = std::dynamic_pointer_cast<
App>(option_group);
4682 add_subcommand(std::move(app_ptr));
4692 CLI::App_p subcom = std::shared_ptr<App>(
new App(std::move(subcommand_description), subcommand_name,
this));
4693 return add_subcommand(std::move(subcom));
4700 if(!subcom->name_.empty()) {
4701 for(
const auto &subc : subcommands_)
4702 if(subc->check_name(subcom->name_) || subcom->check_name(subc->name_))
4705 subcom->parent_ =
this;
4706 subcommands_.push_back(std::move(subcom));
4707 return subcommands_.back().get();
4713 for(
App_p &sub : subcommands_) {
4714 sub->remove_excludes(subcom);
4717 auto iterator = std::find_if(
4718 std::begin(subcommands_), std::end(subcommands_), [subcom](
const App_p &v) {
return v.get() == subcom; });
4719 if(iterator != std::end(subcommands_)) {
4720 subcommands_.erase(iterator);
4728 if(subcom ==
nullptr)
4730 for(
const App_p &subcomptr : subcommands_)
4731 if(subcomptr.get() == subcom)
4738 auto subc = _find_subcommand(subcom,
false,
false);
4746 auto uindex =
static_cast<unsigned>(index);
4747 if(uindex < subcommands_.size())
4748 return subcommands_[uindex].
get();
4755 if(subcom ==
nullptr)
4757 for(
const App_p &subcomptr : subcommands_)
4758 if(subcomptr.get() == subcom)
4765 for(
const App_p &subcomptr : subcommands_)
4766 if(subcomptr->check_name(subcom))
4774 auto uindex =
static_cast<unsigned>(index);
4775 if(uindex < subcommands_.size())
4776 return subcommands_[uindex];
4783 for(
const App_p &
app : subcommands_) {
4794 size_t count()
const {
return parsed_; }
4800 for(
auto &opt : options_) {
4801 cnt += opt->count();
4803 for(
auto &sub : subcommands_) {
4804 cnt += sub->count_all();
4806 if(!get_name().empty()) {
4814 group_ = group_name;
4820 require_subcommand_min_ = 1;
4821 require_subcommand_max_ = 0;
4830 require_subcommand_min_ = 0;
4831 require_subcommand_max_ =
static_cast<size_t>(-value);
4833 require_subcommand_min_ =
static_cast<size_t>(value);
4834 require_subcommand_max_ =
static_cast<size_t>(value);
4842 require_subcommand_min_ = min;
4843 require_subcommand_max_ = max;
4849 require_option_min_ = 1;
4850 require_option_max_ = 0;
4859 require_option_min_ = 0;
4860 require_option_max_ =
static_cast<size_t>(-value);
4862 require_option_min_ =
static_cast<size_t>(value);
4863 require_option_max_ =
static_cast<size_t>(value);
4871 require_option_min_ = min;
4872 require_option_max_ = max;
4879 fallthrough_ = value;
4885 operator bool()
const {
return parsed_ > 0; }
4904 pre_parse_called_ =
false;
4907 parsed_subcommands_.clear();
4908 for(
const Option_p &opt : options_) {
4911 for(
const App_p &subc : subcommands_) {
4918 void parse(
int argc,
const char *
const *argv) {
4920 if(name_.empty() || has_automatic_name_) {
4921 has_automatic_name_ =
true;
4925 std::vector<std::string> args;
4926 args.reserve(static_cast<size_t>(argc - 1));
4927 for(
int i = argc - 1; i > 0; i--)
4928 args.emplace_back(argv[i]);
4929 parse(std::move(args));
4936 void parse(std::string commandline,
bool program_name_included =
false) {
4938 if(program_name_included) {
4940 if((name_.empty()) || (has_automatic_name_)) {
4941 has_automatic_name_ =
true;
4944 commandline = std::move(nstr.second);
4948 if(!commandline.empty()) {
4950 if(allow_windows_style_options_)
4956 args.erase(std::remove(args.begin(), args.end(), std::string{}), args.end());
4957 std::reverse(args.begin(), args.end());
4959 parse(std::move(args));
4964 void parse(std::vector<std::string> &args) {
4984 void parse(std::vector<std::string> &&args) {
4999 _parse(std::move(args));
5005 failure_message_ =
function;
5009 int exit(
const Error &e, std::ostream &out = std::cout, std::ostream &err = std::cerr)
const {
5012 if(dynamic_cast<const CLI::RuntimeError *>(&e) !=
nullptr)
5015 if(dynamic_cast<const CLI::CallForHelp *>(&e) !=
nullptr) {
5020 if(dynamic_cast<const CLI::CallForAllHelp *>(&e) !=
nullptr) {
5026 if(failure_message_)
5027 err << failure_message_(
this, e) << std::flush;
5038 size_t count(std::string option_name)
const {
return get_option(option_name)->count(); }
5047 std::vector<const App *> subcomms(subcommands_.size());
5048 std::transform(std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](
const App_p &v) {
5053 subcomms.erase(std::remove_if(std::begin(subcomms),
5055 [&filter](
const App *
app) {
return !filter(app); }),
5056 std::end(subcomms));
5065 std::vector<App *> subcomms(subcommands_.size());
5066 std::transform(std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](
const App_p &v) {
5072 std::remove_if(std::begin(subcomms), std::end(subcomms), [&filter](
App *
app) {
return !filter(app); }),
5073 std::end(subcomms));
5082 return get_subcommand(subcom)->parsed_ > 0;
5086 bool got_subcommand(std::string subcommand_name)
const {
return get_subcommand(subcommand_name)->parsed_ > 0; }
5090 if(opt ==
nullptr) {
5093 exclude_options_.insert(opt);
5099 if((app ==
this) || (app ==
nullptr)) {
5102 auto res = exclude_subcommands_.insert(app);
5112 auto iterator = std::find(std::begin(exclude_options_), std::end(exclude_options_), opt);
5113 if(iterator != std::end(exclude_options_)) {
5114 exclude_options_.erase(iterator);
5123 auto iterator = std::find(std::begin(exclude_subcommands_), std::end(exclude_subcommands_), app);
5124 if(iterator != std::end(exclude_subcommands_)) {
5125 auto other_app = *iterator;
5126 exclude_subcommands_.erase(iterator);
5127 other_app->remove_excludes(
this);
5140 footer_ = std::move(footer_string);
5146 std::string
config_to_str(
bool default_also =
false,
bool write_description =
false)
const {
5147 return config_formatter_->to_config(
this, default_also, write_description,
"");
5156 prev +=
" " + get_name();
5159 auto selected_subcommands = get_subcommands();
5160 if(!selected_subcommands.empty())
5161 return selected_subcommands.at(0)->help(prev, mode);
5163 return formatter_->make_help(
this, prev, mode);
5181 description_ = std::move(app_description);
5186 std::vector<const Option *>
get_options(
const std::function<
bool(
const Option *)> filter = {})
const {
5187 std::vector<const Option *> options(options_.size());
5188 std::transform(std::begin(options_), std::end(options_), std::begin(options), [](
const Option_p &val) {
5193 options.erase(std::remove_if(std::begin(options),
5195 [&filter](
const Option *opt) {
return !filter(opt); }),
5205 if(opt->check_name(option_name)) {
5209 for(
auto &subc : subcommands_) {
5211 if(subc->get_name().empty()) {
5212 auto opt = subc->get_option_no_throw(option_name);
5213 if(opt !=
nullptr) {
5223 for(
const Option_p &opt : options_) {
5224 if(opt->check_name(option_name)) {
5228 for(
const auto &subc : subcommands_) {
5230 if(subc->get_name().empty()) {
5231 auto opt = subc->get_option_no_throw(option_name);
5232 if(opt !=
nullptr) {
5242 auto opt = get_option_no_throw(option_name);
5243 if(opt ==
nullptr) {
5251 auto opt = get_option_no_throw(option_name);
5252 if(opt ==
nullptr) {
5259 const Option *
operator[](
const std::string &option_name)
const {
return get_option(option_name); }
5348 std::string
get_display_name()
const {
return (!name_.empty()) ? name_ :
"[Option Group: " + get_group() +
"]"; }
5352 std::string local_name = name_;
5353 if(ignore_underscore_) {
5362 return local_name == name_to_check;
5367 std::vector<std::string> groups;
5369 for(
const Option_p &opt : options_) {
5371 if(std::find(groups.begin(), groups.end(), opt->get_group()) == groups.end()) {
5372 groups.push_back(opt->get_group());
5380 const std::vector<Option *> &
parse_order()
const {
return parse_order_; }
5383 std::vector<std::string>
remaining(
bool recurse =
false)
const {
5384 std::vector<std::string> miss_list;
5385 for(
const std::pair<detail::Classifier, std::string> &miss : missing_) {
5386 miss_list.push_back(std::get<1>(miss));
5390 if(!allow_extras_) {
5391 for(
const auto &sub : subcommands_) {
5392 if(sub->name_.empty() && !sub->missing_.empty()) {
5393 for(
const std::pair<detail::Classifier, std::string> &miss : sub->missing_) {
5394 miss_list.push_back(std::get<1>(miss));
5401 for(
const App *sub : parsed_subcommands_) {
5402 std::vector<std::string> output = sub->remaining(recurse);
5403 std::copy(std::begin(output), std::end(output), std::back_inserter(miss_list));
5411 std::vector<std::string> miss_list = remaining(recurse);
5412 std::reverse(std::begin(miss_list), std::end(miss_list));
5418 auto remaining_options =
static_cast<size_t>(std::count_if(
5419 std::begin(missing_), std::end(missing_), [](
const std::pair<detail::Classifier, std::string> &val) {
5424 for(
const App_p &sub : subcommands_) {
5425 remaining_options += sub->remaining_size(recurse);
5428 return remaining_options;
5439 auto pcount = std::count_if(std::begin(options_), std::end(options_), [](
const Option_p &opt) {
5440 return opt->get_items_expected() < 0 && opt->get_positional();
5445 size_t nameless_subs{0};
5446 for(
const App_p &
app : subcommands_) {
5452 if(require_option_min_ > 0) {
5453 if(require_option_max_ > 0) {
5454 if(require_option_max_ < require_option_min_) {
5455 throw(
InvalidError(
"Required min options greater than required max options",
5459 if(require_option_min_ > (options_.size() + nameless_subs)) {
5460 throw(
InvalidError(
"Required min options greater than number of available options",
5470 if(disabled_by_default_) {
5473 if(enabled_by_default_) {
5476 for(
const App_p &
app : subcommands_) {
5493 for(
App *subc : get_subcommands()) {
5494 if(!subc->immediate_callback_)
5495 subc->run_callback();
5498 for(
auto &subc : subcommands_) {
5499 if(!subc->immediate_callback_ && subc->name_.empty() && subc->count_all() > 0) {
5500 subc->run_callback();
5504 if(callback_ && (parsed_ > 0)) {
5505 if(!name_.empty() || count_all() > 0) {
5514 if(require_subcommand_max_ != 0 && parsed_subcommands_.size() >= require_subcommand_max_) {
5517 auto com = _find_subcommand(current,
true, ignore_used);
5518 if(com !=
nullptr) {
5527 std::string dummy1, dummy2;
5531 if(_valid_subcommand(current, ignore_used_subcommands))
5539 if((current ==
"++") && !name_.empty() && parent_ !=
nullptr)
5549 if(config_ptr_ !=
nullptr) {
5551 config_ptr_->run_callback();
5552 config_required_ =
true;
5554 if(!config_name_.empty()) {
5556 std::vector<ConfigItem> values = config_formatter_->from_file(config_name_);
5557 _parse_config(values);
5559 if(config_required_)
5568 for(
const Option_p &opt : options_) {
5569 if(opt->count() == 0 && !opt->envname_.empty()) {
5570 char *buffer =
nullptr;
5571 std::string ename_string;
5576 if(_dupenv_s(&buffer, &sz, opt->envname_.c_str()) == 0 && buffer !=
nullptr) {
5577 ename_string = std::string(buffer);
5582 buffer = std::getenv(opt->envname_.c_str());
5583 if(buffer !=
nullptr)
5584 ename_string = std::string(buffer);
5587 if(!ename_string.empty()) {
5588 opt->add_result(ename_string);
5593 for(
App_p &sub : subcommands_) {
5594 if(sub->get_name().empty() || !sub->immediate_callback_)
5595 sub->_process_env();
5602 for(
App_p &sub : subcommands_) {
5604 if(sub->get_name().empty() && sub->immediate_callback_) {
5605 if(sub->count_all() > 0) {
5606 sub->_process_callbacks();
5607 sub->run_callback();
5612 for(
const Option_p &opt : options_) {
5613 if(opt->count() > 0 && !opt->get_callback_run()) {
5614 opt->run_callback();
5618 for(
App_p &sub : subcommands_) {
5619 if(!sub->immediate_callback_) {
5620 sub->_process_callbacks();
5629 const Option *help_ptr = get_help_ptr();
5630 const Option *help_all_ptr = get_help_all_ptr();
5632 if(help_ptr !=
nullptr && help_ptr->
count() > 0)
5633 trigger_help =
true;
5634 if(help_all_ptr !=
nullptr && help_all_ptr->
count() > 0)
5635 trigger_all_help =
true;
5638 if(!parsed_subcommands_.empty()) {
5639 for(
const App *sub : parsed_subcommands_)
5640 sub->_process_help_flags(trigger_help, trigger_all_help);
5643 }
else if(trigger_all_help) {
5645 }
else if(trigger_help) {
5653 bool excluded{
false};
5654 std::string excluder;
5655 for(
auto &opt : exclude_options_) {
5656 if(opt->count() > 0) {
5658 excluder = opt->get_name();
5661 for(
auto &subc : exclude_subcommands_) {
5662 if(subc->count_all() > 0) {
5664 excluder = subc->get_display_name();
5668 if(count_all() > 0) {
5674 size_t used_options = 0;
5675 for(
const Option_p &opt : options_) {
5677 if(opt->count() != 0) {
5681 if(opt->get_required() || opt->count() != 0) {
5683 if(opt->get_items_expected() < 0 && opt->count() <
static_cast<size_t>(-opt->get_items_expected()))
5687 if(opt->get_required() && opt->count() == 0)
5692 if(opt->count() > 0 && opt_req->
count() == 0)
5696 if(opt->count() > 0 && opt_ex->
count() != 0)
5700 if(require_subcommand_min_ > 0) {
5701 auto selected_subcommands = get_subcommands();
5702 if(require_subcommand_min_ > selected_subcommands.size())
5710 for(
App_p &sub : subcommands_) {
5713 if(sub->name_.empty() && sub->count_all() > 0) {
5718 if(require_option_min_ > used_options || (require_option_max_ > 0 && require_option_max_ < used_options)) {
5719 auto option_list =
detail::join(options_, [](
const Option_p &ptr) {
return ptr->get_name(
false,
true); });
5720 if(option_list.compare(0, 10,
"-h,--help,") == 0) {
5721 option_list.erase(0, 10);
5724 if(!subc_list.empty()) {
5731 for(
App_p &sub : subcommands_) {
5734 if(sub->name_.empty() && sub->required_ ==
false) {
5735 if(sub->count_all() == 0) {
5736 if(require_option_min_ > 0 && require_option_min_ <= used_options) {
5741 if(require_option_max_ > 0 && used_options >= require_option_min_) {
5748 if(sub->count() > 0 || sub->name_.empty()) {
5749 sub->_process_requirements();
5752 if(sub->required_ && sub->count_all() == 0) {
5762 _process_callbacks();
5763 _process_help_flags();
5764 _process_requirements();
5769 if(!(allow_extras_ || prefix_command_)) {
5770 size_t num_left_over = remaining_size();
5771 if(num_left_over > 0) {
5776 for(
App_p &sub : subcommands_) {
5777 if(sub->count() > 0)
5778 sub->_process_extras();
5785 if(!(allow_extras_ || prefix_command_)) {
5786 size_t num_left_over = remaining_size();
5787 if(num_left_over > 0) {
5788 args = remaining(
false);
5793 for(
App_p &sub : subcommands_) {
5794 if(sub->count() > 0)
5795 sub->_process_extras(args);
5802 for(
App_p &sub : subcommands_) {
5803 if(sub->get_name().empty())
5804 sub->increment_parsed();
5808 void _parse(std::vector<std::string> &args) {
5810 _trigger_pre_parse(args.size());
5811 bool positional_only =
false;
5813 while(!args.empty()) {
5814 if(!_parse_single(args, positional_only)) {
5819 if(parent_ ==
nullptr) {
5823 _process_extras(args);
5826 args = remaining_for_passthrough(
false);
5827 }
else if(immediate_callback_) {
5829 _process_callbacks();
5830 _process_help_flags();
5831 _process_requirements();
5837 void _parse(std::vector<std::string> &&args) {
5841 _trigger_pre_parse(args.size());
5842 bool positional_only =
false;
5844 while(!args.empty()) {
5845 _parse_single(args, positional_only);
5859 if(!_parse_single_config(item) && !allow_config_extras_)
5866 if(level < item.
parents.size()) {
5868 auto subcom = get_subcommand(item.
parents.at(level));
5869 return subcom->_parse_single_config(item, level + 1);
5875 Option *op = get_option_no_throw(
"--" + item.
name);
5878 if(get_allow_config_extras())
5890 auto res = config_formatter_->to_flag(item);
5909 switch(classifier) {
5912 positional_only =
true;
5913 if((!_has_remaining_positionals()) && (parent_ !=
nullptr)) {
5916 _move_to_missing(classifier,
"--");
5925 retval = _parse_subcommand(args);
5931 _parse_arg(args, classifier);
5935 retval = _parse_positional(args);
5936 if(retval && positionals_at_end_) {
5937 positional_only =
true;
5943 HorribleError(
"unrecognized classifier (you should not see this!)");
5952 for(
const Option_p &opt : options_)
5953 if(opt->get_positional() && (!required_only || opt->get_required()) && opt->get_items_expected() > 0 &&
5954 static_cast<int>(opt->count()) < opt->get_items_expected())
5955 retval = static_cast<size_t>(opt->get_items_expected()) - opt->count();
5962 for(
const Option_p &opt : options_)
5963 if(opt->get_positional() &&
5964 ((opt->get_items_expected() < 0) || ((static_cast<int>(opt->count()) < opt->get_items_expected()))))
5974 const std::string &positional = args.back();
5975 for(
const Option_p &opt : options_) {
5977 if(opt->get_positional() &&
5978 (
static_cast<int>(opt->count()) < opt->get_items_expected() || opt->get_items_expected() < 0)) {
5979 if(validate_positionals_) {
5980 std::string pos = positional;
5981 pos = opt->_validate(pos);
5986 opt->add_result(positional);
5987 parse_order_.push_back(opt.get());
5993 for(
auto &subc : subcommands_) {
5994 if((subc->name_.empty()) && (!subc->disabled_)) {
5995 if(subc->_parse_positional(args)) {
5996 if(!subc->pre_parse_called_) {
5997 subc->_trigger_pre_parse(args.size());
6004 if(parent_ !=
nullptr && fallthrough_)
6005 return _get_fallthrough_parent()->_parse_positional(args);
6008 auto com = _find_subcommand(args.back(),
true,
false);
6009 if(com !=
nullptr && (require_subcommand_max_ == 0 || require_subcommand_max_ > parsed_subcommands_.size())) {
6016 auto parent_app = (parent_ !=
nullptr) ? _get_fallthrough_parent() :
this;
6017 com = parent_app->_find_subcommand(args.back(),
true,
false);
6018 if(com !=
nullptr && (com->parent_->require_subcommand_max_ == 0 ||
6019 com->parent_->require_subcommand_max_ > com->parent_->parsed_subcommands_.size())) {
6023 if(positionals_at_end_) {
6027 if(parent_ !=
nullptr && name_.empty()) {
6033 if(prefix_command_) {
6034 while(!args.empty()) {
6046 for(
const App_p &com : subcommands_) {
6047 if(com->disabled_ && ignore_disabled)
6049 if(com->get_name().empty()) {
6050 auto subc = com->
_find_subcommand(subc_name, ignore_disabled, ignore_used);
6051 if(subc !=
nullptr) {
6054 }
else if(com->check_name(subc_name)) {
6055 if((!*com) || !ignore_used)
6067 if(_count_remaining_positionals(
true) > 0) {
6068 _parse_positional(args);
6071 auto com = _find_subcommand(args.back(),
true,
true);
6072 if(com !=
nullptr) {
6074 parsed_subcommands_.push_back(com);
6076 auto parent_app = com->parent_;
6077 while(parent_app !=
this) {
6078 parent_app->_trigger_pre_parse(args.size());
6079 parent_app->parsed_subcommands_.push_back(com);
6080 parent_app = parent_app->parent_;
6085 if(parent_ ==
nullptr)
6086 throw HorribleError(
"Subcommand " + args.back() +
" missing");
6094 std::string current = args.back();
6096 std::string arg_name;
6100 switch(current_type) {
6103 throw HorribleError(
"Long parsed but missing (you should not see this):" + args.back());
6107 throw HorribleError(
"Short parsed but missing! You should not see this");
6111 throw HorribleError(
"windows option parsed but missing! You should not see this");
6117 throw HorribleError(
"parsing got called with invalid option! You should not see this");
6121 std::find_if(std::begin(options_), std::end(options_), [arg_name, current_type](
const Option_p &opt) {
6123 return opt->check_lname(arg_name);
6125 return opt->check_sname(arg_name);
6127 return opt->check_lname(arg_name) || opt->check_sname(arg_name);
6131 if(op_ptr == std::end(options_)) {
6132 for(
auto &subc : subcommands_) {
6133 if(subc->name_.empty() && !subc->disabled_) {
6134 if(subc->_parse_arg(args, current_type)) {
6135 if(!subc->pre_parse_called_) {
6136 subc->_trigger_pre_parse(args.size());
6143 if(parent_ !=
nullptr && fallthrough_)
6144 return _get_fallthrough_parent()->_parse_arg(args, current_type);
6146 if(parent_ !=
nullptr && name_.empty()) {
6151 _move_to_missing(current_type, current);
6160 int num = op->get_items_expected();
6164 int result_count = 0;
6167 auto res = op->get_flag_value(arg_name, value);
6168 op->add_result(res);
6169 parse_order_.push_back(op.get());
6172 else if(!value.empty()) {
6173 op->add_result(value, result_count);
6174 parse_order_.push_back(op.get());
6175 collected += result_count;
6178 num = (num >= result_count) ? num - result_count : 0;
6181 }
else if(!rest.empty()) {
6182 op->add_result(rest, result_count);
6183 parse_order_.push_back(op.get());
6185 collected += result_count;
6188 num = (num >= result_count) ? num - result_count : 0;
6194 if(collected >= -num) {
6198 if(_count_remaining_positionals() > 0)
6201 op->add_result(args.back(), result_count);
6202 parse_order_.push_back(op.get());
6204 collected += result_count;
6212 while(num > 0 && !args.empty()) {
6213 std::string current_ = args.back();
6215 op->add_result(current_, result_count);
6216 parse_order_.push_back(op.get());
6217 num -= result_count;
6227 args.push_back(rest);
6234 if(!pre_parse_called_) {
6235 pre_parse_called_ =
true;
6236 if(pre_parse_callback_) {
6237 pre_parse_callback_(remaining_args);
6239 }
else if(immediate_callback_) {
6240 if(!name_.empty()) {
6241 auto pcnt = parsed_;
6242 auto extras = std::move(missing_);
6245 pre_parse_called_ =
true;
6246 missing_ = std::move(extras);
6253 if(parent_ ==
nullptr) {
6256 auto fallthrough_parent = parent_;
6257 while((fallthrough_parent->parent_ !=
nullptr) && (fallthrough_parent->get_name().empty())) {
6258 fallthrough_parent = fallthrough_parent->
parent_;
6260 return fallthrough_parent;
6265 if(allow_extras_ || subcommands_.empty()) {
6266 missing_.emplace_back(val_type, val);
6270 for(
auto &subc : subcommands_) {
6271 if(subc->name_.empty() && subc->allow_extras_) {
6272 subc->missing_.emplace_back(val_type, val);
6277 missing_.emplace_back(val_type, val);
6283 if(opt ==
nullptr) {
6288 for(
auto &subc : subcommands_) {
6289 if(app == subc.get()) {
6297 if((help_ptr_ == opt) || (help_all_ptr_ == opt))
6300 if(config_ptr_ == opt)
6304 std::find_if(std::begin(options_), std::end(options_), [opt](
const Option_p &v) {
return v.get() == opt; });
6305 if(iterator != std::end(options_)) {
6306 const auto &opt_p = *iterator;
6308 return (*v == *opt_p);
6311 app->
options_.push_back(std::move(*iterator));
6312 options_.erase(iterator);
6326 :
App(std::move(group_description),
"", parent) {
6333 if(get_parent() ==
nullptr) {
6336 get_parent()->_move_option(opt,
this);
6344 add_options(args...);
6350 subc->get_parent()->remove_subcommand(subcom);
6351 add_subcommand(std::move(subc));
6363 inline void TriggerOn(
App *trigger_app, std::vector<App *> apps_to_enable) {
6364 for(
auto &
app : apps_to_enable) {
6370 for(
auto &
app : apps_to_enable) {
6385 for(
auto &
app : apps_to_enable) {
6391 for(
auto &
app : apps_to_enable) {
6397 namespace FailureMessage {
6401 std::string header = std::string(e.what()) +
"\n";
6402 std::vector<std::string> names;
6413 header +=
"Run with " +
detail::join(names,
" or ") +
" for more information.\n";
6420 std::string header = std::string(
"ERROR: ") + e.
get_name() +
": " + e.what() +
"\n";
6421 header += app->
help();
6432 template <
typename... Args>
6439 template <
typename... Args>
6457 std::stringstream out;
6461 if(!opt->get_lnames().empty() && opt->get_configurable()) {
6462 std::string name = prefix + opt->get_lnames()[0];
6466 if(opt->get_type_size() != 0) {
6469 if(opt->count() > 0)
6473 else if(default_also && !opt->get_default_str().empty())
6474 value = opt->get_default_str();
6476 }
else if(opt->count() == 1) {
6480 }
else if(opt->count() > 1) {
6484 }
else if(opt->count() == 0 && default_also) {
6488 if(!value.empty()) {
6489 if(write_description && opt->has_description()) {
6490 if(static_cast<int>(out.tellp()) != 0) {
6497 if(opt->get_items_expected() != 1)
6498 out << name <<
"=" << value << std::endl;
6506 out << to_config(subcom, default_also, write_description, prefix + subcom->get_name() +
".");
6519 std::stringstream out;
6521 out <<
"\n" << group <<
":\n";
6522 for(
const Option *opt : opts) {
6523 out << make_option(opt, is_positional);
6530 std::vector<const Option *> opts =
6534 return std::string();
6536 return make_group(get_label(
"Positionals"),
true, opts);
6540 std::stringstream out;
6541 std::vector<std::string> groups = app->
get_groups();
6544 for(
const std::string &group : groups) {
6545 std::vector<const Option *> opts = app->
get_options([app, mode, &group](
const Option *opt) {
6547 && opt->nonpositional()
6552 if(!group.empty() && !opts.empty()) {
6553 out << make_group(group,
false, opts);
6555 if(group != groups.back())
6568 desc +=
" REQUIRED ";
6570 if((max_options == min_options) && (min_options > 0)) {
6571 if(min_options == 1) {
6572 desc +=
" \n[Exactly 1 of the following options is required]";
6574 desc +=
" \n[Exactly " +
std::to_string(min_options) +
"options from the following list are required]";
6576 }
else if(max_options > 0) {
6577 if(min_options > 0) {
6579 " of the follow options are required]";
6581 desc +=
" \n[At most " +
std::to_string(max_options) +
" of the following options are allowed]";
6583 }
else if(min_options > 0) {
6584 desc +=
" \n[At least " +
std::to_string(min_options) +
" of the following options are required]";
6586 return (!desc.empty()) ? desc +
"\n" : std::string{};
6590 std::stringstream out;
6592 out << get_label(
"Usage") <<
":" << (name.empty() ?
"" :
" ") << name;
6594 std::vector<std::string> groups = app->
get_groups();
6597 std::vector<const Option *> non_pos_options =
6599 if(!non_pos_options.empty())
6600 out <<
" [" << get_label(
"OPTIONS") <<
"]";
6603 std::vector<const Option *> positionals = app->
get_options([](
const Option *opt) {
return opt->get_positional(); });
6606 if(!positionals.empty()) {
6608 std::vector<std::string> positional_names(positionals.size());
6609 std::transform(positionals.begin(), positionals.end(), positional_names.begin(), [
this](
const Option *opt) {
6610 return make_option_usage(opt);
6618 [](
const CLI::App *subc) { return ((!subc->get_disabled()) && (!subc->get_name().empty())); })
6634 return footer +
"\n";
6644 return make_expanded(app);
6646 std::stringstream out;
6653 out << make_description(app);
6654 out << make_usage(app, name);
6655 out << make_positionals(app);
6656 out << make_groups(app, mode);
6657 out << make_subcommands(app, mode);
6658 out << make_footer(app);
6664 std::stringstream out;
6669 std::vector<std::string> subcmd_groups_seen;
6670 for(
const App *com : subcommands) {
6671 if(com->get_name().empty()) {
6672 out << make_expanded(com);
6675 std::string group_key = com->get_group();
6676 if(!group_key.empty() &&
6677 std::find_if(subcmd_groups_seen.begin(), subcmd_groups_seen.end(), [&group_key](std::string a) {
6679 }) == subcmd_groups_seen.end())
6680 subcmd_groups_seen.push_back(group_key);
6684 for(
const std::string &group : subcmd_groups_seen) {
6685 out <<
"\n" << group <<
":\n";
6688 for(
const App *new_com : subcommands_group) {
6689 if(new_com->get_name().empty())
6692 out << make_subcommand(new_com);
6704 std::stringstream out;
6710 std::stringstream out;
6713 out << make_description(sub);
6714 out << make_positionals(sub);
6720 tmp = tmp.substr(0, tmp.size() - 1);
6734 std::stringstream out;
6739 if(!opt->get_default_str().
empty())
6740 out <<
"=" << opt->get_default_str();
6741 if(opt->get_expected() > 1)
6742 out <<
" x " << opt->get_expected();
6743 if(opt->get_expected() == -1)
6746 out <<
" " << get_label(
"REQUIRED");
6749 out <<
" (" << get_label(
"Env") <<
":" << opt->
get_envname() <<
")";
6751 out <<
" " << get_label(
"Needs") <<
":";
6753 out <<
" " << op->get_name();
6756 out <<
" " << get_label(
"Excludes") <<
":";
6758 out <<
" " << op->get_name();
6767 std::stringstream out;
6768 out << make_option_name(opt,
true);
6770 if(opt->get_expected() > 1)
6772 else if(opt->get_expected() < 0)
6774 return opt->
get_required() ? out.str() :
"[" + out.str() +
"]";
size_t remaining_size(bool recurse=false) const
This returns the number of remaining options, minus the – separator.
App * get_subcommand(std::string subcom) const
Check to see if a subcommand is part of this command (text version)
std::string get_type_name() const
Get the full typename for this option.
Option * get_option_no_throw(std::string option_name) noexcept
Get an option by name (noexcept non-const version)
const Option * operator[](const char *option_name) const
Shortcut bracket operator for getting a pointer to an option.
CRTP * required(bool value=true)
Set the option as required.
std::string help(std::string prev="", AppFormatMode mode=AppFormatMode::Normal) const
Option * needs(std::string opt_name)
Can find a string if needed.
typename T::value_type value_type
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.
std::string & rtrim(std::string &str, const std::string &filter)
Trim anything from right of string.
App * footer(std::string footer_string)
Set footer.
static auto second(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the second value (really just the underlying value)
Validator & operation(std::function< std::string(std::string &)> op)
Set the Validator operation function.
App * ignore_underscore(bool value=true)
Ignore underscore. Subcommands inherit value.
All errors derive from this one.
CLI::App_p get_subcommand_ptr(std::string subcom) const
Check to see if a subcommand is part of this command (text version)
void _process_env()
Get envname options if not yet passed. Runs on all subcommands.
std::function< bool(results_t)> callback_t
bool got_subcommand(std::string subcommand_name) const
Check with name instead of pointer to see if subcommand was selected.
App * require_option(size_t min, size_t max)
Bound(T max)
Range of one value is 0 to value.
std::vector< std::string > fnames_
a list of flag names with specified default values;
typename std::remove_const< value_type >::type first_type
Option * excludes(std::string opt_name)
Can find a string if needed.
T as() const
return the results as a particular type
const Option * get_option(std::string option_name) const
Get an option by name.
static std::map< std::string, result_t > init_mapping(bool kb_is_1000)
Get <size unit, factor> mapping.
Option * each(std::function< void(std::string)> func)
Adds a user supplied function to run on each item passed in (communicate though lambda capture) ...
Check for an non-existing path.
bool allow_extras_
If true, allow extra arguments (ie, don't throw an error). INHERITABLE.
std::remove_reference< T >::type & smart_deref(T &value)
CRTP * take_last()
Set the multi option policy to take last.
std::string to_lower(std::string str)
Return a lower case version of a string.
IsMember(T set, F filter_function)
std::string description_
Description of the current program/subcommand.
This converter works with INI files.
constexpr const char * type_name()
This one should not be used, since vector types print the internal type.
std::string ignore_space(std::string item)
Helper function to allow checks to ignore spaces to be passed to IsMember or Transform.
App * get_option_group(std::string group_name) const
Check to see if an option group is part of this App.
Option * excludes(Option *opt)
Sets excluded options.
void _process_help_flags(bool trigger_help=false, bool trigger_all_help=false) const
const detail::IPV4Validator ValidIPV4
Check for an IP4 address.
NonexistentPathValidator()
char get_delimiter() const
Get the current delimeter char.
std::string description_
The description for help strings.
bool get_callback_run() const
See if the callback has been run already.
std::unique_ptr< Option > Option_p
-h or –help on command line
std::function< std::string()> default_function_
Run this function to capture a default (ignore if empty)
std::string generate_set(const T &set)
Generate a string representation of a set.
std::function< std::string(std::string &)> func_
void TriggerOff(App *trigger_app, App *app_to_enable)
Helper function to disable one option group/subcommand when another is used.
static ArgumentMismatch FlagOverride(std::string name)
App * require_option(int value)
App * require_subcommand(size_t min, size_t max)
constexpr enabler dummy
An instance to use in EnableIf.
std::string help(const App *app, const Error &e)
Printout the full help string on error (if this fn is set, the old default for CLI11) ...
Option * add_flag(std::string flag_name, std::vector< T > &flag_results, std::string flag_description="")
Vector version to capture multiple flags.
results_t results_
Results of parsing.
Does not output a diagnostic in CLI11_PARSE, but allows to return from main() with a specific error c...
bool allow_config_extras_
If true, allow extra arguments in the ini file (ie, don't throw an error). INHERITABLE.
bool get_prefix_command() const
Get the prefix command status.
std::string & ltrim(std::string &str, const std::string &filter)
Trim anything from left of string.
void failure_message(std::function< std::string(const App *, const Error &e)> function)
Provide a function to print a help message. The function gets access to the App pointer and error...
size_t get_require_option_min() const
Get the required min option value.
Class wrapping some of the accessors of Validator.
void copy_to(T *other) const
Copy the contents to another similar class (one based on OptionBase)
static BadNameString BadLongName(std::string name)
bool _parse_single(std::vector< std::string > &args, bool &positional_only)
std::vector< App * > parsed_subcommands_
This is a list of the subcommands collected, in order.
This class is simply to allow tests access to App's protected functions.
App * required(bool require=true)
Remove the error when extras are left over on the command line.
bool get_required() const
True if this is a required option.
ConversionError(std::string name, std::vector< std::string > results)
bool prefix_command_
If true, return immediately on an unrecognized option (implies allow_extras) INHERITABLE.
bool get_disabled_by_default() const
Get the status of disabled by default.
CRTP * always_capture_default(bool value=true)
std::string find_and_modify(std::string str, std::string trigger, Callable modify)
Validator & name(std::string validator_name)
Specify the type string.
bool remove_subcommand(App *subcom)
Removes a subcommand from the App. Takes a subcommand pointer. Returns true if found and removed...
std::shared_ptr< App > App_p
bool lexical_cast(std::string input, T &output)
Signed integers.
std::set< Option * > exclude_options_
std::vector< std::pair< std::string, std::string > > default_flag_values_
Produce a range (factory). Min and max are inclusive.
App * preparse_callback(std::function< void(size_t)> pp_callback)
typename make_void< Ts... >::type void_t
A copy of std::void_t from C++17 - same reasoning as enable_if_t, it does not hurt to redefine...
Option * _add_flag_internal(std::string flag_name, CLI::callback_t fun, std::string flag_description)
Internal function for adding a flag.
void parse(std::vector< std::string > &args)
std::string ignore_case(std::string item)
Helper function to allow ignore_case to be passed to IsMember or Transform.
const Option * get_help_all_ptr() const
Get a pointer to the help all flag. (const)
Option * add_option(Option *opt)
Add an existing option to the Option_group.
IsMember(T &&set)
This checks to see if an item is in a set (empty function)
App * immediate_callback(bool immediate=true)
Set the subcommand callback to be executed immediately on subcommand completion.
Option * add_result(std::string s)
Puts a result at the end.
std::vector< std::string > split_up(std::string str)
bool split_short(const std::string ¤t, std::string &name, std::string &rest)
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.
Error(std::string name, std::string msg, ExitCodes exit_code)
std::vector< ConfigItem > from_file(const std::string &name)
Parse a config file, throw an error (ParseError:ConfigParseError or FileError) on failure...
Option(std::string option_name, std::string option_description, std::function< bool(results_t)> callback, App *parent)
Making an option by hand is not defined, it must be made by the App class.
bool has_automatic_name_
If set to true the name was automatically generated from the command line vs a user set name...
typename std::remove_const< typename value_type::first_type >::type first_type
std::string as_string(const T &v)
simple utility to convert various types to a string
std::vector< Validator > validators_
A list of validators to run on each value parsed.
bool split_windows_style(const std::string ¤t, std::string &name, std::string &value)
size_t get_require_subcommand_min() const
Get the required min subcommand value.
bool _has_remaining_positionals() const
Count the required remaining positional arguments.
Thrown when an excludes option is present.
Option * help_all_ptr_
A pointer to the help all flag if there is one INHERITABLE.
Option * add_option(std::string option_name, callback_t option_callback, std::string option_description="", bool defaulted=false, std::function< std::string()> func={})
bool _parse_arg(std::vector< std::string > &args, detail::Classifier current_type)
Option * add_flag(std::string flag_name, T &flag_result, std::string flag_description="")
std::string envname_
If given, check the environment for this option.
Validate the given string is a legal ipv4 address.
const detail::NonexistentPathValidator NonexistentPath
Check for an non-existing path.
std::string _validate(std::string &result)
std::string trim_copy(const std::string &str)
Make a copy of the string and then trim it.
Some validators that are provided.
bool get_positionals_at_end() const
Check the status of the allow windows style options.
bool get_required() const
Get the status of required.
App * _find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept
Extension of App to better manage groups of options.
std::string type(const x_type &a_param)
static IncorrectConstruction Set0Opt(std::string name)
const Option * operator[](const std::string &option_name) const
Shortcut bracket operator for getting a pointer to an option.
CRTP * group(std::string name)
Changes the group membership.
static BadNameString DashesOnly(std::string name)
std::vector< std::string > results_t
bool get_ignore_underscore() const
Check the status of ignore_underscore.
bool split_long(const std::string ¤t, std::string &name, std::string &value)
std::string get_display_name() const
Get a display name for an app.
App * get_subcommand(int index=0) const
Get a pointer to subcommand by index.
std::enable_if< std::is_integral< T >::value, bool >::type checked_multiply(T &a, T b)
Performs a *= b; if it doesn't cause integer overflow. Returns false otherwise.
Check to see if something is a vector (fail check by default)
Option * type_name_fn(std::function< std::string()> typefun)
Set the type function to run when displayed on this option.
const detail::ExistingDirectoryValidator ExistingDirectory
Check for an existing directory (returns error message if check fails)
App * add_subcommand(App *subcom)
Add an existing subcommand to be a member of an option_group.
bool remove_excludes(App *app)
Removes a subcommand from this excludes list of this subcommand.
std::string default_str_
A human readable default value, either manually set, captured, or captured by default.
Option * add_mutable_set(std::string option_name, T &member, const std::set< T > &options, std::string option_description, bool defaulted)
Add set of options (with default, set can be changed afterwards - do not destroy the set) DEPRECATED...
enabler
Simple empty scoped class.
std::string trim_copy(const std::string &str, const std::string &filter)
Make a copy of the string and then trim it, any filter string can be used (any char in string is filt...
Adaptor for set-like structure: This just wraps a normal container in a few utilities that do almost ...
static IncorrectConstruction AfterMultiOpt(std::string name)
std::ptrdiff_t find_member(std::string name, const std::vector< std::string > names, bool ignore_case=false, bool ignore_underscore=false)
Check if a string is a member of a list of strings and optionally ignore case or ignore underscores...
App * name(std::string app_name="")
Set a name for the app (empty will use parser to set the name)
Holds values to load into Options.
std::vector< std::string > parents
This is the list of parents.
std::vector< const Option * > get_options(const std::function< bool(const Option *)> filter={}) const
Get the list of options (user facing function, so returns raw pointers), has optional filter function...
void TriggerOn(App *trigger_app, App *app_to_enable)
Helper function to enable one option group/subcommand when another is used.
bool get_validate_positionals() const
Get the status of validating positionals.
size_t count() const
Count the total number of times an option was passed.
typename std::enable_if< B, T >::type enable_if_t
std::shared_ptr< FormatterBase > get_formatter() const
Access the formatter.
void _move_to_missing(detail::Classifier val_type, const std::string &val)
Helper function to place extra values in the most appropriate position.
bool parsed() const
Check to see if this subcommand was parsed, true only if received on command line.
bool _parse_single_config(const ConfigItem &item, size_t level=0)
Fill in a single config option.
OptionDefaults * delimiter(char value='\0')
set a delimiter character to split up single arguments to treat as multiple inputs ...
void sum_flag_vector(const std::vector< std::string > &flags, T &output)
App * positionals_at_end(bool value=true)
Specify that the positional arguments are only at the end of the sequence.
Validator & active(bool active_val=true)
Specify whether the Validator is active or not.
std::vector< std::string > get_groups() const
Get the groups available directly from this option (in order)
Verify items are in a set.
size_t _count_remaining_positionals(bool required_only=false) const
Count the required remaining positional arguments.
bool check_fname(std::string name) const
Requires "--" to be removed from string.
std::string rjoin(const T &v, std::string delim=",")
Join a string in reverse order.
static RequiredError Subcommand(size_t min_subcom)
bool _parse_positional(std::vector< std::string > &args)
const std::string & get_name() const
Get the name of the Validator.
size_t count(std::string option_name) const
Counts the number of times the given option was passed.
Option * type_size(int option_type_size)
Set a custom option size.
Option * set_config(std::string option_name="", std::string default_filename="", 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.
std::vector< std::string > remaining_for_passthrough(bool recurse=false) const
This returns the missing options in a form ready for processing by another command line program...
Error(std::string name, std::string msg, int exit_code=static_cast< int >(ExitCodes::BaseClass))
void _process_requirements()
Verify required options and cross requirements. Subcommands too (only if selected).
std::shared_ptr< Config > get_config_formatter() const
Access the config formatter.
Thrown when an option is set to conflicting values (non-vector and multi args, for example) ...
Option * add_flag_function(std::string flag_name, std::function< void(int64_t)> function, std::string flag_description="")
Add option for callback with an integer value.
bool get_configurable() const
The status of configurable.
bool validate_positionals_
If set to true positional options are validated before assigning INHERITABLE.
Validator(std::string validator_desc)
Construct a Validator with just the description string.
std::string generate_map(const T &map, bool key_only=false)
Generate a string representation of a map.
std::vector< std::string > lnames_
A list of the long names (--a) without the leading dashes.
std::string pname_
A positional name.
Option * add_set(std::string option_name, T &member, std::set< T > options, std::string option_description="")
Add set of options (No default, temp reference, such as an inline set) DEPRECATED.
App * require_subcommand()
The argumentless form of require subcommand requires 1 or more subcommands.
#define CLI11_DEPRECATED(reason)
bool remove_excludes(Option *opt)
Removes an option from the excludes list of this subcommand.
App * add_subcommand(CLI::App_p subcom)
Add a previously created app as a subcommand.
App * require_option()
The argumentless form of require option requires 1 or more options be used.
App * get_subcommand(App *subcom) const
Option * get_help_ptr()
Get a pointer to the help flag.
App * group(std::string group_name)
Changes the group membership.
CRTP * mandatory(bool value=true)
Support Plumbum term.
bool isalpha(const std::string &str)
Verify that str consists of letters only.
IsMember(std::initializer_list< T > values, Args &&... args)
This allows in-place construction using an initializer list.
static IncorrectConstruction SetFlag(std::string name)
std::set< Option * > get_needs() const
The set of options needed.
void parse(std::vector< std::string > &&args)
The real work is done here. Expects a reversed vector.
void parse(std::string commandline, bool program_name_included=false)
bool allow_windows_style_options_
Allow '/' for options for Windows like options. Defaults to true on Windows, false otherwise...
std::pair< std::string, std::string > split_program_name(std::string commandline)
Option * add_option(std::string option_name, T &option_description)
Add option with description but with no variable assignment or callback.
static IncorrectConstruction MultiOptionPolicy(std::string name)
Option * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times (or another policy)
std::string get_description() const
Get the app or subcommand description.
Check for an existing path.
Check to see if something is copyable pointer.
Option * add_set(std::string option_name, T &member, std::set< T > options, std::string option_description, bool defaulted)
Add set of options (with default, static set, such as an inline set) DEPRECATED.
bool get_ignore_case() const
The status of ignore case.
std::vector< ConfigItem > from_config(std::istream &input) const override
Convert a configuration into an app.
std::vector< std::string > remaining(bool recurse=false) const
This returns the missing options from the current subcommand.
Option * check(std::function< std::string(const std::string &)> validator, std::string validator_description="", std::string validator_name="")
Adds a Validator. Takes a const string& and returns an error message (empty if conversion/check is ok...
App * validate_positionals(bool validate=true)
Set the subcommand to validate positional arguments before assigning.
static std::string generate_description(const std::string &name, Options opts)
Generate description like this: NUMBER [UNIT].
std::string to_config(const App *, bool default_also, bool write_description, std::string prefix) const override
Convert an app into a configuration.
bool get_active() const
Get a boolean if the validator is active.
std::vector< std::string > results() const
Get a copy of the results.
bool get_always_capture_default() const
Return true if this will automatically capture the default value for help printing.
std::vector< std::string > split_names(std::string current)
const Option * get_help_ptr() const
Get a pointer to the help flag. (const)
static IncorrectConstruction PositionalFlag(std::string name)
typename std::remove_const< value_type >::type second_type
bool valid_later_char(T c)
Verify following characters of an option.
bool valid_name_string(const std::string &str)
Verify an option name.
bool get_immediate_callback() const
Get the status of disabled.
Check for an existing file (returns error message if check fails)
std::string to_string(T &&value)
Convert an object to a string (streaming must be supported for that type)
Option * set_help_flag(std::string flag_name="", const std::string &help_description="")
Set a help flag, replace the existing one if present.
static auto test_find(long) -> std::false_type
bool get_disabled() const
Get the status of disabled.
std::set< Option * > needs_
A list of options that are required with this option.
int64_t to_flag_value(std::string val)
Convert a flag into an integer value typically binary flags.
std::string & rtrim(std::string &str)
Trim whitespace from right of string.
Check for an existing directory (returns error message if check fails)
bool get_modifying() const
Get a boolean if the validator is allowed to modify the input returns true if it can modify the input...
App * callback(std::function< void()> app_callback)
App * parent_
Remember the parent app.
Creates a command line program, with very few defaults.
Option * add_flag(std::string flag_name, T &flag_count, std::string flag_description="")
bool get_fallthrough() const
Check the status of fallthrough.
Option * help_ptr_
A pointer to the help flag if there is one INHERITABLE.
OptionDefaults * disable_flag_override(bool value=true)
Disable overriding flag values with an '=' segment.
bool remove_option(Option *opt)
Removes an option from the App. Takes an option pointer. Returns true if found and removed...
bool valid_first_char(T c)
Verify the first character of an option.
OptionDefaults * ignore_case(bool value=true)
Ignore the case of the option name.
Validator & non_modifying(bool no_modify=true)
Specify whether the Validator can be modifying or not.
std::tuple< std::vector< std::string >, std::vector< std::string >, std::string > get_names(const std::vector< std::string > &input)
Get a vector of short names, one of long names, and a single name.
App * formatter(std::shared_ptr< FormatterBase > fmt)
Set the help formatter.
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.
Validator(std::function< std::string(std::string &)> op, std::string validator_desc, std::string validator_name="")
App * ignore_case(bool value=true)
Ignore case. Subcommands inherit value.
bool get_ignore_underscore() const
The status of ignore_underscore.
static auto first(Q &&pair_value) -> decltype(std::get< 0 >(std::forward< Q >(pair_value)))
Get the first value (really just the underlying value)
std::function< std::string(const App *, const Error &e)> failure_message_
The error message printing function INHERITABLE.
App * require_subcommand(int value)
Thrown when a requires option is missing.
std::set< Option * > excludes_
A list of options that are excluded with this option.
App * disabled(bool disable=true)
Disable the subcommand or option group.
Option * envname(std::string name)
Sets environment variable to read if no option given.
void _parse(std::vector< std::string > &&args)
Internal parse function.
std::string ignore_underscore(std::string item)
Helper function to allow ignore_underscore to be passed to IsMember or Transform. ...
Option * capture_default_str()
Capture the default value from the original value (if it can be captured)
static void validate_mapping(std::map< std::string, Number > &mapping, Options opts)
static IncorrectConstruction MissingOption(std::string name)
Option * add_option_function(std::string option_name, const std::function< void(const T &)> &func, std::string option_description="")
Add option for a callback of a specific type.
void clear()
Reset the parsed data.
CRTP * take_first()
Set the multi option policy to take last.
std::string operator()(std::string &str) const
App(std::string app_description, std::string app_name, App *parent)
Special private constructor for subcommand.
Option * excludes(A opt, B opt1, ARG... args)
Any number supported, any mix of string and Opt.
Validate the argument is a number and greater than or equal to 0.
static IncorrectConstruction ChangeNotVector(std::string name)
static OptionAlreadyAdded Requires(std::string name, std::string other)
void _process()
Process callbacks and such.
Option * get_config_ptr()
Get a pointer to the config option.
void _process_callbacks()
Process callbacks. Runs on all subcommands.
Usually something like –help-all on command line.
#define CLI11_ERROR_DEF(parent, name)
bool get_allow_windows_style_options() const
Check the status of the allow windows style options.
bool get_allow_config_extras() const
Get the status of allow extras.
std::string get_name() const
App * prefix_command(bool allow=true)
Do not parse anything after the first unrecognized option and return.
Check to see if something is a shared pointer.
std::string & trim(std::string &str, const std::string filter)
Trim anything from string.
int _add_result(std::string &&result)
App * allow_config_extras(bool allow=true)
std::string footer_
Footer to put after all options in the help output INHERITABLE.
Thrown when extra values are found in an INI file.
static BadNameString MultiPositionalNames(std::string name)
void add_options(Option *opt)
Add an existing option to the Option_group.
void _process_extras()
Throw an error if anything is left over and should not be.
bool active_
Enable for Validator to allow it to be disabled if need be.
Thrown when validation fails before parsing.
auto search(const T &set, const V &val, const std::function< V(V)> &filter_function) -> std::pair< bool, decltype(std::begin(detail::smart_deref(set)))>
A search function with a filter function.
void increment_parsed()
Internal function to recursively increment the parsed counter on the current app as well unnamed subc...
std::istream & operator>>(std::istream &in, T &item)
input streaming for enumerations
typename T::value_type value_type
AsSizeValue(bool kb_is_1000)
const x_value & at(const std::map< x_key, x_value > &a_map, const x_key &a_key, const x_value &a_default)
std::string get_name() const
Get the name of the current app.
virtual void pre_callback()
virtual std::string to_flag(const ConfigItem &item) const
Get a flag value.
Option * needs(A opt, B opt1, ARG... args)
Any number supported, any mix of string and Opt.
bool get_ignore_case() const
Check the status of ignore_case.
bool has_default_flag_values(const std::string &flags)
check if the flag definitions has possible false flags
Option * disable_flag_override(bool value=true)
disable flag overrides
std::string fullname() const
The list of parents and name joined by ".".
const std::string & get_group() const
Get the group of this subcommand.
std::vector< App_p > subcommands_
Storage for subcommand list.
Thrown when parsing an INI file and it is missing.
Option * transform(std::function< std::string(std::string)> func, std::string transform_description="", std::string transform_name="")
Adds a validator-like function that can change result.
size_t get_require_subcommand_max() const
Get the required max subcommand value.
std::set< App * > exclude_subcommands_
this is a list of subcommands that are exclusionary to this one
void _merge_description(const Validator &val1, const Validator &val2, const std::string &merger)
std::set< Option * > get_excludes() const
The set of options excluded.
std::ostream & operator<<(std::ostream &in, const T &item)
output streaming for enumerations
static ArgumentMismatch AtLeast(std::string name, int num)
void _parse(std::vector< std::string > &args)
Internal parse function.
Option_group(std::string group_description, std::string group_name, App *parent)
Option * needs(Option *opt)
Sets required options.
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) ...
static BadNameString OneCharName(std::string name)
#define CLI11_ERROR_SIMPLE(name)
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.
bool operator==(const Option &other) const
If options share any of the same names, they are equal (not counting positional)
const detail::ExistingFileValidator ExistingFile
Check for existing file (returns error message if check fails)
OptionDefaults * ignore_underscore(bool value=true)
Ignore underscores in the option name.
size_t empty() const
True if the option was not passed.
void run_callback()
Process the callback.
A copy of std::void_t from C++17 (helper for C++11 and C++14)
Check to see if something is bool (fail check by default)
Option * add_option(std::string option_name)
Add option with no description or variable assignment.
constexpr std::chrono::duration< Rep, Period > abs(std::chrono::duration< Rep, Period > d)
Option * transform(Validator validator, std::string validator_name="")
Adds a transforming validator with a built in type name.
std::ostream & format_help(std::ostream &out, std::string name, std::string description, size_t wid)
Print a two part "help" string.
OptionDefaults option_defaults_
The default values for options, customizable and changeable INHERITABLE.
std::vector< std::pair< std::string, T > > TransformPairs
definition of the default transformation object
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...
CRTP * delimiter(char value='\0')
Allow in a configuration file.
CRTP * configurable(bool value=true)
Allow in a configuration file.
Option * add_complex(std::string option_name, T &variable, std::string option_description="", bool defaulted=false, std::string label="COMPLEX")
Add a complex number.
bool remove_needs(Option *opt)
Remove needs link from an option. Returns true if the option really was in the needs list...
std::vector< std::string > snames_
A list of the short names (-a) without the leading dashes.
static OptionAlreadyAdded Excludes(std::string name, std::string other)
bool remove_excludes(Option *opt)
Remove needs link from an option. Returns true if the option really was in the needs list...
std::string & add_quotes_if_needed(std::string &str)
Add quotes if the string contains spaces.
static App * get_fallthrough_parent(App *app)
Wrap the fallthrough parent function to make sure that is working correctly.
const App * get_parent() const
Get the parent of this subcommand (or nullptr if master app) (const version)
Option * ignore_underscore(bool value=true)
std::vector< std::pair< detail::Classifier, std::string > > missing_t
std::string get_description() const
Generate type description information for the Validator.
void _process_ini()
Read and process an ini file (main app only)
Construction errors (not in parsing)
ExistingDirectoryValidator()
const std::string & get_footer() const
Get footer.
void clear()
Clear the parsed results (mostly for testing)
static RequiredError Option(size_t min_option, size_t max_option, size_t used, const std::string &option_list)
static FileError Missing(std::string name)
bool check_sname(std::string name) const
Requires "-" to be removed from string.
App * get_parent()
Get the parent of this subcommand (or nullptr if master app)
App * enabled_by_default(bool enable=true)
std::function< void()> callback_
This is a function that runs when complete. Great for subcommands. Can throw.
typename std::conditional< is_copyable_ptr< T >::value, typename std::pointer_traits< T >::element_type, T >::type type
Thrown when an option already exists.
Validate the argument is a number and greater than or equal to 0.
Thrown when counting a non-existent option.
Option * ignore_case(bool value=true)
auto parse(const std::basic_string< CharT, Traits, Alloc > &format, Parsable &tp) -> decltype(from_stream(std::declval< std::basic_istream< CharT, Traits > &>(), format.c_str(), tp), parse_manip< Parsable, CharT, Traits, Alloc >
static auto second(Q &&pair_value) -> decltype(std::get< 1 >(std::forward< Q >(pair_value)))
Get the second value (really just the underlying value)
std::string find_and_replace(std::string str, std::string from, std::string to)
Find and replace a substring with another substring.
bool ignore_underscore_
If true, the program should ignore underscores INHERITABLE.
App * formatter_fn(std::function< std::string(const App *, std::string, AppFormatMode)> fmt)
Set the help formatter.
void remove_default_flag_values(std::string &flags)
typename element_type< T >::type::value_type type
std::string simple(const App *app, const Error &e)
Printout a clean, simple message on error (the default in CLI11 1.5+)
This can be specialized to override the type deduction for IsMember.
size_t require_subcommand_max_
Max number of subcommands allowed (parsing stops after this number). 0 is unlimited INHERITABLE...
std::string get_flag_value(std::string name, std::string input_value) const
bool _parse_subcommand(std::vector< std::string > &args)
int get_type_size() const
The number of arguments the option expects.
This class provides a converter for configuration files.
OptionDefaults * option_defaults()
Get the OptionDefault object, to set option defaults.
CRTP * join()
Set the multi option policy to take last.
This is a successful completion on parsing, supposed to exit.
App * config_formatter(std::shared_ptr< Config > fmt)
Set the config formatter.
auto search(const T &set, const V &val) -> std::pair< bool, decltype(std::begin(detail::smart_deref(set)))>
A search function.
std::vector< App * > get_subcommands(const std::function< bool(App *)> &filter)
std::string fix_newlines(std::string leader, std::string input)
bool _valid_subcommand(const std::string ¤t, bool ignore_used=true) const
Check to see if a subcommand is valid. Give up immediately if subcommand max has been reached...
typename std::remove_const< typename value_type::second_type >::type second_type
Option * default_function(const std::function< std::string()> &func)
Set a capture function for the default. Mostly used by App.
bool fallthrough_
Allow subcommand fallthrough, so that parent commands can collect commands after subcommand. INHERITABLE.
std::string join(const T &v, Callable func, std::string delim=",")
Simple function to join a string from processed elements.
bool get_enabled_by_default() const
Get the status of disabled by default.
std::vector< std::pair< std::string, std::string > > get_default_flag_values(const std::string &str)
extract default flag values either {def} or starting with a !
Option * add_result(std::string s, int &results_added)
Puts a result at the end and get a count of the number of arguments actually added.
App * allow_windows_style_options(bool value=true)
Allow windows style options, such as /opt. First matching short or long name used. Subcommands inherit value.
static ArgumentMismatch TypedAtLeast(std::string name, int num, std::string type)
static ConversionError TooManyInputsFlag(std::string name)
bool ignore_case_
If true, the program name is not case sensitive INHERITABLE.
const Option * get_option_no_throw(std::string option_name) const noexcept
Get an option by name (noexcept const version)
void _move_option(Option *opt, App *app)
function that could be used by subclasses of App to shift options around into subcommands ...
const detail::Number Number
Check for a number.
Option * add_option(std::string option_name, T &variable, std::string option_description="", bool defaulted=false)
Add option for non-vectors (duplicate copy needed without defaulted to avoid iostream << value) ...
OptionDefaults * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times.
std::vector< Option * > parse_order_
This is a list of pointers to options with the original parse order.
callback_t callback_
Options store a callback to do all the work.
size_t escape_detect(std::string &str, size_t offset)
std::vector< ConfigItem > items
bool check_lname(std::string name) const
Requires "--" to be removed from string.
Option * add_result(std::vector< std::string > s)
Puts a result at the end.
Thrown on construction of a bad name.
std::string group_
The group membership INHERITABLE.
bool disabled_
If set to true the subcommand is disabled and cannot be used, ignored for main app.
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.
std::enable_if< std::is_floating_point< T >::value, bool >::type checked_multiply(T &a, T b)
Performs a *= b; if it doesn't equal infinity. Returns false otherwise.
bool got_subcommand(App *subcom) const
Check to see if given subcommand was selected.
std::string name_
The name for search purposes of the Validator.
void run_callback()
Internal function to run (App) callback, bottom up.
Validator operator!() const
Create a validator that fails when a given validator succeeds.
App * parent_
A pointer to the parent if this is a subcommand.
void _parse_config(std::vector< ConfigItem > &args)
void add_options(Option *opt, Args... args)
Add a bunch of options to the group.
static ConfigError NotConfigurable(std::string item)
App * _get_fallthrough_parent()
Get the appropriate parent to fallthrough to which is the first one that has a name or the main app...
auto as_string(T &&v) -> decltype(std::forward< T >(v))
Option * default_val(std::string val)
Set the default value string representation and evaluate into the bound value.
App * disabled_by_default(bool disable=true)
Set the subcommand to be disabled by default, so on clear(), at the start of each parse it is disable...
static ConfigError Extras(std::string item)
Option * add_option(std::string option_name, std::vector< T > &variable, std::string option_description="", bool defaulted=false)
Add option for vectors.
auto smart_deref(T value) -> decltype(*value)
std::string config_to_str(bool default_also=false, bool write_description=false) const
bool get_allow_extras() const
Get the status of allow extras.
Anything that can error in Parse.
App * fallthrough(bool value=true)
void _process_extras(std::vector< std::string > &args)
AsNumberWithUnit(std::map< std::string, Number > mapping, Options opts=DEFAULT, const std::string &unit_name="UNIT")
Option * add_flag(std::string flag_name)
Add a flag with no description or variable assignment.
std::shared_ptr< FormatterBase > formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer) ...
const detail::PositiveNumber PositiveNumber
Check for a positive number.
MultiOptionPolicy get_multi_option_policy() const
The status of the multi option policy.
Validator * get_validator(const std::string &validator_name="")
Get a named Validator.
const Option * get_config_ptr() const
Get a pointer to the config option. (const)
App * add_subcommand(std::string subcommand_name="", std::string subcommand_description="")
Add a subcommand. Inherits INHERITABLE and OptionDefaults, and help flag.
std::string operator()(const std::string &str) const
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.
size_t get_require_option_max() const
Get the required max option value.
const std::string & get_group() const
Get the group of this option.
std::function< std::string()> desc_function_
This is the description function, if empty the description_ will be used.
Option * add_mutable_set(std::string option_name, T &member, const std::set< T > &options, std::string option_description="")
Add set of options (No default, set can be changed afterwards - do not destroy the set) DEPRECATED...
void parse(int argc, const char *const *argv)
std::string remove_underscore(std::string str)
remove underscores from a string
bool check_name(std::string name) const
Check a name. Requires "-" or "--" for short / long, supports positional name.
App * allow_extras(bool allow=true)
Remove the error when extras are left over on the command line.
Option * default_str(std::string val)
Set the default value string representation (does not change the contained value) ...
bool get_disable_flag_override() const
The status of configurable.
Thrown when the wrong number of arguments has been received.
Option * check(Validator validator, std::string validator_name="")
Adds a Validator with a built in type name.
Thrown when conversion call back fails, such as when an int fails to coerce to a string.
Range(T max)
Range of one value is 0 to value.
std::string name_
Subcommand name or program name (from parser if name is empty)
std::string name
This is the name.
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.
App * excludes(Option *opt)
Sets excluded options for the subcommand.
Option * get_option(std::string option_name)
Get an option by name (non-const version)
std::vector< std::string > split(const std::string &s, char delim)
Split a string by a delim.
std::string & trim(std::string &str)
Trim whitespace from string.
Option * type_name(std::string typeval)
Set a custom option typestring.
bool check_name(std::string name_to_check) const
Check the name, case insensitive and underscore insensitive if set.
static auto first(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the first value (really just the underlying value)
std::string config_name_
The name of the connected config file.
Produce a bounded range (factory). Min and max are inclusive.
std::vector< App * > get_subcommands() const
typename std::conditional< B, T, F >::type conditional_t
A copy of std::conditional_t from C++14 - same reasoning as enable_if_t, it does not hurt to redefine...
T * add_option_group(std::string group_name, std::string group_description="")
creates an option group as part of the given app
Validator operator|(const Validator &other) const
static std::map< std::string, result_t > get_mapping(bool kb_is_1000)
Cache calculated mapping.
std::function< std::string(std::string)> filter_fn_t
Validator & description(std::string validator_desc)
Specify the type string.
std::string join(const T &v, std::string delim=",")
Simple function to join a string.
std::shared_ptr< Config > config_formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer) ...
App * description(std::string app_description)
Set the description of the app.
const detail::ExistingPathValidator ExistingPath
Check for an existing path.
std::string ini_join(std::vector< std::string > args)
Comma separated join, adds quotes if needed.
auto to_string(T &&value) -> decltype(std::forward< T >(value))
Convert an object to a string (directly forward if this can become a string)
std::string get_envname() const
The environment variable associated to this value.
std::vector< const App * > get_subcommands(const std::function< bool(const App *)> &filter) const
const std::vector< Option * > & parse_order() const
This gets a vector of pointers with the original parse order.
Thrown when a required option is missing.
App * excludes(App *app)
Sets excluded subcommands for the subcommand.
void results(T &output) const
get the results as a particular type
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.
void _trigger_pre_parse(size_t remaining_args)
Trigger the pre_parse callback if needed.
void results(std::vector< T > &output) const
get the results as a vector of a particular type
CLI::App_p get_subcommand_ptr(int index=0) const
Get an owning pointer to subcommand by index.
Option * add_flag(std::string flag_name, T &flag_description)
std::vector< std::string > inputs
Listing of inputs.
std::function< void(size_t)> pre_parse_callback_
This is a function that runs prior to the start of parsing.
int get_exit_code() const
static ConversionError TrueFalse(std::string name)
Option * expected(int value)
Set the number of expected arguments (Flags don't use this)
std::vector< Option_p > options_
The list of options, stored locally.
Thrown when validation of results fails.