Go to the documentation of this file.
22 #if defined CLI11_CPP17 && defined __has_include && !defined CLI11_HAS_FILESYSTEM
23 #if __has_include(<filesystem>)
25 #if defined __MAC_OS_X_VERSION_MIN_REQUIRED && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500
26 #define CLI11_HAS_FILESYSTEM 0
29 #if defined __cpp_lib_filesystem && __cpp_lib_filesystem >= 201703
30 #define CLI11_HAS_FILESYSTEM 1
32 #define CLI11_HAS_FILESYSTEM 0
38 #if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
42 #include <sys/types.h>
68 std::function<std::string(std::string &)>
func_{[](std::string &) {
return std::string{}; }};
83 Validator(std::function<std::string(std::string &)> op, std::string validator_desc, std::string validator_name =
"")
85 name_(std::move(validator_name)) {}
88 func_ = std::move(op);
94 std::string retstring;
97 std::string value = str;
98 retstring =
func_(value);
100 retstring =
func_(str);
109 std::string value = str;
121 newval.
desc_function_ = [validator_desc]() {
return validator_desc; };
129 return std::string{};
133 name_ = std::move(validator_name);
139 newval.
name_ = std::move(validator_name);
185 newval._merge_description(*
this, other,
" AND ");
188 const std::function<std::string(std::string & filename)> &f1 =
func_;
189 const std::function<std::string(std::string & filename)> &f2 = other.func_;
191 newval.
func_ = [f1, f2](std::string &input) {
192 std::string s1 = f1(input);
193 std::string s2 = f2(input);
194 if(!s1.empty() && !s2.empty())
195 return std::string(
"(") + s1 +
") AND (" + s2 +
")";
210 newval._merge_description(*
this, other,
" OR ");
213 const std::function<std::string(std::string &)> &f1 =
func_;
214 const std::function<std::string(std::string &)> &f2 = other.func_;
216 newval.
func_ = [f1, f2](std::string &input) {
217 std::string s1 = f1(input);
218 std::string s2 = f2(input);
219 if(s1.empty() || s2.empty())
220 return std::string();
222 return std::string(
"(") + s1 +
") OR (" + s2 +
")";
235 return (!str.empty()) ? std::string(
"NOT ") + str : std::string{};
238 const std::function<std::string(std::string & res)> &f1 =
func_;
240 newval.
func_ = [f1, dfunc1](std::string &test) -> std::string {
241 std::string s1 = f1(test);
243 return std::string(
"check ") + dfunc1() +
" succeeded improperly";
245 return std::string{};
253 void _merge_description(
const Validator &val1,
const Validator &val2,
const std::string &merger) {
259 std::string f1 = dfunc1();
260 std::string f2 = dfunc2();
261 if((f1.empty()) || (f2.empty())) {
264 return std::string(1,
'(') + f1 +
')' + merger +
'(' + f2 +
')';
281 #if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
285 auto stat = std::filesystem::status(file, ec);
289 switch(stat.type()) {
290 case std::filesystem::file_type::none:
291 case std::filesystem::file_type::not_found:
293 case std::filesystem::file_type::directory:
295 case std::filesystem::file_type::symlink:
296 case std::filesystem::file_type::block:
297 case std::filesystem::file_type::character:
298 case std::filesystem::file_type::fifo:
299 case std::filesystem::file_type::socket:
300 case std::filesystem::file_type::regular:
301 case std::filesystem::file_type::unknown:
309 #if defined(_MSC_VER)
310 struct __stat64 buffer;
311 if(_stat64(file, &buffer) == 0) {
316 if(stat(file, &buffer) == 0) {
323 class ExistingFileValidator :
public Validator {
327 func_ = [](std::string &filename) {
328 auto path_result =
check_path(filename.c_str());
330 return "File does not exist: " + filename;
333 return "File is actually a directory: " + filename;
335 return std::string();
344 func_ = [](std::string &filename) {
345 auto path_result =
check_path(filename.c_str());
347 return "Directory does not exist: " + filename;
350 return "Directory is actually a file: " + filename;
352 return std::string();
361 func_ = [](std::string &filename) {
362 auto path_result =
check_path(filename.c_str());
364 return "Path does not exist: " + filename;
366 return std::string();
375 func_ = [](std::string &filename) {
376 auto path_result =
check_path(filename.c_str());
378 return "Path already exists: " + filename;
380 return std::string();
389 func_ = [](std::string &ip_addr) {
391 if(result.size() != 4) {
392 return std::string(
"Invalid IPV4 address must have four parts (") + ip_addr +
')';
395 for(
const auto &var : result) {
398 return std::string(
"Failed parsing number (") + var +
')';
400 if(num < 0 || num > 255) {
401 return std::string(
"Each IP number must be between 0 and 255 ") + var;
404 return std::string();
413 func_ = [](std::string &number_str) {
416 return std::string(
"Failed parsing number: (") + number_str +
')';
419 return std::string(
"Number less or equal to 0: (") + number_str +
')';
421 return std::string();
429 func_ = [](std::string &number_str) {
432 return std::string(
"Failed parsing number: (") + number_str +
')';
435 return std::string(
"Number less than 0: (") + number_str +
')';
437 return std::string();
446 func_ = [](std::string &number_str) {
449 return std::string(
"Failed parsing as a number (") + number_str +
')';
451 return std::string();
491 template <
typename T>
Range(T min, T max) {
492 std::stringstream out;
493 out << detail::type_name<T>() <<
" in [" << min <<
" - " << max <<
"]";
496 func_ = [min, max](std::string &input) {
499 if((!converted) || (val < min || val > max))
500 return std::string(
"Value ") + input +
" not in range " +
std::to_string(min) +
" to " +
503 return std::string();
508 template <
typename T>
explicit Range(T max) :
Range(static_cast<T>(0), max) {}
518 template <
typename T>
Bound(T min, T max) {
519 std::stringstream out;
520 out << detail::type_name<T>() <<
" bounded to [" << min <<
" - " << max <<
"]";
523 func_ = [min, max](std::string &input) {
527 return std::string(
"Value ") + input +
" could not be converted";
534 return std::string{};
539 template <
typename T>
explicit Bound(T max) :
Bound(static_cast<T>(0), max) {}
543 template <
typename T,
559 std::string out(1,
'{');
569 template <
typename T> std::string
generate_map(
const T &map,
bool key_only =
false) {
572 std::string out(1,
'{');
575 [key_only](
const iteration_type_t &v) {
589 template <
typename C,
typename V>
struct has_find {
590 template <
typename CC,
typename VV>
591 static auto test(
int) -> decltype(std::declval<CC>().find(std::declval<VV>()), std::true_type());
592 template <
typename,
typename>
static auto test(...) -> decltype(std::false_type());
595 using type = std::integral_constant<bool, value>;
603 auto it = std::find_if(std::begin(setref), std::end(setref), [&val](decltype(*std::begin(setref)) v) {
606 return {(it != std::end(setref)), it};
613 auto it = setref.find(val);
614 return {(it != std::end(setref)), it};
618 template <
typename T,
typename V>
619 auto search(
const T &set,
const V &val,
const std::function<V(V)> &filter_function)
623 auto res =
search(set, val);
624 if((res.first) || (!(filter_function))) {
629 auto it = std::find_if(std::begin(setref), std::end(setref), [&](decltype(*std::begin(setref)) v) {
631 a = filter_function(a);
634 return {(it != std::end(setref)), it};
641 template <
typename T>
642 inline typename std::enable_if<std::is_signed<T>::value, T>::type
overflowCheck(
const T &a,
const T &b) {
643 if((a > 0) == (b > 0)) {
644 return ((std::numeric_limits<T>::max)() / (std::abs)(a) < (std::abs)(b));
646 return ((std::numeric_limits<T>::min)() / (std::abs)(a) > -(std::abs)(b));
650 template <
typename T>
651 inline typename std::enable_if<!std::is_signed<T>::value, T>::type
overflowCheck(
const T &a,
const T &b) {
652 return ((std::numeric_limits<T>::max)() / a < b);
656 template <
typename T>
typename std::enable_if<std::is_integral<T>::value,
bool>::type
checked_multiply(T &a, T b) {
657 if(a == 0 || b == 0 || a == 1 || b == 1) {
661 if(a == (std::numeric_limits<T>::min)() || b == (std::numeric_limits<T>::min)()) {
672 template <
typename T>
673 typename std::enable_if<std::is_floating_point<T>::value,
bool>::type
checked_multiply(T &a, T b) {
675 if(std::isinf(c) && !std::isinf(a) && !std::isinf(b)) {
689 template <
typename T,
typename... Args>
690 IsMember(std::initializer_list<T> values, Args &&... args)
691 :
IsMember(std::vector<T>(values), std::forward<Args>(args)...) {}
694 template <
typename T>
explicit IsMember(T &&set) :
IsMember(std::forward<T>(set), nullptr) {}
698 template <
typename T,
typename F>
explicit IsMember(T set, F filter_function) {
709 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
716 func_ = [set, filter_fn](std::string &input) {
732 return std::string{};
736 std::string out(
" not in ");
743 template <
typename T,
typename... Args>
746 std::forward<T>(set),
747 [filter_fn_1, filter_fn_2](std::string a) {
return filter_fn_2(filter_fn_1(a)); },
752 template <
typename T>
using TransformPairs = std::vector<std::pair<std::string, T>>;
760 template <
typename... Args>
761 Transformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&... args)
769 template <
typename T,
typename F>
explicit Transformer(T mapping, F filter_function) {
772 "mapping must produce value pairs");
781 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
786 func_ = [mapping, filter_fn](std::string &input) {
789 return std::string();
799 return std::string{};
804 template <
typename T,
typename... Args>
807 std::forward<T>(mapping),
808 [filter_fn_1, filter_fn_2](std::string a) {
return filter_fn_2(filter_fn_1(a)); },
818 template <
typename... Args>
819 CheckedTransformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&... args)
830 "mapping must produce value pairs");
841 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
843 auto tfunc = [mapping]() {
844 std::string out(
"value in ");
856 func_ = [mapping, tfunc, filter_fn](std::string &input) {
866 return std::string{};
871 if(output_string == input) {
872 return std::string();
876 return "Check " + input +
" " + tfunc() +
" FAILED";
881 template <
typename T,
typename... Args>
884 std::forward<T>(mapping),
885 [filter_fn_1, filter_fn_2](std::string a) {
return filter_fn_2(filter_fn_1(a)); },
897 item.erase(std::remove(std::begin(item), std::end(item),
' '), std::end(item));
898 item.erase(std::remove(std::begin(item), std::end(item),
'\t'), std::end(item));
927 template <
typename Number>
930 const std::string &unit_name =
"UNIT") {
931 description(generate_description<Number>(unit_name, opts));
932 validate_mapping(mapping, opts);
935 func_ = [mapping, opts](std::string &input) -> std::string {
944 auto unit_begin = input.end();
945 while(unit_begin > input.begin() &&
std::isalpha(*(unit_begin - 1), std::locale())) {
949 std::string unit{unit_begin, input.end()};
950 input.resize(
static_cast<std::size_t
>(std::distance(input.begin(), unit_begin)));
962 throw ValidationError(std::string(
"Value ") + input +
" could not be converted to " +
963 detail::type_name<Number>());
972 auto it = mapping.find(unit);
973 if(it == mapping.end()) {
975 " unit not recognized. "
984 " factor would cause number overflow. Use smaller value.");
995 template <
typename Number>
static void validate_mapping(std::map<std::string, Number> &mapping,
Options opts) {
996 for(
auto &kv : mapping) {
997 if(kv.first.empty()) {
1001 throw ValidationError(
"Unit must contain only letters.");
1007 std::map<std::string, Number> lower_mapping;
1008 for(
auto &kv : mapping) {
1010 if(lower_mapping.count(s)) {
1011 throw ValidationError(std::string(
"Several matching lowercase unit representations are found: ") +
1016 mapping = std::move(lower_mapping);
1021 template <
typename Number>
static std::string generate_description(
const std::string &
name,
Options opts) {
1022 std::stringstream out;
1023 out << detail::type_name<Number>() <<
' ';
1027 out <<
'[' <<
name <<
']';
1057 description(
"SIZE [b, kb(=1000b), kib(=1024b), ...]");
1065 static std::map<std::string, result_t> init_mapping(
bool kb_is_1000) {
1066 std::map<std::string, result_t> m;
1067 result_t k_factor = kb_is_1000 ? 1000 : 1024;
1072 for(std::string p : {
"k",
"m",
"g",
"t",
"p",
"e"}) {
1084 static std::map<std::string, result_t> get_mapping(
bool kb_is_1000) {
1086 static auto m = init_mapping(
true);
1089 static auto m = init_mapping(
false);
1102 std::pair<std::string, std::string> vals;
1104 auto esp = commandline.find_first_of(
' ', 1);
1106 esp = commandline.find_first_of(
' ', esp + 1);
1107 if(esp == std::string::npos) {
1110 esp = commandline.find_first_of(
' ', 1);
1114 vals.first = commandline.substr(0, esp);
1117 vals.second = (esp != std::string::npos) ? commandline.substr(esp + 1) : std::string{};
ExistingDirectoryValidator()
Definition: Validators.hpp:343
Range(T max)
Range of one value is 0 to value.
Definition: Validators.hpp:508
bool get_active() const
Get a boolean if the validator is active.
Definition: Validators.hpp:175
const detail::PositiveNumber PositiveNumber
Check for a positive number.
Definition: Validators.hpp:476
@ UNIT_REQUIRED
Definition: Validators.hpp:923
std::string ignore_space(std::string item)
Helper function to allow checks to ignore spaces to be passed to IsMember or Transform.
Definition: Validators.hpp:896
Range(T min, T max)
Definition: Validators.hpp:491
Validator description(std::string validator_desc) const
Specify the type string.
Definition: Validators.hpp:119
std::string get_description() const
Generate type description information for the Validator.
Definition: Validators.hpp:125
const detail::Number Number
Check for a number.
Definition: Validators.hpp:482
Validator operator|(const Validator &other) const
Definition: Validators.hpp:207
Produce a bounded range (factory). Min and max are inclusive.
Definition: Validators.hpp:512
static auto test(int) -> decltype(std::declval< CC >().find(std::declval< VV >()), std::true_type())
Validator & active(bool active_val=true)
Specify whether the Validator is active or not.
Definition: Validators.hpp:145
T type
Definition: TypeTools.hpp:74
enabler
Simple empty scoped class.
Definition: TypeTools.hpp:22
ExistingPathValidator()
Definition: Validators.hpp:360
std::enable_if< std::is_signed< T >::value, T >::type overflowCheck(const T &a, const T &b)
Do a check for overflow on signed numbers.
Definition: Validators.hpp:642
AsSizeValue(bool kb_is_1000)
Definition: Validators.hpp:1055
Some validators that are provided.
Definition: Validators.hpp:61
Validator operator&(const Validator &other) const
Definition: Validators.hpp:182
int get_application_index() const
Get the current value of the application index.
Definition: Validators.hpp:173
Bound(T max)
Range of one value is 0 to value.
Definition: Validators.hpp:539
Definition: Validators.hpp:589
std::vector< std::string > split(const std::string &s, char delim)
Split a string by a delim.
Definition: StringTools.hpp:39
uint64_t result_t
Definition: Validators.hpp:1046
Options
Definition: Validators.hpp:919
Validate the argument is a number and greater than 0.
Definition: Validators.hpp:410
std::function< std::string(std::string &)> func_
Definition: Validators.hpp:68
Validator name(std::string validator_name) const
Specify the type string.
Definition: Validators.hpp:137
typename std::enable_if< B, T >::type enable_if_t
Definition: TypeTools.hpp:33
static const auto value
Definition: Validators.hpp:594
AsNumberWithUnit(std::map< std::string, Number > mapping, Options opts=DEFAULT, const std::string &unit_name="UNIT")
Definition: Validators.hpp:928
bool get_modifying() const
Get a boolean if the validator is allowed to modify the input returns true if it can modify the input...
Definition: Validators.hpp:178
Definition: Validators.hpp:1044
Class wrapping some of the accessors of Validator.
Definition: Validators.hpp:270
bool active_
Enable for Validator to allow it to be disabled if need be.
Definition: Validators.hpp:74
std::string & rtrim(std::string &str)
Trim whitespace from right of string.
Definition: StringTools.hpp:112
std::string generate_set(const T &set)
Generate a string representation of a set.
Definition: Validators.hpp:556
Produce a range (factory). Min and max are inclusive.
Definition: Validators.hpp:485
std::string join(const T &v, std::string delim=",")
Simple function to join a string.
Definition: StringTools.hpp:56
typename std::remove_const< value_type >::type first_type
Definition: TypeTools.hpp:100
const std::string & get_name() const
Get the name of the Validator.
Definition: Validators.hpp:143
path_type check_path(const char *file) noexcept
get the type of the path from a file name
Definition: Validators.hpp:308
auto smart_deref(T value) -> decltype(*value)
Definition: Validators.hpp:545
auto to_string(T &&value) -> decltype(std::forward< T >(value))
Convert an object to a string (directly forward if this can become a string)
Definition: TypeTools.hpp:222
PositiveNumber()
Definition: Validators.hpp:412
Validate the given string is a legal ipv4 address.
Definition: Validators.hpp:386
Check for an existing directory (returns error message if check fails)
Definition: Validators.hpp:341
bool lexical_cast(const std::string &input, T &output)
Signed integers.
Definition: TypeTools.hpp:596
IsMember(T &&set)
This checks to see if an item is in a set (empty function)
Definition: Validators.hpp:694
static auto first(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the first value (really just the underlying value)
Definition: TypeTools.hpp:104
Validator application_index(int app_index) const
Specify the application index of a validator.
Definition: Validators.hpp:167
auto search(const T &set, const V &val) -> std::pair< bool, decltype(std::begin(detail::smart_deref(set)))>
A search function.
Definition: Validators.hpp:600
Validate the argument is a number.
Definition: Validators.hpp:443
std::pair< std::string, std::string > split_program_name(std::string commandline)
Definition: Validators.hpp:1100
constexpr enabler dummy
An instance to use in EnableIf.
Definition: TypeTools.hpp:25
std::string & ltrim(std::string &str)
Trim whitespace from left of string.
Definition: StringTools.hpp:98
std::string name_
The name for search purposes of the Validator.
Definition: Validators.hpp:70
std::string ignore_case(std::string item)
Helper function to allow ignore_case to be passed to IsMember or Transform.
Definition: Validators.hpp:890
Check for an existing file (returns error message if check fails)
Definition: Validators.hpp:324
const detail::ExistingDirectoryValidator ExistingDirectory
Check for an existing directory (returns error message if check fails)
Definition: Validators.hpp:464
std::string ignore_underscore(std::string item)
Helper function to allow ignore_underscore to be passed to IsMember or Transform.
Definition: Validators.hpp:893
std::integral_constant< bool, value > type
Definition: Validators.hpp:595
Validator & application_index(int app_index)
Specify the application index of a validator.
Definition: Validators.hpp:162
std::string to_lower(std::string str)
Return a lower case version of a string.
Definition: StringTools.hpp:196
std::string operator()(std::string &str) const
Definition: Validators.hpp:93
const detail::IPV4Validator ValidIPV4
Check for an IP4 address.
Definition: Validators.hpp:473
IsMember(std::initializer_list< T > values, Args &&... args)
This allows in-place construction using an initializer list.
Definition: Validators.hpp:690
@ UNIT_OPTIONAL
Definition: Validators.hpp:922
Check for an non-existing path.
Definition: Validators.hpp:372
@ CASE_INSENSITIVE
Definition: Validators.hpp:921
std::string remove_underscore(std::string str)
remove underscores from a string
Definition: StringTools.hpp:204
Verify items are in a set.
Definition: Validators.hpp:684
@ CASE_SENSITIVE
Definition: Validators.hpp:920
Thrown when validation of results fails.
Definition: Error.hpp:198
std::string & trim(std::string &str)
Trim whitespace from string.
Definition: StringTools.hpp:127
NonNegativeNumber()
Definition: Validators.hpp:428
const detail::ExistingPathValidator ExistingPath
Check for an existing path.
Definition: Validators.hpp:467
ExistingFileValidator()
Definition: Validators.hpp:326
Definition: Validators.hpp:913
typename T::value_type value_type
Definition: TypeTools.hpp:99
T type
Definition: TypeTools.hpp:87
IsMember(T set, F filter_function)
Definition: Validators.hpp:698
std::vector< std::pair< std::string, T > > TransformPairs
definition of the default transformation object
Definition: Validators.hpp:752
Number()
Definition: Validators.hpp:445
Validator & operation(std::function< std::string(std::string &)> op)
Set the Validator operation function.
Definition: Validators.hpp:87
Bound(T min, T max)
Definition: Validators.hpp:518
Adaptor for set-like structure: This just wraps a normal container in a few utilities that do almost ...
Definition: TypeTools.hpp:98
const detail::ExistingFileValidator ExistingFile
Check for existing file (returns error message if check fails)
Definition: Validators.hpp:461
Validator & name(std::string validator_name)
Specify the type string.
Definition: Validators.hpp:132
Validate the argument is a number and greater than or equal to 0.
Definition: Validators.hpp:426
Validator operator!() const
Create a validator that fails when a given validator succeeds.
Definition: Validators.hpp:230
Validator & non_modifying(bool no_modify=true)
Specify whether the Validator can be modifying or not.
Definition: Validators.hpp:157
bool non_modifying_
specify that a validator should not modify the input
Definition: Validators.hpp:76
std::string value_string(const T &value)
get a string as a convertible value for arithmetic types
Definition: TypeTools.hpp:281
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.
Definition: Validators.hpp:656
const detail::NonexistentPathValidator NonexistentPath
Check for an non-existing path.
Definition: Validators.hpp:470
Check for an existing path.
Definition: Validators.hpp:358
@ DEFAULT
Definition: Validators.hpp:924
Validator(std::function< std::string(std::string &)> op, std::string validator_desc, std::string validator_name="")
Construct Validator from basic information.
Definition: Validators.hpp:83
std::string operator()(const std::string &str) const
Definition: Validators.hpp:108
std::function< std::string(std::string)> filter_fn_t
Definition: Validators.hpp:686
Validator active(bool active_val=true) const
Specify whether the Validator is active or not.
Definition: Validators.hpp:150
bool isalpha(const std::string &str)
Verify that str consists of letters only.
Definition: StringTools.hpp:191
IPV4Validator()
Definition: Validators.hpp:388
const detail::NonNegativeNumber NonNegativeNumber
Check for a non-negative number.
Definition: Validators.hpp:479
NonexistentPathValidator()
Definition: Validators.hpp:374
Validator & description(std::string validator_desc)
Specify the type string.
Definition: Validators.hpp:114
int application_index_
A Validator will only apply to an indexed value (-1 is all elements)
Definition: Validators.hpp:72
path_type
CLI enumeration of different file types.
Definition: Validators.hpp:279
IsMember(T &&set, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&... other)
You can pass in as many filter functions as you like, they nest (string only currently)
Definition: Validators.hpp:744
Validator(std::string validator_desc)
Construct a Validator with just the description string.
Definition: Validators.hpp:81
std::function< std::string()> desc_function_
This is the description function, if empty the description_ will be used.
Definition: Validators.hpp:64
std::string generate_map(const T &map, bool key_only=false)
Generate a string representation of a map.
Definition: Validators.hpp:569