CLI11 2.7.2
C++11 Command Line Interface Parser
Loading...
Searching...
No Matches
ExtraValidators.hpp
1// Copyright (c) 2017-2026, University of Cincinnati, developed by Henry Schreiner
2// under NSF AWARD 1414736 and by the respective contributors.
3// All rights reserved.
4//
5// SPDX-License-Identifier: BSD-3-Clause
6
7#pragma once
8#if (defined(CLI11_ENABLE_EXTRA_VALIDATORS) && CLI11_ENABLE_EXTRA_VALIDATORS != 0) || \
9 (!defined(CLI11_DISABLE_EXTRA_VALIDATORS) || CLI11_DISABLE_EXTRA_VALIDATORS == 0)
10// IWYU pragma: private, include "CLI/CLI.hpp"
11
12#include "Error.hpp"
13#include "Macros.hpp"
14#include "StringTools.hpp"
15#include "Validators.hpp"
16
17// [CLI11:public_includes:set]
18#include <algorithm>
19#include <cstddef>
20#include <cstdint>
21#include <functional>
22#include <initializer_list>
23#include <iterator>
24#include <locale>
25#include <map>
26#include <memory>
27#include <sstream>
28#include <string>
29#include <type_traits>
30#include <utility>
31#include <vector>
32// [CLI11:public_includes:end]
33
34namespace CLI {
35// [CLI11:extra_validators_hpp:verbatim]
36// The implementation of the extra validators is using the Validator class;
37// the user is only expected to use the const (static) versions (since there's no setup).
38// Therefore, this is in detail.
39namespace detail {
40
42class IPV4Validator : public Validator {
43 public:
44 IPV4Validator();
45};
46
47} // namespace detail
48
50template <typename DesiredType> class TypeValidator : public Validator {
51 public:
52 explicit TypeValidator(const std::string &validator_name)
53 : Validator(validator_name, [](std::string &input_string) {
54 using CLI::detail::lexical_cast;
55 auto val = DesiredType();
56 if(!lexical_cast(input_string, val)) {
57 return std::string("Failed parsing ") + input_string + " as a " + detail::type_name<DesiredType>();
58 }
59 return std::string{};
60 }) {}
61 TypeValidator() : TypeValidator(detail::type_name<DesiredType>()) {}
62};
63
65CLI11_MODULE_INLINE const TypeValidator<double> Number("NUMBER");
66
68class Bound : public Validator {
69 public:
74 template <typename T> Bound(T min_val, T max_val) {
75 if(detail::is_nan(min_val) || detail::is_nan(max_val)) {
76 throw ValidationError("Bound endpoints must not be NaN");
77 }
78 std::stringstream out;
79 out << detail::type_name<T>() << " bounded to [" << min_val << " - " << max_val << "]";
80 description(out.str());
81
82 func_ = [min_val, max_val](std::string &input) {
83 using CLI::detail::lexical_cast;
84 T val;
85 bool converted = lexical_cast(input, val);
86 if(!converted) {
87 return std::string("Value ") + input + " could not be converted";
88 }
89 if(detail::is_nan(val)) {
90 std::stringstream err;
91 err << "Value " << input << " cannot be bounded to [";
92 err << min_val << " - " << max_val << "]";
93 return err.str();
94 }
95 if(val < min_val)
96 input = detail::to_string(min_val);
97 else if(val > max_val)
98 input = detail::to_string(max_val);
99
100 return std::string{};
101 };
102 }
103
105 template <typename T> explicit Bound(T max_val) : Bound(static_cast<T>(0), max_val) {}
106};
107
108// Static is not needed here, because global const implies static.
109
111CLI11_MODULE_INLINE const detail::IPV4Validator ValidIPV4;
112
113namespace detail {
114template <typename T,
115 enable_if_t<is_copyable_ptr<typename std::remove_reference<T>::type>::value, detail::enabler> = detail::dummy>
116auto smart_deref(T value) -> decltype(*value) {
117 return *value;
118}
119
120template <
121 typename T,
122 enable_if_t<!is_copyable_ptr<typename std::remove_reference<T>::type>::value, detail::enabler> = detail::dummy>
123typename std::remove_reference<T>::type &smart_deref(T &value) {
124 // NOLINTNEXTLINE
125 return value;
126}
128template <typename T> std::string generate_set(const T &set) {
129 using element_t = typename detail::element_type<T>::type;
130 using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
131 std::string out(1, '{');
132 out.append(detail::join(
133 detail::smart_deref(set),
134 [](const iteration_type_t &v) { return detail::pair_adaptor<element_t>::first(v); },
135 ","));
136 out.push_back('}');
137 return out;
138}
139
141template <typename T> std::string generate_map(const T &map, bool key_only = false) {
142 using element_t = typename detail::element_type<T>::type;
143 using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
144 std::string out(1, '{');
145 out.append(detail::join(
146 detail::smart_deref(map),
147 [key_only](const iteration_type_t &v) {
148 std::string res{detail::to_string(detail::pair_adaptor<element_t>::first(v))};
149
150 if(!key_only) {
151 res.append("->");
152 res += detail::to_string(detail::pair_adaptor<element_t>::second(v));
153 }
154 return res;
155 },
156 ","));
157 out.push_back('}');
158 return out;
159}
160
161template <typename C, typename V> struct has_find {
162 template <typename CC, typename VV>
163 static auto test(int) -> decltype(std::declval<CC>().find(std::declval<VV>()), std::true_type());
164 template <typename, typename> static auto test(...) -> decltype(std::false_type());
165
166 static const auto value = decltype(test<C, V>(0))::value;
167 using type = std::integral_constant<bool, value>;
168};
169
171template <typename T, typename V, enable_if_t<!has_find<T, V>::value, detail::enabler> = detail::dummy>
172auto search(const T &set, const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
173 using element_t = typename detail::element_type<T>::type;
174 auto &setref = detail::smart_deref(set);
175 auto it = std::find_if(std::begin(setref), std::end(setref), [&val](decltype(*std::begin(setref)) v) {
177 });
178 return {(it != std::end(setref)), it};
179}
180
182template <typename T, typename V, enable_if_t<has_find<T, V>::value, detail::enabler> = detail::dummy>
183auto search(const T &set, const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
184 auto &setref = detail::smart_deref(set);
185 auto it = setref.find(val);
186 return {(it != std::end(setref)), it};
187}
188
190template <typename T, typename V>
191auto search(const T &set, const V &val, const std::function<V(V)> &filter_function)
192 -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
193 using element_t = typename detail::element_type<T>::type;
194 // do the potentially faster first search
195 auto res = search(set, val);
196 if((res.first) || (!(filter_function))) {
197 return res;
198 }
199 // if we haven't found it do the longer linear search with all the element translations
200 auto &setref = detail::smart_deref(set);
201 auto it = std::find_if(std::begin(setref), std::end(setref), [&](decltype(*std::begin(setref)) v) {
203 a = filter_function(a);
204 return (a == val);
205 });
206 return {(it != std::end(setref)), it};
207}
208
209} // namespace detail
211class IsMember : public Validator {
212 public:
213 using filter_fn_t = std::function<std::string(std::string)>;
214
216 template <typename T, typename... Args>
217 IsMember(std::initializer_list<T> values, Args &&...args)
218 : IsMember(std::vector<T>(values), std::forward<Args>(args)...) {}
219
221 template <typename T> explicit IsMember(T &&set) : IsMember(std::forward<T>(set), nullptr) {}
222
225 template <typename T, typename F> explicit IsMember(T set, F filter_function) {
226
227 // Get the type of the contained item - requires a container have ::value_type
228 // if the type does not have first_type and second_type, these are both value_type
229 using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
230 using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
231
232 using local_item_t = typename IsMemberType<item_t>::type; // This will convert bad types to good ones
233 // (const char * to std::string)
234
235 // Make a local copy of the filter function, using a std::function if not one already
236 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
237
238 // Store a single copy of the set in a shared_ptr so the lambdas below can share it
239 auto shared_set = std::make_shared<T>(std::move(set));
240
241 // This is the type name for help, it will take the current version of the set contents
242 desc_function_ = [shared_set]() { return detail::generate_set(detail::smart_deref(*shared_set)); };
243
244 // This is the function that validates
245 // It stores a copy of the set pointer-like, so shared_ptr will stay alive
246 func_ = [shared_set, filter_fn](std::string &input) {
247 using CLI::detail::lexical_cast;
248 local_item_t b;
249 if(!lexical_cast(input, b)) {
250 return input; // name is added later
251 }
252 if(filter_fn) {
253 b = filter_fn(b);
254 }
255 auto res = detail::search(*shared_set, b, filter_fn);
256 if(res.first) {
257 // Make sure the version in the input string is identical to the one in the set
258 if(filter_fn) {
259 input = detail::value_string(detail::pair_adaptor<element_t>::first(*(res.second)));
260 }
261
262 // Return empty error string (success)
263 return std::string{};
264 }
265
266 // If you reach this point, the result was not found
267 return input + " not in " + detail::generate_set(detail::smart_deref(*shared_set));
268 };
269 }
270
272 template <typename T, typename... Args>
273 IsMember(T &&set, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
274 : IsMember(
275 std::forward<T>(set),
276 [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
277 other...) {}
278};
279
281template <typename T> using TransformPairs = std::vector<std::pair<std::string, T>>;
282
284class Transformer : public Validator {
285 public:
286 using filter_fn_t = std::function<std::string(std::string)>;
287
289 template <typename... Args>
290 Transformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
291 : Transformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
292
294 template <typename T> explicit Transformer(T &&mapping) : Transformer(std::forward<T>(mapping), nullptr) {}
295
298 template <typename T, typename F> explicit Transformer(T mapping, F filter_function) {
299
301 "mapping must produce value pairs");
302 // Get the type of the contained item - requires a container have ::value_type
303 // if the type does not have first_type and second_type, these are both value_type
304 using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
305 using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
306 using local_item_t = typename IsMemberType<item_t>::type; // Will convert bad types to good ones
307 // (const char * to std::string)
308
309 // Make a local copy of the filter function, using a std::function if not one already
310 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
311
312 // Store a single copy of the mapping in a shared_ptr so the lambdas below can share it
313 auto shared_mapping = std::make_shared<T>(std::move(mapping));
314
315 // This is the type name for help, it will take the current version of the set contents
316 desc_function_ = [shared_mapping]() { return detail::generate_map(detail::smart_deref(*shared_mapping)); };
317
318 func_ = [shared_mapping, filter_fn](std::string &input) {
319 using CLI::detail::lexical_cast;
320 local_item_t b;
321 if(!lexical_cast(input, b)) {
322 return std::string();
323 // there is no possible way we can match anything in the mapping if we can't convert so just return
324 }
325 if(filter_fn) {
326 b = filter_fn(b);
327 }
328 auto res = detail::search(*shared_mapping, b, filter_fn);
329 if(res.first) {
330 input = detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
331 }
332 return std::string{};
333 };
334 }
335
337 template <typename T, typename... Args>
338 Transformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
339 : Transformer(
340 std::forward<T>(mapping),
341 [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
342 other...) {}
343};
344
346class CheckedTransformer : public Validator {
347 public:
348 using filter_fn_t = std::function<std::string(std::string)>;
349
351 template <typename... Args>
352 CheckedTransformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
353 : CheckedTransformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
354
356 template <typename T> explicit CheckedTransformer(T mapping) : CheckedTransformer(std::move(mapping), nullptr) {}
357
360 template <typename T, typename F> explicit CheckedTransformer(T mapping, F filter_function) {
361
363 "mapping must produce value pairs");
364 // Get the type of the contained item - requires a container have ::value_type
365 // if the type does not have first_type and second_type, these are both value_type
366 using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
367 using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
368 using local_item_t = typename IsMemberType<item_t>::type; // Will convert bad types to good ones
369 // (const char * to std::string)
370 using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
371
372 // Make a local copy of the filter function, using a std::function if not one already
373 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
374
375 // Store a single copy of the mapping in a shared_ptr so the lambdas below can share it
376 auto shared_mapping = std::make_shared<T>(std::move(mapping));
377
378 auto tfunc = [shared_mapping]() {
379 std::string out("value in ");
380 out += detail::generate_map(detail::smart_deref(*shared_mapping)) + " OR {";
381 out += detail::join(
382 detail::smart_deref(*shared_mapping),
383 [](const iteration_type_t &v) {
384 return detail::value_string(detail::pair_adaptor<element_t>::second(v));
385 },
386 ",");
387 out.push_back('}');
388 return out;
389 };
390
391 desc_function_ = tfunc;
392
393 func_ = [shared_mapping, tfunc, filter_fn](std::string &input) {
394 using CLI::detail::lexical_cast;
395 local_item_t b;
396 bool converted = lexical_cast(input, b);
397 if(converted) {
398 if(filter_fn) {
399 b = filter_fn(b);
400 }
401 auto res = detail::search(*shared_mapping, b, filter_fn);
402 if(res.first) {
403 input = detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
404 return std::string{};
405 }
406 }
407 for(const auto &v : detail::smart_deref(*shared_mapping)) {
408 auto output_string = detail::value_string(detail::pair_adaptor<element_t>::second(v));
409 if(output_string == input) {
410 return std::string();
411 }
412 }
413
414 return "Check " + input + " " + tfunc() + " FAILED";
415 };
416 }
417
419 template <typename T, typename... Args>
420 CheckedTransformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
422 std::forward<T>(mapping),
423 [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
424 other...) {}
425};
426
428inline std::string ignore_case(std::string item) { return detail::to_lower(item); }
429
431inline std::string ignore_underscore(std::string item) { return detail::remove_underscore(item); }
432
434inline std::string ignore_space(std::string item) {
435 item.erase(std::remove(std::begin(item), std::end(item), ' '), std::end(item));
436 item.erase(std::remove(std::begin(item), std::end(item), '\t'), std::end(item));
437 return item;
438}
439
451class AsNumberWithUnit : public Validator {
452 public:
457 enum Options : std::uint8_t {
458 CASE_SENSITIVE = 0,
459 CASE_INSENSITIVE = 1,
460 UNIT_OPTIONAL = 0,
461 UNIT_REQUIRED = 2,
462 DEFAULT = CASE_INSENSITIVE | UNIT_OPTIONAL
463 };
464
465 template <typename Number>
466 explicit AsNumberWithUnit(std::map<std::string, Number> mapping,
467 Options opts = DEFAULT,
468 const std::string &unit_name = "UNIT") {
469 description(generate_description<Number>(unit_name, opts));
470 validate_mapping(mapping, opts);
471
472 // transform function
473 func_ = [mapping, opts](std::string &input) -> std::string {
474 Number num{};
475
476 detail::rtrim(input);
477 if(input.empty()) {
478 return std::string("Input is empty");
479 }
480
481 // Find split position between number and prefix
482 auto unit_begin = input.end();
483 const std::locale loc{};
484 while(unit_begin > input.begin() && std::isalpha(*(unit_begin - 1), loc)) {
485 --unit_begin;
486 }
487
488 std::string unit{unit_begin, input.end()};
489 input.resize(static_cast<std::size_t>(std::distance(input.begin(), unit_begin)));
490 detail::trim(input);
491
492 if(opts & UNIT_REQUIRED && unit.empty()) {
493 return std::string("Missing mandatory unit");
494 }
495 if(opts & CASE_INSENSITIVE) {
496 unit = detail::to_lower(unit);
497 }
498 if(unit.empty()) {
499 using CLI::detail::lexical_cast;
500 if(!lexical_cast(input, num)) {
501 return std::string("Value ") + input + " could not be converted to " + detail::type_name<Number>();
502 }
503 // No need to modify input if no unit passed
504 return {};
505 }
506
507 // find corresponding factor
508 auto it = mapping.find(unit);
509 if(it == mapping.end()) {
510 return unit +
511 " unit not recognized. "
512 "Allowed values: " +
513 detail::generate_map(mapping, true);
514 }
515
516 if(!input.empty()) {
517 using CLI::detail::lexical_cast;
518 bool converted = lexical_cast(input, num);
519 if(!converted) {
520 return std::string("Value ") + input + " could not be converted to " + detail::type_name<Number>();
521 }
522 // perform safe multiplication
523 bool ok = detail::checked_multiply(num, it->second);
524 if(!ok) {
525 return detail::to_string(num) + " multiplied by " + unit +
526 " factor would cause number overflow. Use smaller value.";
527 }
528 } else {
529 num = static_cast<Number>(it->second);
530 }
531
532 input = detail::to_string(num);
533
534 return {};
535 };
536 }
537
538 private:
541 template <typename Number> static void validate_mapping(std::map<std::string, Number> &mapping, Options opts) {
542 for(auto &kv : mapping) {
543 if(kv.first.empty()) {
544 throw ValidationError("Unit must not be empty.");
545 }
546 if(!detail::isalpha(kv.first)) {
547 throw ValidationError("Unit must contain only letters.");
548 }
549 }
550
551 // make all units lowercase if CASE_INSENSITIVE
552 if(opts & CASE_INSENSITIVE) {
553 std::map<std::string, Number> lower_mapping;
554 for(auto &kv : mapping) {
555 auto s = detail::to_lower(kv.first);
556 if(lower_mapping.count(s)) {
557 throw ValidationError(std::string("Several matching lowercase unit representations are found: ") +
558 s);
559 }
560 lower_mapping[std::move(s)] = kv.second;
561 }
562 mapping = std::move(lower_mapping);
563 }
564 }
565
567 template <typename Number> static std::string generate_description(const std::string &name, Options opts) {
568 std::stringstream out;
569 out << detail::type_name<Number>() << ' ';
570 if(opts & UNIT_REQUIRED) {
571 out << name;
572 } else {
573 out << '[' << name << ']';
574 }
575 return out.str();
576 }
577};
578
580 return static_cast<AsNumberWithUnit::Options>(static_cast<int>(a) | static_cast<int>(b));
581}
582
594class AsSizeValue : public AsNumberWithUnit {
595 public:
596 using result_t = std::uint64_t;
597
605 explicit AsSizeValue(bool kb_is_1000);
606
607 private:
609 static std::map<std::string, result_t> init_mapping(bool kb_is_1000);
610
612 static const std::map<std::string, result_t> &get_mapping(bool kb_is_1000);
613};
614
615#if defined(CLI11_ENABLE_EXTRA_VALIDATORS) && CLI11_ENABLE_EXTRA_VALIDATORS != 0
616// new extra validators
617#if CLI11_HAS_FILESYSTEM
618namespace detail {
619enum class Permission : std::uint8_t { none = 0, read = 1, write = 2, exec = 4 };
620class PermissionValidator : public Validator {
621 public:
622 explicit PermissionValidator(Permission permission);
623};
624} // namespace detail
625
626class FileSizeValidator : public Validator {
627 public:
628 explicit FileSizeValidator(std::uint64_t min_size, std::uint64_t max_size = 0);
629};
630
632CLI11_MODULE_INLINE const detail::PermissionValidator ReadPermissions(detail::Permission::read);
633
635CLI11_MODULE_INLINE const detail::PermissionValidator WritePermissions(detail::Permission::write);
636
638CLI11_MODULE_INLINE const detail::PermissionValidator ExecPermissions(detail::Permission::exec);
639
641CLI11_MODULE_INLINE const FileSizeValidator NonEmptyFile(1, 0);
642#endif
643
644#endif
645// [CLI11:extra_validators_hpp:end]
646} // namespace CLI
647
648#ifndef CLI11_COMPILE
649#include "impl/ExtraValidators_inl.hpp" // IWYU pragma: export
650#endif
651
652#endif
Definition ExtraValidators.hpp:451
Options
Definition ExtraValidators.hpp:457
AsSizeValue(bool kb_is_1000)
Definition ExtraValidators_inl.hpp:60
Bound(T min_val, T max_val)
Definition ExtraValidators.hpp:74
Bound(T max_val)
Range of one value is 0 to value.
Definition ExtraValidators.hpp:105
CheckedTransformer(T mapping)
direct map of std::string to std::string
Definition ExtraValidators.hpp:356
CheckedTransformer(T &&mapping, 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.
Definition ExtraValidators.hpp:420
CheckedTransformer(std::initializer_list< std::pair< std::string, std::string > > values, Args &&...args)
This allows in-place construction.
Definition ExtraValidators.hpp:352
CheckedTransformer(T mapping, F filter_function)
Definition ExtraValidators.hpp:360
IsMember(T &&set)
This checks to see if an item is in a set (empty function).
Definition ExtraValidators.hpp:221
IsMember(T set, F filter_function)
Definition ExtraValidators.hpp:225
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 ExtraValidators.hpp:273
IsMember(std::initializer_list< T > values, Args &&...args)
This allows in-place construction using an initializer list.
Definition ExtraValidators.hpp:217
Transformer(T &&mapping, 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.
Definition ExtraValidators.hpp:338
Transformer(std::initializer_list< std::pair< std::string, std::string > > values, Args &&...args)
This allows in-place construction.
Definition ExtraValidators.hpp:290
Transformer(T &&mapping)
direct map of std::string to std::string
Definition ExtraValidators.hpp:294
Transformer(T mapping, F filter_function)
Definition ExtraValidators.hpp:298
Validate the input as a particular type.
Definition ExtraValidators.hpp:50
Thrown when validation of results fails.
Definition Error.hpp:222
Some validators that are provided.
Definition Validators.hpp:55
Validator & description(std::string validator_desc)
Specify the type string.
Definition Validators.hpp:96
Validator & name(std::string validator_name)
Specify the type string.
Definition Validators.hpp:106
std::function< std::string()> desc_function_
This is the description function, if empty the description_ will be used.
Definition Validators.hpp:58
std::function< std::string(std::string &)> func_
Definition Validators.hpp:62
Definition ExtraValidators.hpp:161
Adaptor for set-like structure: This just wraps a normal container in a few utilities that do almost ...
Definition TypeTools.hpp:137
static auto second(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the second value (really just the underlying value).
Definition TypeTools.hpp:147
static auto first(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the first value (really just the underlying value).
Definition TypeTools.hpp:143