PointCloudCrafter
Loading...
Searching...
No Matches
CLI11.hpp
1// CLI11: Version 2.3.1
2// Originally designed by Henry Schreiner
3// https://github.com/CLIUtils/CLI11
4//
5// This is a standalone header file generated by MakeSingleHeader.py in CLI11/scripts
6// from: v2.3.1
7//
8// CLI11 2.3.1 Copyright (c) 2017-2022 University of Cincinnati, developed by Henry
9// Schreiner under NSF AWARD 1414736. All rights reserved.
10//
11// Redistribution and use in source and binary forms of CLI11, with or without
12// modification, are permitted provided that the following conditions are met:
13//
14// 1. Redistributions of source code must retain the above copyright notice, this
15// list of conditions and the following disclaimer.
16// 2. Redistributions in binary form must reproduce the above copyright notice,
17// this list of conditions and the following disclaimer in the documentation
18// and/or other materials provided with the distribution.
19// 3. Neither the name of the copyright holder nor the names of its contributors
20// may be used to endorse or promote products derived from this software without
21// specific prior written permission.
22//
23// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
27// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
30// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
34#pragma once
35
36// Standard combined includes:
37#include <algorithm>
38#include <cmath>
39#include <cstdint>
40#include <exception>
41#include <fstream>
42#include <functional>
43#include <iomanip>
44#include <iostream>
45#include <iterator>
46#include <limits>
47#include <locale>
48#include <map>
49#include <memory>
50#include <numeric>
51#include <set>
52#include <sstream>
53#include <stdexcept>
54#include <string>
55#include <tuple>
56#include <type_traits>
57#include <utility>
58#include <vector>
59
60#define CLI11_VERSION_MAJOR 2
61#define CLI11_VERSION_MINOR 3
62#define CLI11_VERSION_PATCH 1
63#define CLI11_VERSION "2.3.1"
64
65// The following version macro is very similar to the one in pybind11
66#if !(defined(_MSC_VER) && __cplusplus == 199711L) && !defined(__INTEL_COMPILER)
67#if __cplusplus >= 201402L
68#define CLI11_CPP14
69#if __cplusplus >= 201703L
70#define CLI11_CPP17
71#if __cplusplus > 201703L
72#define CLI11_CPP20
73#endif
74#endif
75#endif
76#elif defined(_MSC_VER) && __cplusplus == 199711L
77// MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully implemented)
78// Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 or newer
79#if _MSVC_LANG >= 201402L
80#define CLI11_CPP14
81#if _MSVC_LANG > 201402L && _MSC_VER >= 1910
82#define CLI11_CPP17
83#if _MSVC_LANG > 201703L && _MSC_VER >= 1910
84#define CLI11_CPP20
85#endif
86#endif
87#endif
88#endif
89
90#if defined(CLI11_CPP14)
91#define CLI11_DEPRECATED(reason) [[deprecated(reason)]]
92#elif defined(_MSC_VER)
93#define CLI11_DEPRECATED(reason) __declspec(deprecated(reason))
94#else
95#define CLI11_DEPRECATED(reason) __attribute__((deprecated(reason)))
96#endif
97
98// GCC < 10 doesn't ignore this in unevaluated contexts
99#if !defined(CLI11_CPP17) || (defined(__GNUC__) && !defined(__llvm__) && \
100 !defined(__INTEL_COMPILER) && __GNUC__ < 10 && __GNUC__ > 4)
101#define CLI11_NODISCARD
102#else
103#define CLI11_NODISCARD [[nodiscard]]
104#endif
105
107#ifndef CLI11_USE_STATIC_RTTI
108#if (defined(_HAS_STATIC_RTTI) && _HAS_STATIC_RTTI)
109#define CLI11_USE_STATIC_RTTI 1
110#elif defined(__cpp_rtti)
111#if (defined(_CPPRTTI) && _CPPRTTI == 0)
112#define CLI11_USE_STATIC_RTTI 1
113#else
114#define CLI11_USE_STATIC_RTTI 0
115#endif
116#elif (defined(__GCC_RTTI) && __GXX_RTTI)
117#define CLI11_USE_STATIC_RTTI 0
118#else
119#define CLI11_USE_STATIC_RTTI 1
120#endif
121#endif
122
124#ifdef CLI11_COMPILE
125#define CLI11_INLINE
126#else
127#define CLI11_INLINE inline
128#endif
129
130// C standard library
131// Only needed for existence checking
132#if defined CLI11_CPP17 && defined __has_include && !defined CLI11_HAS_FILESYSTEM
133#if __has_include(<filesystem>)
134// Filesystem cannot be used if targeting macOS < 10.15
135#if defined __MAC_OS_X_VERSION_MIN_REQUIRED && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500
136#define CLI11_HAS_FILESYSTEM 0
137#elif defined(__wasi__)
138// As of wasi-sdk-14, filesystem is not implemented
139#define CLI11_HAS_FILESYSTEM 0
140#else
141#include <filesystem>
142#if defined __cpp_lib_filesystem && __cpp_lib_filesystem >= 201703
143#if defined _GLIBCXX_RELEASE && _GLIBCXX_RELEASE >= 9
144#define CLI11_HAS_FILESYSTEM 1
145#elif defined(__GLIBCXX__)
146// if we are using gcc and Version <9 default to no filesystem
147#define CLI11_HAS_FILESYSTEM 0
148#else
149#define CLI11_HAS_FILESYSTEM 1
150#endif
151#else
152#define CLI11_HAS_FILESYSTEM 0
153#endif
154#endif
155#endif
156#endif
157
158#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
159#include <filesystem> // NOLINT(build/include)
160#else
161#include <sys/stat.h>
162#include <sys/types.h>
163#endif
164
165namespace CLI {
166
169namespace enums {
170
172template <typename T, typename = typename std::enable_if<std::is_enum<T>::value>::type>
173std::ostream &operator<<(std::ostream &in, const T &item) {
174 // make sure this is out of the detail namespace otherwise it won't be found when needed
175 return in << static_cast<typename std::underlying_type<T>::type>(item);
176}
177
178} // namespace enums
179
181using enums::operator<<;
182
183namespace detail {
186constexpr int expected_max_vector_size{1 << 29};
187// Based on http://stackoverflow.com/questions/236129/split-a-string-in-c
189CLI11_INLINE std::vector<std::string> split(const std::string &s, char delim);
190
192template <typename T>
193std::string join(const T &v, std::string delim = ",") {
194 std::ostringstream s;
195 auto beg = std::begin(v);
196 auto end = std::end(v);
197 if (beg != end) s << *beg++;
198 while (beg != end) {
199 s << delim << *beg++;
200 }
201 return s.str();
202}
203
205template <
206 typename T,
207 typename Callable,
208 typename = typename std::enable_if<!std::is_constructible<std::string, Callable>::value>::type>
209std::string join(const T &v, Callable func, std::string delim = ",") {
210 std::ostringstream s;
211 auto beg = std::begin(v);
212 auto end = std::end(v);
213 auto loc = s.tellp();
214 while (beg != end) {
215 auto nloc = s.tellp();
216 if (nloc > loc) {
217 s << delim;
218 loc = nloc;
219 }
220 s << func(*beg++);
221 }
222 return s.str();
223}
224
226template <typename T>
227std::string rjoin(const T &v, std::string delim = ",") {
228 std::ostringstream s;
229 for (std::size_t start = 0; start < v.size(); start++) {
230 if (start > 0) s << delim;
231 s << v[v.size() - start - 1];
232 }
233 return s.str();
234}
235
236// Based roughly on http://stackoverflow.com/questions/25829143/c-trim-whitespace-from-a-string
237
239CLI11_INLINE std::string &ltrim(std::string &str);
240
242CLI11_INLINE std::string &ltrim(std::string &str, const std::string &filter);
243
245CLI11_INLINE std::string &rtrim(std::string &str);
246
248CLI11_INLINE std::string &rtrim(std::string &str, const std::string &filter);
249
251inline std::string &trim(std::string &str) { return ltrim(rtrim(str)); }
252
254inline std::string &trim(std::string &str, const std::string filter) {
255 return ltrim(rtrim(str, filter), filter);
256}
257
259inline std::string trim_copy(const std::string &str) {
260 std::string s = str;
261 return trim(s);
262}
263
265CLI11_INLINE std::string &remove_quotes(std::string &str);
266
271CLI11_INLINE std::string fix_newlines(const std::string &leader, std::string input);
272
275inline std::string trim_copy(const std::string &str, const std::string &filter) {
276 std::string s = str;
277 return trim(s, filter);
278}
280CLI11_INLINE std::ostream &format_help(std::ostream &out,
281 std::string name,
282 const std::string &description,
283 std::size_t wid);
284
286CLI11_INLINE std::ostream &format_aliases(std::ostream &out,
287 const std::vector<std::string> &aliases,
288 std::size_t wid);
289
293template <typename T>
294bool valid_first_char(T c) {
295 return ((c != '-') && (c != '!') && (c != ' ') && c != '\n');
296}
297
299template <typename T>
300bool valid_later_char(T c) {
301 // = and : are value separators, { has special meaning for option defaults,
302 // and \n would just be annoying to deal with in many places allowing space here has too much
303 // potential for inadvertent entry errors and bugs
304 return ((c != '=') && (c != ':') && (c != '{') && (c != ' ') && c != '\n');
305}
306
308CLI11_INLINE bool valid_name_string(const std::string &str);
309
311inline bool valid_alias_name_string(const std::string &str) {
312 static const std::string badChars(std::string("\n") + '\0');
313 return (str.find_first_of(badChars) == std::string::npos);
314}
315
317inline bool is_separator(const std::string &str) {
318 static const std::string sep("%%");
319 return (str.empty() || str == sep);
320}
321
323inline bool isalpha(const std::string &str) {
324 return std::all_of(str.begin(), str.end(),
325 [](char c) { return std::isalpha(c, std::locale()); });
326}
327
329inline std::string to_lower(std::string str) {
330 std::transform(std::begin(str), std::end(str), std::begin(str),
331 [](const std::string::value_type &x) { return std::tolower(x, std::locale()); });
332 return str;
333}
334
336inline std::string remove_underscore(std::string str) {
337 str.erase(std::remove(std::begin(str), std::end(str), '_'), std::end(str));
338 return str;
339}
340
342CLI11_INLINE std::string find_and_replace(std::string str, std::string from, std::string to);
343
345inline bool has_default_flag_values(const std::string &flags) {
346 return (flags.find_first_of("{!") != std::string::npos);
347}
348
349CLI11_INLINE void remove_default_flag_values(std::string &flags);
350
353CLI11_INLINE std::ptrdiff_t find_member(std::string name,
354 const std::vector<std::string> names,
355 bool ignore_case = false,
356 bool ignore_underscore = false);
357
361template <typename Callable>
362inline std::string find_and_modify(std::string str, std::string trigger, Callable modify) {
363 std::size_t start_pos = 0;
364 while ((start_pos = str.find(trigger, start_pos)) != std::string::npos) {
365 start_pos = modify(str, start_pos);
366 }
367 return str;
368}
369
372CLI11_INLINE std::vector<std::string> split_up(std::string str, char delimiter = '\0');
373
379CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset);
380
382CLI11_INLINE std::string &add_quotes_if_needed(std::string &str);
383
384} // namespace detail
385
386namespace detail {
387CLI11_INLINE std::vector<std::string> split(const std::string &s, char delim) {
388 std::vector<std::string> elems;
389 // Check to see if empty string, give consistent result
390 if (s.empty()) {
391 elems.emplace_back();
392 } else {
393 std::stringstream ss;
394 ss.str(s);
395 std::string item;
396 while (std::getline(ss, item, delim)) {
397 elems.push_back(item);
398 }
399 }
400 return elems;
401}
402
403CLI11_INLINE std::string &ltrim(std::string &str) {
404 auto it = std::find_if(str.begin(), str.end(),
405 [](char ch) { return !std::isspace<char>(ch, std::locale()); });
406 str.erase(str.begin(), it);
407 return str;
408}
409
410CLI11_INLINE std::string &ltrim(std::string &str, const std::string &filter) {
411 auto it = std::find_if(str.begin(), str.end(),
412 [&filter](char ch) { return filter.find(ch) == std::string::npos; });
413 str.erase(str.begin(), it);
414 return str;
415}
416
417CLI11_INLINE std::string &rtrim(std::string &str) {
418 auto it = std::find_if(str.rbegin(), str.rend(),
419 [](char ch) { return !std::isspace<char>(ch, std::locale()); });
420 str.erase(it.base(), str.end());
421 return str;
422}
423
424CLI11_INLINE std::string &rtrim(std::string &str, const std::string &filter) {
425 auto it = std::find_if(str.rbegin(), str.rend(),
426 [&filter](char ch) { return filter.find(ch) == std::string::npos; });
427 str.erase(it.base(), str.end());
428 return str;
429}
430
431CLI11_INLINE std::string &remove_quotes(std::string &str) {
432 if (str.length() > 1 && (str.front() == '"' || str.front() == '\'')) {
433 if (str.front() == str.back()) {
434 str.pop_back();
435 str.erase(str.begin(), str.begin() + 1);
436 }
437 }
438 return str;
439}
440
441CLI11_INLINE std::string fix_newlines(const std::string &leader, std::string input) {
442 std::string::size_type n = 0;
443 while (n != std::string::npos && n < input.size()) {
444 n = input.find('\n', n);
445 if (n != std::string::npos) {
446 input = input.substr(0, n + 1) + leader + input.substr(n + 1);
447 n += leader.size();
448 }
449 }
450 return input;
451}
452
453CLI11_INLINE std::ostream &format_help(std::ostream &out,
454 std::string name,
455 const std::string &description,
456 std::size_t wid) {
457 name = " " + name;
458 out << std::setw(static_cast<int>(wid)) << std::left << name;
459 if (!description.empty()) {
460 if (name.length() >= wid) out << "\n" << std::setw(static_cast<int>(wid)) << "";
461 for (const char c : description) {
462 out.put(c);
463 if (c == '\n') {
464 out << std::setw(static_cast<int>(wid)) << "";
465 }
466 }
467 }
468 out << "\n";
469 return out;
470}
471
472CLI11_INLINE std::ostream &format_aliases(std::ostream &out,
473 const std::vector<std::string> &aliases,
474 std::size_t wid) {
475 if (!aliases.empty()) {
476 out << std::setw(static_cast<int>(wid)) << " aliases: ";
477 bool front = true;
478 for (const auto &alias : aliases) {
479 if (!front) {
480 out << ", ";
481 } else {
482 front = false;
483 }
484 out << detail::fix_newlines(" ", alias);
485 }
486 out << "\n";
487 }
488 return out;
489}
490
491CLI11_INLINE bool valid_name_string(const std::string &str) {
492 if (str.empty() || !valid_first_char(str[0])) {
493 return false;
494 }
495 auto e = str.end();
496 for (auto c = str.begin() + 1; c != e; ++c)
497 if (!valid_later_char(*c)) return false;
498 return true;
499}
500
501CLI11_INLINE std::string find_and_replace(std::string str, std::string from, std::string to) {
502 std::size_t start_pos = 0;
503
504 while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
505 str.replace(start_pos, from.length(), to);
506 start_pos += to.length();
507 }
508
509 return str;
510}
511
512CLI11_INLINE void remove_default_flag_values(std::string &flags) {
513 auto loc = flags.find_first_of('{', 2);
514 while (loc != std::string::npos) {
515 auto finish = flags.find_first_of("},", loc + 1);
516 if ((finish != std::string::npos) && (flags[finish] == '}')) {
517 flags.erase(flags.begin() + static_cast<std::ptrdiff_t>(loc),
518 flags.begin() + static_cast<std::ptrdiff_t>(finish) + 1);
519 }
520 loc = flags.find_first_of('{', loc + 1);
521 }
522 flags.erase(std::remove(flags.begin(), flags.end(), '!'), flags.end());
523}
524
525CLI11_INLINE std::ptrdiff_t find_member(std::string name,
526 const std::vector<std::string> names,
527 bool ignore_case,
528 bool ignore_underscore) {
529 auto it = std::end(names);
530 if (ignore_case) {
531 if (ignore_underscore) {
532 name = detail::to_lower(detail::remove_underscore(name));
533 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
534 return detail::to_lower(detail::remove_underscore(local_name)) == name;
535 });
536 } else {
537 name = detail::to_lower(name);
538 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
539 return detail::to_lower(local_name) == name;
540 });
541 }
542
543 } else if (ignore_underscore) {
544 name = detail::remove_underscore(name);
545 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
546 return detail::remove_underscore(local_name) == name;
547 });
548 } else {
549 it = std::find(std::begin(names), std::end(names), name);
550 }
551
552 return (it != std::end(names)) ? (it - std::begin(names)) : (-1);
553}
554
555CLI11_INLINE std::vector<std::string> split_up(std::string str, char delimiter) {
556 const std::string delims("\'\"`");
557 auto find_ws = [delimiter](char ch) {
558 return (delimiter == '\0') ? std::isspace<char>(ch, std::locale()) : (ch == delimiter);
559 };
560 trim(str);
561
562 std::vector<std::string> output;
563 bool embeddedQuote = false;
564 char keyChar = ' ';
565 while (!str.empty()) {
566 if (delims.find_first_of(str[0]) != std::string::npos) {
567 keyChar = str[0];
568 auto end = str.find_first_of(keyChar, 1);
569 while ((end != std::string::npos) &&
570 (str[end - 1] == '\\')) { // deal with escaped quotes
571 end = str.find_first_of(keyChar, end + 1);
572 embeddedQuote = true;
573 }
574 if (end != std::string::npos) {
575 output.push_back(str.substr(1, end - 1));
576 if (end + 2 < str.size()) {
577 str = str.substr(end + 2);
578 } else {
579 str.clear();
580 }
581
582 } else {
583 output.push_back(str.substr(1));
584 str = "";
585 }
586 } else {
587 auto it = std::find_if(std::begin(str), std::end(str), find_ws);
588 if (it != std::end(str)) {
589 std::string value = std::string(str.begin(), it);
590 output.push_back(value);
591 str = std::string(it + 1, str.end());
592 } else {
593 output.push_back(str);
594 str = "";
595 }
596 }
597 // transform any embedded quotes into the regular character
598 if (embeddedQuote) {
599 output.back() = find_and_replace(output.back(), std::string("\\") + keyChar,
600 std::string(1, keyChar));
601 embeddedQuote = false;
602 }
603 trim(str);
604 }
605 return output;
606}
607
608CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset) {
609 auto next = str[offset + 1];
610 if ((next == '\"') || (next == '\'') || (next == '`')) {
611 auto astart = str.find_last_of("-/ \"\'`", offset - 1);
612 if (astart != std::string::npos) {
613 if (str[astart] == ((str[offset] == '=') ? '-' : '/'))
614 str[offset] = ' '; // interpret this as a space so the split_up works properly
615 }
616 }
617 return offset + 1;
618}
619
620CLI11_INLINE std::string &add_quotes_if_needed(std::string &str) {
621 if ((str.front() != '"' && str.front() != '\'') || str.front() != str.back()) {
622 char quote = str.find('"') < str.find('\'') ? '\'' : '"';
623 if (str.find(' ') != std::string::npos) {
624 str.insert(0, 1, quote);
625 str.append(1, quote);
626 }
627 }
628 return str;
629}
630
631} // namespace detail
632
633// Use one of these on all error classes.
634// These are temporary and are undef'd at the end of this file.
635#define CLI11_ERROR_DEF(parent, name) \
636protected: \
637 name(std::string ename, std::string msg, int exit_code) \
638 : parent(std::move(ename), std::move(msg), exit_code) {} \
639 name(std::string ename, std::string msg, ExitCodes exit_code) \
640 : parent(std::move(ename), std::move(msg), exit_code) {} \
641 \
642public: \
643 name(std::string msg, ExitCodes exit_code) : parent(#name, std::move(msg), exit_code) {} \
644 name(std::string msg, int exit_code) : parent(#name, std::move(msg), exit_code) {}
645
646// This is added after the one above if a class is used directly and builds its own message
647#define CLI11_ERROR_SIMPLE(name) \
648 explicit name(std::string msg) : name(#name, msg, ExitCodes::name) {}
649
652enum class ExitCodes {
653 Success = 0,
657 FileError,
669 BaseClass = 127
670};
671
672// Error definitions
673
679
681class Error : public std::runtime_error {
682 int actual_exit_code;
683 std::string error_name{"Error"};
684
685public:
686 CLI11_NODISCARD int get_exit_code() const { return actual_exit_code; }
687
688 CLI11_NODISCARD std::string get_name() const { return error_name; }
689
690 Error(std::string name, std::string msg, int exit_code = static_cast<int>(ExitCodes::BaseClass))
691 : runtime_error(msg), actual_exit_code(exit_code), error_name(std::move(name)) {}
692
693 Error(std::string name, std::string msg, ExitCodes exit_code)
694 : Error(name, msg, static_cast<int>(exit_code)) {}
695};
696
697// Note: Using Error::Error constructors does not work on GCC 4.7
698
700class ConstructionError : public Error {
701 CLI11_ERROR_DEF(Error, ConstructionError)
702};
703
707 CLI11_ERROR_SIMPLE(IncorrectConstruction)
708 static IncorrectConstruction PositionalFlag(std::string name) {
709 return IncorrectConstruction(name + ": Flags cannot be positional");
710 }
711 static IncorrectConstruction Set0Opt(std::string name) {
712 return IncorrectConstruction(name + ": Cannot set 0 expected, use a flag instead");
713 }
714 static IncorrectConstruction SetFlag(std::string name) {
715 return IncorrectConstruction(name + ": Cannot set an expected number for flags");
716 }
717 static IncorrectConstruction ChangeNotVector(std::string name) {
718 return IncorrectConstruction(name +
719 ": You can only change the expected arguments for vectors");
720 }
721 static IncorrectConstruction AfterMultiOpt(std::string name) {
723 name +
724 ": You can't change expected arguments after you've changed the multi option policy!");
725 }
726 static IncorrectConstruction MissingOption(std::string name) {
727 return IncorrectConstruction("Option " + name + " is not defined");
728 }
729 static IncorrectConstruction MultiOptionPolicy(std::string name) {
731 name + ": multi_option_policy only works for flags and exact value options");
732 }
733};
734
737 CLI11_ERROR_DEF(ConstructionError, BadNameString)
738 CLI11_ERROR_SIMPLE(BadNameString)
739 static BadNameString OneCharName(std::string name) {
740 return BadNameString("Invalid one char name: " + name);
741 }
742 static BadNameString BadLongName(std::string name) {
743 return BadNameString("Bad long name: " + name);
744 }
745 static BadNameString DashesOnly(std::string name) {
746 return BadNameString("Must have a name, not just dashes: " + name);
747 }
748 static BadNameString MultiPositionalNames(std::string name) {
749 return BadNameString("Only one positional name allowed, remove: " + name);
750 }
751};
752
754class OptionAlreadyAdded : public ConstructionError {
755 CLI11_ERROR_DEF(ConstructionError, OptionAlreadyAdded)
756 explicit OptionAlreadyAdded(std::string name)
757 : OptionAlreadyAdded(name + " is already added", ExitCodes::OptionAlreadyAdded) {}
758 static OptionAlreadyAdded Requires(std::string name, std::string other) {
759 return {name + " requires " + other, ExitCodes::OptionAlreadyAdded};
760 }
761 static OptionAlreadyAdded Excludes(std::string name, std::string other) {
762 return {name + " excludes " + other, ExitCodes::OptionAlreadyAdded};
763 }
764};
765
766// Parsing errors
767
769class ParseError : public Error {
770 CLI11_ERROR_DEF(Error, ParseError)
771};
772
773// Not really "errors"
774
776class Success : public ParseError {
777 CLI11_ERROR_DEF(ParseError, Success)
778 Success() : Success("Successfully completed, should be caught and quit", ExitCodes::Success) {}
779};
780
782class CallForHelp : public Success {
783 CLI11_ERROR_DEF(Success, CallForHelp)
784 CallForHelp()
785 : CallForHelp("This should be caught in your main function, see examples",
786 ExitCodes::Success) {}
787};
788
790class CallForAllHelp : public Success {
791 CLI11_ERROR_DEF(Success, CallForAllHelp)
792 CallForAllHelp()
793 : CallForAllHelp("This should be caught in your main function, see examples",
794 ExitCodes::Success) {}
795};
796
798class CallForVersion : public Success {
799 CLI11_ERROR_DEF(Success, CallForVersion)
800 CallForVersion()
801 : CallForVersion("This should be caught in your main function, see examples",
802 ExitCodes::Success) {}
803};
804
807class RuntimeError : public ParseError {
808 CLI11_ERROR_DEF(ParseError, RuntimeError)
809 explicit RuntimeError(int exit_code = 1) : RuntimeError("Runtime error", exit_code) {}
810};
811
813class FileError : public ParseError {
814 CLI11_ERROR_DEF(ParseError, FileError)
815 CLI11_ERROR_SIMPLE(FileError)
816 static FileError Missing(std::string name) {
817 return FileError(name + " was not readable (missing?)");
818 }
819};
820
822class ConversionError : public ParseError {
823 CLI11_ERROR_DEF(ParseError, ConversionError)
824 CLI11_ERROR_SIMPLE(ConversionError)
825 ConversionError(std::string member, std::string name)
826 : ConversionError("The value " + member + " is not an allowed value for " + name) {}
827 ConversionError(std::string name, std::vector<std::string> results)
828 : ConversionError("Could not convert: " + name + " = " + detail::join(results)) {}
829 static ConversionError TooManyInputsFlag(std::string name) {
830 return ConversionError(name + ": too many inputs for a flag");
831 }
832 static ConversionError TrueFalse(std::string name) {
833 return ConversionError(name + ": Should be true/false or a number");
834 }
835};
836
838class ValidationError : public ParseError {
839 CLI11_ERROR_DEF(ParseError, ValidationError)
840 CLI11_ERROR_SIMPLE(ValidationError)
841 explicit ValidationError(std::string name, std::string msg)
842 : ValidationError(name + ": " + msg) {}
843};
844
846class RequiredError : public ParseError {
847 CLI11_ERROR_DEF(ParseError, RequiredError)
848 explicit RequiredError(std::string name)
849 : RequiredError(name + " is required", ExitCodes::RequiredError) {}
850 static RequiredError Subcommand(std::size_t min_subcom) {
851 if (min_subcom == 1) {
852 return RequiredError("A subcommand");
853 }
854 return {"Requires at least " + std::to_string(min_subcom) + " subcommands",
855 ExitCodes::RequiredError};
856 }
857 static RequiredError Option(std::size_t min_option,
858 std::size_t max_option,
859 std::size_t used,
860 const std::string &option_list) {
861 if ((min_option == 1) && (max_option == 1) && (used == 0))
862 return RequiredError("Exactly 1 option from [" + option_list + "]");
863 if ((min_option == 1) && (max_option == 1) && (used > 1)) {
864 return {"Exactly 1 option from [" + option_list + "] is required and " +
865 std::to_string(used) + " were given",
866 ExitCodes::RequiredError};
867 }
868 if ((min_option == 1) && (used == 0))
869 return RequiredError("At least 1 option from [" + option_list + "]");
870 if (used < min_option) {
871 return {"Requires at least " + std::to_string(min_option) + " options used and only " +
872 std::to_string(used) + "were given from [" + option_list + "]",
873 ExitCodes::RequiredError};
874 }
875 if (max_option == 1)
876 return {"Requires at most 1 options be given from [" + option_list + "]",
877 ExitCodes::RequiredError};
878
879 return {"Requires at most " + std::to_string(max_option) + " options be used and " +
880 std::to_string(used) + "were given from [" + option_list + "]",
881 ExitCodes::RequiredError};
882 }
883};
884
886class ArgumentMismatch : public ParseError {
887 CLI11_ERROR_DEF(ParseError, ArgumentMismatch)
888 CLI11_ERROR_SIMPLE(ArgumentMismatch)
889 ArgumentMismatch(std::string name, int expected, std::size_t received)
890 : ArgumentMismatch(expected > 0
891 ? ("Expected exactly " + std::to_string(expected) +
892 " arguments to " + name + ", got " + std::to_string(received))
893 : ("Expected at least " + std::to_string(-expected) +
894 " arguments to " + name + ", got " + std::to_string(received)),
895 ExitCodes::ArgumentMismatch) {}
896
897 static ArgumentMismatch AtLeast(std::string name, int num, std::size_t received) {
898 return ArgumentMismatch(name + ": At least " + std::to_string(num) +
899 " required but received " + std::to_string(received));
900 }
901 static ArgumentMismatch AtMost(std::string name, int num, std::size_t received) {
902 return ArgumentMismatch(name + ": At Most " + std::to_string(num) +
903 " required but received " + std::to_string(received));
904 }
905 static ArgumentMismatch TypedAtLeast(std::string name, int num, std::string type) {
906 return ArgumentMismatch(name + ": " + std::to_string(num) + " required " + type +
907 " missing");
908 }
909 static ArgumentMismatch FlagOverride(std::string name) {
910 return ArgumentMismatch(name + " was given a disallowed flag override");
911 }
912 static ArgumentMismatch PartialType(std::string name, int num, std::string type) {
913 return ArgumentMismatch(name + ": " + type + " only partially specified: " +
914 std::to_string(num) + " required for each element");
915 }
916};
917
919class RequiresError : public ParseError {
920 CLI11_ERROR_DEF(ParseError, RequiresError)
921 RequiresError(std::string curname, std::string subname)
922 : RequiresError(curname + " requires " + subname, ExitCodes::RequiresError) {}
923};
924
926class ExcludesError : public ParseError {
927 CLI11_ERROR_DEF(ParseError, ExcludesError)
928 ExcludesError(std::string curname, std::string subname)
929 : ExcludesError(curname + " excludes " + subname, ExitCodes::ExcludesError) {}
930};
931
933class ExtrasError : public ParseError {
934 CLI11_ERROR_DEF(ParseError, ExtrasError)
935 explicit ExtrasError(std::vector<std::string> args)
936 : ExtrasError((args.size() > 1 ? "The following arguments were not expected: "
937 : "The following argument was not expected: ") +
938 detail::rjoin(args, " "),
939 ExitCodes::ExtrasError) {}
940 ExtrasError(const std::string &name, std::vector<std::string> args)
941 : ExtrasError(name,
942 (args.size() > 1 ? "The following arguments were not expected: "
943 : "The following argument was not expected: ") +
944 detail::rjoin(args, " "),
945 ExitCodes::ExtrasError) {}
946};
947
949class ConfigError : public ParseError {
950 CLI11_ERROR_DEF(ParseError, ConfigError)
951 CLI11_ERROR_SIMPLE(ConfigError)
952 static ConfigError Extras(std::string item) {
953 return ConfigError("INI was not able to parse " + item);
954 }
955 static ConfigError NotConfigurable(std::string item) {
956 return ConfigError(item + ": This option is not allowed in a configuration file");
957 }
958};
959
961class InvalidError : public ParseError {
962 CLI11_ERROR_DEF(ParseError, InvalidError)
963 explicit InvalidError(std::string name)
964 : InvalidError(name + ": Too many positional arguments with unlimited expected args",
965 ExitCodes::InvalidError) {}
966};
967
970class HorribleError : public ParseError {
971 CLI11_ERROR_DEF(ParseError, HorribleError)
972 CLI11_ERROR_SIMPLE(HorribleError)
973};
974
975// After parsing
976
978class OptionNotFound : public Error {
979 CLI11_ERROR_DEF(Error, OptionNotFound)
980 explicit OptionNotFound(std::string name)
981 : OptionNotFound(name + " not found", ExitCodes::OptionNotFound) {}
982};
983
984#undef CLI11_ERROR_DEF
985#undef CLI11_ERROR_SIMPLE
986
988
989// Type tools
990
991// Utilities for type enabling
992namespace detail {
993// Based generally on https://rmf.io/cxx11/almost-static-if
995enum class enabler {};
996
998constexpr enabler dummy = {};
999} // namespace detail
1000
1006template <bool B, class T = void>
1007using enable_if_t = typename std::enable_if<B, T>::type;
1008
1010template <typename... Ts>
1012 using type = void;
1013};
1014
1016template <typename... Ts>
1017using void_t = typename make_void<Ts...>::type;
1018
1021template <bool B, class T, class F>
1022using conditional_t = typename std::conditional<B, T, F>::type;
1023
1025template <typename T>
1026struct is_bool : std::false_type {};
1027
1029template <>
1030struct is_bool<bool> : std::true_type {};
1031
1033template <typename T>
1034struct is_shared_ptr : std::false_type {};
1035
1037template <typename T>
1038struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
1039
1041template <typename T>
1042struct is_shared_ptr<const std::shared_ptr<T>> : std::true_type {};
1043
1045template <typename T>
1047 static bool const value = is_shared_ptr<T>::value || std::is_pointer<T>::value;
1048};
1049
1051template <typename T>
1053 using type = T;
1054};
1055
1057template <>
1058struct IsMemberType<const char *> {
1059 using type = std::string;
1060};
1061
1062namespace detail {
1063
1064// These are utilities for IsMember and other transforming objects
1065
1068
1070template <typename T, typename Enable = void>
1072 using type = T;
1073};
1074
1075template <typename T>
1076struct element_type<T, typename std::enable_if<is_copyable_ptr<T>::value>::type> {
1077 using type = typename std::pointer_traits<T>::element_type;
1078};
1079
1082template <typename T>
1084 using type = typename element_type<T>::type::value_type;
1085};
1086
1089template <typename T, typename _ = void>
1090struct pair_adaptor : std::false_type {
1091 using value_type = typename T::value_type;
1092 using first_type = typename std::remove_const<value_type>::type;
1093 using second_type = typename std::remove_const<value_type>::type;
1094
1096 template <typename Q>
1097 static auto first(Q &&pair_value) -> decltype(std::forward<Q>(pair_value)) {
1098 return std::forward<Q>(pair_value);
1099 }
1100
1101 template <typename Q>
1102 static auto second(Q &&pair_value) -> decltype(std::forward<Q>(pair_value)) {
1103 return std::forward<Q>(pair_value);
1104 }
1105};
1106
1109template <typename T>
1111 T,
1112 conditional_t<false,
1113 void_t<typename T::value_type::first_type, typename T::value_type::second_type>,
1114 void>> : std::true_type {
1115 using value_type = typename T::value_type;
1116 using first_type = typename std::remove_const<typename value_type::first_type>::type;
1117 using second_type = typename std::remove_const<typename value_type::second_type>::type;
1118
1120 template <typename Q>
1121 static auto first(Q &&pair_value) -> decltype(std::get<0>(std::forward<Q>(pair_value))) {
1122 return std::get<0>(std::forward<Q>(pair_value));
1123 }
1124
1125 template <typename Q>
1126 static auto second(Q &&pair_value) -> decltype(std::get<1>(std::forward<Q>(pair_value))) {
1127 return std::get<1>(std::forward<Q>(pair_value));
1128 }
1129};
1130
1131// Warning is suppressed due to "bug" in gcc<5.0 and gcc 7.0 with c++17 enabled that generates a
1132// Wnarrowing warning in the unevaluated context even if the function that was using this wasn't
1133// used. The standard says narrowing in brace initialization shouldn't be allowed but for backwards
1134// compatibility gcc allows it in some contexts. It is a little fuzzy what happens in template
1135// constructs and I think that was something GCC took a little while to work out. But regardless
1136// some versions of gcc generate a warning when they shouldn't from the following code so that
1137// should be suppressed
1138#ifdef __GNUC__
1139#pragma GCC diagnostic push
1140#pragma GCC diagnostic ignored "-Wnarrowing"
1141#endif
1142// check for constructibility from a specific type and copy assignable used in the parse detection
1143template <typename T, typename C>
1145 template <typename TT, typename CC>
1146 static auto test(int, std::true_type) -> decltype(
1147// NVCC warns about narrowing conversions here
1148#ifdef __CUDACC__
1149#pragma diag_suppress 2361
1150#endif
1151 TT{std::declval<CC>()}
1152#ifdef __CUDACC__
1153#pragma diag_default 2361
1154#endif
1155 ,
1156 std::is_move_assignable<TT>());
1157
1158 template <typename TT, typename CC>
1159 static auto test(int, std::false_type) -> std::false_type;
1160
1161 template <typename, typename>
1162 static auto test(...) -> std::false_type;
1163
1164public:
1165 static constexpr bool value =
1166 decltype(test<T, C>(0, typename std::is_constructible<T, C>::type()))::value;
1167};
1168#ifdef __GNUC__
1169#pragma GCC diagnostic pop
1170#endif
1171
1172// Check for output streamability
1173// Based on
1174// https://stackoverflow.com/questions/22758291/how-can-i-detect-if-a-type-can-be-streamed-to-an-stdostream
1175
1176template <typename T, typename S = std::ostringstream>
1178 template <typename TT, typename SS>
1179 static auto test(int) -> decltype(std::declval<SS &>() << std::declval<TT>(), std::true_type());
1180
1181 template <typename, typename>
1182 static auto test(...) -> std::false_type;
1183
1184public:
1185 static constexpr bool value = decltype(test<T, S>(0))::value;
1186};
1187
1189template <typename T, typename S = std::istringstream>
1191 template <typename TT, typename SS>
1192 static auto test(int)
1193 -> decltype(std::declval<SS &>() >> std::declval<TT &>(), std::true_type());
1194
1195 template <typename, typename>
1196 static auto test(...) -> std::false_type;
1197
1198public:
1199 static constexpr bool value = decltype(test<T, S>(0))::value;
1200};
1201
1203template <typename T>
1205 template <typename TT>
1206 static auto test(int)
1207 -> decltype(std::declval<TT>().real(), std::declval<TT>().imag(), std::true_type());
1208
1209 template <typename>
1210 static auto test(...) -> std::false_type;
1211
1212public:
1213 static constexpr bool value = decltype(test<T>(0))::value;
1214};
1215
1217template <typename T, enable_if_t<is_istreamable<T>::value, detail::enabler> = detail::dummy>
1218bool from_stream(const std::string &istring, T &obj) {
1219 std::istringstream is;
1220 is.str(istring);
1221 is >> obj;
1222 return !is.fail() && !is.rdbuf()->in_avail();
1223}
1224
1225template <typename T, enable_if_t<!is_istreamable<T>::value, detail::enabler> = detail::dummy>
1226bool from_stream(const std::string & /*istring*/, T & /*obj*/) {
1227 return false;
1228}
1229
1230// check to see if an object is a mutable container (fail by default)
1231template <typename T, typename _ = void>
1232struct is_mutable_container : std::false_type {};
1233
1237template <typename T>
1239 T,
1240 conditional_t<
1241 false,
1242 void_t<typename T::value_type,
1243 decltype(std::declval<T>().end()),
1244 decltype(std::declval<T>().clear()),
1245 decltype(std::declval<T>().insert(std::declval<decltype(std::declval<T>().end())>(),
1246 std::declval<const typename T::value_type &>()))>,
1247 void>> : public conditional_t<std::is_constructible<T, std::string>::value,
1248 std::false_type,
1249 std::true_type> {};
1250
1251// check to see if an object is a mutable container (fail by default)
1252template <typename T, typename _ = void>
1253struct is_readable_container : std::false_type {};
1254
1258template <typename T>
1260 T,
1261 conditional_t<false,
1262 void_t<decltype(std::declval<T>().end()), decltype(std::declval<T>().begin())>,
1263 void>> : public std::true_type {};
1264
1265// check to see if an object is a wrapper (fail by default)
1266template <typename T, typename _ = void>
1267struct is_wrapper : std::false_type {};
1268
1269// check if an object is a wrapper (it has a value_type defined)
1270template <typename T>
1271struct is_wrapper<T, conditional_t<false, void_t<typename T::value_type>, void>>
1272 : public std::true_type {};
1273
1274// Check for tuple like types, as in classes with a tuple_size type trait
1275template <typename S>
1277 template <typename SS>
1278 // static auto test(int)
1279 // -> decltype(std::conditional<(std::tuple_size<SS>::value > 0), std::true_type,
1280 // std::false_type>::type());
1281 static auto test(int)
1282 -> decltype(std::tuple_size<typename std::decay<SS>::type>::value, std::true_type{});
1283 template <typename>
1284 static auto test(...) -> std::false_type;
1285
1286public:
1287 static constexpr bool value = decltype(test<S>(0))::value;
1288};
1289
1291template <typename T,
1292 enable_if_t<std::is_convertible<T, std::string>::value, detail::enabler> = detail::dummy>
1293auto to_string(T &&value) -> decltype(std::forward<T>(value)) {
1294 return std::forward<T>(value);
1295}
1296
1298template <typename T,
1299 enable_if_t<std::is_constructible<std::string, T>::value &&
1300 !std::is_convertible<T, std::string>::value,
1301 detail::enabler> = detail::dummy>
1302std::string to_string(const T &value) {
1303 return std::string(value); // NOLINT(google-readability-casting)
1304}
1305
1307template <typename T,
1308 enable_if_t<!std::is_convertible<std::string, T>::value &&
1309 !std::is_constructible<std::string, T>::value && is_ostreamable<T>::value,
1310 detail::enabler> = detail::dummy>
1311std::string to_string(T &&value) {
1312 std::stringstream stream;
1313 stream << value;
1314 return stream.str();
1315}
1316
1319template <typename T,
1320 enable_if_t<!std::is_constructible<std::string, T>::value && !is_ostreamable<T>::value &&
1322 detail::enabler> = detail::dummy>
1323std::string to_string(T &&) {
1324 return {};
1325}
1326
1328template <typename T,
1329 enable_if_t<!std::is_constructible<std::string, T>::value && !is_ostreamable<T>::value &&
1331 detail::enabler> = detail::dummy>
1332std::string to_string(T &&variable) {
1333 auto cval = variable.begin();
1334 auto end = variable.end();
1335 if (cval == end) {
1336 return {"{}"};
1337 }
1338 std::vector<std::string> defaults;
1339 while (cval != end) {
1340 defaults.emplace_back(CLI::detail::to_string(*cval));
1341 ++cval;
1342 }
1343 return {"[" + detail::join(defaults) + "]"};
1344}
1345
1347template <typename T1,
1348 typename T2,
1349 typename T,
1350 enable_if_t<std::is_same<T1, T2>::value, detail::enabler> = detail::dummy>
1351auto checked_to_string(T &&value) -> decltype(to_string(std::forward<T>(value))) {
1352 return to_string(std::forward<T>(value));
1353}
1354
1356template <typename T1,
1357 typename T2,
1358 typename T,
1359 enable_if_t<!std::is_same<T1, T2>::value, detail::enabler> = detail::dummy>
1360std::string checked_to_string(T &&) {
1361 return std::string{};
1362}
1364template <typename T, enable_if_t<std::is_arithmetic<T>::value, detail::enabler> = detail::dummy>
1365std::string value_string(const T &value) {
1366 return std::to_string(value);
1367}
1369template <typename T, enable_if_t<std::is_enum<T>::value, detail::enabler> = detail::dummy>
1370std::string value_string(const T &value) {
1371 return std::to_string(static_cast<typename std::underlying_type<T>::type>(value));
1372}
1374template <typename T,
1375 enable_if_t<!std::is_enum<T>::value && !std::is_arithmetic<T>::value, detail::enabler> =
1376 detail::dummy>
1377auto value_string(const T &value) -> decltype(to_string(value)) {
1378 return to_string(value);
1379}
1380
1382template <typename T, typename def, typename Enable = void>
1384 using type = def;
1385};
1386
1388template <typename T, typename def>
1389struct wrapped_type<T, def, typename std::enable_if<is_wrapper<T>::value>::type> {
1390 using type = typename T::value_type;
1391};
1392
1394template <typename T, typename Enable = void>
1396 static const int value{0};
1397};
1398
1400template <typename T>
1402 T,
1403 typename std::enable_if<!is_tuple_like<T>::value && !is_mutable_container<T>::value &&
1404 !std::is_void<T>::value>::type> {
1405 static constexpr int value{1};
1406};
1407
1409template <typename T>
1411 T,
1412 typename std::enable_if<is_tuple_like<T>::value && !is_mutable_container<T>::value>::type> {
1413 static constexpr int value{std::tuple_size<T>::value};
1414};
1415
1417template <typename T>
1418struct type_count_base<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1419 static constexpr int value{type_count_base<typename T::value_type>::value};
1420};
1421
1423
1425template <typename T>
1427
1429template <typename T>
1431
1433template <typename T, typename Enable = void>
1435 static const int value{0};
1436};
1437
1439template <typename T>
1440struct type_count<T,
1441 typename std::enable_if<!is_wrapper<T>::value && !is_tuple_like<T>::value &&
1442 !is_complex<T>::value && !std::is_void<T>::value>::type> {
1443 static constexpr int value{1};
1444};
1445
1447template <typename T>
1448struct type_count<T, typename std::enable_if<is_complex<T>::value>::type> {
1449 static constexpr int value{2};
1450};
1451
1454template <typename T>
1455struct type_count<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1456 static constexpr int value{subtype_count<typename T::value_type>::value};
1457};
1458
1461template <typename T>
1463 T,
1464 typename std::enable_if<is_wrapper<T>::value && !is_complex<T>::value &&
1465 !is_tuple_like<T>::value && !is_mutable_container<T>::value>::type> {
1466 static constexpr int value{type_count<typename T::value_type>::value};
1467};
1468
1470template <typename T, std::size_t I>
1471constexpr typename std::enable_if<I == type_count_base<T>::value, int>::type tuple_type_size() {
1472 return 0;
1473}
1474
1476template <typename T, std::size_t I>
1477 constexpr typename std::enable_if < I<type_count_base<T>::value, int>::type tuple_type_size() {
1478 return subtype_count<typename std::tuple_element<I, T>::type>::value +
1479 tuple_type_size<T, I + 1>();
1480}
1481
1483template <typename T>
1484struct type_count<T, typename std::enable_if<is_tuple_like<T>::value>::type> {
1485 static constexpr int value{tuple_type_size<T, 0>()};
1486};
1487
1489template <typename T>
1490struct subtype_count {
1491 static constexpr int value{is_mutable_container<T>::value ? expected_max_vector_size
1492 : type_count<T>::value};
1493};
1494
1496template <typename T, typename Enable = void>
1497struct type_count_min {
1498 static const int value{0};
1499};
1500
1502template <typename T>
1503struct type_count_min<
1504 T,
1505 typename std::enable_if<!is_mutable_container<T>::value && !is_tuple_like<T>::value &&
1506 !is_wrapper<T>::value && !is_complex<T>::value &&
1507 !std::is_void<T>::value>::type> {
1508 static constexpr int value{type_count<T>::value};
1509};
1510
1512template <typename T>
1513struct type_count_min<T, typename std::enable_if<is_complex<T>::value>::type> {
1514 static constexpr int value{1};
1515};
1516
1519template <typename T>
1520struct type_count_min<T,
1521 typename std::enable_if<is_wrapper<T>::value && !is_complex<T>::value &&
1522 !is_tuple_like<T>::value>::type> {
1523 static constexpr int value{subtype_count_min<typename T::value_type>::value};
1524};
1525
1527template <typename T, std::size_t I>
1528constexpr typename std::enable_if<I == type_count_base<T>::value, int>::type tuple_type_size_min() {
1529 return 0;
1530}
1531
1533template <typename T, std::size_t I>
1534 constexpr typename std::enable_if <
1535 I<type_count_base<T>::value, int>::type tuple_type_size_min() {
1537 tuple_type_size_min<T, I + 1>();
1538}
1539
1541template <typename T>
1542struct type_count_min<T, typename std::enable_if<is_tuple_like<T>::value>::type> {
1543 static constexpr int value{tuple_type_size_min<T, 0>()};
1544};
1545
1547template <typename T>
1548struct subtype_count_min {
1549 static constexpr int value{
1550 is_mutable_container<T>::value
1551 ? ((type_count<T>::value < expected_max_vector_size) ? type_count<T>::value : 0)
1552 : type_count_min<T>::value};
1553};
1554
1556template <typename T, typename Enable = void>
1557struct expected_count {
1558 static const int value{0};
1559};
1560
1562template <typename T>
1563struct expected_count<
1564 T,
1565 typename std::enable_if<!is_mutable_container<T>::value && !is_wrapper<T>::value &&
1566 !std::is_void<T>::value>::type> {
1567 static constexpr int value{1};
1568};
1570template <typename T>
1571struct expected_count<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1572 static constexpr int value{expected_max_vector_size};
1573};
1574
1576template <typename T>
1577struct expected_count<
1578 T,
1579 typename std::enable_if<!is_mutable_container<T>::value && is_wrapper<T>::value>::type> {
1580 static constexpr int value{expected_count<typename T::value_type>::value};
1581};
1582
1583// Enumeration of the different supported categorizations of objects
1584enum class object_category : int {
1585 char_value = 1,
1586 integral_value = 2,
1587 unsigned_integral = 4,
1588 enumeration = 6,
1589 boolean_value = 8,
1590 floating_point = 10,
1591 number_constructible = 12,
1592 double_constructible = 14,
1593 integer_constructible = 16,
1594 // string like types
1595 string_assignable = 23,
1596 string_constructible = 24,
1597 other = 45,
1598 // special wrapper or container types
1599 wrapper_value = 50,
1600 complex_number = 60,
1601 tuple_value = 70,
1602 container_value = 80,
1603
1604};
1605
1607
1609template <typename T, typename Enable = void>
1610struct classify_object {
1611 static constexpr object_category value{object_category::other};
1612};
1613
1615template <typename T>
1616struct classify_object<
1617 T,
1618 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, char>::value &&
1619 std::is_signed<T>::value && !is_bool<T>::value &&
1620 !std::is_enum<T>::value>::type> {
1621 static constexpr object_category value{object_category::integral_value};
1622};
1623
1625template <typename T>
1626struct classify_object<
1627 T,
1628 typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value &&
1629 !std::is_same<T, char>::value && !is_bool<T>::value>::type> {
1630 static constexpr object_category value{object_category::unsigned_integral};
1631};
1632
1634template <typename T>
1635struct classify_object<
1636 T,
1637 typename std::enable_if<std::is_same<T, char>::value && !std::is_enum<T>::value>::type> {
1638 static constexpr object_category value{object_category::char_value};
1639};
1640
1642template <typename T>
1643struct classify_object<T, typename std::enable_if<is_bool<T>::value>::type> {
1644 static constexpr object_category value{object_category::boolean_value};
1645};
1646
1648template <typename T>
1649struct classify_object<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
1650 static constexpr object_category value{object_category::floating_point};
1651};
1652
1654template <typename T>
1655struct classify_object<
1656 T,
1657 typename std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1658 std::is_assignable<T &, std::string>::value>::type> {
1659 static constexpr object_category value{object_category::string_assignable};
1660};
1661
1663template <typename T>
1664struct classify_object<
1665 T,
1666 typename std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1667 !std::is_assignable<T &, std::string>::value &&
1668 (type_count<T>::value == 1) &&
1669 std::is_constructible<T, std::string>::value>::type> {
1670 static constexpr object_category value{object_category::string_constructible};
1671};
1672
1674template <typename T>
1675struct classify_object<T, typename std::enable_if<std::is_enum<T>::value>::type> {
1676 static constexpr object_category value{object_category::enumeration};
1677};
1678
1679template <typename T>
1680struct classify_object<T, typename std::enable_if<is_complex<T>::value>::type> {
1681 static constexpr object_category value{object_category::complex_number};
1682};
1683
1686template <typename T>
1687struct uncommon_type {
1688 using type = typename std::conditional<
1689 !std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1690 !std::is_assignable<T &, std::string>::value &&
1691 !std::is_constructible<T, std::string>::value && !is_complex<T>::value &&
1692 !is_mutable_container<T>::value && !std::is_enum<T>::value,
1693 std::true_type,
1694 std::false_type>::type;
1695 static constexpr bool value = type::value;
1696};
1697
1699template <typename T>
1700struct classify_object<
1701 T,
1702 typename std::enable_if<(!is_mutable_container<T>::value && is_wrapper<T>::value &&
1703 !is_tuple_like<T>::value && uncommon_type<T>::value)>::type> {
1704 static constexpr object_category value{object_category::wrapper_value};
1705};
1706
1708template <typename T>
1709struct classify_object<
1710 T,
1711 typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1712 !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
1713 is_direct_constructible<T, int>::value>::type> {
1714 static constexpr object_category value{object_category::number_constructible};
1715};
1716
1718template <typename T>
1719struct classify_object<
1720 T,
1721 typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1722 !is_wrapper<T>::value && !is_direct_constructible<T, double>::value &&
1723 is_direct_constructible<T, int>::value>::type> {
1724 static constexpr object_category value{object_category::integer_constructible};
1725};
1726
1728template <typename T>
1729struct classify_object<
1730 T,
1731 typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1732 !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
1733 !is_direct_constructible<T, int>::value>::type> {
1734 static constexpr object_category value{object_category::double_constructible};
1735};
1736
1738template <typename T>
1739struct classify_object<
1740 T,
1741 typename std::enable_if<is_tuple_like<T>::value &&
1742 ((type_count<T>::value >= 2 && !is_wrapper<T>::value) ||
1743 (uncommon_type<T>::value &&
1744 !is_direct_constructible<T, double>::value &&
1745 !is_direct_constructible<T, int>::value) ||
1746 (uncommon_type<T>::value && type_count<T>::value >= 2))>::type> {
1747 static constexpr object_category value{object_category::tuple_value};
1748 // the condition on this class requires it be like a tuple, but on some compilers (like Xcode)
1749 // tuples can be constructed from just the first element so tuples of <string, int,int> can be
1750 // constructed from a string, which could lead to issues so there are two variants of the
1751 // condition, the first isolates things with a type size >=2 mainly to get tuples on Xcode with
1752 // the exception of wrappers, the second is the main one and just separating out those cases
1753 // that are caught by other object classifications
1754};
1755
1757template <typename T>
1758struct classify_object<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1759 static constexpr object_category value{object_category::container_value};
1760};
1761
1762// Type name print
1763
1767
1768template <typename T,
1769 enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> =
1770 detail::dummy>
1771constexpr const char *type_name() {
1772 return "CHAR";
1773}
1774
1775template <typename T,
1776 enable_if_t<classify_object<T>::value == object_category::integral_value ||
1777 classify_object<T>::value == object_category::integer_constructible,
1778 detail::enabler> = detail::dummy>
1779constexpr const char *type_name() {
1780 return "INT";
1781}
1782
1783template <typename T,
1784 enable_if_t<classify_object<T>::value == object_category::unsigned_integral,
1785 detail::enabler> = detail::dummy>
1786constexpr const char *type_name() {
1787 return "UINT";
1788}
1789
1790template <typename T,
1791 enable_if_t<classify_object<T>::value == object_category::floating_point ||
1792 classify_object<T>::value == object_category::number_constructible ||
1793 classify_object<T>::value == object_category::double_constructible,
1794 detail::enabler> = detail::dummy>
1795constexpr const char *type_name() {
1796 return "FLOAT";
1797}
1798
1800template <typename T,
1801 enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> =
1802 detail::dummy>
1803constexpr const char *type_name() {
1804 return "ENUM";
1805}
1806
1808template <typename T,
1809 enable_if_t<classify_object<T>::value == object_category::boolean_value,
1810 detail::enabler> = detail::dummy>
1811constexpr const char *type_name() {
1812 return "BOOLEAN";
1813}
1814
1816template <typename T,
1817 enable_if_t<classify_object<T>::value == object_category::complex_number,
1818 detail::enabler> = detail::dummy>
1819constexpr const char *type_name() {
1820 return "COMPLEX";
1821}
1822
1824template <typename T,
1825 enable_if_t<classify_object<T>::value >= object_category::string_assignable &&
1826 classify_object<T>::value <= object_category::other,
1827 detail::enabler> = detail::dummy>
1828constexpr const char *type_name() {
1829 return "TEXT";
1830}
1832template <typename T,
1833 enable_if_t<classify_object<T>::value == object_category::tuple_value &&
1834 type_count_base<T>::value >= 2,
1835 detail::enabler> = detail::dummy>
1836std::string type_name(); // forward declaration
1837
1839template <typename T,
1840 enable_if_t<classify_object<T>::value == object_category::container_value ||
1841 classify_object<T>::value == object_category::wrapper_value,
1842 detail::enabler> = detail::dummy>
1843std::string type_name(); // forward declaration
1844
1846template <typename T,
1847 enable_if_t<classify_object<T>::value == object_category::tuple_value &&
1848 type_count_base<T>::value == 1,
1849 detail::enabler> = detail::dummy>
1850inline std::string type_name() {
1851 return type_name<typename std::decay<typename std::tuple_element<0, T>::type>::type>();
1852}
1853
1855template <typename T, std::size_t I>
1856inline typename std::enable_if<I == type_count_base<T>::value, std::string>::type tuple_name() {
1857 return std::string{};
1858}
1859
1861template <typename T, std::size_t I>
1862inline typename std::enable_if<(I < type_count_base<T>::value), std::string>::type tuple_name() {
1863 auto str =
1864 std::string{
1865 type_name<typename std::decay<typename std::tuple_element<I, T>::type>::type>()} +
1866 ',' + tuple_name<T, I + 1>();
1867 if (str.back() == ',') str.pop_back();
1868 return str;
1869}
1870
1872template <typename T,
1873 enable_if_t<classify_object<T>::value == object_category::tuple_value &&
1874 type_count_base<T>::value >= 2,
1875 detail::enabler>>
1876inline std::string type_name() {
1877 auto tname = std::string(1, '[') + tuple_name<T, 0>();
1878 tname.push_back(']');
1879 return tname;
1880}
1881
1883template <typename T,
1884 enable_if_t<classify_object<T>::value == object_category::container_value ||
1885 classify_object<T>::value == object_category::wrapper_value,
1886 detail::enabler>>
1887inline std::string type_name() {
1888 return type_name<typename T::value_type>();
1889}
1890
1891// Lexical cast
1892
1894template <typename T, enable_if_t<std::is_unsigned<T>::value, detail::enabler> = detail::dummy>
1895bool integral_conversion(const std::string &input, T &output) noexcept {
1896 if (input.empty()) {
1897 return false;
1898 }
1899 char *val = nullptr;
1900 std::uint64_t output_ll = std::strtoull(input.c_str(), &val, 0);
1901 output = static_cast<T>(output_ll);
1902 if (val == (input.c_str() + input.size()) && static_cast<std::uint64_t>(output) == output_ll) {
1903 return true;
1904 }
1905 val = nullptr;
1906 std::int64_t output_sll = std::strtoll(input.c_str(), &val, 0);
1907 if (val == (input.c_str() + input.size())) {
1908 output = (output_sll < 0) ? static_cast<T>(0) : static_cast<T>(output_sll);
1909 return (static_cast<std::int64_t>(output) == output_sll);
1910 }
1911 return false;
1912}
1913
1915template <typename T, enable_if_t<std::is_signed<T>::value, detail::enabler> = detail::dummy>
1916bool integral_conversion(const std::string &input, T &output) noexcept {
1917 if (input.empty()) {
1918 return false;
1919 }
1920 char *val = nullptr;
1921 std::int64_t output_ll = std::strtoll(input.c_str(), &val, 0);
1922 output = static_cast<T>(output_ll);
1923 if (val == (input.c_str() + input.size()) && static_cast<std::int64_t>(output) == output_ll) {
1924 return true;
1925 }
1926 if (input == "true") {
1927 // this is to deal with a few oddities with flags and wrapper int types
1928 output = static_cast<T>(1);
1929 return true;
1930 }
1931 return false;
1932}
1933
1935inline std::int64_t to_flag_value(std::string val) {
1936 static const std::string trueString("true");
1937 static const std::string falseString("false");
1938 if (val == trueString) {
1939 return 1;
1940 }
1941 if (val == falseString) {
1942 return -1;
1943 }
1944 val = detail::to_lower(val);
1945 std::int64_t ret = 0;
1946 if (val.size() == 1) {
1947 if (val[0] >= '1' && val[0] <= '9') {
1948 return (static_cast<std::int64_t>(val[0]) - '0');
1949 }
1950 switch (val[0]) {
1951 case '0':
1952 case 'f':
1953 case 'n':
1954 case '-':
1955 ret = -1;
1956 break;
1957 case 't':
1958 case 'y':
1959 case '+':
1960 ret = 1;
1961 break;
1962 default:
1963 throw std::invalid_argument("unrecognized character");
1964 }
1965 return ret;
1966 }
1967 if (val == trueString || val == "on" || val == "yes" || val == "enable") {
1968 ret = 1;
1969 } else if (val == falseString || val == "off" || val == "no" || val == "disable") {
1970 ret = -1;
1971 } else {
1972 ret = std::stoll(val);
1973 }
1974 return ret;
1975}
1976
1978template <typename T,
1979 enable_if_t<classify_object<T>::value == object_category::integral_value ||
1980 classify_object<T>::value == object_category::unsigned_integral,
1981 detail::enabler> = detail::dummy>
1982bool lexical_cast(const std::string &input, T &output) {
1983 return integral_conversion(input, output);
1984}
1985
1987template <typename T,
1988 enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> =
1989 detail::dummy>
1990bool lexical_cast(const std::string &input, T &output) {
1991 if (input.size() == 1) {
1992 output = static_cast<T>(input[0]);
1993 return true;
1994 }
1995 return integral_conversion(input, output);
1996}
1997
1999template <typename T,
2000 enable_if_t<classify_object<T>::value == object_category::boolean_value,
2001 detail::enabler> = detail::dummy>
2002bool lexical_cast(const std::string &input, T &output) {
2003 try {
2004 auto out = to_flag_value(input);
2005 output = (out > 0);
2006 return true;
2007 } catch (const std::invalid_argument &) {
2008 return false;
2009 } catch (const std::out_of_range &) {
2010 // if the number is out of the range of a 64 bit value then it is still a number and for
2011 // this purpose is still valid all we care about the sign
2012 output = (input[0] != '-');
2013 return true;
2014 }
2015}
2016
2018template <typename T,
2019 enable_if_t<classify_object<T>::value == object_category::floating_point,
2020 detail::enabler> = detail::dummy>
2021bool lexical_cast(const std::string &input, T &output) {
2022 if (input.empty()) {
2023 return false;
2024 }
2025 char *val = nullptr;
2026 auto output_ld = std::strtold(input.c_str(), &val);
2027 output = static_cast<T>(output_ld);
2028 return val == (input.c_str() + input.size());
2029}
2030
2032template <typename T,
2033 enable_if_t<classify_object<T>::value == object_category::complex_number,
2034 detail::enabler> = detail::dummy>
2035bool lexical_cast(const std::string &input, T &output) {
2036 using XC = typename wrapped_type<T, double>::type;
2037 XC x{0.0}, y{0.0};
2038 auto str1 = input;
2039 bool worked = false;
2040 auto nloc = str1.find_last_of("+-");
2041 if (nloc != std::string::npos && nloc > 0) {
2042 worked = detail::lexical_cast(str1.substr(0, nloc), x);
2043 str1 = str1.substr(nloc);
2044 if (str1.back() == 'i' || str1.back() == 'j') str1.pop_back();
2045 worked = worked && detail::lexical_cast(str1, y);
2046 } else {
2047 if (str1.back() == 'i' || str1.back() == 'j') {
2048 str1.pop_back();
2049 worked = detail::lexical_cast(str1, y);
2050 x = XC{0};
2051 } else {
2052 worked = detail::lexical_cast(str1, x);
2053 y = XC{0};
2054 }
2055 }
2056 if (worked) {
2057 output = T{x, y};
2058 return worked;
2059 }
2060 return from_stream(input, output);
2061}
2062
2064template <typename T,
2065 enable_if_t<classify_object<T>::value == object_category::string_assignable,
2066 detail::enabler> = detail::dummy>
2067bool lexical_cast(const std::string &input, T &output) {
2068 output = input;
2069 return true;
2070}
2071
2073template <typename T,
2074 enable_if_t<classify_object<T>::value == object_category::string_constructible,
2075 detail::enabler> = detail::dummy>
2076bool lexical_cast(const std::string &input, T &output) {
2077 output = T(input);
2078 return true;
2079}
2080
2082template <typename T,
2083 enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> =
2084 detail::dummy>
2085bool lexical_cast(const std::string &input, T &output) {
2086 typename std::underlying_type<T>::type val;
2087 if (!integral_conversion(input, val)) {
2088 return false;
2089 }
2090 output = static_cast<T>(val);
2091 return true;
2092}
2093
2095template <typename T,
2096 enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
2097 std::is_assignable<T &, typename T::value_type>::value,
2098 detail::enabler> = detail::dummy>
2099bool lexical_cast(const std::string &input, T &output) {
2100 typename T::value_type val;
2101 if (lexical_cast(input, val)) {
2102 output = val;
2103 return true;
2104 }
2105 return from_stream(input, output);
2106}
2107
2108template <typename T,
2109 enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
2110 !std::is_assignable<T &, typename T::value_type>::value &&
2111 std::is_assignable<T &, T>::value,
2112 detail::enabler> = detail::dummy>
2113bool lexical_cast(const std::string &input, T &output) {
2114 typename T::value_type val;
2115 if (lexical_cast(input, val)) {
2116 output = T{val};
2117 return true;
2118 }
2119 return from_stream(input, output);
2120}
2121
2123template <typename T,
2124 enable_if_t<classify_object<T>::value == object_category::number_constructible,
2125 detail::enabler> = detail::dummy>
2126bool lexical_cast(const std::string &input, T &output) {
2127 int val = 0;
2128 if (integral_conversion(input, val)) {
2129 output = T(val);
2130 return true;
2131 }
2132
2133 double dval = 0.0;
2134 if (lexical_cast(input, dval)) {
2135 output = T{dval};
2136 return true;
2137 }
2138
2139 return from_stream(input, output);
2140}
2141
2143template <typename T,
2144 enable_if_t<classify_object<T>::value == object_category::integer_constructible,
2145 detail::enabler> = detail::dummy>
2146bool lexical_cast(const std::string &input, T &output) {
2147 int val = 0;
2148 if (integral_conversion(input, val)) {
2149 output = T(val);
2150 return true;
2151 }
2152 return from_stream(input, output);
2153}
2154
2156template <typename T,
2157 enable_if_t<classify_object<T>::value == object_category::double_constructible,
2158 detail::enabler> = detail::dummy>
2159bool lexical_cast(const std::string &input, T &output) {
2160 double val = 0.0;
2161 if (lexical_cast(input, val)) {
2162 output = T{val};
2163 return true;
2164 }
2165 return from_stream(input, output);
2166}
2167
2169template <typename T,
2170 enable_if_t<classify_object<T>::value == object_category::other &&
2171 std::is_assignable<T &, int>::value,
2172 detail::enabler> = detail::dummy>
2173bool lexical_cast(const std::string &input, T &output) {
2174 int val = 0;
2175 if (integral_conversion(input, val)) {
2176#ifdef _MSC_VER
2177#pragma warning(push)
2178#pragma warning(disable : 4800)
2179#endif
2180 // with Atomic<XX> this could produce a warning due to the conversion but if atomic gets
2181 // here it is an old style so will most likely still work
2182 output = val;
2183#ifdef _MSC_VER
2184#pragma warning(pop)
2185#endif
2186 return true;
2187 }
2188 // LCOV_EXCL_START
2189 // This version of cast is only used for odd cases in an older compilers the fail over
2190 // from_stream is tested elsewhere an not relevant for coverage here
2191 return from_stream(input, output);
2192 // LCOV_EXCL_STOP
2193}
2194
2196template <typename T,
2197 enable_if_t<classify_object<T>::value == object_category::other &&
2198 !std::is_assignable<T &, int>::value,
2199 detail::enabler> = detail::dummy>
2200bool lexical_cast(const std::string &input, T &output) {
2201 static_assert(is_istreamable<T>::value,
2202 "option object type must have a lexical cast overload or streaming input "
2203 "operator(>>) defined, if it "
2204 "is convertible from another type use the add_option<T, XC>(...) with XC being "
2205 "the known type");
2206 return from_stream(input, output);
2207}
2208
2211template <
2212 typename AssignTo,
2213 typename ConvertTo,
2214 enable_if_t<std::is_same<AssignTo, ConvertTo>::value &&
2215 (classify_object<AssignTo>::value == object_category::string_assignable ||
2216 classify_object<AssignTo>::value == object_category::string_constructible),
2217 detail::enabler> = detail::dummy>
2218bool lexical_assign(const std::string &input, AssignTo &output) {
2219 return lexical_cast(input, output);
2220}
2221
2223template <typename AssignTo,
2224 typename ConvertTo,
2225 enable_if_t<std::is_same<AssignTo, ConvertTo>::value &&
2226 std::is_assignable<AssignTo &, AssignTo>::value &&
2227 classify_object<AssignTo>::value != object_category::string_assignable &&
2228 classify_object<AssignTo>::value != object_category::string_constructible,
2229 detail::enabler> = detail::dummy>
2230bool lexical_assign(const std::string &input, AssignTo &output) {
2231 if (input.empty()) {
2232 output = AssignTo{};
2233 return true;
2234 }
2235
2236 return lexical_cast(input, output);
2237}
2238
2240template <typename AssignTo,
2241 typename ConvertTo,
2242 enable_if_t<std::is_same<AssignTo, ConvertTo>::value &&
2243 !std::is_assignable<AssignTo &, AssignTo>::value &&
2244 classify_object<AssignTo>::value == object_category::wrapper_value,
2245 detail::enabler> = detail::dummy>
2246bool lexical_assign(const std::string &input, AssignTo &output) {
2247 if (input.empty()) {
2248 typename AssignTo::value_type emptyVal{};
2249 output = emptyVal;
2250 return true;
2251 }
2252 return lexical_cast(input, output);
2253}
2254
2257template <typename AssignTo,
2258 typename ConvertTo,
2259 enable_if_t<std::is_same<AssignTo, ConvertTo>::value &&
2260 !std::is_assignable<AssignTo &, AssignTo>::value &&
2261 classify_object<AssignTo>::value != object_category::wrapper_value &&
2262 std::is_assignable<AssignTo &, int>::value,
2263 detail::enabler> = detail::dummy>
2264bool lexical_assign(const std::string &input, AssignTo &output) {
2265 if (input.empty()) {
2266 output = 0;
2267 return true;
2268 }
2269 int val = 0;
2270 if (lexical_cast(input, val)) {
2271 output = val;
2272 return true;
2273 }
2274 return false;
2275}
2276
2278template <typename AssignTo,
2279 typename ConvertTo,
2280 enable_if_t<!std::is_same<AssignTo, ConvertTo>::value &&
2281 std::is_assignable<AssignTo &, ConvertTo &>::value,
2282 detail::enabler> = detail::dummy>
2283bool lexical_assign(const std::string &input, AssignTo &output) {
2284 ConvertTo val{};
2285 bool parse_result = (!input.empty()) ? lexical_cast<ConvertTo>(input, val) : true;
2286 if (parse_result) {
2287 output = val;
2288 }
2289 return parse_result;
2290}
2291
2293template <typename AssignTo,
2294 typename ConvertTo,
2295 enable_if_t<!std::is_same<AssignTo, ConvertTo>::value &&
2296 !std::is_assignable<AssignTo &, ConvertTo &>::value &&
2297 std::is_move_assignable<AssignTo>::value,
2298 detail::enabler> = detail::dummy>
2299bool lexical_assign(const std::string &input, AssignTo &output) {
2300 ConvertTo val{};
2301 bool parse_result = input.empty() ? true : lexical_cast<ConvertTo>(input, val);
2302 if (parse_result) {
2303 output = AssignTo(val); // use () form of constructor to allow some implicit conversions
2304 }
2305 return parse_result;
2306}
2307
2309template <typename AssignTo,
2310 typename ConvertTo,
2311 enable_if_t<classify_object<ConvertTo>::value <= object_category::other &&
2312 classify_object<AssignTo>::value <= object_category::wrapper_value,
2313 detail::enabler> = detail::dummy>
2314bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2315 return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2316}
2317
2320template <typename AssignTo,
2321 typename ConvertTo,
2322 enable_if_t<(type_count<AssignTo>::value <= 2) && expected_count<AssignTo>::value == 1 &&
2323 is_tuple_like<ConvertTo>::value && type_count_base<ConvertTo>::value == 2,
2324 detail::enabler> = detail::dummy>
2325bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2326 // the remove const is to handle pair types coming from a container
2327 typename std::remove_const<typename std::tuple_element<0, ConvertTo>::type>::type v1;
2328 typename std::tuple_element<1, ConvertTo>::type v2;
2329 bool retval = lexical_assign<decltype(v1), decltype(v1)>(strings[0], v1);
2330 if (strings.size() > 1) {
2331 retval = retval && lexical_assign<decltype(v2), decltype(v2)>(strings[1], v2);
2332 }
2333 if (retval) {
2334 output = AssignTo{v1, v2};
2335 }
2336 return retval;
2337}
2338
2340template <
2341 class AssignTo,
2342 class ConvertTo,
2343 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2344 type_count<ConvertTo>::value == 1,
2345 detail::enabler> = detail::dummy>
2346bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2347 output.erase(output.begin(), output.end());
2348 if (strings.size() == 1 && strings[0] == "{}") {
2349 return true;
2350 }
2351 bool skip_remaining = false;
2352 if (strings.size() == 2 && strings[0] == "{}" && is_separator(strings[1])) {
2353 skip_remaining = true;
2354 }
2355 for (const auto &elem : strings) {
2356 typename AssignTo::value_type out;
2357 bool retval = lexical_assign<typename AssignTo::value_type, typename ConvertTo::value_type>(
2358 elem, out);
2359 if (!retval) {
2360 return false;
2361 }
2362 output.insert(output.end(), std::move(out));
2363 if (skip_remaining) {
2364 break;
2365 }
2366 }
2367 return (!output.empty());
2368}
2369
2371template <class AssignTo,
2372 class ConvertTo,
2373 enable_if_t<is_complex<ConvertTo>::value, detail::enabler> = detail::dummy>
2374bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2375 if (strings.size() >= 2 && !strings[1].empty()) {
2376 using XC2 = typename wrapped_type<ConvertTo, double>::type;
2377 XC2 x{0.0}, y{0.0};
2378 auto str1 = strings[1];
2379 if (str1.back() == 'i' || str1.back() == 'j') {
2380 str1.pop_back();
2381 }
2382 auto worked = detail::lexical_cast(strings[0], x) && detail::lexical_cast(str1, y);
2383 if (worked) {
2384 output = ConvertTo{x, y};
2385 }
2386 return worked;
2387 }
2388 return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2389}
2390
2392template <
2393 class AssignTo,
2394 class ConvertTo,
2395 enable_if_t<is_mutable_container<AssignTo>::value && (expected_count<ConvertTo>::value == 1) &&
2396 (type_count<ConvertTo>::value == 1),
2397 detail::enabler> = detail::dummy>
2398bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2399 bool retval = true;
2400 output.clear();
2401 output.reserve(strings.size());
2402 for (const auto &elem : strings) {
2403 output.emplace_back();
2404 retval =
2405 retval && lexical_assign<typename AssignTo::value_type, ConvertTo>(elem, output.back());
2406 }
2407 return (!output.empty()) && retval;
2408}
2409
2410// forward declaration
2411
2413template <
2414 class AssignTo,
2415 class ConvertTo,
2416 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2417 type_count_base<ConvertTo>::value == 2,
2418 detail::enabler> = detail::dummy>
2419bool lexical_conversion(std::vector<std::string> strings, AssignTo &output);
2420
2422template <
2423 class AssignTo,
2424 class ConvertTo,
2425 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2426 type_count_base<ConvertTo>::value != 2 &&
2427 ((type_count<ConvertTo>::value > 2) ||
2428 (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
2429 detail::enabler> = detail::dummy>
2430bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output);
2431
2433template <class AssignTo,
2434 class ConvertTo,
2435 enable_if_t<is_tuple_like<AssignTo>::value && is_tuple_like<ConvertTo>::value &&
2436 (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2437 type_count<ConvertTo>::value > 2),
2438 detail::enabler> = detail::dummy>
2439bool lexical_conversion(const std::vector<std::string> &strings,
2440 AssignTo &output); // forward declaration
2441
2444template <
2445 typename AssignTo,
2446 typename ConvertTo,
2447 enable_if_t<!is_tuple_like<AssignTo>::value && !is_mutable_container<AssignTo>::value &&
2448 classify_object<ConvertTo>::value != object_category::wrapper_value &&
2449 (is_mutable_container<ConvertTo>::value || type_count<ConvertTo>::value > 2),
2450 detail::enabler> = detail::dummy>
2451bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2452 if (strings.size() > 1 || (!strings.empty() && !(strings.front().empty()))) {
2453 ConvertTo val;
2454 auto retval = lexical_conversion<ConvertTo, ConvertTo>(strings, val);
2455 output = AssignTo{val};
2456 return retval;
2457 }
2458 output = AssignTo{};
2459 return true;
2460}
2461
2463template <class AssignTo, class ConvertTo, std::size_t I>
2464inline typename std::enable_if<(I >= type_count_base<AssignTo>::value), bool>::type
2465tuple_conversion(const std::vector<std::string> &, AssignTo &) {
2466 return true;
2467}
2468
2470template <class AssignTo, class ConvertTo>
2471inline typename std::enable_if<!is_mutable_container<ConvertTo>::value &&
2472 type_count<ConvertTo>::value == 1,
2473 bool>::type
2474tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2475 auto retval = lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2476 strings.erase(strings.begin());
2477 return retval;
2478}
2479
2482template <class AssignTo, class ConvertTo>
2483inline typename std::enable_if<!is_mutable_container<ConvertTo>::value &&
2484 (type_count<ConvertTo>::value > 1) &&
2485 type_count<ConvertTo>::value == type_count_min<ConvertTo>::value,
2486 bool>::type
2487tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2488 auto retval = lexical_conversion<AssignTo, ConvertTo>(strings, output);
2489 strings.erase(strings.begin(), strings.begin() + type_count<ConvertTo>::value);
2490 return retval;
2491}
2492
2495template <class AssignTo, class ConvertTo>
2496inline typename std::enable_if<is_mutable_container<ConvertTo>::value ||
2497 type_count<ConvertTo>::value != type_count_min<ConvertTo>::value,
2498 bool>::type
2499tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2500 std::size_t index{subtype_count_min<ConvertTo>::value};
2501 const std::size_t mx_count{subtype_count<ConvertTo>::value};
2502 const std::size_t mx{(std::max)(mx_count, strings.size())};
2503
2504 while (index < mx) {
2505 if (is_separator(strings[index])) {
2506 break;
2507 }
2508 ++index;
2509 }
2510 bool retval = lexical_conversion<AssignTo, ConvertTo>(
2511 std::vector<std::string>(strings.begin(),
2512 strings.begin() + static_cast<std::ptrdiff_t>(index)),
2513 output);
2514 strings.erase(strings.begin(), strings.begin() + static_cast<std::ptrdiff_t>(index) + 1);
2515 return retval;
2516}
2517
2519template <class AssignTo, class ConvertTo, std::size_t I>
2520inline typename std::enable_if<(I < type_count_base<AssignTo>::value), bool>::type tuple_conversion(
2521 std::vector<std::string> strings, AssignTo &output) {
2522 bool retval = true;
2523 using ConvertToElement =
2524 typename std::conditional<is_tuple_like<ConvertTo>::value,
2525 typename std::tuple_element<I, ConvertTo>::type, ConvertTo>::type;
2526 if (!strings.empty()) {
2527 retval =
2528 retval &&
2529 tuple_type_conversion<typename std::tuple_element<I, AssignTo>::type, ConvertToElement>(
2530 strings, std::get<I>(output));
2531 }
2532 retval = retval && tuple_conversion<AssignTo, ConvertTo, I + 1>(std::move(strings), output);
2533 return retval;
2534}
2535
2537template <
2538 class AssignTo,
2539 class ConvertTo,
2540 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2541 type_count_base<ConvertTo>::value == 2,
2542 detail::enabler>>
2543bool lexical_conversion(std::vector<std::string> strings, AssignTo &output) {
2544 output.clear();
2545 while (!strings.empty()) {
2546 typename std::remove_const<
2547 typename std::tuple_element<0, typename ConvertTo::value_type>::type>::type v1;
2548 typename std::tuple_element<1, typename ConvertTo::value_type>::type v2;
2549 bool retval = tuple_type_conversion<decltype(v1), decltype(v1)>(strings, v1);
2550 if (!strings.empty()) {
2551 retval = retval && tuple_type_conversion<decltype(v2), decltype(v2)>(strings, v2);
2552 }
2553 if (retval) {
2554 output.insert(output.end(), typename AssignTo::value_type{v1, v2});
2555 } else {
2556 return false;
2557 }
2558 }
2559 return (!output.empty());
2560}
2561
2564template <class AssignTo,
2565 class ConvertTo,
2566 enable_if_t<is_tuple_like<AssignTo>::value && is_tuple_like<ConvertTo>::value &&
2567 (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2568 type_count<ConvertTo>::value > 2),
2569 detail::enabler>>
2570bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2571 static_assert(!is_tuple_like<ConvertTo>::value ||
2572 type_count_base<AssignTo>::value == type_count_base<ConvertTo>::value,
2573 "if the conversion type is defined as a tuple it must be the same size as the "
2574 "type you are converting to");
2575 return tuple_conversion<AssignTo, ConvertTo, 0>(strings, output);
2576}
2577
2580template <
2581 class AssignTo,
2582 class ConvertTo,
2583 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2584 type_count_base<ConvertTo>::value != 2 &&
2585 ((type_count<ConvertTo>::value > 2) ||
2586 (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
2587 detail::enabler>>
2588bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2589 bool retval = true;
2590 output.clear();
2591 std::vector<std::string> temp;
2592 std::size_t ii{0};
2593 std::size_t icount{0};
2594 std::size_t xcm{type_count<ConvertTo>::value};
2595 auto ii_max = strings.size();
2596 while (ii < ii_max) {
2597 temp.push_back(strings[ii]);
2598 ++ii;
2599 ++icount;
2600 if (icount == xcm || is_separator(temp.back()) || ii == ii_max) {
2601 if (static_cast<int>(xcm) > type_count_min<ConvertTo>::value &&
2602 is_separator(temp.back())) {
2603 temp.pop_back();
2604 }
2605 typename AssignTo::value_type temp_out;
2606 retval =
2607 retval &&
2608 lexical_conversion<typename AssignTo::value_type, typename ConvertTo::value_type>(
2609 temp, temp_out);
2610 temp.clear();
2611 if (!retval) {
2612 return false;
2613 }
2614 output.insert(output.end(), std::move(temp_out));
2615 icount = 0;
2616 }
2617 }
2618 return retval;
2619}
2620
2622template <typename AssignTo,
2623 class ConvertTo,
2624 enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2625 std::is_assignable<ConvertTo &, ConvertTo>::value,
2626 detail::enabler> = detail::dummy>
2627bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2628 if (strings.empty() || strings.front().empty()) {
2629 output = ConvertTo{};
2630 return true;
2631 }
2632 typename ConvertTo::value_type val;
2633 if (lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings,
2634 val)) {
2635 output = ConvertTo{val};
2636 return true;
2637 }
2638 return false;
2639}
2640
2642template <typename AssignTo,
2643 class ConvertTo,
2644 enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2645 !std::is_assignable<AssignTo &, ConvertTo>::value,
2646 detail::enabler> = detail::dummy>
2647bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2648 using ConvertType = typename ConvertTo::value_type;
2649 if (strings.empty() || strings.front().empty()) {
2650 output = ConvertType{};
2651 return true;
2652 }
2653 ConvertType val;
2654 if (lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings,
2655 val)) {
2656 output = val;
2657 return true;
2658 }
2659 return false;
2660}
2661
2663inline std::string sum_string_vector(const std::vector<std::string> &values) {
2664 double val{0.0};
2665 bool fail{false};
2666 std::string output;
2667 for (const auto &arg : values) {
2668 double tv{0.0};
2669 auto comp = detail::lexical_cast<double>(arg, tv);
2670 if (!comp) {
2671 try {
2672 tv = static_cast<double>(detail::to_flag_value(arg));
2673 } catch (const std::exception &) {
2674 fail = true;
2675 break;
2676 }
2677 }
2678 val += tv;
2679 }
2680 if (fail) {
2681 for (const auto &arg : values) {
2682 output.append(arg);
2683 }
2684 } else {
2685 if (val <= static_cast<double>((std::numeric_limits<std::int64_t>::min)()) ||
2686 val >= static_cast<double>((std::numeric_limits<std::int64_t>::max)()) ||
2687 // NOLINTNEXTLINE(clang-diagnostic-float-equal,bugprone-narrowing-conversions)
2688 val == static_cast<std::int64_t>(val)) {
2689 output = detail::value_string(static_cast<int64_t>(val));
2690 } else {
2691 output = detail::value_string(val);
2692 }
2693 }
2694 return output;
2695}
2696
2697} // namespace detail
2698
2699namespace detail {
2700
2701// Returns false if not a short option. Otherwise, sets opt name and rest and returns true
2702CLI11_INLINE bool split_short(const std::string &current, std::string &name, std::string &rest);
2703
2704// Returns false if not a long option. Otherwise, sets opt name and other side of = and returns true
2705CLI11_INLINE bool split_long(const std::string &current, std::string &name, std::string &value);
2706
2707// Returns false if not a windows style option. Otherwise, sets opt name and value and returns true
2708CLI11_INLINE bool split_windows_style(const std::string &current,
2709 std::string &name,
2710 std::string &value);
2711
2712// Splits a string into multiple long and short names
2713CLI11_INLINE std::vector<std::string> split_names(std::string current);
2714
2716CLI11_INLINE std::vector<std::pair<std::string, std::string>> get_default_flag_values(
2717 const std::string &str);
2718
2720CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string> get_names(
2721 const std::vector<std::string> &input);
2722
2723} // namespace detail
2724
2725namespace detail {
2726
2727CLI11_INLINE bool split_short(const std::string &current, std::string &name, std::string &rest) {
2728 if (current.size() > 1 && current[0] == '-' && valid_first_char(current[1])) {
2729 name = current.substr(1, 1);
2730 rest = current.substr(2);
2731 return true;
2732 }
2733 return false;
2734}
2735
2736CLI11_INLINE bool split_long(const std::string &current, std::string &name, std::string &value) {
2737 if (current.size() > 2 && current.substr(0, 2) == "--" && valid_first_char(current[2])) {
2738 auto loc = current.find_first_of('=');
2739 if (loc != std::string::npos) {
2740 name = current.substr(2, loc - 2);
2741 value = current.substr(loc + 1);
2742 } else {
2743 name = current.substr(2);
2744 value = "";
2745 }
2746 return true;
2747 }
2748 return false;
2749}
2750
2751CLI11_INLINE bool split_windows_style(const std::string &current,
2752 std::string &name,
2753 std::string &value) {
2754 if (current.size() > 1 && current[0] == '/' && valid_first_char(current[1])) {
2755 auto loc = current.find_first_of(':');
2756 if (loc != std::string::npos) {
2757 name = current.substr(1, loc - 1);
2758 value = current.substr(loc + 1);
2759 } else {
2760 name = current.substr(1);
2761 value = "";
2762 }
2763 return true;
2764 }
2765 return false;
2766}
2767
2768CLI11_INLINE std::vector<std::string> split_names(std::string current) {
2769 std::vector<std::string> output;
2770 std::size_t val = 0;
2771 while ((val = current.find(',')) != std::string::npos) {
2772 output.push_back(trim_copy(current.substr(0, val)));
2773 current = current.substr(val + 1);
2774 }
2775 output.push_back(trim_copy(current));
2776 return output;
2777}
2778
2779CLI11_INLINE std::vector<std::pair<std::string, std::string>> get_default_flag_values(
2780 const std::string &str) {
2781 std::vector<std::string> flags = split_names(str);
2782 flags.erase(std::remove_if(flags.begin(), flags.end(),
2783 [](const std::string &name) {
2784 return ((name.empty()) ||
2785 (!(((name.find_first_of('{') != std::string::npos) &&
2786 (name.back() == '}')) ||
2787 (name[0] == '!'))));
2788 }),
2789 flags.end());
2790 std::vector<std::pair<std::string, std::string>> output;
2791 output.reserve(flags.size());
2792 for (auto &flag : flags) {
2793 auto def_start = flag.find_first_of('{');
2794 std::string defval = "false";
2795 if ((def_start != std::string::npos) && (flag.back() == '}')) {
2796 defval = flag.substr(def_start + 1);
2797 defval.pop_back();
2798 flag.erase(def_start,
2799 std::string::npos); // NOLINT(readability-suspicious-call-argument)
2800 }
2801 flag.erase(0, flag.find_first_not_of("-!"));
2802 output.emplace_back(flag, defval);
2803 }
2804 return output;
2805}
2806
2807CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string> get_names(
2808 const std::vector<std::string> &input) {
2809 std::vector<std::string> short_names;
2810 std::vector<std::string> long_names;
2811 std::string pos_name;
2812
2813 for (std::string name : input) {
2814 if (name.length() == 0) {
2815 continue;
2816 }
2817 if (name.length() > 1 && name[0] == '-' && name[1] != '-') {
2818 if (name.length() == 2 && valid_first_char(name[1]))
2819 short_names.emplace_back(1, name[1]);
2820 else
2821 throw BadNameString::OneCharName(name);
2822 } else if (name.length() > 2 && name.substr(0, 2) == "--") {
2823 name = name.substr(2);
2824 if (valid_name_string(name))
2825 long_names.push_back(name);
2826 else
2827 throw BadNameString::BadLongName(name);
2828 } else if (name == "-" || name == "--") {
2829 throw BadNameString::DashesOnly(name);
2830 } else {
2831 if (pos_name.length() > 0) throw BadNameString::MultiPositionalNames(name);
2832 pos_name = name;
2833 }
2834 }
2835
2836 return std::make_tuple(short_names, long_names, pos_name);
2837}
2838
2839} // namespace detail
2840
2841class App;
2842
2846 std::vector<std::string> parents{};
2847
2849 std::string name{};
2850
2852 std::vector<std::string> inputs{};
2853
2855 CLI11_NODISCARD std::string fullname() const {
2856 std::vector<std::string> tmp = parents;
2857 tmp.emplace_back(name);
2858 return detail::join(tmp, ".");
2859 }
2860};
2861
2863class Config {
2864protected:
2865 std::vector<ConfigItem> items{};
2866
2867public:
2869 virtual std::string to_config(const App *, bool, bool, std::string) const = 0;
2870
2872 virtual std::vector<ConfigItem> from_config(std::istream &) const = 0;
2873
2875 CLI11_NODISCARD virtual std::string to_flag(const ConfigItem &item) const {
2876 if (item.inputs.size() == 1) {
2877 return item.inputs.at(0);
2878 }
2879 if (item.inputs.empty()) {
2880 return "{}";
2881 }
2882 throw ConversionError::TooManyInputsFlag(item.fullname()); // LCOV_EXCL_LINE
2883 }
2884
2886 CLI11_NODISCARD std::vector<ConfigItem> from_file(const std::string &name) const {
2887 std::ifstream input{name};
2888 if (!input.good()) throw FileError::Missing(name);
2889
2890 return from_config(input);
2891 }
2892
2894 virtual ~Config() = default;
2895};
2896
2898class ConfigBase : public Config {
2899protected:
2901 char commentChar = '#';
2903 char arrayStart = '[';
2905 char arrayEnd = ']';
2907 char arraySeparator = ',';
2909 char valueDelimiter = '=';
2911 char stringQuote = '"';
2913 char characterQuote = '\'';
2915 uint8_t maximumLayers{255};
2919 int16_t configIndex{-1};
2921 std::string configSection{};
2922
2923public:
2924 std::string to_config(const App * /*app*/,
2925 bool default_also,
2926 bool write_description,
2927 std::string prefix) const override;
2928
2929 std::vector<ConfigItem> from_config(std::istream &input) const override;
2931 ConfigBase *comment(char cchar) {
2932 commentChar = cchar;
2933 return this;
2934 }
2935
2936 ConfigBase *arrayBounds(char aStart, char aEnd) {
2937 arrayStart = aStart;
2938 arrayEnd = aEnd;
2939 return this;
2940 }
2941
2943 arraySeparator = aSep;
2944 return this;
2945 }
2946
2948 valueDelimiter = vSep;
2949 return this;
2950 }
2951
2952 ConfigBase *quoteCharacter(char qString, char qChar) {
2953 stringQuote = qString;
2954 characterQuote = qChar;
2955 return this;
2956 }
2957
2958 ConfigBase *maxLayers(uint8_t layers) {
2959 maximumLayers = layers;
2960 return this;
2961 }
2962
2964 parentSeparatorChar = sep;
2965 return this;
2966 }
2967
2968 std::string &sectionRef() { return configSection; }
2970 CLI11_NODISCARD const std::string &section() const { return configSection; }
2972 ConfigBase *section(const std::string &sectionName) {
2973 configSection = sectionName;
2974 return this;
2975 }
2976
2978 int16_t &indexRef() { return configIndex; }
2980 CLI11_NODISCARD int16_t index() const { return configIndex; }
2982 ConfigBase *index(int16_t sectionIndex) {
2983 configIndex = sectionIndex;
2984 return this;
2985 }
2986};
2987
2989using ConfigTOML = ConfigBase;
2990
2992class ConfigINI : public ConfigTOML {
2993public:
2994 ConfigINI() {
2995 commentChar = ';';
2996 arrayStart = '\0';
2997 arrayEnd = '\0';
2998 arraySeparator = ' ';
2999 valueDelimiter = '=';
3000 }
3001};
3002
3003class Option;
3004
3006
3013
3015class Validator {
3016protected:
3018 std::function<std::string()> desc_function_{[]() { return std::string{}; }};
3019
3022 std::function<std::string(std::string &)> func_{[](std::string &) { return std::string{}; }};
3024 std::string name_{};
3028 bool active_{true};
3030 bool non_modifying_{false};
3031
3032 Validator(std::string validator_desc, std::function<std::string(std::string &)> func)
3033 : desc_function_([validator_desc]() { return validator_desc; }), func_(std::move(func)) {}
3034
3035public:
3036 Validator() = default;
3038 explicit Validator(std::string validator_desc)
3039 : desc_function_([validator_desc]() { return validator_desc; }) {}
3040
3041 Validator(std::function<std::string(std::string &)> op,
3042 std::string validator_desc,
3043 std::string validator_name = "")
3044 : desc_function_([validator_desc]() { return validator_desc; }),
3045 func_(std::move(op)),
3046 name_(std::move(validator_name)) {}
3047
3048 Validator &operation(std::function<std::string(std::string &)> op) {
3049 func_ = std::move(op);
3050 return *this;
3051 }
3052
3054 std::string operator()(std::string &str) const;
3055
3058 std::string operator()(const std::string &str) const {
3059 std::string value = str;
3060 return (active_) ? func_(value) : std::string{};
3061 }
3062
3064 Validator &description(std::string validator_desc) {
3065 desc_function_ = [validator_desc]() { return validator_desc; };
3066 return *this;
3067 }
3068
3069 CLI11_NODISCARD Validator description(std::string validator_desc) const;
3070
3072 CLI11_NODISCARD std::string get_description() const {
3073 if (active_) {
3074 return desc_function_();
3075 }
3076 return std::string{};
3077 }
3078
3079 Validator &name(std::string validator_name) {
3080 name_ = std::move(validator_name);
3081 return *this;
3082 }
3083
3084 CLI11_NODISCARD Validator name(std::string validator_name) const {
3085 Validator newval(*this);
3086 newval.name_ = std::move(validator_name);
3087 return newval;
3088 }
3089
3090 CLI11_NODISCARD const std::string &get_name() const { return name_; }
3092 Validator &active(bool active_val = true) {
3093 active_ = active_val;
3094 return *this;
3095 }
3096
3097 CLI11_NODISCARD Validator active(bool active_val = true) const {
3098 Validator newval(*this);
3099 newval.active_ = active_val;
3100 return newval;
3101 }
3102
3104 Validator &non_modifying(bool no_modify = true) {
3105 non_modifying_ = no_modify;
3106 return *this;
3107 }
3108
3109 Validator &application_index(int app_index) {
3110 application_index_ = app_index;
3111 return *this;
3112 }
3113
3114 CLI11_NODISCARD Validator application_index(int app_index) const {
3115 Validator newval(*this);
3116 newval.application_index_ = app_index;
3117 return newval;
3118 }
3119
3120 CLI11_NODISCARD int get_application_index() const { return application_index_; }
3122 CLI11_NODISCARD bool get_active() const { return active_; }
3123
3126 CLI11_NODISCARD bool get_modifying() const { return !non_modifying_; }
3127
3130 Validator operator&(const Validator &other) const;
3131
3134 Validator operator|(const Validator &other) const;
3135
3137 Validator operator!() const;
3138
3139private:
3140 void _merge_description(const Validator &val1,
3141 const Validator &val2,
3142 const std::string &merger);
3143};
3144
3146class CustomValidator : public Validator {
3147public:
3148};
3149// The implementation of the built in validators is using the Validator class;
3150// the user is only expected to use the const (static) versions (since there's no setup).
3151// Therefore, this is in detail.
3152namespace detail {
3153
3155enum class path_type { nonexistent, file, directory };
3156
3158CLI11_INLINE path_type check_path(const char *file) noexcept;
3159
3161class ExistingFileValidator : public Validator {
3162public:
3163 ExistingFileValidator();
3164};
3165
3167class ExistingDirectoryValidator : public Validator {
3168public:
3169 ExistingDirectoryValidator();
3170};
3171
3173class ExistingPathValidator : public Validator {
3174public:
3175 ExistingPathValidator();
3176};
3177
3179class NonexistentPathValidator : public Validator {
3180public:
3181 NonexistentPathValidator();
3182};
3183
3185class IPV4Validator : public Validator {
3186public:
3187 IPV4Validator();
3188};
3189
3190} // namespace detail
3191
3192// Static is not needed here, because global const implies static.
3193
3195const detail::ExistingFileValidator ExistingFile;
3196
3198const detail::ExistingDirectoryValidator ExistingDirectory;
3199
3201const detail::ExistingPathValidator ExistingPath;
3202
3204const detail::NonexistentPathValidator NonexistentPath;
3205
3207const detail::IPV4Validator ValidIPV4;
3208
3210template <typename DesiredType>
3211class TypeValidator : public Validator {
3212public:
3213 explicit TypeValidator(const std::string &validator_name)
3214 : Validator(validator_name, [](std::string &input_string) {
3215 auto val = DesiredType();
3216 if (!detail::lexical_cast(input_string, val)) {
3217 return std::string("Failed parsing ") + input_string + " as a " +
3218 detail::type_name<DesiredType>();
3219 }
3220 return std::string();
3221 }) {}
3222 TypeValidator() : TypeValidator(detail::type_name<DesiredType>()) {}
3223};
3224
3226const TypeValidator<double> Number("NUMBER");
3227
3230class FileOnDefaultPath : public Validator {
3231public:
3232 explicit FileOnDefaultPath(std::string default_path, bool enableErrorReturn = true);
3233};
3234
3236class Range : public Validator {
3237public:
3242 template <typename T>
3243 Range(T min_val, T max_val, const std::string &validator_name = std::string{})
3244 : Validator(validator_name) {
3245 if (validator_name.empty()) {
3246 std::stringstream out;
3247 out << detail::type_name<T>() << " in [" << min_val << " - " << max_val << "]";
3248 description(out.str());
3249 }
3250
3251 func_ = [min_val, max_val](std::string &input) {
3252 T val;
3253 bool converted = detail::lexical_cast(input, val);
3254 if ((!converted) || (val < min_val || val > max_val)) {
3255 std::stringstream out;
3256 out << "Value " << input << " not in range [";
3257 out << min_val << " - " << max_val << "]";
3258 return out.str();
3259 }
3260 return std::string{};
3261 };
3262 }
3263
3265 template <typename T>
3266 explicit Range(T max_val, const std::string &validator_name = std::string{})
3267 : Range(static_cast<T>(0), max_val, validator_name) {}
3268};
3269
3271const Range NonNegativeNumber((std::numeric_limits<double>::max)(), "NONNEGATIVE");
3272
3275const Range PositiveNumber((std::numeric_limits<double>::min)(),
3276 (std::numeric_limits<double>::max)(),
3277 "POSITIVE");
3278
3280class Bound : public Validator {
3281public:
3286 template <typename T>
3287 Bound(T min_val, T max_val) {
3288 std::stringstream out;
3289 out << detail::type_name<T>() << " bounded to [" << min_val << " - " << max_val << "]";
3290 description(out.str());
3291
3292 func_ = [min_val, max_val](std::string &input) {
3293 T val;
3294 bool converted = detail::lexical_cast(input, val);
3295 if (!converted) {
3296 return std::string("Value ") + input + " could not be converted";
3297 }
3298 if (val < min_val)
3299 input = detail::to_string(min_val);
3300 else if (val > max_val)
3301 input = detail::to_string(max_val);
3302
3303 return std::string{};
3304 };
3305 }
3306
3308 template <typename T>
3309 explicit Bound(T max_val) : Bound(static_cast<T>(0), max_val) {}
3310};
3311
3312namespace detail {
3313template <typename T,
3314 enable_if_t<is_copyable_ptr<typename std::remove_reference<T>::type>::value,
3315 detail::enabler> = detail::dummy>
3316auto smart_deref(T value) -> decltype(*value) {
3317 return *value;
3318}
3319
3320template <typename T,
3321 enable_if_t<!is_copyable_ptr<typename std::remove_reference<T>::type>::value,
3322 detail::enabler> = detail::dummy>
3323typename std::remove_reference<T>::type &smart_deref(T &value) {
3324 return value;
3325}
3327template <typename T>
3328std::string generate_set(const T &set) {
3329 using element_t = typename detail::element_type<T>::type;
3330 using iteration_type_t =
3331 typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3332 std::string out(1, '{');
3333 out.append(detail::join(
3334 detail::smart_deref(set),
3335 [](const iteration_type_t &v) { return detail::pair_adaptor<element_t>::first(v); }, ","));
3336 out.push_back('}');
3337 return out;
3338}
3339
3341template <typename T>
3342std::string generate_map(const T &map, bool key_only = false) {
3343 using element_t = typename detail::element_type<T>::type;
3344 using iteration_type_t =
3345 typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3346 std::string out(1, '{');
3347 out.append(detail::join(
3348 detail::smart_deref(map),
3349 [key_only](const iteration_type_t &v) {
3350 std::string res{detail::to_string(detail::pair_adaptor<element_t>::first(v))};
3351
3352 if (!key_only) {
3353 res.append("->");
3354 res += detail::to_string(detail::pair_adaptor<element_t>::second(v));
3355 }
3356 return res;
3357 },
3358 ","));
3359 out.push_back('}');
3360 return out;
3361}
3362
3363template <typename C, typename V>
3364struct has_find {
3365 template <typename CC, typename VV>
3366 static auto test(int)
3367 -> decltype(std::declval<CC>().find(std::declval<VV>()), std::true_type());
3368 template <typename, typename>
3369 static auto test(...) -> decltype(std::false_type());
3370
3371 static const auto value = decltype(test<C, V>(0))::value;
3372 using type = std::integral_constant<bool, value>;
3373};
3374
3376template <typename T,
3377 typename V,
3378 enable_if_t<!has_find<T, V>::value, detail::enabler> = detail::dummy>
3379auto search(const T &set, const V &val)
3380 -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3381 using element_t = typename detail::element_type<T>::type;
3382 auto &setref = detail::smart_deref(set);
3383 auto it =
3384 std::find_if(std::begin(setref), std::end(setref), [&val](decltype(*std::begin(setref)) v) {
3385 return (detail::pair_adaptor<element_t>::first(v) == val);
3386 });
3387 return {(it != std::end(setref)), it};
3388}
3389
3391template <typename T,
3392 typename V,
3393 enable_if_t<has_find<T, V>::value, detail::enabler> = detail::dummy>
3394auto search(const T &set, const V &val)
3395 -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3396 auto &setref = detail::smart_deref(set);
3397 auto it = setref.find(val);
3398 return {(it != std::end(setref)), it};
3399}
3400
3402template <typename T, typename V>
3403auto search(const T &set, const V &val, const std::function<V(V)> &filter_function)
3404 -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3405 using element_t = typename detail::element_type<T>::type;
3406 // do the potentially faster first search
3407 auto res = search(set, val);
3408 if ((res.first) || (!(filter_function))) {
3409 return res;
3410 }
3411 // if we haven't found it do the longer linear search with all the element translations
3412 auto &setref = detail::smart_deref(set);
3413 auto it =
3414 std::find_if(std::begin(setref), std::end(setref), [&](decltype(*std::begin(setref)) v) {
3416 a = filter_function(a);
3417 return (a == val);
3418 });
3419 return {(it != std::end(setref)), it};
3420}
3421
3422// the following suggestion was made by Nikita Ofitserov(@himikof)
3423// done in templates to prevent compiler warnings on negation of unsigned numbers
3424
3426template <typename T>
3427inline typename std::enable_if<std::is_signed<T>::value, T>::type overflowCheck(const T &a,
3428 const T &b) {
3429 if ((a > 0) == (b > 0)) {
3430 return ((std::numeric_limits<T>::max)() / (std::abs)(a) < (std::abs)(b));
3431 }
3432 return ((std::numeric_limits<T>::min)() / (std::abs)(a) > -(std::abs)(b));
3433}
3435template <typename T>
3436inline typename std::enable_if<!std::is_signed<T>::value, T>::type overflowCheck(const T &a,
3437 const T &b) {
3438 return ((std::numeric_limits<T>::max)() / a < b);
3439}
3440
3442template <typename T>
3443typename std::enable_if<std::is_integral<T>::value, bool>::type checked_multiply(T &a, T b) {
3444 if (a == 0 || b == 0 || a == 1 || b == 1) {
3445 a *= b;
3446 return true;
3447 }
3448 if (a == (std::numeric_limits<T>::min)() || b == (std::numeric_limits<T>::min)()) {
3449 return false;
3450 }
3451 if (overflowCheck(a, b)) {
3452 return false;
3453 }
3454 a *= b;
3455 return true;
3456}
3457
3459template <typename T>
3460typename std::enable_if<std::is_floating_point<T>::value, bool>::type checked_multiply(T &a, T b) {
3461 T c = a * b;
3462 if (std::isinf(c) && !std::isinf(a) && !std::isinf(b)) {
3463 return false;
3464 }
3465 a = c;
3466 return true;
3467}
3468
3469} // namespace detail
3471class IsMember : public Validator {
3472public:
3473 using filter_fn_t = std::function<std::string(std::string)>;
3474
3476 template <typename T, typename... Args>
3477 IsMember(std::initializer_list<T> values, Args &&...args)
3478 : IsMember(std::vector<T>(values), std::forward<Args>(args)...) {}
3479
3481 template <typename T>
3482 explicit IsMember(T &&set) : IsMember(std::forward<T>(set), nullptr) {}
3483
3486 template <typename T, typename F>
3487 explicit IsMember(T set, F filter_function) {
3488 // Get the type of the contained item - requires a container have ::value_type
3489 // if the type does not have first_type and second_type, these are both value_type
3490 using element_t =
3491 typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3492 using item_t =
3493 typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3494
3495 using local_item_t =
3496 typename IsMemberType<item_t>::type; // This will convert bad types to good ones
3497 // (const char * to std::string)
3498
3499 // Make a local copy of the filter function, using a std::function if not one already
3500 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3501
3502 // This is the type name for help, it will take the current version of the set contents
3503 desc_function_ = [set]() { return detail::generate_set(detail::smart_deref(set)); };
3504
3505 // This is the function that validates
3506 // It stores a copy of the set pointer-like, so shared_ptr will stay alive
3507 func_ = [set, filter_fn](std::string &input) {
3508 local_item_t b;
3509 if (!detail::lexical_cast(input, b)) {
3510 throw ValidationError(input); // name is added later
3511 }
3512 if (filter_fn) {
3513 b = filter_fn(b);
3514 }
3515 auto res = detail::search(set, b, filter_fn);
3516 if (res.first) {
3517 // Make sure the version in the input string is identical to the one in the set
3518 if (filter_fn) {
3519 input =
3520 detail::value_string(detail::pair_adaptor<element_t>::first(*(res.second)));
3521 }
3522
3523 // Return empty error string (success)
3524 return std::string{};
3525 }
3526
3527 // If you reach this point, the result was not found
3528 return input + " not in " + detail::generate_set(detail::smart_deref(set));
3529 };
3530 }
3531
3533 template <typename T, typename... Args>
3534 IsMember(T &&set, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3535 : IsMember(
3536 std::forward<T>(set),
3537 [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3538 other...) {}
3539};
3540
3542template <typename T>
3543using TransformPairs = std::vector<std::pair<std::string, T>>;
3544
3546class Transformer : public Validator {
3547public:
3548 using filter_fn_t = std::function<std::string(std::string)>;
3549
3551 template <typename... Args>
3552 Transformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
3553 : Transformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
3554
3556 template <typename T>
3557 explicit Transformer(T &&mapping) : Transformer(std::forward<T>(mapping), nullptr) {}
3558
3561 template <typename T, typename F>
3562 explicit Transformer(T mapping, F filter_function) {
3564 "mapping must produce value pairs");
3565 // Get the type of the contained item - requires a container have ::value_type
3566 // if the type does not have first_type and second_type, these are both value_type
3567 using element_t =
3568 typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3569 using item_t =
3570 typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3571 using local_item_t =
3572 typename IsMemberType<item_t>::type; // Will convert bad types to good ones
3573 // (const char * to std::string)
3574
3575 // Make a local copy of the filter function, using a std::function if not one already
3576 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3577
3578 // This is the type name for help, it will take the current version of the set contents
3579 desc_function_ = [mapping]() { return detail::generate_map(detail::smart_deref(mapping)); };
3580
3581 func_ = [mapping, filter_fn](std::string &input) {
3582 local_item_t b;
3583 if (!detail::lexical_cast(input, b)) {
3584 return std::string();
3585 // there is no possible way we can match anything in the mapping if we can't convert
3586 // so just return
3587 }
3588 if (filter_fn) {
3589 b = filter_fn(b);
3590 }
3591 auto res = detail::search(mapping, b, filter_fn);
3592 if (res.first) {
3593 input = detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
3594 }
3595 return std::string{};
3596 };
3597 }
3598
3600 template <typename T, typename... Args>
3601 Transformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3602 : Transformer(
3603 std::forward<T>(mapping),
3604 [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3605 other...) {}
3606};
3607
3609class CheckedTransformer : public Validator {
3610public:
3611 using filter_fn_t = std::function<std::string(std::string)>;
3612
3614 template <typename... Args>
3615 CheckedTransformer(std::initializer_list<std::pair<std::string, std::string>> values,
3616 Args &&...args)
3617 : CheckedTransformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
3618
3620 template <typename T>
3621 explicit CheckedTransformer(T mapping) : CheckedTransformer(std::move(mapping), nullptr) {}
3622
3625 template <typename T, typename F>
3626 explicit CheckedTransformer(T mapping, F filter_function) {
3628 "mapping must produce value pairs");
3629 // Get the type of the contained item - requires a container have ::value_type
3630 // if the type does not have first_type and second_type, these are both value_type
3631 using element_t =
3632 typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3633 using item_t =
3634 typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3635 using local_item_t =
3636 typename IsMemberType<item_t>::type; // Will convert bad types to good ones
3637 // (const char * to std::string)
3638 using iteration_type_t =
3639 typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3640
3641 // Make a local copy of the filter function, using a std::function if not one already
3642 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3643
3644 auto tfunc = [mapping]() {
3645 std::string out("value in ");
3646 out += detail::generate_map(detail::smart_deref(mapping)) + " OR {";
3647 out += detail::join(
3648 detail::smart_deref(mapping),
3649 [](const iteration_type_t &v) {
3650 return detail::to_string(detail::pair_adaptor<element_t>::second(v));
3651 },
3652 ",");
3653 out.push_back('}');
3654 return out;
3655 };
3656
3657 desc_function_ = tfunc;
3658
3659 func_ = [mapping, tfunc, filter_fn](std::string &input) {
3660 local_item_t b;
3661 bool converted = detail::lexical_cast(input, b);
3662 if (converted) {
3663 if (filter_fn) {
3664 b = filter_fn(b);
3665 }
3666 auto res = detail::search(mapping, b, filter_fn);
3667 if (res.first) {
3668 input =
3669 detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
3670 return std::string{};
3671 }
3672 }
3673 for (const auto &v : detail::smart_deref(mapping)) {
3674 auto output_string =
3675 detail::value_string(detail::pair_adaptor<element_t>::second(v));
3676 if (output_string == input) {
3677 return std::string();
3678 }
3679 }
3680
3681 return "Check " + input + " " + tfunc() + " FAILED";
3682 };
3683 }
3684
3686 template <typename T, typename... Args>
3688 filter_fn_t filter_fn_1,
3689 filter_fn_t filter_fn_2,
3690 Args &&...other)
3692 std::forward<T>(mapping),
3693 [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3694 other...) {}
3695};
3696
3698inline std::string ignore_case(std::string item) { return detail::to_lower(item); }
3699
3701inline std::string ignore_underscore(std::string item) { return detail::remove_underscore(item); }
3702
3704inline std::string ignore_space(std::string item) {
3705 item.erase(std::remove(std::begin(item), std::end(item), ' '), std::end(item));
3706 item.erase(std::remove(std::begin(item), std::end(item), '\t'), std::end(item));
3707 return item;
3708}
3709
3721class AsNumberWithUnit : public Validator {
3722public:
3727 enum Options {
3728 CASE_SENSITIVE = 0,
3729 CASE_INSENSITIVE = 1,
3730 UNIT_OPTIONAL = 0,
3731 UNIT_REQUIRED = 2,
3732 DEFAULT = CASE_INSENSITIVE | UNIT_OPTIONAL
3733 };
3734
3735 template <typename Number>
3736 explicit AsNumberWithUnit(std::map<std::string, Number> mapping,
3737 Options opts = DEFAULT,
3738 const std::string &unit_name = "UNIT") {
3739 description(generate_description<Number>(unit_name, opts));
3740 validate_mapping(mapping, opts);
3741
3742 // transform function
3743 func_ = [mapping, opts](std::string &input) -> std::string {
3744 Number num{};
3745
3746 detail::rtrim(input);
3747 if (input.empty()) {
3748 throw ValidationError("Input is empty");
3749 }
3750
3751 // Find split position between number and prefix
3752 auto unit_begin = input.end();
3753 while (unit_begin > input.begin() && std::isalpha(*(unit_begin - 1), std::locale())) {
3754 --unit_begin;
3755 }
3756
3757 std::string unit{unit_begin, input.end()};
3758 input.resize(static_cast<std::size_t>(std::distance(input.begin(), unit_begin)));
3759 detail::trim(input);
3760
3761 if (opts & UNIT_REQUIRED && unit.empty()) {
3762 throw ValidationError("Missing mandatory unit");
3763 }
3764 if (opts & CASE_INSENSITIVE) {
3765 unit = detail::to_lower(unit);
3766 }
3767 if (unit.empty()) {
3768 if (!detail::lexical_cast(input, num)) {
3769 throw ValidationError(std::string("Value ") + input +
3770 " could not be converted to " +
3771 detail::type_name<Number>());
3772 }
3773 // No need to modify input if no unit passed
3774 return {};
3775 }
3776
3777 // find corresponding factor
3778 auto it = mapping.find(unit);
3779 if (it == mapping.end()) {
3780 throw ValidationError(unit +
3781 " unit not recognized. "
3782 "Allowed values: " +
3783 detail::generate_map(mapping, true));
3784 }
3785
3786 if (!input.empty()) {
3787 bool converted = detail::lexical_cast(input, num);
3788 if (!converted) {
3789 throw ValidationError(std::string("Value ") + input +
3790 " could not be converted to " +
3791 detail::type_name<Number>());
3792 }
3793 // perform safe multiplication
3794 bool ok = detail::checked_multiply(num, it->second);
3795 if (!ok) {
3796 throw ValidationError(
3797 detail::to_string(num) + " multiplied by " + unit +
3798 " factor would cause number overflow. Use smaller value.");
3799 }
3800 } else {
3801 num = static_cast<Number>(it->second);
3802 }
3803
3804 input = detail::to_string(num);
3805
3806 return {};
3807 };
3808 }
3809
3810private:
3813 template <typename Number>
3814 static void validate_mapping(std::map<std::string, Number> &mapping, Options opts) {
3815 for (auto &kv : mapping) {
3816 if (kv.first.empty()) {
3817 throw ValidationError("Unit must not be empty.");
3818 }
3819 if (!detail::isalpha(kv.first)) {
3820 throw ValidationError("Unit must contain only letters.");
3821 }
3822 }
3823
3824 // make all units lowercase if CASE_INSENSITIVE
3825 if (opts & CASE_INSENSITIVE) {
3826 std::map<std::string, Number> lower_mapping;
3827 for (auto &kv : mapping) {
3828 auto s = detail::to_lower(kv.first);
3829 if (lower_mapping.count(s)) {
3830 throw ValidationError(
3831 std::string("Several matching lowercase unit representations are found: ") +
3832 s);
3833 }
3834 lower_mapping[detail::to_lower(kv.first)] = kv.second;
3835 }
3836 mapping = std::move(lower_mapping);
3837 }
3838 }
3839
3841 template <typename Number>
3842 static std::string generate_description(const std::string &name, Options opts) {
3843 std::stringstream out;
3844 out << detail::type_name<Number>() << ' ';
3845 if (opts & UNIT_REQUIRED) {
3846 out << name;
3847 } else {
3848 out << '[' << name << ']';
3849 }
3850 return out.str();
3851 }
3852};
3853
3855 const AsNumberWithUnit::Options &b) {
3856 return static_cast<AsNumberWithUnit::Options>(static_cast<int>(a) | static_cast<int>(b));
3857}
3858
3867class AsSizeValue : public AsNumberWithUnit {
3868public:
3869 using result_t = std::uint64_t;
3870
3878 explicit AsSizeValue(bool kb_is_1000);
3879
3880private:
3882 static std::map<std::string, result_t> init_mapping(bool kb_is_1000);
3883
3885 static std::map<std::string, result_t> get_mapping(bool kb_is_1000);
3886};
3887
3888namespace detail {
3893CLI11_INLINE std::pair<std::string, std::string> split_program_name(std::string commandline);
3894
3895} // namespace detail
3897
3898CLI11_INLINE std::string Validator::operator()(std::string &str) const {
3899 std::string retstring;
3900 if (active_) {
3901 if (non_modifying_) {
3902 std::string value = str;
3903 retstring = func_(value);
3904 } else {
3905 retstring = func_(str);
3906 }
3907 }
3908 return retstring;
3909}
3910
3911CLI11_NODISCARD CLI11_INLINE Validator Validator::description(std::string validator_desc) const {
3912 Validator newval(*this);
3913 newval.desc_function_ = [validator_desc]() { return validator_desc; };
3914 return newval;
3915}
3916
3917CLI11_INLINE Validator Validator::operator&(const Validator &other) const {
3918 Validator newval;
3919
3920 newval._merge_description(*this, other, " AND ");
3921
3922 // Give references (will make a copy in lambda function)
3923 const std::function<std::string(std::string & filename)> &f1 = func_;
3924 const std::function<std::string(std::string & filename)> &f2 = other.func_;
3925
3926 newval.func_ = [f1, f2](std::string &input) {
3927 std::string s1 = f1(input);
3928 std::string s2 = f2(input);
3929 if (!s1.empty() && !s2.empty()) return std::string("(") + s1 + ") AND (" + s2 + ")";
3930 return s1 + s2;
3931 };
3932
3933 newval.active_ = active_ && other.active_;
3935 return newval;
3936}
3937
3938CLI11_INLINE Validator Validator::operator|(const Validator &other) const {
3939 Validator newval;
3940
3941 newval._merge_description(*this, other, " OR ");
3942
3943 // Give references (will make a copy in lambda function)
3944 const std::function<std::string(std::string &)> &f1 = func_;
3945 const std::function<std::string(std::string &)> &f2 = other.func_;
3946
3947 newval.func_ = [f1, f2](std::string &input) {
3948 std::string s1 = f1(input);
3949 std::string s2 = f2(input);
3950 if (s1.empty() || s2.empty()) return std::string();
3951
3952 return std::string("(") + s1 + ") OR (" + s2 + ")";
3953 };
3954 newval.active_ = active_ && other.active_;
3956 return newval;
3957}
3958
3959CLI11_INLINE Validator Validator::operator!() const {
3960 Validator newval;
3961 const std::function<std::string()> &dfunc1 = desc_function_;
3962 newval.desc_function_ = [dfunc1]() {
3963 auto str = dfunc1();
3964 return (!str.empty()) ? std::string("NOT ") + str : std::string{};
3965 };
3966 // Give references (will make a copy in lambda function)
3967 const std::function<std::string(std::string & res)> &f1 = func_;
3968
3969 newval.func_ = [f1, dfunc1](std::string &test) -> std::string {
3970 std::string s1 = f1(test);
3971 if (s1.empty()) {
3972 return std::string("check ") + dfunc1() + " succeeded improperly";
3973 }
3974 return std::string{};
3975 };
3976 newval.active_ = active_;
3978 return newval;
3979}
3980
3981CLI11_INLINE void Validator::_merge_description(const Validator &val1,
3982 const Validator &val2,
3983 const std::string &merger) {
3984 const std::function<std::string()> &dfunc1 = val1.desc_function_;
3985 const std::function<std::string()> &dfunc2 = val2.desc_function_;
3986
3987 desc_function_ = [=]() {
3988 std::string f1 = dfunc1();
3989 std::string f2 = dfunc2();
3990 if ((f1.empty()) || (f2.empty())) {
3991 return f1 + f2;
3992 }
3993 return std::string(1, '(') + f1 + ')' + merger + '(' + f2 + ')';
3994 };
3995}
3996
3997namespace detail {
3998
3999#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
4000CLI11_INLINE path_type check_path(const char *file) noexcept {
4001 std::error_code ec;
4002 auto stat = std::filesystem::status(file, ec);
4003 if (ec) {
4004 return path_type::nonexistent;
4005 }
4006 switch (stat.type()) {
4007 case std::filesystem::file_type::none: // LCOV_EXCL_LINE
4008 case std::filesystem::file_type::not_found:
4009 return path_type::nonexistent;
4010 case std::filesystem::file_type::directory:
4011 return path_type::directory;
4012 case std::filesystem::file_type::symlink:
4013 case std::filesystem::file_type::block:
4014 case std::filesystem::file_type::character:
4015 case std::filesystem::file_type::fifo:
4016 case std::filesystem::file_type::socket:
4017 case std::filesystem::file_type::regular:
4018 case std::filesystem::file_type::unknown:
4019 default:
4020 return path_type::file;
4021 }
4022}
4023#else
4024CLI11_INLINE path_type check_path(const char *file) noexcept {
4025#if defined(_MSC_VER)
4026 struct __stat64 buffer;
4027 if (_stat64(file, &buffer) == 0) {
4028 return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
4029 }
4030#else
4031 struct stat buffer;
4032 if (stat(file, &buffer) == 0) {
4033 return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
4034 }
4035#endif
4036 return path_type::nonexistent;
4037}
4038#endif
4039
4040CLI11_INLINE ExistingFileValidator::ExistingFileValidator() : Validator("FILE") {
4041 func_ = [](std::string &filename) {
4042 auto path_result = check_path(filename.c_str());
4043 if (path_result == path_type::nonexistent) {
4044 return "File does not exist: " + filename;
4045 }
4046 if (path_result == path_type::directory) {
4047 return "File is actually a directory: " + filename;
4048 }
4049 return std::string();
4050 };
4051}
4052
4053CLI11_INLINE ExistingDirectoryValidator::ExistingDirectoryValidator() : Validator("DIR") {
4054 func_ = [](std::string &filename) {
4055 auto path_result = check_path(filename.c_str());
4056 if (path_result == path_type::nonexistent) {
4057 return "Directory does not exist: " + filename;
4058 }
4059 if (path_result == path_type::file) {
4060 return "Directory is actually a file: " + filename;
4061 }
4062 return std::string();
4063 };
4064}
4065
4066CLI11_INLINE ExistingPathValidator::ExistingPathValidator() : Validator("PATH(existing)") {
4067 func_ = [](std::string &filename) {
4068 auto path_result = check_path(filename.c_str());
4069 if (path_result == path_type::nonexistent) {
4070 return "Path does not exist: " + filename;
4071 }
4072 return std::string();
4073 };
4074}
4075
4076CLI11_INLINE NonexistentPathValidator::NonexistentPathValidator()
4077 : Validator("PATH(non-existing)") {
4078 func_ = [](std::string &filename) {
4079 auto path_result = check_path(filename.c_str());
4080 if (path_result != path_type::nonexistent) {
4081 return "Path already exists: " + filename;
4082 }
4083 return std::string();
4084 };
4085}
4086
4087CLI11_INLINE IPV4Validator::IPV4Validator() : Validator("IPV4") {
4088 func_ = [](std::string &ip_addr) {
4089 auto result = CLI::detail::split(ip_addr, '.');
4090 if (result.size() != 4) {
4091 return std::string("Invalid IPV4 address must have four parts (") + ip_addr + ')';
4092 }
4093 int num = 0;
4094 for (const auto &var : result) {
4095 bool retval = detail::lexical_cast(var, num);
4096 if (!retval) {
4097 return std::string("Failed parsing number (") + var + ')';
4098 }
4099 if (num < 0 || num > 255) {
4100 return std::string("Each IP number must be between 0 and 255 ") + var;
4101 }
4102 }
4103 return std::string();
4104 };
4105}
4106
4107} // namespace detail
4108
4109CLI11_INLINE FileOnDefaultPath::FileOnDefaultPath(std::string default_path, bool enableErrorReturn)
4110 : Validator("FILE") {
4111 func_ = [default_path, enableErrorReturn](std::string &filename) {
4112 auto path_result = detail::check_path(filename.c_str());
4113 if (path_result == detail::path_type::nonexistent) {
4114 std::string test_file_path = default_path;
4115 if (default_path.back() != '/' && default_path.back() != '\\') {
4116 // Add folder separator
4117 test_file_path += '/';
4118 }
4119 test_file_path.append(filename);
4120 path_result = detail::check_path(test_file_path.c_str());
4121 if (path_result == detail::path_type::file) {
4122 filename = test_file_path;
4123 } else {
4124 if (enableErrorReturn) {
4125 return "File does not exist: " + filename;
4126 }
4127 }
4128 }
4129 return std::string{};
4130 };
4131}
4132
4133CLI11_INLINE AsSizeValue::AsSizeValue(bool kb_is_1000) : AsNumberWithUnit(get_mapping(kb_is_1000)) {
4134 if (kb_is_1000) {
4135 description("SIZE [b, kb(=1000b), kib(=1024b), ...]");
4136 } else {
4137 description("SIZE [b, kb(=1024b), ...]");
4138 }
4139}
4140
4141CLI11_INLINE std::map<std::string, AsSizeValue::result_t> AsSizeValue::init_mapping(
4142 bool kb_is_1000) {
4143 std::map<std::string, result_t> m;
4144 result_t k_factor = kb_is_1000 ? 1000 : 1024;
4145 result_t ki_factor = 1024;
4146 result_t k = 1;
4147 result_t ki = 1;
4148 m["b"] = 1;
4149 for (std::string p : {"k", "m", "g", "t", "p", "e"}) {
4150 k *= k_factor;
4151 ki *= ki_factor;
4152 m[p] = k;
4153 m[p + "b"] = k;
4154 m[p + "i"] = ki;
4155 m[p + "ib"] = ki;
4156 }
4157 return m;
4158}
4159
4160CLI11_INLINE std::map<std::string, AsSizeValue::result_t> AsSizeValue::get_mapping(
4161 bool kb_is_1000) {
4162 if (kb_is_1000) {
4163 static auto m = init_mapping(true);
4164 return m;
4165 }
4166 static auto m = init_mapping(false);
4167 return m;
4168}
4169
4170namespace detail {
4171
4172CLI11_INLINE std::pair<std::string, std::string> split_program_name(std::string commandline) {
4173 // try to determine the programName
4174 std::pair<std::string, std::string> vals;
4175 trim(commandline);
4176 auto esp = commandline.find_first_of(' ', 1);
4177 while (detail::check_path(commandline.substr(0, esp).c_str()) != path_type::file) {
4178 esp = commandline.find_first_of(' ', esp + 1);
4179 if (esp == std::string::npos) {
4180 // if we have reached the end and haven't found a valid file just assume the first
4181 // argument is the program name
4182 if (commandline[0] == '"' || commandline[0] == '\'' || commandline[0] == '`') {
4183 bool embeddedQuote = false;
4184 auto keyChar = commandline[0];
4185 auto end = commandline.find_first_of(keyChar, 1);
4186 while ((end != std::string::npos) &&
4187 (commandline[end - 1] == '\\')) { // deal with escaped quotes
4188 end = commandline.find_first_of(keyChar, end + 1);
4189 embeddedQuote = true;
4190 }
4191 if (end != std::string::npos) {
4192 vals.first = commandline.substr(1, end - 1);
4193 esp = end + 1;
4194 if (embeddedQuote) {
4195 vals.first = find_and_replace(vals.first, std::string("\\") + keyChar,
4196 std::string(1, keyChar));
4197 }
4198 } else {
4199 esp = commandline.find_first_of(' ', 1);
4200 }
4201 } else {
4202 esp = commandline.find_first_of(' ', 1);
4203 }
4204
4205 break;
4206 }
4207 }
4208 if (vals.first.empty()) {
4209 vals.first = commandline.substr(0, esp);
4210 rtrim(vals.first);
4211 }
4212
4213 // strip the program name
4214 vals.second = (esp < commandline.length() - 1) ? commandline.substr(esp + 1) : std::string{};
4215 ltrim(vals.second);
4216 return vals;
4217}
4218
4219} // namespace detail
4221
4222class Option;
4223class App;
4224
4229
4230enum class AppFormatMode {
4231 Normal,
4232 All,
4233 Sub,
4234};
4235
4240class FormatterBase {
4241protected:
4244
4246 std::size_t column_width_{30};
4247
4250 std::map<std::string, std::string> labels_{};
4251
4255
4256public:
4257 FormatterBase() = default;
4258 FormatterBase(const FormatterBase &) = default;
4259 FormatterBase(FormatterBase &&) = default;
4260 FormatterBase &operator=(const FormatterBase &) = default;
4261 FormatterBase &operator=(FormatterBase &&) = default;
4262
4264 virtual ~FormatterBase() noexcept {} // NOLINT(modernize-use-equals-default)
4265
4267 virtual std::string make_help(const App *, std::string, AppFormatMode) const = 0;
4268
4272
4274 void label(std::string key, std::string val) { labels_[key] = val; }
4275
4277 void column_width(std::size_t val) { column_width_ = val; }
4278
4282
4284 CLI11_NODISCARD std::string get_label(std::string key) const {
4285 if (labels_.find(key) == labels_.end()) return key;
4286 return labels_.at(key);
4287 }
4288
4290 CLI11_NODISCARD std::size_t get_column_width() const { return column_width_; }
4291
4293};
4294
4296class FormatterLambda final : public FormatterBase {
4297 using funct_t = std::function<std::string(const App *, std::string, AppFormatMode)>;
4298
4300 funct_t lambda_;
4301
4302public:
4304 explicit FormatterLambda(funct_t funct) : lambda_(std::move(funct)) {}
4305
4307 ~FormatterLambda() noexcept override {} // NOLINT(modernize-use-equals-default)
4308
4310 std::string make_help(const App *app, std::string name, AppFormatMode mode) const override {
4311 return lambda_(app, name, mode);
4312 }
4313};
4314
4317class Formatter : public FormatterBase {
4318public:
4319 Formatter() = default;
4320 Formatter(const Formatter &) = default;
4321 Formatter(Formatter &&) = default;
4322 Formatter &operator=(const Formatter &) = default;
4323 Formatter &operator=(Formatter &&) = default;
4324
4327
4330 CLI11_NODISCARD virtual std::string make_group(std::string group,
4331 bool is_positional,
4332 std::vector<const Option *> opts) const;
4333
4335 virtual std::string make_positionals(const App *app) const;
4336
4338 std::string make_groups(const App *app, AppFormatMode mode) const;
4339
4341 virtual std::string make_subcommands(const App *app, AppFormatMode mode) const;
4342
4344 virtual std::string make_subcommand(const App *sub) const;
4345
4347 virtual std::string make_expanded(const App *sub) const;
4348
4350 virtual std::string make_footer(const App *app) const;
4351
4353 virtual std::string make_description(const App *app) const;
4354
4356 virtual std::string make_usage(const App *app, std::string name) const;
4357
4359 std::string make_help(const App * /*app*/, std::string, AppFormatMode) const override;
4360
4364
4366 virtual std::string make_option(const Option *opt, bool is_positional) const {
4367 std::stringstream out;
4368 detail::format_help(out, make_option_name(opt, is_positional) + make_option_opts(opt),
4370 return out.str();
4371 }
4372
4374 virtual std::string make_option_name(const Option *, bool) const;
4375
4377 virtual std::string make_option_opts(const Option *) const;
4378
4380 virtual std::string make_option_desc(const Option *) const;
4381
4383 virtual std::string make_option_usage(const Option *opt) const;
4384
4386};
4387
4388using results_t = std::vector<std::string>;
4390using callback_t = std::function<bool(const results_t &)>;
4391
4392class Option;
4393class App;
4394
4395using Option_p = std::unique_ptr<Option>;
4397enum class MultiOptionPolicy : char {
4398 Throw,
4399 TakeLast,
4400 TakeFirst,
4401 Join,
4403 TakeAll,
4404 Sum
4405};
4406
4409template <typename CRTP>
4411 friend App;
4412
4413protected:
4415 std::string group_ = std::string("Options");
4416
4418 bool required_{false};
4419
4421 bool ignore_case_{false};
4422
4425
4427 bool configurable_{true};
4428
4431
4433 char delimiter_{'\0'};
4434
4437
4439 MultiOptionPolicy multi_option_policy_{MultiOptionPolicy::Throw};
4440
4442 template <typename T>
4443 void copy_to(T *other) const;
4444
4445public:
4446 // setters
4447
4449 CRTP *group(const std::string &name) {
4450 if (!detail::valid_alias_name_string(name)) {
4451 throw IncorrectConstruction("Group names may not contain newlines or null characters");
4452 }
4453 group_ = name;
4454 return static_cast<CRTP *>(this);
4455 }
4456
4458 CRTP *required(bool value = true) {
4459 required_ = value;
4460 return static_cast<CRTP *>(this);
4461 }
4462
4464 CRTP *mandatory(bool value = true) { return required(value); }
4465
4466 CRTP *always_capture_default(bool value = true) {
4468 return static_cast<CRTP *>(this);
4469 }
4470
4471 // Getters
4472
4474 CLI11_NODISCARD const std::string &get_group() const { return group_; }
4475
4477 CLI11_NODISCARD bool get_required() const { return required_; }
4478
4480 CLI11_NODISCARD bool get_ignore_case() const { return ignore_case_; }
4481
4483 CLI11_NODISCARD bool get_ignore_underscore() const { return ignore_underscore_; }
4484
4486 CLI11_NODISCARD bool get_configurable() const { return configurable_; }
4487
4489 CLI11_NODISCARD bool get_disable_flag_override() const { return disable_flag_override_; }
4490
4492 CLI11_NODISCARD char get_delimiter() const { return delimiter_; }
4493
4495 CLI11_NODISCARD bool get_always_capture_default() const { return always_capture_default_; }
4496
4498 CLI11_NODISCARD MultiOptionPolicy get_multi_option_policy() const {
4499 return multi_option_policy_;
4500 }
4501
4502 // Shortcuts for multi option policy
4503
4505 CRTP *take_last() {
4506 auto *self = static_cast<CRTP *>(this);
4507 self->multi_option_policy(MultiOptionPolicy::TakeLast);
4508 return self;
4509 }
4510
4512 CRTP *take_first() {
4513 auto *self = static_cast<CRTP *>(this);
4514 self->multi_option_policy(MultiOptionPolicy::TakeFirst);
4515 return self;
4516 }
4517
4519 CRTP *take_all() {
4520 auto self = static_cast<CRTP *>(this);
4521 self->multi_option_policy(MultiOptionPolicy::TakeAll);
4522 return self;
4523 }
4524
4526 CRTP *join() {
4527 auto *self = static_cast<CRTP *>(this);
4528 self->multi_option_policy(MultiOptionPolicy::Join);
4529 return self;
4530 }
4531
4533 CRTP *join(char delim) {
4534 auto self = static_cast<CRTP *>(this);
4535 self->delimiter_ = delim;
4536 self->multi_option_policy(MultiOptionPolicy::Join);
4537 return self;
4538 }
4539
4541 CRTP *configurable(bool value = true) {
4542 configurable_ = value;
4543 return static_cast<CRTP *>(this);
4544 }
4545
4547 CRTP *delimiter(char value = '\0') {
4548 delimiter_ = value;
4549 return static_cast<CRTP *>(this);
4550 }
4551};
4552
4555class OptionDefaults : public OptionBase<OptionDefaults> {
4556public:
4557 OptionDefaults() = default;
4558
4559 // Methods here need a different implementation if they are Option vs. OptionDefault
4560
4562 OptionDefaults *multi_option_policy(MultiOptionPolicy value = MultiOptionPolicy::Throw) {
4563 multi_option_policy_ = value;
4564 return this;
4565 }
4566
4568 OptionDefaults *ignore_case(bool value = true) {
4569 ignore_case_ = value;
4570 return this;
4571 }
4572
4574 OptionDefaults *ignore_underscore(bool value = true) {
4575 ignore_underscore_ = value;
4576 return this;
4577 }
4578
4580 OptionDefaults *disable_flag_override(bool value = true) {
4581 disable_flag_override_ = value;
4582 return this;
4583 }
4584
4586 OptionDefaults *delimiter(char value = '\0') {
4587 delimiter_ = value;
4588 return this;
4589 }
4590};
4591
4592class Option : public OptionBase<Option> {
4593 friend App;
4594
4595protected:
4598
4600 std::vector<std::string> snames_{};
4601
4603 std::vector<std::string> lnames_{};
4604
4608 std::vector<std::pair<std::string, std::string>> default_flag_values_{};
4609
4611 std::vector<std::string> fnames_{};
4612
4614 std::string pname_{};
4615
4617 std::string envname_{};
4618
4622
4624 std::string description_{};
4625
4627 std::string default_str_{};
4628
4630 std::string option_text_{};
4631
4635 std::function<std::string()> type_name_{[]() { return std::string(); }};
4636
4638 std::function<std::string()> default_function_{};
4639
4643
4649
4654
4656 std::vector<Validator> validators_{};
4657
4659 std::set<Option *> needs_{};
4660
4662 std::set<Option *> excludes_{};
4663
4667
4669 App *parent_{nullptr};
4670
4672 callback_t callback_{};
4673
4677
4679 results_t results_{};
4681 results_t proc_results_{};
4683 enum class option_state : char {
4688 };
4689
4694 bool flag_like_{false};
4703 bool force_callback_{false};
4705
4707 Option(std::string option_name,
4708 std::string option_description,
4709 callback_t callback,
4710 App *parent)
4711 : description_(std::move(option_description)),
4712 parent_(parent),
4713 callback_(std::move(callback)) {
4714 std::tie(snames_, lnames_, pname_) = detail::get_names(detail::split_names(option_name));
4715 }
4716
4717public:
4720
4721 Option(const Option &) = delete;
4722 Option &operator=(const Option &) = delete;
4723
4725 CLI11_NODISCARD std::size_t count() const { return results_.size(); }
4726
4728 CLI11_NODISCARD bool empty() const { return results_.empty(); }
4729
4732 explicit operator bool() const { return !empty() || force_callback_; }
4733
4735 void clear() {
4736 results_.clear();
4738 }
4739
4743
4745 Option *expected(int value);
4746
4748 Option *expected(int value_min, int value_max);
4749
4752 Option *allow_extra_args(bool value = true) {
4753 allow_extra_args_ = value;
4754 return this;
4755 }
4756
4757 CLI11_NODISCARD bool get_allow_extra_args() const { return allow_extra_args_; }
4760 Option *trigger_on_parse(bool value = true) {
4761 trigger_on_result_ = value;
4762 return this;
4763 }
4764
4765 CLI11_NODISCARD bool get_trigger_on_parse() const { return trigger_on_result_; }
4766
4768 Option *force_callback(bool value = true) {
4769 force_callback_ = value;
4770 return this;
4771 }
4772
4773 CLI11_NODISCARD bool get_force_callback() const { return force_callback_; }
4774
4778 Option *run_callback_for_default(bool value = true) {
4780 return this;
4781 }
4782
4783 CLI11_NODISCARD bool get_run_callback_for_default() const { return run_callback_for_default_; }
4784
4786 Option *check(Validator validator, const std::string &validator_name = "");
4787
4790 Option *check(std::function<std::string(const std::string &)> Validator,
4791 std::string Validator_description = "",
4792 std::string Validator_name = "");
4793
4795 Option *transform(Validator Validator, const std::string &Validator_name = "");
4796
4798 Option *transform(const std::function<std::string(std::string)> &func,
4799 std::string transform_description = "",
4800 std::string transform_name = "");
4801
4804 Option *each(const std::function<void(std::string)> &func);
4805
4807 Validator *get_validator(const std::string &Validator_name = "");
4808
4810 Validator *get_validator(int index);
4811
4814 if (opt != this) {
4815 needs_.insert(opt);
4816 }
4817 return this;
4818 }
4819
4821 template <typename T = App>
4822 Option *needs(std::string opt_name) {
4823 auto opt = static_cast<T *>(parent_)->get_option_no_throw(opt_name);
4824 if (opt == nullptr) {
4825 throw IncorrectConstruction::MissingOption(opt_name);
4826 }
4827 return needs(opt);
4828 }
4829
4831 template <typename A, typename B, typename... ARG>
4832 Option *needs(A opt, B opt1, ARG... args) {
4833 needs(opt);
4834 return needs(opt1, args...); // NOLINT(readability-suspicious-call-argument)
4835 }
4836
4838 bool remove_needs(Option *opt);
4839
4841 Option *excludes(Option *opt);
4842
4844 template <typename T = App>
4845 Option *excludes(std::string opt_name) {
4846 auto opt = static_cast<T *>(parent_)->get_option_no_throw(opt_name);
4847 if (opt == nullptr) {
4848 throw IncorrectConstruction::MissingOption(opt_name);
4849 }
4850 return excludes(opt);
4851 }
4852
4854 template <typename A, typename B, typename... ARG>
4855 Option *excludes(A opt, B opt1, ARG... args) {
4856 excludes(opt);
4857 return excludes(opt1, args...);
4858 }
4859
4861 bool remove_excludes(Option *opt);
4862
4864 Option *envname(std::string name) {
4865 envname_ = std::move(name);
4866 return this;
4867 }
4868
4873 template <typename T = App>
4874 Option *ignore_case(bool value = true);
4875
4880 template <typename T = App>
4881 Option *ignore_underscore(bool value = true);
4882
4884 Option *multi_option_policy(MultiOptionPolicy value = MultiOptionPolicy::Throw);
4885
4887 Option *disable_flag_override(bool value = true) {
4888 disable_flag_override_ = value;
4889 return this;
4890 }
4891
4894
4896 CLI11_NODISCARD int get_type_size() const { return type_size_min_; }
4897
4899 CLI11_NODISCARD int get_type_size_min() const { return type_size_min_; }
4901 CLI11_NODISCARD int get_type_size_max() const { return type_size_max_; }
4902
4904 CLI11_NODISCARD bool get_inject_separator() const { return inject_separator_; }
4905
4907 CLI11_NODISCARD std::string get_envname() const { return envname_; }
4908
4910 CLI11_NODISCARD std::set<Option *> get_needs() const { return needs_; }
4911
4913 CLI11_NODISCARD std::set<Option *> get_excludes() const { return excludes_; }
4914
4916 CLI11_NODISCARD std::string get_default_str() const { return default_str_; }
4917
4919 CLI11_NODISCARD callback_t get_callback() const { return callback_; }
4920
4922 CLI11_NODISCARD const std::vector<std::string> &get_lnames() const { return lnames_; }
4923
4925 CLI11_NODISCARD const std::vector<std::string> &get_snames() const { return snames_; }
4926
4928 CLI11_NODISCARD const std::vector<std::string> &get_fnames() const { return fnames_; }
4930 CLI11_NODISCARD const std::string &get_single_name() const {
4931 if (!lnames_.empty()) {
4932 return lnames_[0];
4933 }
4934 if (!pname_.empty()) {
4935 return pname_;
4936 }
4937 if (!snames_.empty()) {
4938 return snames_[0];
4939 }
4940 return envname_;
4941 }
4942
4943 CLI11_NODISCARD int get_expected() const { return expected_min_; }
4944
4946 CLI11_NODISCARD int get_expected_min() const { return expected_min_; }
4948 CLI11_NODISCARD int get_expected_max() const { return expected_max_; }
4949
4951 CLI11_NODISCARD int get_items_expected_min() const { return type_size_min_ * expected_min_; }
4952
4954 CLI11_NODISCARD int get_items_expected_max() const {
4955 int t = type_size_max_;
4956 return detail::checked_multiply(t, expected_max_) ? t : detail::expected_max_vector_size;
4957 }
4958
4959 CLI11_NODISCARD int get_items_expected() const { return get_items_expected_min(); }
4960
4962 CLI11_NODISCARD bool get_positional() const { return pname_.length() > 0; }
4963
4965 CLI11_NODISCARD bool nonpositional() const { return (snames_.size() + lnames_.size()) > 0; }
4966
4968 CLI11_NODISCARD bool has_description() const { return description_.length() > 0; }
4969
4971 CLI11_NODISCARD const std::string &get_description() const { return description_; }
4972
4974 Option *description(std::string option_description) {
4975 description_ = std::move(option_description);
4976 return this;
4977 }
4978
4979 Option *option_text(std::string text) {
4980 option_text_ = std::move(text);
4981 return this;
4982 }
4983
4984 CLI11_NODISCARD const std::string &get_option_text() const { return option_text_; }
4985
4989
4994 CLI11_NODISCARD std::string get_name(bool positional = false,
4995 bool all_options = false
4996 ) const;
4997
5001
5003 void run_callback();
5004
5006 CLI11_NODISCARD const std::string &matching_name(const Option &other) const;
5007
5009 bool operator==(const Option &other) const { return !matching_name(other).empty(); }
5010
5012 CLI11_NODISCARD bool check_name(const std::string &name) const;
5013
5015 CLI11_NODISCARD bool check_sname(std::string name) const {
5016 return (detail::find_member(std::move(name), snames_, ignore_case_) >= 0);
5017 }
5018
5020 CLI11_NODISCARD bool check_lname(std::string name) const {
5021 return (detail::find_member(std::move(name), lnames_, ignore_case_, ignore_underscore_) >=
5022 0);
5023 }
5024
5026 CLI11_NODISCARD bool check_fname(std::string name) const {
5027 if (fnames_.empty()) {
5028 return false;
5029 }
5030 return (detail::find_member(std::move(name), fnames_, ignore_case_, ignore_underscore_) >=
5031 0);
5032 }
5033
5036 CLI11_NODISCARD std::string get_flag_value(const std::string &name,
5037 std::string input_value) const;
5038
5040 Option *add_result(std::string s);
5041
5043 Option *add_result(std::string s, int &results_added);
5044
5046 Option *add_result(std::vector<std::string> s);
5047
5049 CLI11_NODISCARD const results_t &results() const { return results_; }
5050
5052 CLI11_NODISCARD results_t reduced_results() const;
5053
5055 template <typename T>
5056 void results(T &output) const {
5057 bool retval = false;
5059 (results_.size() == 1 && validators_.empty())) {
5060 const results_t &res = (proc_results_.empty()) ? results_ : proc_results_;
5061 retval = detail::lexical_conversion<T, T>(res, output);
5062 } else {
5063 results_t res;
5064 if (results_.empty()) {
5065 if (!default_str_.empty()) {
5066 // _add_results takes an rvalue only
5067 _add_result(std::string(default_str_), res);
5068 _validate_results(res);
5069 results_t extra;
5070 _reduce_results(extra, res);
5071 if (!extra.empty()) {
5072 res = std::move(extra);
5073 }
5074 } else {
5075 res.emplace_back();
5076 }
5077 } else {
5078 res = reduced_results();
5079 }
5080 retval = detail::lexical_conversion<T, T>(res, output);
5081 }
5082 if (!retval) {
5084 }
5085 }
5086
5088 template <typename T>
5089 CLI11_NODISCARD T as() const {
5090 T output;
5091 results(output);
5092 return output;
5093 }
5094
5096 CLI11_NODISCARD bool get_callback_run() const {
5098 }
5099
5103
5105 Option *type_name_fn(std::function<std::string()> typefun) {
5106 type_name_ = std::move(typefun);
5107 return this;
5108 }
5109
5111 Option *type_name(std::string typeval) {
5112 type_name_fn([typeval]() { return typeval; });
5113 return this;
5114 }
5115
5117 Option *type_size(int option_type_size);
5118
5120 Option *type_size(int option_type_size_min, int option_type_size_max);
5121
5123 void inject_separator(bool value = true) { inject_separator_ = value; }
5124
5126 Option *default_function(const std::function<std::string()> &func) {
5127 default_function_ = func;
5128 return this;
5129 }
5130
5133 if (default_function_) {
5135 }
5136 return this;
5137 }
5138
5140 Option *default_str(std::string val) {
5141 default_str_ = std::move(val);
5142 return this;
5143 }
5144
5147 template <typename X>
5148 Option *default_val(const X &val) {
5149 std::string val_str = detail::to_string(val);
5150 auto old_option_state = current_option_state_;
5151 results_t old_results{std::move(results_)};
5152 results_.clear();
5153 try {
5154 add_result(val_str);
5155 // if trigger_on_result_ is set the callback already ran
5157 run_callback(); // run callback sets the state, we need to reset it again
5159 } else {
5160 _validate_results(results_);
5161 current_option_state_ = old_option_state;
5162 }
5163 } catch (const CLI::Error &) {
5164 // this should be done
5165 results_ = std::move(old_results);
5166 current_option_state_ = old_option_state;
5167 throw;
5168 }
5169 results_ = std::move(old_results);
5170 default_str_ = std::move(val_str);
5171 return this;
5172 }
5173
5175 CLI11_NODISCARD std::string get_type_name() const;
5176
5177private:
5179 void _validate_results(results_t &res) const;
5180
5184 void _reduce_results(results_t &out, const results_t &original) const;
5185
5186 // Run a result through the Validators
5187 std::string _validate(std::string &result, int index) const;
5188
5190 int _add_result(std::string &&result, std::vector<std::string> &res) const;
5191};
5192
5193template <typename CRTP>
5194template <typename T>
5195void OptionBase<CRTP>::copy_to(T *other) const {
5196 other->group(group_);
5197 other->required(required_);
5198 other->ignore_case(ignore_case_);
5199 other->ignore_underscore(ignore_underscore_);
5200 other->configurable(configurable_);
5201 other->disable_flag_override(disable_flag_override_);
5202 other->delimiter(delimiter_);
5203 other->always_capture_default(always_capture_default_);
5204 other->multi_option_policy(multi_option_policy_);
5205}
5206
5207CLI11_INLINE Option *Option::expected(int value) {
5208 if (value < 0) {
5209 expected_min_ = -value;
5212 }
5213 allow_extra_args_ = true;
5214 flag_like_ = false;
5215 } else if (value == detail::expected_max_vector_size) {
5216 expected_min_ = 1;
5217 expected_max_ = detail::expected_max_vector_size;
5218 allow_extra_args_ = true;
5219 flag_like_ = false;
5220 } else {
5221 expected_min_ = value;
5222 expected_max_ = value;
5223 flag_like_ = (expected_min_ == 0);
5224 }
5225 return this;
5226}
5227
5228CLI11_INLINE Option *Option::expected(int value_min, int value_max) {
5229 if (value_min < 0) {
5230 value_min = -value_min;
5231 }
5232
5233 if (value_max < 0) {
5234 value_max = detail::expected_max_vector_size;
5235 }
5236 if (value_max < value_min) {
5237 expected_min_ = value_max;
5238 expected_max_ = value_min;
5239 } else {
5240 expected_max_ = value_max;
5241 expected_min_ = value_min;
5242 }
5243
5244 return this;
5245}
5246
5247CLI11_INLINE Option *Option::check(Validator validator, const std::string &validator_name) {
5248 validator.non_modifying();
5249 validators_.push_back(std::move(validator));
5250 if (!validator_name.empty()) validators_.back().name(validator_name);
5251 return this;
5252}
5253
5254CLI11_INLINE Option *Option::check(std::function<std::string(const std::string &)> Validator,
5255 std::string Validator_description,
5256 std::string Validator_name) {
5257 validators_.emplace_back(Validator, std::move(Validator_description),
5258 std::move(Validator_name));
5259 validators_.back().non_modifying();
5260 return this;
5261}
5262
5263CLI11_INLINE Option *Option::transform(Validator Validator, const std::string &Validator_name) {
5264 validators_.insert(validators_.begin(), std::move(Validator));
5265 if (!Validator_name.empty()) validators_.front().name(Validator_name);
5266 return this;
5267}
5268
5269CLI11_INLINE Option *Option::transform(const std::function<std::string(std::string)> &func,
5270 std::string transform_description,
5271 std::string transform_name) {
5272 validators_.insert(validators_.begin(),
5273 Validator(
5274 [func](std::string &val) {
5275 val = func(val);
5276 return std::string{};
5277 },
5278 std::move(transform_description), std::move(transform_name)));
5279
5280 return this;
5281}
5282
5283CLI11_INLINE Option *Option::each(const std::function<void(std::string)> &func) {
5284 validators_.emplace_back(
5285 [func](std::string &inout) {
5286 func(inout);
5287 return std::string{};
5288 },
5289 std::string{});
5290 return this;
5291}
5292
5293CLI11_INLINE Validator *Option::get_validator(const std::string &Validator_name) {
5294 for (auto &Validator : validators_) {
5295 if (Validator_name == Validator.get_name()) {
5296 return &Validator;
5297 }
5298 }
5299 if ((Validator_name.empty()) && (!validators_.empty())) {
5300 return &(validators_.front());
5301 }
5302 throw OptionNotFound(std::string{"Validator "} + Validator_name + " Not Found");
5303}
5304
5305CLI11_INLINE Validator *Option::get_validator(int index) {
5306 // This is an signed int so that it is not equivalent to a pointer.
5307 if (index >= 0 && index < static_cast<int>(validators_.size())) {
5308 return &(validators_[static_cast<decltype(validators_)::size_type>(index)]);
5309 }
5310 throw OptionNotFound("Validator index is not valid");
5311}
5312
5313CLI11_INLINE bool Option::remove_needs(Option *opt) {
5314 auto iterator = std::find(std::begin(needs_), std::end(needs_), opt);
5315
5316 if (iterator == std::end(needs_)) {
5317 return false;
5318 }
5319 needs_.erase(iterator);
5320 return true;
5321}
5322
5323CLI11_INLINE Option *Option::excludes(Option *opt) {
5324 if (opt == this) {
5325 throw(IncorrectConstruction("and option cannot exclude itself"));
5326 }
5327 excludes_.insert(opt);
5328
5329 // Help text should be symmetric - excluding a should exclude b
5330 opt->excludes_.insert(this);
5331
5332 // Ignoring the insert return value, excluding twice is now allowed.
5333 // (Mostly to allow both directions to be excluded by user, even though the library does it for
5334 // you.)
5335
5336 return this;
5337}
5338
5339CLI11_INLINE bool Option::remove_excludes(Option *opt) {
5340 auto iterator = std::find(std::begin(excludes_), std::end(excludes_), opt);
5341
5342 if (iterator == std::end(excludes_)) {
5343 return false;
5344 }
5345 excludes_.erase(iterator);
5346 return true;
5347}
5348
5349template <typename T>
5351 if (!ignore_case_ && value) {
5352 ignore_case_ = value;
5353 auto *parent = static_cast<T *>(parent_);
5354 for (const Option_p &opt : parent->options_) {
5355 if (opt.get() == this) {
5356 continue;
5357 }
5358 const auto &omatch = opt->matching_name(*this);
5359 if (!omatch.empty()) {
5360 ignore_case_ = false;
5361 throw OptionAlreadyAdded("adding ignore case caused a name conflict with " +
5362 omatch);
5363 }
5364 }
5365 } else {
5366 ignore_case_ = value;
5367 }
5368 return this;
5369}
5370
5371template <typename T>
5373 if (!ignore_underscore_ && value) {
5374 ignore_underscore_ = value;
5375 auto *parent = static_cast<T *>(parent_);
5376 for (const Option_p &opt : parent->options_) {
5377 if (opt.get() == this) {
5378 continue;
5379 }
5380 const auto &omatch = opt->matching_name(*this);
5381 if (!omatch.empty()) {
5382 ignore_underscore_ = false;
5383 throw OptionAlreadyAdded("adding ignore underscore caused a name conflict with " +
5384 omatch);
5385 }
5386 }
5387 } else {
5388 ignore_underscore_ = value;
5389 }
5390 return this;
5391}
5392
5393CLI11_INLINE Option *Option::multi_option_policy(MultiOptionPolicy value) {
5394 if (value != multi_option_policy_) {
5395 if (multi_option_policy_ == MultiOptionPolicy::Throw &&
5396 expected_max_ == detail::expected_max_vector_size &&
5397 expected_min_ > 1) { // this bizarre condition is to maintain backwards compatibility
5398 // with the previous behavior of expected_ with vectors
5400 }
5401 multi_option_policy_ = value;
5403 }
5404 return this;
5405}
5406
5407CLI11_NODISCARD CLI11_INLINE std::string Option::get_name(bool positional, bool all_options) const {
5408 if (get_group().empty()) return {}; // Hidden
5409
5410 if (all_options) {
5411 std::vector<std::string> name_list;
5412
5414 if ((positional && (!pname_.empty())) || (snames_.empty() && lnames_.empty())) {
5415 name_list.push_back(pname_);
5416 }
5417 if ((get_items_expected() == 0) && (!fnames_.empty())) {
5418 for (const std::string &sname : snames_) {
5419 name_list.push_back("-" + sname);
5420 if (check_fname(sname)) {
5421 name_list.back() += "{" + get_flag_value(sname, "") + "}";
5422 }
5423 }
5424
5425 for (const std::string &lname : lnames_) {
5426 name_list.push_back("--" + lname);
5427 if (check_fname(lname)) {
5428 name_list.back() += "{" + get_flag_value(lname, "") + "}";
5429 }
5430 }
5431 } else {
5432 for (const std::string &sname : snames_) name_list.push_back("-" + sname);
5433
5434 for (const std::string &lname : lnames_) name_list.push_back("--" + lname);
5435 }
5436
5437 return detail::join(name_list);
5438 }
5439
5440 // This returns the positional name no matter what
5441 if (positional) return pname_;
5442
5443 // Prefer long name
5444 if (!lnames_.empty()) return std::string(2, '-') + lnames_[0];
5445
5446 // Or short name if no long name
5447 if (!snames_.empty()) return std::string(1, '-') + snames_[0];
5448
5449 // If positional is the only name, it's okay to use that
5450 return pname_;
5451}
5452
5453CLI11_INLINE void Option::run_callback() {
5454 if (force_callback_ && results_.empty()) {
5456 }
5458 _validate_results(results_);
5460 }
5461
5463 _reduce_results(proc_results_, results_);
5465 }
5468 if (!(callback_)) {
5469 return;
5470 }
5471 const results_t &send_results = proc_results_.empty() ? results_ : proc_results_;
5472 bool local_result = callback_(send_results);
5473
5474 if (!local_result) throw ConversionError(get_name(), results_);
5475 }
5476}
5477
5478CLI11_NODISCARD CLI11_INLINE const std::string &Option::matching_name(const Option &other) const {
5479 static const std::string estring;
5480 for (const std::string &sname : snames_)
5481 if (other.check_sname(sname)) return sname;
5482 for (const std::string &lname : lnames_)
5483 if (other.check_lname(lname)) return lname;
5484
5485 if (ignore_case_ || ignore_underscore_) { // We need to do the inverse, in case we are
5486 // ignore_case or ignore underscore
5487 for (const std::string &sname : other.snames_)
5488 if (check_sname(sname)) return sname;
5489 for (const std::string &lname : other.lnames_)
5490 if (check_lname(lname)) return lname;
5491 }
5492 return estring;
5493}
5494
5495CLI11_NODISCARD CLI11_INLINE bool Option::check_name(const std::string &name) const {
5496 if (name.length() > 2 && name[0] == '-' && name[1] == '-') return check_lname(name.substr(2));
5497 if (name.length() > 1 && name.front() == '-') return check_sname(name.substr(1));
5498 if (!pname_.empty()) {
5499 std::string local_pname = pname_;
5500 std::string local_name = name;
5501 if (ignore_underscore_) {
5502 local_pname = detail::remove_underscore(local_pname);
5503 local_name = detail::remove_underscore(local_name);
5504 }
5505 if (ignore_case_) {
5506 local_pname = detail::to_lower(local_pname);
5507 local_name = detail::to_lower(local_name);
5508 }
5509 if (local_name == local_pname) {
5510 return true;
5511 }
5512 }
5513
5514 if (!envname_.empty()) {
5515 // this needs to be the original since envname_ shouldn't match on case insensitivity
5516 return (name == envname_);
5517 }
5518 return false;
5519}
5520
5521CLI11_NODISCARD CLI11_INLINE std::string Option::get_flag_value(const std::string &name,
5522 std::string input_value) const {
5523 static const std::string trueString{"true"};
5524 static const std::string falseString{"false"};
5525 static const std::string emptyString{"{}"};
5526 // check for disable flag override_
5528 if (!((input_value.empty()) || (input_value == emptyString))) {
5529 auto default_ind = detail::find_member(name, fnames_, ignore_case_, ignore_underscore_);
5530 if (default_ind >= 0) {
5531 // We can static cast this to std::size_t because it is more than 0 in this block
5532 if (default_flag_values_[static_cast<std::size_t>(default_ind)].second !=
5533 input_value) {
5534 throw(ArgumentMismatch::FlagOverride(name));
5535 }
5536 } else {
5537 if (input_value != trueString) {
5538 throw(ArgumentMismatch::FlagOverride(name));
5539 }
5540 }
5541 }
5542 }
5543 auto ind = detail::find_member(name, fnames_, ignore_case_, ignore_underscore_);
5544 if ((input_value.empty()) || (input_value == emptyString)) {
5545 if (flag_like_) {
5546 return (ind < 0) ? trueString
5547 : default_flag_values_[static_cast<std::size_t>(ind)].second;
5548 }
5549 return (ind < 0) ? default_str_
5550 : default_flag_values_[static_cast<std::size_t>(ind)].second;
5551 }
5552 if (ind < 0) {
5553 return input_value;
5554 }
5555 if (default_flag_values_[static_cast<std::size_t>(ind)].second == falseString) {
5556 try {
5557 auto val = detail::to_flag_value(input_value);
5558 return (val == 1) ? falseString : (val == (-1) ? trueString : std::to_string(-val));
5559 } catch (const std::invalid_argument &) {
5560 return input_value;
5561 }
5562 } else {
5563 return input_value;
5564 }
5565}
5566
5567CLI11_INLINE Option *Option::add_result(std::string s) {
5568 _add_result(std::move(s), results_);
5570 return this;
5571}
5572
5573CLI11_INLINE Option *Option::add_result(std::string s, int &results_added) {
5574 results_added = _add_result(std::move(s), results_);
5576 return this;
5577}
5578
5579CLI11_INLINE Option *Option::add_result(std::vector<std::string> s) {
5581 for (auto &str : s) {
5582 _add_result(std::move(str), results_);
5583 }
5584 return this;
5585}
5586
5587CLI11_NODISCARD CLI11_INLINE results_t Option::reduced_results() const {
5588 results_t res = proc_results_.empty() ? results_ : proc_results_;
5591 res = results_;
5592 _validate_results(res);
5593 }
5594 if (!res.empty()) {
5595 results_t extra;
5596 _reduce_results(extra, res);
5597 if (!extra.empty()) {
5598 res = std::move(extra);
5599 }
5600 }
5601 }
5602 return res;
5603}
5604
5605CLI11_INLINE Option *Option::type_size(int option_type_size) {
5606 if (option_type_size < 0) {
5607 // this section is included for backwards compatibility
5608 type_size_max_ = -option_type_size;
5609 type_size_min_ = -option_type_size;
5610 expected_max_ = detail::expected_max_vector_size;
5611 } else {
5612 type_size_max_ = option_type_size;
5613 if (type_size_max_ < detail::expected_max_vector_size) {
5614 type_size_min_ = option_type_size;
5615 } else {
5616 inject_separator_ = true;
5617 }
5618 if (type_size_max_ == 0) required_ = false;
5619 }
5620 return this;
5621}
5622
5623CLI11_INLINE Option *Option::type_size(int option_type_size_min, int option_type_size_max) {
5624 if (option_type_size_min < 0 || option_type_size_max < 0) {
5625 // this section is included for backwards compatibility
5626 expected_max_ = detail::expected_max_vector_size;
5627 option_type_size_min = (std::abs)(option_type_size_min);
5628 option_type_size_max = (std::abs)(option_type_size_max);
5629 }
5630
5631 if (option_type_size_min > option_type_size_max) {
5632 type_size_max_ = option_type_size_min;
5633 type_size_min_ = option_type_size_max;
5634 } else {
5635 type_size_min_ = option_type_size_min;
5636 type_size_max_ = option_type_size_max;
5637 }
5638 if (type_size_max_ == 0) {
5639 required_ = false;
5640 }
5641 if (type_size_max_ >= detail::expected_max_vector_size) {
5642 inject_separator_ = true;
5643 }
5644 return this;
5645}
5646
5647CLI11_NODISCARD CLI11_INLINE std::string Option::get_type_name() const {
5648 std::string full_type_name = type_name_();
5649 if (!validators_.empty()) {
5650 for (const auto &Validator : validators_) {
5651 std::string vtype = Validator.get_description();
5652 if (!vtype.empty()) {
5653 full_type_name += ":" + vtype;
5654 }
5655 }
5656 }
5657 return full_type_name;
5658}
5659
5660CLI11_INLINE void Option::_validate_results(results_t &res) const {
5661 // Run the Validators (can change the string)
5662 if (!validators_.empty()) {
5663 if (type_size_max_ > 1) { // in this context index refers to the index in the type
5664 int index = 0;
5665 if (get_items_expected_max() < static_cast<int>(res.size()) &&
5666 multi_option_policy_ == CLI::MultiOptionPolicy::TakeLast) {
5667 // create a negative index for the earliest ones
5668 index = get_items_expected_max() - static_cast<int>(res.size());
5669 }
5670
5671 for (std::string &result : res) {
5672 if (detail::is_separator(result) && type_size_max_ != type_size_min_ &&
5673 index >= 0) {
5674 index = 0; // reset index for variable size chunks
5675 continue;
5676 }
5677 auto err_msg = _validate(result, (index >= 0) ? (index % type_size_max_) : index);
5678 if (!err_msg.empty()) throw ValidationError(get_name(), err_msg);
5679 ++index;
5680 }
5681 } else {
5682 int index = 0;
5683 if (expected_max_ < static_cast<int>(res.size()) &&
5684 multi_option_policy_ == CLI::MultiOptionPolicy::TakeLast) {
5685 // create a negative index for the earliest ones
5686 index = expected_max_ - static_cast<int>(res.size());
5687 }
5688 for (std::string &result : res) {
5689 auto err_msg = _validate(result, index);
5690 ++index;
5691 if (!err_msg.empty()) throw ValidationError(get_name(), err_msg);
5692 }
5693 }
5694 }
5695}
5696
5697CLI11_INLINE void Option::_reduce_results(results_t &out, const results_t &original) const {
5698 // max num items expected or length of vector, always at least 1
5699 // Only valid for a trimming policy
5700
5701 out.clear();
5702 // Operation depends on the policy setting
5703 switch (multi_option_policy_) {
5704 case MultiOptionPolicy::TakeAll:
5705 break;
5706 case MultiOptionPolicy::TakeLast: {
5707 // Allow multi-option sizes (including 0)
5708 std::size_t trim_size = std::min<std::size_t>(
5709 static_cast<std::size_t>(std::max<int>(get_items_expected_max(), 1)),
5710 original.size());
5711 if (original.size() != trim_size) {
5712 out.assign(original.end() - static_cast<results_t::difference_type>(trim_size),
5713 original.end());
5714 }
5715 } break;
5716 case MultiOptionPolicy::TakeFirst: {
5717 std::size_t trim_size = std::min<std::size_t>(
5718 static_cast<std::size_t>(std::max<int>(get_items_expected_max(), 1)),
5719 original.size());
5720 if (original.size() != trim_size) {
5721 out.assign(original.begin(),
5722 original.begin() + static_cast<results_t::difference_type>(trim_size));
5723 }
5724 } break;
5725 case MultiOptionPolicy::Join:
5726 if (results_.size() > 1) {
5727 out.push_back(detail::join(
5728 original, std::string(1, (delimiter_ == '\0') ? '\n' : delimiter_)));
5729 }
5730 break;
5731 case MultiOptionPolicy::Sum:
5732 out.push_back(detail::sum_string_vector(original));
5733 break;
5734 case MultiOptionPolicy::Throw:
5735 default: {
5736 auto num_min = static_cast<std::size_t>(get_items_expected_min());
5737 auto num_max = static_cast<std::size_t>(get_items_expected_max());
5738 if (num_min == 0) {
5739 num_min = 1;
5740 }
5741 if (num_max == 0) {
5742 num_max = 1;
5743 }
5744 if (original.size() < num_min) {
5745 throw ArgumentMismatch::AtLeast(get_name(), static_cast<int>(num_min),
5746 original.size());
5747 }
5748 if (original.size() > num_max) {
5749 throw ArgumentMismatch::AtMost(get_name(), static_cast<int>(num_max),
5750 original.size());
5751 }
5752 break;
5753 }
5754 }
5755 // this check is to allow an empty vector in certain circumstances but not if expected is not
5756 // zero.
5757 // {} is the indicator for an empty container
5758 if (out.empty()) {
5759 if (original.size() == 1 && original[0] == "{}" && get_items_expected_min() > 0) {
5760 out.push_back("{}");
5761 out.push_back("%%");
5762 }
5763 } else if (out.size() == 1 && out[0] == "{}" && get_items_expected_min() > 0) {
5764 out.push_back("%%");
5765 }
5766}
5767
5768CLI11_INLINE std::string Option::_validate(std::string &result, int index) const {
5769 std::string err_msg;
5770 if (result.empty() && expected_min_ == 0) {
5771 // an empty with nothing expected is allowed
5772 return err_msg;
5773 }
5774 for (const auto &vali : validators_) {
5775 auto v = vali.get_application_index();
5776 if (v == -1 || v == index) {
5777 try {
5778 err_msg = vali(result);
5779 } catch (const ValidationError &err) {
5780 err_msg = err.what();
5781 }
5782 if (!err_msg.empty()) break;
5783 }
5784 }
5785
5786 return err_msg;
5787}
5788
5789CLI11_INLINE int Option::_add_result(std::string &&result, std::vector<std::string> &res) const {
5790 int result_count = 0;
5791 if (allow_extra_args_ && !result.empty() && result.front() == '[' &&
5792 result.back() ==
5793 ']') { // this is now a vector string likely from the default or user entry
5794 result.pop_back();
5795
5796 for (auto &var : CLI::detail::split(result.substr(1), ',')) {
5797 if (!var.empty()) {
5798 result_count += _add_result(std::move(var), res);
5799 }
5800 }
5801 return result_count;
5802 }
5803 if (delimiter_ == '\0') {
5804 res.push_back(std::move(result));
5805 ++result_count;
5806 } else {
5807 if ((result.find_first_of(delimiter_) != std::string::npos)) {
5808 for (const auto &var : CLI::detail::split(result, delimiter_)) {
5809 if (!var.empty()) {
5810 res.push_back(var);
5811 ++result_count;
5812 }
5813 }
5814 } else {
5815 res.push_back(std::move(result));
5816 ++result_count;
5817 }
5818 }
5819 return result_count;
5820}
5821
5822#ifndef CLI11_PARSE
5823#define CLI11_PARSE(app, argc, argv) \
5824 try { \
5825 (app).parse((argc), (argv)); \
5826 } catch (const CLI::ParseError &e) { \
5827 return (app).exit(e); \
5828 }
5829#endif
5830
5831namespace detail {
5832enum class Classifier {
5833 NONE,
5834 POSITIONAL_MARK,
5835 SHORT,
5836 LONG,
5837 WINDOWS_STYLE,
5838 SUBCOMMAND,
5839 SUBCOMMAND_TERMINATOR
5840};
5841struct AppFriend;
5842} // namespace detail
5843
5844namespace FailureMessage {
5845std::string simple(const App *app, const Error &e);
5846std::string help(const App *app, const Error &e);
5847} // namespace FailureMessage
5848
5850
5851enum class config_extras_mode : char { error = 0, ignore, ignore_all, capture };
5852
5853class App;
5854
5855using App_p = std::shared_ptr<App>;
5856
5857namespace detail {
5859
5860template <
5861 typename T,
5862 enable_if_t<!std::is_integral<T>::value || (sizeof(T) <= 1U), detail::enabler> = detail::dummy>
5863Option *default_flag_modifiers(Option *opt) {
5864 return opt->always_capture_default();
5865}
5866
5868template <
5869 typename T,
5870 enable_if_t<std::is_integral<T>::value && (sizeof(T) > 1U), detail::enabler> = detail::dummy>
5871Option *default_flag_modifiers(Option *opt) {
5872 return opt->multi_option_policy(MultiOptionPolicy::Sum)->default_str("0")->force_callback();
5873}
5874
5875} // namespace detail
5876
5877class Option_group;
5879
5883class App {
5884 friend Option;
5885 friend detail::AppFriend;
5886
5887protected:
5888 // This library follows the Google style guide for member names ending in underscores
5889
5892
5894 std::string name_{};
5895
5897 std::string description_{};
5898
5900 bool allow_extras_{false};
5901
5904 config_extras_mode allow_config_extras_{config_extras_mode::ignore};
5905
5907 bool prefix_command_{false};
5908
5911
5913 bool required_{false};
5914
5916 bool disabled_{false};
5917
5920
5924
5926 std::function<void(std::size_t)> pre_parse_callback_{};
5927
5929 std::function<void()> parse_complete_callback_{};
5930
5932 std::function<void()> final_callback_{};
5933
5937
5940
5942 std::vector<Option_p> options_{};
5943
5947
5949 std::string footer_{};
5950
5952 std::function<std::string()> footer_callback_{};
5953
5955 Option *help_ptr_{nullptr};
5956
5958 Option *help_all_ptr_{nullptr};
5959
5961 Option *version_ptr_{nullptr};
5962
5964 std::shared_ptr<FormatterBase> formatter_{new Formatter()};
5965
5967 std::function<std::string(const App *, const Error &e)> failure_message_{
5968 FailureMessage::simple};
5969
5973
5974 using missing_t = std::vector<std::pair<detail::Classifier, std::string>>;
5975
5981 missing_t missing_{};
5982
5984 std::vector<Option *> parse_order_{};
5985
5987 std::vector<App *> parsed_subcommands_{};
5988
5990 std::set<App *> exclude_subcommands_{};
5991
5994 std::set<Option *> exclude_options_{};
5995
5998 std::set<App *> need_subcommands_{};
5999
6002 std::set<Option *> need_options_{};
6003
6007
6009 std::vector<App_p> subcommands_{};
6010
6012 bool ignore_case_{false};
6013
6016
6019 bool fallthrough_{false};
6020
6024#ifdef _WIN32
6025 true
6026#else
6027 false
6028#endif
6029 };
6030
6032
6033 enum class startup_mode : char { stable, enabled, disabled };
6036 startup_mode default_startup{startup_mode::stable};
6037
6039 bool configurable_{false};
6040
6043
6046
6049 bool silent_{false};
6050
6052 std::uint32_t parsed_{0U};
6053
6056
6060
6062 std::size_t require_option_min_{0};
6063
6065 std::size_t require_option_max_{0};
6066
6068 App *parent_{nullptr};
6069
6071 std::string group_{"Subcommands"};
6072
6074 std::vector<std::string> aliases_{};
6075
6079
6081 Option *config_ptr_{nullptr};
6082
6084 std::shared_ptr<Config> config_formatter_{new ConfigTOML()};
6085
6087
6089 App(std::string app_description, std::string app_name, App *parent);
6090
6091public:
6094
6096 explicit App(std::string app_description = "", std::string app_name = "")
6097 : App(app_description, app_name, nullptr) {
6098 set_help_flag("-h,--help", "Print this help message and exit");
6099 }
6100
6101 App(const App &) = delete;
6102 App &operator=(const App &) = delete;
6103
6105 virtual ~App() = default;
6106
6113 App *callback(std::function<void()> app_callback) {
6114 if (immediate_callback_) {
6115 parse_complete_callback_ = std::move(app_callback);
6116 } else {
6117 final_callback_ = std::move(app_callback);
6118 }
6119 return this;
6120 }
6121
6124 App *final_callback(std::function<void()> app_callback) {
6125 final_callback_ = std::move(app_callback);
6126 return this;
6127 }
6128
6131 App *parse_complete_callback(std::function<void()> pc_callback) {
6132 parse_complete_callback_ = std::move(pc_callback);
6133 return this;
6134 }
6135
6138 App *preparse_callback(std::function<void(std::size_t)> pp_callback) {
6139 pre_parse_callback_ = std::move(pp_callback);
6140 return this;
6141 }
6142
6144 App *name(std::string app_name = "");
6145
6147 App *alias(std::string app_name);
6148
6150 App *allow_extras(bool allow = true) {
6151 allow_extras_ = allow;
6152 return this;
6153 }
6154
6156 App *required(bool require = true) {
6157 required_ = require;
6158 return this;
6159 }
6160
6162 App *disabled(bool disable = true) {
6163 disabled_ = disable;
6164 return this;
6165 }
6166
6168 App *silent(bool silence = true) {
6169 silent_ = silence;
6170 return this;
6171 }
6172
6175 App *disabled_by_default(bool disable = true) {
6176 if (disable) {
6177 default_startup = startup_mode::disabled;
6178 } else {
6179 default_startup = (default_startup == startup_mode::enabled) ? startup_mode::enabled
6180 : startup_mode::stable;
6181 }
6182 return this;
6183 }
6184
6187 App *enabled_by_default(bool enable = true) {
6188 if (enable) {
6189 default_startup = startup_mode::enabled;
6190 } else {
6191 default_startup = (default_startup == startup_mode::disabled) ? startup_mode::disabled
6192 : startup_mode::stable;
6193 }
6194 return this;
6195 }
6196
6198 App *immediate_callback(bool immediate = true);
6199
6201 App *validate_positionals(bool validate = true) {
6202 validate_positionals_ = validate;
6203 return this;
6204 }
6205
6207 App *validate_optional_arguments(bool validate = true) {
6209 return this;
6210 }
6211
6213 App *allow_config_extras(bool allow = true) {
6214 if (allow) {
6215 allow_config_extras_ = config_extras_mode::capture;
6216 allow_extras_ = true;
6217 } else {
6218 allow_config_extras_ = config_extras_mode::error;
6219 }
6220 return this;
6221 }
6222
6224 App *allow_config_extras(config_extras_mode mode) {
6225 allow_config_extras_ = mode;
6226 return this;
6227 }
6228
6230 App *prefix_command(bool allow = true) {
6231 prefix_command_ = allow;
6232 return this;
6233 }
6234
6236 App *ignore_case(bool value = true);
6237
6240 App *allow_windows_style_options(bool value = true) {
6242 return this;
6243 }
6244
6246 App *positionals_at_end(bool value = true) {
6247 positionals_at_end_ = value;
6248 return this;
6249 }
6250
6252 App *configurable(bool value = true) {
6253 configurable_ = value;
6254 return this;
6255 }
6256
6258 App *ignore_underscore(bool value = true);
6259
6261 App *formatter(std::shared_ptr<FormatterBase> fmt) {
6262 formatter_ = fmt;
6263 return this;
6264 }
6265
6267 App *formatter_fn(std::function<std::string(const App *, std::string, AppFormatMode)> fmt) {
6268 formatter_ = std::make_shared<FormatterLambda>(fmt);
6269 return this;
6270 }
6271
6273 App *config_formatter(std::shared_ptr<Config> fmt) {
6274 config_formatter_ = fmt;
6275 return this;
6276 }
6277
6279 CLI11_NODISCARD bool parsed() const { return parsed_ > 0; }
6280
6283
6287
6302 Option *add_option(std::string option_name,
6303 callback_t option_callback,
6304 std::string option_description = "",
6305 bool defaulted = false,
6306 std::function<std::string()> func = {});
6307
6309 template <typename AssignTo,
6310 typename ConvertTo = AssignTo,
6311 enable_if_t<!std::is_const<ConvertTo>::value, detail::enabler> = detail::dummy>
6312 Option *add_option(std::string option_name,
6313 AssignTo &variable,
6314 std::string option_description = "") {
6315 auto fun = [&variable](const CLI::results_t &res) { // comment for spacing
6316 return detail::lexical_conversion<AssignTo, ConvertTo>(res, variable);
6317 };
6318
6319 Option *opt = add_option(option_name, fun, option_description, false, [&variable]() {
6320 return CLI::detail::checked_to_string<AssignTo, ConvertTo>(variable);
6321 });
6322 opt->type_name(detail::type_name<ConvertTo>());
6323 // these must be actual lvalues since (std::max) sometimes is defined in terms of references
6324 // and references to structs used in the evaluation can be temporary so that would cause
6325 // issues.
6326 auto Tcount = detail::type_count<AssignTo>::value;
6327 auto XCcount = detail::type_count<ConvertTo>::value;
6328 opt->type_size(detail::type_count_min<ConvertTo>::value, (std::max)(Tcount, XCcount));
6329 opt->expected(detail::expected_count<ConvertTo>::value);
6331 return opt;
6332 }
6333
6335 template <typename AssignTo,
6336 enable_if_t<!std::is_const<AssignTo>::value, detail::enabler> = detail::dummy>
6337 Option *add_option_no_stream(std::string option_name,
6338 AssignTo &variable,
6339 std::string option_description = "") {
6340 auto fun = [&variable](const CLI::results_t &res) { // comment for spacing
6341 return detail::lexical_conversion<AssignTo, AssignTo>(res, variable);
6342 };
6343
6344 Option *opt =
6345 add_option(option_name, fun, option_description, false, []() { return std::string{}; });
6346 opt->type_name(detail::type_name<AssignTo>());
6347 opt->type_size(detail::type_count_min<AssignTo>::value,
6348 detail::type_count<AssignTo>::value);
6349 opt->expected(detail::expected_count<AssignTo>::value);
6351 return opt;
6352 }
6353
6355 template <typename ArgType>
6357 std::string option_name,
6358 const std::function<void(const ArgType &)> &func,
6359 std::string option_description = "") {
6360 auto fun = [func](const CLI::results_t &res) {
6361 ArgType variable;
6362 bool result = detail::lexical_conversion<ArgType, ArgType>(res, variable);
6363 if (result) {
6364 func(variable);
6365 }
6366 return result;
6367 };
6368
6369 Option *opt = add_option(option_name, std::move(fun), option_description, false);
6370 opt->type_name(detail::type_name<ArgType>());
6371 opt->type_size(detail::type_count_min<ArgType>::value, detail::type_count<ArgType>::value);
6372 opt->expected(detail::expected_count<ArgType>::value);
6373 return opt;
6374 }
6375
6377 Option *add_option(std::string option_name) {
6378 return add_option(option_name, CLI::callback_t{}, std::string{}, false);
6379 }
6380
6382 template <typename T,
6383 enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value,
6384 detail::enabler> = detail::dummy>
6385 Option *add_option(std::string option_name, T &option_description) {
6386 return add_option(option_name, CLI::callback_t(), option_description, false);
6387 }
6388
6390 Option *set_help_flag(std::string flag_name = "", const std::string &help_description = "");
6391
6393 Option *set_help_all_flag(std::string help_name = "", const std::string &help_description = "");
6394
6397 std::string flag_name = "",
6398 const std::string &versionString = "",
6399 const std::string &version_help = "Display program version information and exit");
6400
6403 std::string flag_name,
6404 std::function<std::string()> vfunc,
6405 const std::string &version_help = "Display program version information and exit");
6406
6407private:
6409 Option *_add_flag_internal(std::string flag_name,
6410 CLI::callback_t fun,
6411 std::string flag_description);
6412
6413public:
6415 Option *add_flag(std::string flag_name) {
6416 return _add_flag_internal(flag_name, CLI::callback_t(), std::string{});
6417 }
6418
6422 template <typename T,
6423 enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value,
6424 detail::enabler> = detail::dummy>
6425 Option *add_flag(std::string flag_name, T &flag_description) {
6426 return _add_flag_internal(flag_name, CLI::callback_t(), flag_description);
6427 }
6428
6431 template <typename T,
6432 enable_if_t<!detail::is_mutable_container<T>::value && !std::is_const<T>::value &&
6433 !std::is_constructible<std::function<void(int)>, T>::value,
6434 detail::enabler> = detail::dummy>
6435 Option *add_flag(std::string flag_name,
6436 T &flag_result,
6437 std::string flag_description = "") {
6438 CLI::callback_t fun = [&flag_result](const CLI::results_t &res) {
6439 return CLI::detail::lexical_cast(res[0], flag_result);
6440 };
6441 auto *opt = _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
6442 return detail::default_flag_modifiers<T>(opt);
6443 }
6444
6446 template <typename T,
6447 enable_if_t<!std::is_assignable<std::function<void(std::int64_t)> &, T>::value,
6448 detail::enabler> = detail::dummy>
6449 Option *add_flag(std::string flag_name,
6450 std::vector<T> &flag_results,
6451 std::string flag_description = "") {
6452 CLI::callback_t fun = [&flag_results](const CLI::results_t &res) {
6453 bool retval = true;
6454 for (const auto &elem : res) {
6455 flag_results.emplace_back();
6456 retval &= detail::lexical_cast(elem, flag_results.back());
6457 }
6458 return retval;
6459 };
6460 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
6461 ->multi_option_policy(MultiOptionPolicy::TakeAll)
6463 }
6464
6467 std::string flag_name,
6468 std::function<void(void)> function,
6469 std::string flag_description = "");
6470
6473 std::string flag_name,
6474 std::function<void(std::int64_t)> function,
6475 std::string flag_description = "");
6476
6477#ifdef CLI11_CPP14
6480 std::string flag_name,
6481 std::function<void(std::int64_t)> function,
6482 std::string flag_description = "") {
6483 return add_flag_function(std::move(flag_name), std::move(function),
6484 std::move(flag_description));
6485 }
6486#endif
6487
6489 Option *set_config(std::string option_name = "",
6490 std::string default_filename = "",
6491 const std::string &help_message = "Read an ini file",
6492 bool config_required = false);
6493
6495 bool remove_option(Option *opt);
6496
6498 template <typename T = Option_group>
6499 T *add_option_group(std::string group_name, std::string group_description = "") {
6500 if (!detail::valid_alias_name_string(group_name)) {
6502 "option group names may not contain newlines or null characters");
6503 }
6504 auto option_group = std::make_shared<T>(std::move(group_description), group_name, this);
6505 auto *ptr = option_group.get();
6506 // move to App_p for overload resolution on older gcc versions
6507 App_p app_ptr = std::dynamic_pointer_cast<App>(option_group);
6508 add_subcommand(std::move(app_ptr));
6509 return ptr;
6510 }
6511
6515
6517 App *add_subcommand(std::string subcommand_name = "", std::string subcommand_description = "");
6518
6520 App *add_subcommand(CLI::App_p subcom);
6521
6524 bool remove_subcommand(App *subcom);
6525
6528 App *get_subcommand(const App *subcom) const;
6529
6531 CLI11_NODISCARD App *get_subcommand(std::string subcom) const;
6532
6534 CLI11_NODISCARD App *get_subcommand(int index = 0) const;
6535
6537 CLI::App_p get_subcommand_ptr(App *subcom) const;
6538
6540 CLI11_NODISCARD CLI::App_p get_subcommand_ptr(std::string subcom) const;
6541
6543 CLI11_NODISCARD CLI::App_p get_subcommand_ptr(int index = 0) const;
6544
6546 CLI11_NODISCARD App *get_option_group(std::string group_name) const;
6547
6551 CLI11_NODISCARD std::size_t count() const { return parsed_; }
6552
6555 CLI11_NODISCARD std::size_t count_all() const;
6556
6558 App *group(std::string group_name) {
6559 group_ = group_name;
6560 return this;
6561 }
6562
6567 return this;
6568 }
6569
6574 if (value < 0) {
6576 require_subcommand_max_ = static_cast<std::size_t>(-value);
6577 } else {
6578 require_subcommand_min_ = static_cast<std::size_t>(value);
6579 require_subcommand_max_ = static_cast<std::size_t>(value);
6580 }
6581 return this;
6582 }
6583
6586 App *require_subcommand(std::size_t min, std::size_t max) {
6589 return this;
6590 }
6591
6596 return this;
6597 }
6598
6602 App *require_option(int value) {
6603 if (value < 0) {
6605 require_option_max_ = static_cast<std::size_t>(-value);
6606 } else {
6607 require_option_min_ = static_cast<std::size_t>(value);
6608 require_option_max_ = static_cast<std::size_t>(value);
6609 }
6610 return this;
6611 }
6612
6615 App *require_option(std::size_t min, std::size_t max) {
6616 require_option_min_ = min;
6617 require_option_max_ = max;
6618 return this;
6619 }
6620
6623 App *fallthrough(bool value = true) {
6624 fallthrough_ = value;
6625 return this;
6626 }
6627
6630 explicit operator bool() const { return parsed_ > 0; }
6631
6635
6639 virtual void pre_callback() {}
6640
6644 //
6646 void clear();
6647
6650 void parse(int argc, const char *const *argv);
6651
6656 void parse(std::string commandline, bool program_name_included = false);
6657
6660 void parse(std::vector<std::string> &args);
6661
6663 void parse(std::vector<std::string> &&args);
6664
6665 void parse_from_stream(std::istream &input);
6666
6669 void failure_message(std::function<std::string(const App *, const Error &e)> function) {
6670 failure_message_ = function;
6671 }
6672
6674 int exit(const Error &e, std::ostream &out = std::cout, std::ostream &err = std::cerr) const;
6675
6679
6681 CLI11_NODISCARD std::size_t count(std::string option_name) const {
6682 return get_option(option_name)->count();
6683 }
6684
6687 CLI11_NODISCARD std::vector<App *> get_subcommands() const { return parsed_subcommands_; }
6688
6691 std::vector<const App *> get_subcommands(const std::function<bool(const App *)> &filter) const;
6692
6695 std::vector<App *> get_subcommands(const std::function<bool(App *)> &filter);
6696
6698 bool got_subcommand(const App *subcom) const {
6699 // get subcom needed to verify that this was a real subcommand
6700 return get_subcommand(subcom)->parsed_ > 0;
6701 }
6702
6704 CLI11_NODISCARD bool got_subcommand(std::string subcommand_name) const {
6705 return get_subcommand(subcommand_name)->parsed_ > 0;
6706 }
6707
6709 App *excludes(Option *opt) {
6710 if (opt == nullptr) {
6711 throw OptionNotFound("nullptr passed");
6712 }
6713 exclude_options_.insert(opt);
6714 return this;
6715 }
6716
6719 if (app == nullptr) {
6720 throw OptionNotFound("nullptr passed");
6721 }
6722 if (app == this) {
6723 throw OptionNotFound("cannot self reference in needs");
6724 }
6725 auto res = exclude_subcommands_.insert(app);
6726 // subcommand exclusion should be symmetric
6727 if (res.second) {
6728 app->exclude_subcommands_.insert(this);
6729 }
6730 return this;
6731 }
6732
6733 App *needs(Option *opt) {
6734 if (opt == nullptr) {
6735 throw OptionNotFound("nullptr passed");
6736 }
6737 need_options_.insert(opt);
6738 return this;
6739 }
6740
6741 App *needs(App *app) {
6742 if (app == nullptr) {
6743 throw OptionNotFound("nullptr passed");
6744 }
6745 if (app == this) {
6746 throw OptionNotFound("cannot self reference in needs");
6747 }
6748 need_subcommands_.insert(app);
6749 return this;
6750 }
6751
6753 bool remove_excludes(Option *opt);
6754
6756 bool remove_excludes(App *app);
6757
6759 bool remove_needs(Option *opt);
6760
6762 bool remove_needs(App *app);
6766
6768 App *footer(std::string footer_string) {
6769 footer_ = std::move(footer_string);
6770 return this;
6771 }
6772
6773 App *footer(std::function<std::string()> footer_function) {
6774 footer_callback_ = std::move(footer_function);
6775 return this;
6776 }
6777
6780 CLI11_NODISCARD std::string config_to_str(bool default_also = false,
6781 bool write_description = false) const {
6782 return config_formatter_->to_config(this, default_also, write_description, "");
6783 }
6784
6787 CLI11_NODISCARD std::string help(std::string prev = "",
6788 AppFormatMode mode = AppFormatMode::Normal) const;
6789
6791 CLI11_NODISCARD std::string version() const;
6795
6797 CLI11_NODISCARD std::shared_ptr<FormatterBase> get_formatter() const { return formatter_; }
6798
6800 CLI11_NODISCARD std::shared_ptr<Config> get_config_formatter() const {
6801 return config_formatter_;
6802 }
6803
6805 CLI11_NODISCARD std::shared_ptr<ConfigBase> get_config_formatter_base() const {
6806 // This is safer as a dynamic_cast if we have RTTI, as Config -> ConfigBase
6807#if CLI11_USE_STATIC_RTTI == 0
6808 return std::dynamic_pointer_cast<ConfigBase>(config_formatter_);
6809#else
6810 return std::static_pointer_cast<ConfigBase>(config_formatter_);
6811#endif
6812 }
6813
6815 CLI11_NODISCARD std::string get_description() const { return description_; }
6816
6818 App *description(std::string app_description) {
6819 description_ = std::move(app_description);
6820 return this;
6821 }
6822
6825 std::vector<const Option *> get_options(
6826 const std::function<bool(const Option *)> filter = {}) const;
6827
6829 std::vector<Option *> get_options(const std::function<bool(Option *)> filter = {});
6830
6832 Option *get_option_no_throw(std::string option_name) noexcept;
6833
6835 CLI11_NODISCARD const Option *get_option_no_throw(std::string option_name) const noexcept;
6836
6838 CLI11_NODISCARD const Option *get_option(std::string option_name) const {
6839 const auto *opt = get_option_no_throw(option_name);
6840 if (opt == nullptr) {
6841 throw OptionNotFound(option_name);
6842 }
6843 return opt;
6844 }
6845
6847 Option *get_option(std::string option_name) {
6848 auto *opt = get_option_no_throw(option_name);
6849 if (opt == nullptr) {
6850 throw OptionNotFound(option_name);
6851 }
6852 return opt;
6853 }
6854
6856 const Option *operator[](const std::string &option_name) const {
6857 return get_option(option_name);
6858 }
6859
6861 const Option *operator[](const char *option_name) const { return get_option(option_name); }
6862
6864 CLI11_NODISCARD bool get_ignore_case() const { return ignore_case_; }
6865
6867 CLI11_NODISCARD bool get_ignore_underscore() const { return ignore_underscore_; }
6868
6870 CLI11_NODISCARD bool get_fallthrough() const { return fallthrough_; }
6871
6873 CLI11_NODISCARD bool get_allow_windows_style_options() const {
6875 }
6876
6878 CLI11_NODISCARD bool get_positionals_at_end() const { return positionals_at_end_; }
6879
6881 CLI11_NODISCARD bool get_configurable() const { return configurable_; }
6882
6884 CLI11_NODISCARD const std::string &get_group() const { return group_; }
6885
6887 CLI11_NODISCARD std::string get_footer() const {
6888 return (footer_callback_) ? footer_callback_() + '\n' + footer_ : footer_;
6889 }
6890
6892 CLI11_NODISCARD std::size_t get_require_subcommand_min() const {
6894 }
6895
6897 CLI11_NODISCARD std::size_t get_require_subcommand_max() const {
6899 }
6900
6902 CLI11_NODISCARD std::size_t get_require_option_min() const { return require_option_min_; }
6903
6905 CLI11_NODISCARD std::size_t get_require_option_max() const { return require_option_max_; }
6906
6908 CLI11_NODISCARD bool get_prefix_command() const { return prefix_command_; }
6909
6911 CLI11_NODISCARD bool get_allow_extras() const { return allow_extras_; }
6912
6914 CLI11_NODISCARD bool get_required() const { return required_; }
6915
6917 CLI11_NODISCARD bool get_disabled() const { return disabled_; }
6918
6920 CLI11_NODISCARD bool get_silent() const { return silent_; }
6921
6923 CLI11_NODISCARD bool get_immediate_callback() const { return immediate_callback_; }
6924
6926 CLI11_NODISCARD bool get_disabled_by_default() const {
6927 return (default_startup == startup_mode::disabled);
6928 }
6929
6931 CLI11_NODISCARD bool get_enabled_by_default() const {
6932 return (default_startup == startup_mode::enabled);
6933 }
6934
6935 CLI11_NODISCARD bool get_validate_positionals() const { return validate_positionals_; }
6937 CLI11_NODISCARD bool get_validate_optional_arguments() const {
6939 }
6940
6942 CLI11_NODISCARD config_extras_mode get_allow_config_extras() const {
6943 return allow_config_extras_;
6944 }
6945
6947 Option *get_help_ptr() { return help_ptr_; }
6948
6950 CLI11_NODISCARD const Option *get_help_ptr() const { return help_ptr_; }
6951
6953 CLI11_NODISCARD const Option *get_help_all_ptr() const { return help_all_ptr_; }
6954
6956 Option *get_config_ptr() { return config_ptr_; }
6957
6959 CLI11_NODISCARD const Option *get_config_ptr() const { return config_ptr_; }
6960
6962 Option *get_version_ptr() { return version_ptr_; }
6963
6965 CLI11_NODISCARD const Option *get_version_ptr() const { return version_ptr_; }
6966
6968 App *get_parent() { return parent_; }
6969
6971 CLI11_NODISCARD const App *get_parent() const { return parent_; }
6972
6974 CLI11_NODISCARD const std::string &get_name() const { return name_; }
6975
6977 CLI11_NODISCARD const std::vector<std::string> &get_aliases() const { return aliases_; }
6978
6981 aliases_.clear();
6982 return this;
6983 }
6984
6986 CLI11_NODISCARD std::string get_display_name(bool with_aliases = false) const;
6987
6989 CLI11_NODISCARD bool check_name(std::string name_to_check) const;
6990
6992 CLI11_NODISCARD std::vector<std::string> get_groups() const;
6993
6995 CLI11_NODISCARD const std::vector<Option *> &parse_order() const { return parse_order_; }
6996
6998 CLI11_NODISCARD std::vector<std::string> remaining(bool recurse = false) const;
6999
7002 CLI11_NODISCARD std::vector<std::string> remaining_for_passthrough(bool recurse = false) const;
7003
7005 CLI11_NODISCARD std::size_t remaining_size(bool recurse = false) const;
7006
7008
7009protected:
7014 void _validate() const;
7015
7019 void _configure();
7020
7022 void run_callback(bool final_mode = false, bool suppress_final_callback = false);
7023
7026 CLI11_NODISCARD bool _valid_subcommand(const std::string &current,
7027 bool ignore_used = true) const;
7028
7030 CLI11_NODISCARD detail::Classifier _recognize(const std::string &current,
7031 bool ignore_used_subcommands = true) const;
7032
7033 // The parse function is now broken into several parts, and part of process
7034
7036 void _process_config_file();
7037
7039 void _process_env();
7040
7042 void _process_callbacks();
7043
7047 void _process_help_flags(bool trigger_help = false, bool trigger_all_help = false) const;
7048
7050 void _process_requirements();
7051
7053 void _process();
7054
7056 void _process_extras();
7057
7060 void _process_extras(std::vector<std::string> &args);
7061
7064 void increment_parsed();
7065
7067 void _parse(std::vector<std::string> &args);
7068
7070 void _parse(std::vector<std::string> &&args);
7071
7073 void _parse_stream(std::istream &input);
7074
7080 void _parse_config(const std::vector<ConfigItem> &args);
7081
7083 bool _parse_single_config(const ConfigItem &item, std::size_t level = 0);
7084
7088 bool _parse_single(std::vector<std::string> &args, bool &positional_only);
7089
7091 CLI11_NODISCARD std::size_t _count_remaining_positionals(bool required_only = false) const;
7092
7094 CLI11_NODISCARD bool _has_remaining_positionals() const;
7095
7099 bool _parse_positional(std::vector<std::string> &args, bool haltOnSubcommand);
7100
7103 CLI11_NODISCARD App *_find_subcommand(const std::string &subc_name,
7104 bool ignore_disabled,
7105 bool ignore_used) const noexcept;
7106
7111 bool _parse_subcommand(std::vector<std::string> &args);
7112
7115 bool _parse_arg(std::vector<std::string> &args, detail::Classifier current_type);
7116
7118 void _trigger_pre_parse(std::size_t remaining_args);
7119
7123
7126 CLI11_NODISCARD const std::string &_compare_subcommand_names(const App &subcom,
7127 const App &base) const;
7128
7130 void _move_to_missing(detail::Classifier val_type, const std::string &val);
7131
7132public:
7134 void _move_option(Option *opt, App *app);
7135}; // namespace CLI
7136
7138class Option_group : public App {
7139public:
7140 Option_group(std::string group_description, std::string group_name, App *parent)
7141 : App(std::move(group_description), "", parent) {
7142 group(group_name);
7143 // option groups should have automatic fallthrough
7144 }
7145 using App::add_option;
7147 Option *add_option(Option *opt) {
7148 if (get_parent() == nullptr) {
7149 throw OptionNotFound("Unable to locate the specified option");
7150 }
7151 get_parent()->_move_option(opt, this);
7152 return opt;
7153 }
7154
7155 void add_options(Option *opt) { add_option(opt); }
7157 template <typename... Args>
7158 void add_options(Option *opt, Args... args) {
7159 add_option(opt);
7160 add_options(args...);
7161 }
7162 using App::add_subcommand;
7165 App_p subc = subcom->get_parent()->get_subcommand_ptr(subcom);
7166 subc->get_parent()->remove_subcommand(subcom);
7167 add_subcommand(std::move(subc));
7168 return subcom;
7169 }
7170};
7171
7173CLI11_INLINE void TriggerOn(App *trigger_app, App *app_to_enable);
7174
7176CLI11_INLINE void TriggerOn(App *trigger_app, std::vector<App *> apps_to_enable);
7177
7179CLI11_INLINE void TriggerOff(App *trigger_app, App *app_to_enable);
7180
7182CLI11_INLINE void TriggerOff(App *trigger_app, std::vector<App *> apps_to_enable);
7183
7185CLI11_INLINE void deprecate_option(Option *opt, const std::string &replacement = "");
7186
7188inline void deprecate_option(App *app,
7189 const std::string &option_name,
7190 const std::string &replacement = "") {
7191 auto *opt = app->get_option(option_name);
7192 deprecate_option(opt, replacement);
7193}
7194
7196inline void deprecate_option(App &app,
7197 const std::string &option_name,
7198 const std::string &replacement = "") {
7199 auto *opt = app.get_option(option_name);
7200 deprecate_option(opt, replacement);
7201}
7202
7204CLI11_INLINE void retire_option(App *app, Option *opt);
7205
7207CLI11_INLINE void retire_option(App &app, Option *opt);
7208
7210CLI11_INLINE void retire_option(App *app, const std::string &option_name);
7211
7213CLI11_INLINE void retire_option(App &app, const std::string &option_name);
7214
7215namespace FailureMessage {
7216
7218CLI11_INLINE std::string simple(const App *app, const Error &e);
7219
7221CLI11_INLINE std::string help(const App *app, const Error &e);
7222
7223} // namespace FailureMessage
7224
7225namespace detail {
7228#ifdef CLI11_CPP14
7229
7231 template <typename... Args>
7232 static decltype(auto) parse_arg(App *app, Args &&...args) {
7233 return app->_parse_arg(std::forward<Args>(args)...);
7234 }
7235
7237 template <typename... Args>
7238 static decltype(auto) parse_subcommand(App *app, Args &&...args) {
7239 return app->_parse_subcommand(std::forward<Args>(args)...);
7240 }
7241#else
7243 template <typename... Args>
7244 static auto parse_arg(App *app, Args &&...args) ->
7245 typename std::result_of<decltype (&App::_parse_arg)(App, Args...)>::type {
7246 return app->_parse_arg(std::forward<Args>(args)...);
7247 }
7248
7250 template <typename... Args>
7251 static auto parse_subcommand(App *app, Args &&...args) ->
7252 typename std::result_of<decltype (&App::_parse_subcommand)(App, Args...)>::type {
7253 return app->_parse_subcommand(std::forward<Args>(args)...);
7254 }
7255#endif
7258};
7259} // namespace detail
7260
7261CLI11_INLINE App::App(std::string app_description, std::string app_name, App *parent)
7262 : name_(std::move(app_name)), description_(std::move(app_description)), parent_(parent) {
7263 // Inherit if not from a nullptr
7264 if (parent_ != nullptr) {
7265 if (parent_->help_ptr_ != nullptr)
7266 set_help_flag(parent_->help_ptr_->get_name(false, true),
7267 parent_->help_ptr_->get_description());
7268 if (parent_->help_all_ptr_ != nullptr)
7269 set_help_all_flag(parent_->help_all_ptr_->get_name(false, true),
7270 parent_->help_all_ptr_->get_description());
7271
7273 option_defaults_ = parent_->option_defaults_;
7274
7275 // INHERITABLE
7276 failure_message_ = parent_->failure_message_;
7277 allow_extras_ = parent_->allow_extras_;
7278 allow_config_extras_ = parent_->allow_config_extras_;
7279 prefix_command_ = parent_->prefix_command_;
7280 immediate_callback_ = parent_->immediate_callback_;
7281 ignore_case_ = parent_->ignore_case_;
7282 ignore_underscore_ = parent_->ignore_underscore_;
7283 fallthrough_ = parent_->fallthrough_;
7284 validate_positionals_ = parent_->validate_positionals_;
7285 validate_optional_arguments_ = parent_->validate_optional_arguments_;
7286 configurable_ = parent_->configurable_;
7287 allow_windows_style_options_ = parent_->allow_windows_style_options_;
7288 group_ = parent_->group_;
7289 footer_ = parent_->footer_;
7290 formatter_ = parent_->formatter_;
7291 config_formatter_ = parent_->config_formatter_;
7292 require_subcommand_max_ = parent_->require_subcommand_max_;
7293 }
7294}
7295
7296CLI11_INLINE App *App::name(std::string app_name) {
7297 if (parent_ != nullptr) {
7298 auto oname = name_;
7299 name_ = app_name;
7300 const auto &res = _compare_subcommand_names(*this, *_get_fallthrough_parent());
7301 if (!res.empty()) {
7302 name_ = oname;
7303 throw(OptionAlreadyAdded(app_name + " conflicts with existing subcommand names"));
7304 }
7305 } else {
7306 name_ = app_name;
7307 }
7308 has_automatic_name_ = false;
7309 return this;
7310}
7311
7312CLI11_INLINE App *App::alias(std::string app_name) {
7313 if (app_name.empty() || !detail::valid_alias_name_string(app_name)) {
7315 "Aliases may not be empty or contain newlines or null characters");
7316 }
7317 if (parent_ != nullptr) {
7318 aliases_.push_back(app_name);
7319 const auto &res = _compare_subcommand_names(*this, *_get_fallthrough_parent());
7320 if (!res.empty()) {
7321 aliases_.pop_back();
7322 throw(OptionAlreadyAdded("alias already matches an existing subcommand: " + app_name));
7323 }
7324 } else {
7325 aliases_.push_back(app_name);
7326 }
7327
7328 return this;
7329}
7330
7331CLI11_INLINE App *App::immediate_callback(bool immediate) {
7332 immediate_callback_ = immediate;
7333 if (immediate_callback_) {
7336 }
7337 } else if (!(final_callback_) && parse_complete_callback_) {
7339 }
7340 return this;
7341}
7342
7343CLI11_INLINE App *App::ignore_case(bool value) {
7344 if (value && !ignore_case_) {
7345 ignore_case_ = true;
7346 auto *p = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
7347 const auto &match = _compare_subcommand_names(*this, *p);
7348 if (!match.empty()) {
7349 ignore_case_ = false; // we are throwing so need to be exception invariant
7350 throw OptionAlreadyAdded("ignore case would cause subcommand name conflicts: " + match);
7351 }
7352 }
7353 ignore_case_ = value;
7354 return this;
7355}
7356
7357CLI11_INLINE App *App::ignore_underscore(bool value) {
7358 if (value && !ignore_underscore_) {
7359 ignore_underscore_ = true;
7360 auto *p = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
7361 const auto &match = _compare_subcommand_names(*this, *p);
7362 if (!match.empty()) {
7363 ignore_underscore_ = false;
7364 throw OptionAlreadyAdded("ignore underscore would cause subcommand name conflicts: " +
7365 match);
7366 }
7367 }
7368 ignore_underscore_ = value;
7369 return this;
7370}
7371
7372CLI11_INLINE Option *App::add_option(std::string option_name,
7373 callback_t option_callback,
7374 std::string option_description,
7375 bool defaulted,
7376 std::function<std::string()> func) {
7377 Option myopt{option_name, option_description, option_callback, this};
7378
7379 if (std::find_if(std::begin(options_), std::end(options_),
7380 [&myopt](const Option_p &v) { return *v == myopt; }) == std::end(options_)) {
7381 options_.emplace_back();
7382 Option_p &option = options_.back();
7383 option.reset(new Option(option_name, option_description, option_callback, this));
7384
7385 // Set the default string capture function
7386 option->default_function(func);
7387
7388 // For compatibility with CLI11 1.7 and before, capture the default string here
7389 if (defaulted) option->capture_default_str();
7390
7391 // Transfer defaults to the new option
7392 option_defaults_.copy_to(option.get());
7393
7394 // Don't bother to capture if we already did
7395 if (!defaulted && option->get_always_capture_default()) option->capture_default_str();
7396
7397 return option.get();
7398 }
7399 // we know something matches now find what it is so we can produce more error information
7400 for (auto &opt : options_) {
7401 const auto &matchname = opt->matching_name(myopt);
7402 if (!matchname.empty()) {
7403 throw(OptionAlreadyAdded("added option matched existing option name: " + matchname));
7404 }
7405 }
7406 // this line should not be reached the above loop should trigger the throw
7407 throw(OptionAlreadyAdded("added option matched existing option name")); // LCOV_EXCL_LINE
7408}
7409
7410CLI11_INLINE Option *App::set_help_flag(std::string flag_name,
7411 const std::string &help_description) {
7412 // take flag_description by const reference otherwise add_flag tries to assign to
7413 // help_description
7414 if (help_ptr_ != nullptr) {
7416 help_ptr_ = nullptr;
7417 }
7418
7419 // Empty name will simply remove the help flag
7420 if (!flag_name.empty()) {
7421 help_ptr_ = add_flag(flag_name, help_description);
7422 help_ptr_->configurable(false);
7423 }
7424
7425 return help_ptr_;
7426}
7427
7428CLI11_INLINE Option *App::set_help_all_flag(std::string help_name,
7429 const std::string &help_description) {
7430 // take flag_description by const reference otherwise add_flag tries to assign to
7431 // flag_description
7432 if (help_all_ptr_ != nullptr) {
7434 help_all_ptr_ = nullptr;
7435 }
7436
7437 // Empty name will simply remove the help all flag
7438 if (!help_name.empty()) {
7439 help_all_ptr_ = add_flag(help_name, help_description);
7440 help_all_ptr_->configurable(false);
7441 }
7442
7443 return help_all_ptr_;
7444}
7445
7446CLI11_INLINE Option *App::set_version_flag(std::string flag_name,
7447 const std::string &versionString,
7448 const std::string &version_help) {
7449 // take flag_description by const reference otherwise add_flag tries to assign to
7450 // version_description
7451 if (version_ptr_ != nullptr) {
7453 version_ptr_ = nullptr;
7454 }
7455
7456 // Empty name will simply remove the version flag
7457 if (!flag_name.empty()) {
7459 flag_name, [versionString]() { throw(CLI::CallForVersion(versionString, 0)); },
7460 version_help);
7461 version_ptr_->configurable(false);
7462 }
7463
7464 return version_ptr_;
7465}
7466
7467CLI11_INLINE Option *App::set_version_flag(std::string flag_name,
7468 std::function<std::string()> vfunc,
7469 const std::string &version_help) {
7470 if (version_ptr_ != nullptr) {
7472 version_ptr_ = nullptr;
7473 }
7474
7475 // Empty name will simply remove the version flag
7476 if (!flag_name.empty()) {
7478 flag_name, [vfunc]() { throw(CLI::CallForVersion(vfunc(), 0)); }, version_help);
7479 version_ptr_->configurable(false);
7480 }
7481
7482 return version_ptr_;
7483}
7484
7485CLI11_INLINE Option *App::_add_flag_internal(std::string flag_name,
7486 CLI::callback_t fun,
7487 std::string flag_description) {
7488 Option *opt = nullptr;
7489 if (detail::has_default_flag_values(flag_name)) {
7490 // check for default values and if it has them
7491 auto flag_defaults = detail::get_default_flag_values(flag_name);
7492 detail::remove_default_flag_values(flag_name);
7493 opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description), false);
7494 for (const auto &fname : flag_defaults) opt->fnames_.push_back(fname.first);
7495 opt->default_flag_values_ = std::move(flag_defaults);
7496 } else {
7497 opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description), false);
7498 }
7499 // flags cannot have positional values
7500 if (opt->get_positional()) {
7501 auto pos_name = opt->get_name(true);
7502 remove_option(opt);
7503 throw IncorrectConstruction::PositionalFlag(pos_name);
7504 }
7505 opt->multi_option_policy(MultiOptionPolicy::TakeLast);
7506 opt->expected(0);
7507 opt->required(false);
7508 return opt;
7509}
7510
7511CLI11_INLINE Option *App::add_flag_callback(
7512 std::string flag_name,
7513 std::function<void(void)> function,
7514 std::string flag_description) {
7515 CLI::callback_t fun = [function](const CLI::results_t &res) {
7516 bool trigger{false};
7517 auto result = CLI::detail::lexical_cast(res[0], trigger);
7518 if (result && trigger) {
7519 function();
7520 }
7521 return result;
7522 };
7523 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
7524}
7525
7526CLI11_INLINE Option *App::add_flag_function(
7527 std::string flag_name,
7528 std::function<void(std::int64_t)> function,
7529 std::string flag_description) {
7530 CLI::callback_t fun = [function](const CLI::results_t &res) {
7531 std::int64_t flag_count{0};
7532 CLI::detail::lexical_cast(res[0], flag_count);
7533 function(flag_count);
7534 return true;
7535 };
7536 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
7537 ->multi_option_policy(MultiOptionPolicy::Sum);
7538}
7539
7540CLI11_INLINE Option *App::set_config(std::string option_name,
7541 std::string default_filename,
7542 const std::string &help_message,
7543 bool config_required) {
7544 // Remove existing config if present
7545 if (config_ptr_ != nullptr) {
7547 config_ptr_ = nullptr; // need to remove the config_ptr completely
7548 }
7549
7550 // Only add config if option passed
7551 if (!option_name.empty()) {
7552 config_ptr_ = add_option(option_name, help_message);
7553 if (config_required) {
7554 config_ptr_->required();
7555 }
7556 if (!default_filename.empty()) {
7557 config_ptr_->default_str(std::move(default_filename));
7558 }
7559 config_ptr_->configurable(false);
7560 }
7561
7562 return config_ptr_;
7563}
7564
7565CLI11_INLINE bool App::remove_option(Option *opt) {
7566 // Make sure no links exist
7567 for (Option_p &op : options_) {
7568 op->remove_needs(opt);
7569 op->remove_excludes(opt);
7570 }
7571
7572 if (help_ptr_ == opt) help_ptr_ = nullptr;
7573 if (help_all_ptr_ == opt) help_all_ptr_ = nullptr;
7574
7575 auto iterator = std::find_if(std::begin(options_), std::end(options_),
7576 [opt](const Option_p &v) { return v.get() == opt; });
7577 if (iterator != std::end(options_)) {
7578 options_.erase(iterator);
7579 return true;
7580 }
7581 return false;
7582}
7583
7584CLI11_INLINE App *App::add_subcommand(std::string subcommand_name,
7585 std::string subcommand_description) {
7586 if (!subcommand_name.empty() && !detail::valid_name_string(subcommand_name)) {
7587 if (!detail::valid_first_char(subcommand_name[0])) {
7589 "Subcommand name starts with invalid character, '!' and '-' are not allowed");
7590 }
7591 for (auto c : subcommand_name) {
7592 if (!detail::valid_later_char(c)) {
7594 std::string("Subcommand name contains invalid character ('") + c +
7595 "'), all characters are allowed except"
7596 "'=',':','{','}', and ' '");
7597 }
7598 }
7599 }
7600 CLI::App_p subcom =
7601 std::shared_ptr<App>(new App(std::move(subcommand_description), subcommand_name, this));
7602 return add_subcommand(std::move(subcom));
7603}
7604
7605CLI11_INLINE App *App::add_subcommand(CLI::App_p subcom) {
7606 if (!subcom) throw IncorrectConstruction("passed App is not valid");
7607 auto *ckapp = (name_.empty() && parent_ != nullptr) ? _get_fallthrough_parent() : this;
7608 const auto &mstrg = _compare_subcommand_names(*subcom, *ckapp);
7609 if (!mstrg.empty()) {
7610 throw(OptionAlreadyAdded("subcommand name or alias matches existing subcommand: " + mstrg));
7611 }
7612 subcom->parent_ = this;
7613 subcommands_.push_back(std::move(subcom));
7614 return subcommands_.back().get();
7615}
7616
7617CLI11_INLINE bool App::remove_subcommand(App *subcom) {
7618 // Make sure no links exist
7619 for (App_p &sub : subcommands_) {
7620 sub->remove_excludes(subcom);
7621 sub->remove_needs(subcom);
7622 }
7623
7624 auto iterator = std::find_if(std::begin(subcommands_), std::end(subcommands_),
7625 [subcom](const App_p &v) { return v.get() == subcom; });
7626 if (iterator != std::end(subcommands_)) {
7627 subcommands_.erase(iterator);
7628 return true;
7629 }
7630 return false;
7631}
7632
7633CLI11_INLINE App *App::get_subcommand(const App *subcom) const {
7634 if (subcom == nullptr) throw OptionNotFound("nullptr passed");
7635 for (const App_p &subcomptr : subcommands_)
7636 if (subcomptr.get() == subcom) return subcomptr.get();
7637 throw OptionNotFound(subcom->get_name());
7638}
7639
7640CLI11_NODISCARD CLI11_INLINE App *App::get_subcommand(std::string subcom) const {
7641 auto *subc = _find_subcommand(subcom, false, false);
7642 if (subc == nullptr) throw OptionNotFound(subcom);
7643 return subc;
7644}
7645
7646CLI11_NODISCARD CLI11_INLINE App *App::get_subcommand(int index) const {
7647 if (index >= 0) {
7648 auto uindex = static_cast<unsigned>(index);
7649 if (uindex < subcommands_.size()) return subcommands_[uindex].get();
7650 }
7651 throw OptionNotFound(std::to_string(index));
7652}
7653
7654CLI11_INLINE CLI::App_p App::get_subcommand_ptr(App *subcom) const {
7655 if (subcom == nullptr) throw OptionNotFound("nullptr passed");
7656 for (const App_p &subcomptr : subcommands_)
7657 if (subcomptr.get() == subcom) return subcomptr;
7658 throw OptionNotFound(subcom->get_name());
7659}
7660
7661CLI11_NODISCARD CLI11_INLINE CLI::App_p App::get_subcommand_ptr(std::string subcom) const {
7662 for (const App_p &subcomptr : subcommands_)
7663 if (subcomptr->check_name(subcom)) return subcomptr;
7664 throw OptionNotFound(subcom);
7665}
7666
7667CLI11_NODISCARD CLI11_INLINE CLI::App_p App::get_subcommand_ptr(int index) const {
7668 if (index >= 0) {
7669 auto uindex = static_cast<unsigned>(index);
7670 if (uindex < subcommands_.size()) return subcommands_[uindex];
7671 }
7672 throw OptionNotFound(std::to_string(index));
7673}
7674
7675CLI11_NODISCARD CLI11_INLINE CLI::App *App::get_option_group(std::string group_name) const {
7676 for (const App_p &app : subcommands_) {
7677 if (app->name_.empty() && app->group_ == group_name) {
7678 return app.get();
7679 }
7680 }
7681 throw OptionNotFound(group_name);
7682}
7683
7684CLI11_NODISCARD CLI11_INLINE std::size_t App::count_all() const {
7685 std::size_t cnt{0};
7686 for (const auto &opt : options_) {
7687 cnt += opt->count();
7688 }
7689 for (const auto &sub : subcommands_) {
7690 cnt += sub->count_all();
7691 }
7692 if (!get_name()
7693 .empty()) { // for named subcommands add the number of times the subcommand was called
7694 cnt += parsed_;
7695 }
7696 return cnt;
7697}
7698
7699CLI11_INLINE void App::clear() {
7700 parsed_ = 0;
7701 pre_parse_called_ = false;
7702
7703 missing_.clear();
7704 parsed_subcommands_.clear();
7705 for (const Option_p &opt : options_) {
7706 opt->clear();
7707 }
7708 for (const App_p &subc : subcommands_) {
7709 subc->clear();
7710 }
7711}
7712
7713CLI11_INLINE void App::parse(int argc, const char *const *argv) {
7714 // If the name is not set, read from command line
7715 if (name_.empty() || has_automatic_name_) {
7716 has_automatic_name_ = true;
7717 name_ = argv[0];
7718 }
7719
7720 std::vector<std::string> args;
7721 args.reserve(static_cast<std::size_t>(argc) - 1U);
7722 for (auto i = static_cast<std::size_t>(argc) - 1U; i > 0U; --i) args.emplace_back(argv[i]);
7723 parse(std::move(args));
7724}
7725
7726CLI11_INLINE void App::parse(std::string commandline, bool program_name_included) {
7727 if (program_name_included) {
7728 auto nstr = detail::split_program_name(commandline);
7729 if ((name_.empty()) || (has_automatic_name_)) {
7730 has_automatic_name_ = true;
7731 name_ = nstr.first;
7732 }
7733 commandline = std::move(nstr.second);
7734 } else {
7735 detail::trim(commandline);
7736 }
7737 // the next section of code is to deal with quoted arguments after an '=' or ':' for windows
7738 // like operations
7739 if (!commandline.empty()) {
7740 commandline = detail::find_and_modify(commandline, "=", detail::escape_detect);
7742 commandline = detail::find_and_modify(commandline, ":", detail::escape_detect);
7743 }
7744
7745 auto args = detail::split_up(std::move(commandline));
7746 // remove all empty strings
7747 args.erase(std::remove(args.begin(), args.end(), std::string{}), args.end());
7748 std::reverse(args.begin(), args.end());
7749
7750 parse(std::move(args));
7751}
7752
7753CLI11_INLINE void App::parse(std::vector<std::string> &args) {
7754 // Clear if parsed
7755 if (parsed_ > 0) clear();
7756
7757 // parsed_ is incremented in commands/subcommands,
7758 // but placed here to make sure this is cleared when
7759 // running parse after an error is thrown, even by _validate or _configure.
7760 parsed_ = 1;
7761 _validate();
7762 _configure();
7763 // set the parent as nullptr as this object should be the top now
7764 parent_ = nullptr;
7765 parsed_ = 0;
7766
7767 _parse(args);
7768 run_callback();
7769}
7770
7771CLI11_INLINE void App::parse(std::vector<std::string> &&args) {
7772 // Clear if parsed
7773 if (parsed_ > 0) clear();
7774
7775 // parsed_ is incremented in commands/subcommands,
7776 // but placed here to make sure this is cleared when
7777 // running parse after an error is thrown, even by _validate or _configure.
7778 parsed_ = 1;
7779 _validate();
7780 _configure();
7781 // set the parent as nullptr as this object should be the top now
7782 parent_ = nullptr;
7783 parsed_ = 0;
7784
7785 _parse(std::move(args));
7786 run_callback();
7787}
7788
7789CLI11_INLINE void App::parse_from_stream(std::istream &input) {
7790 if (parsed_ == 0) {
7791 _validate();
7792 _configure();
7793 // set the parent as nullptr as this object should be the top now
7794 }
7795
7796 _parse_stream(input);
7797 run_callback();
7798}
7799
7800CLI11_INLINE int App::exit(const Error &e, std::ostream &out, std::ostream &err) const {
7802 if (e.get_name() == "RuntimeError") return e.get_exit_code();
7803
7804 if (e.get_name() == "CallForHelp") {
7805 out << help();
7806 return e.get_exit_code();
7807 }
7808
7809 if (e.get_name() == "CallForAllHelp") {
7810 out << help("", AppFormatMode::All);
7811 return e.get_exit_code();
7812 }
7813
7814 if (e.get_name() == "CallForVersion") {
7815 out << e.what() << std::endl;
7816 return e.get_exit_code();
7817 }
7818
7819 if (e.get_exit_code() != static_cast<int>(ExitCodes::Success)) {
7820 if (failure_message_) err << failure_message_(this, e) << std::flush;
7821 }
7822
7823 return e.get_exit_code();
7824}
7825
7826CLI11_INLINE std::vector<const App *> App::get_subcommands(
7827 const std::function<bool(const App *)> &filter) const {
7828 std::vector<const App *> subcomms(subcommands_.size());
7829 std::transform(std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms),
7830 [](const App_p &v) { return v.get(); });
7831
7832 if (filter) {
7833 subcomms.erase(std::remove_if(std::begin(subcomms), std::end(subcomms),
7834 [&filter](const App *app) { return !filter(app); }),
7835 std::end(subcomms));
7836 }
7837
7838 return subcomms;
7839}
7840
7841CLI11_INLINE std::vector<App *> App::get_subcommands(const std::function<bool(App *)> &filter) {
7842 std::vector<App *> subcomms(subcommands_.size());
7843 std::transform(std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms),
7844 [](const App_p &v) { return v.get(); });
7845
7846 if (filter) {
7847 subcomms.erase(std::remove_if(std::begin(subcomms), std::end(subcomms),
7848 [&filter](App *app) { return !filter(app); }),
7849 std::end(subcomms));
7850 }
7851
7852 return subcomms;
7853}
7854
7855CLI11_INLINE bool App::remove_excludes(Option *opt) {
7856 auto iterator = std::find(std::begin(exclude_options_), std::end(exclude_options_), opt);
7857 if (iterator == std::end(exclude_options_)) {
7858 return false;
7859 }
7860 exclude_options_.erase(iterator);
7861 return true;
7862}
7863
7864CLI11_INLINE bool App::remove_excludes(App *app) {
7865 auto iterator =
7866 std::find(std::begin(exclude_subcommands_), std::end(exclude_subcommands_), app);
7867 if (iterator == std::end(exclude_subcommands_)) {
7868 return false;
7869 }
7870 auto *other_app = *iterator;
7871 exclude_subcommands_.erase(iterator);
7872 other_app->remove_excludes(this);
7873 return true;
7874}
7875
7876CLI11_INLINE bool App::remove_needs(Option *opt) {
7877 auto iterator = std::find(std::begin(need_options_), std::end(need_options_), opt);
7878 if (iterator == std::end(need_options_)) {
7879 return false;
7880 }
7881 need_options_.erase(iterator);
7882 return true;
7883}
7884
7885CLI11_INLINE bool App::remove_needs(App *app) {
7886 auto iterator = std::find(std::begin(need_subcommands_), std::end(need_subcommands_), app);
7887 if (iterator == std::end(need_subcommands_)) {
7888 return false;
7889 }
7890 need_subcommands_.erase(iterator);
7891 return true;
7892}
7893
7894CLI11_NODISCARD CLI11_INLINE std::string App::help(std::string prev, AppFormatMode mode) const {
7895 if (prev.empty())
7896 prev = get_name();
7897 else
7898 prev += " " + get_name();
7899
7900 // Delegate to subcommand if needed
7901 auto selected_subcommands = get_subcommands();
7902 if (!selected_subcommands.empty()) {
7903 return selected_subcommands.at(0)->help(prev, mode);
7904 }
7905 return formatter_->make_help(this, prev, mode);
7906}
7907
7908CLI11_NODISCARD CLI11_INLINE std::string App::version() const {
7909 std::string val;
7910 if (version_ptr_ != nullptr) {
7911 auto rv = version_ptr_->results();
7912 version_ptr_->clear();
7913 version_ptr_->add_result("true");
7914 try {
7915 version_ptr_->run_callback();
7916 } catch (const CLI::CallForVersion &cfv) {
7917 val = cfv.what();
7918 }
7919 version_ptr_->clear();
7920 version_ptr_->add_result(rv);
7921 }
7922 return val;
7923}
7924
7925CLI11_INLINE std::vector<const Option *> App::get_options(
7926 const std::function<bool(const Option *)> filter) const {
7927 std::vector<const Option *> options(options_.size());
7928 std::transform(std::begin(options_), std::end(options_), std::begin(options),
7929 [](const Option_p &val) { return val.get(); });
7930
7931 if (filter) {
7932 options.erase(std::remove_if(std::begin(options), std::end(options),
7933 [&filter](const Option *opt) { return !filter(opt); }),
7934 std::end(options));
7935 }
7936
7937 return options;
7938}
7939
7940CLI11_INLINE std::vector<Option *> App::get_options(const std::function<bool(Option *)> filter) {
7941 std::vector<Option *> options(options_.size());
7942 std::transform(std::begin(options_), std::end(options_), std::begin(options),
7943 [](const Option_p &val) { return val.get(); });
7944
7945 if (filter) {
7946 options.erase(std::remove_if(std::begin(options), std::end(options),
7947 [&filter](Option *opt) { return !filter(opt); }),
7948 std::end(options));
7949 }
7950
7951 return options;
7952}
7953
7954CLI11_INLINE Option *App::get_option_no_throw(std::string option_name) noexcept {
7955 for (Option_p &opt : options_) {
7956 if (opt->check_name(option_name)) {
7957 return opt.get();
7958 }
7959 }
7960 for (auto &subc : subcommands_) {
7961 // also check down into nameless subcommands
7962 if (subc->get_name().empty()) {
7963 auto *opt = subc->get_option_no_throw(option_name);
7964 if (opt != nullptr) {
7965 return opt;
7966 }
7967 }
7968 }
7969 return nullptr;
7970}
7971
7972CLI11_NODISCARD CLI11_INLINE const Option *App::get_option_no_throw(
7973 std::string option_name) const noexcept {
7974 for (const Option_p &opt : options_) {
7975 if (opt->check_name(option_name)) {
7976 return opt.get();
7977 }
7978 }
7979 for (const auto &subc : subcommands_) {
7980 // also check down into nameless subcommands
7981 if (subc->get_name().empty()) {
7982 auto *opt = subc->get_option_no_throw(option_name);
7983 if (opt != nullptr) {
7984 return opt;
7985 }
7986 }
7987 }
7988 return nullptr;
7989}
7990
7991CLI11_NODISCARD CLI11_INLINE std::string App::get_display_name(bool with_aliases) const {
7992 if (name_.empty()) {
7993 return std::string("[Option Group: ") + get_group() + "]";
7994 }
7995 if (aliases_.empty() || !with_aliases) {
7996 return name_;
7997 }
7998 std::string dispname = name_;
7999 for (const auto &lalias : aliases_) {
8000 dispname.push_back(',');
8001 dispname.push_back(' ');
8002 dispname.append(lalias);
8003 }
8004 return dispname;
8005}
8006
8007CLI11_NODISCARD CLI11_INLINE bool App::check_name(std::string name_to_check) const {
8008 std::string local_name = name_;
8009 if (ignore_underscore_) {
8010 local_name = detail::remove_underscore(name_);
8011 name_to_check = detail::remove_underscore(name_to_check);
8012 }
8013 if (ignore_case_) {
8014 local_name = detail::to_lower(name_);
8015 name_to_check = detail::to_lower(name_to_check);
8016 }
8017
8018 if (local_name == name_to_check) {
8019 return true;
8020 }
8021 for (auto les : aliases_) { // NOLINT(performance-for-range-copy)
8022 if (ignore_underscore_) {
8023 les = detail::remove_underscore(les);
8024 }
8025 if (ignore_case_) {
8026 les = detail::to_lower(les);
8027 }
8028 if (les == name_to_check) {
8029 return true;
8030 }
8031 }
8032 return false;
8033}
8034
8035CLI11_NODISCARD CLI11_INLINE std::vector<std::string> App::get_groups() const {
8036 std::vector<std::string> groups;
8037
8038 for (const Option_p &opt : options_) {
8039 // Add group if it is not already in there
8040 if (std::find(groups.begin(), groups.end(), opt->get_group()) == groups.end()) {
8041 groups.push_back(opt->get_group());
8042 }
8043 }
8044
8045 return groups;
8046}
8047
8048CLI11_NODISCARD CLI11_INLINE std::vector<std::string> App::remaining(bool recurse) const {
8049 std::vector<std::string> miss_list;
8050 for (const std::pair<detail::Classifier, std::string> &miss : missing_) {
8051 miss_list.push_back(std::get<1>(miss));
8052 }
8053 // Get from a subcommand that may allow extras
8054 if (recurse) {
8055 if (!allow_extras_) {
8056 for (const auto &sub : subcommands_) {
8057 if (sub->name_.empty() && !sub->missing_.empty()) {
8058 for (const std::pair<detail::Classifier, std::string> &miss : sub->missing_) {
8059 miss_list.push_back(std::get<1>(miss));
8060 }
8061 }
8062 }
8063 }
8064 // Recurse into subcommands
8065
8066 for (const App *sub : parsed_subcommands_) {
8067 std::vector<std::string> output = sub->remaining(recurse);
8068 std::copy(std::begin(output), std::end(output), std::back_inserter(miss_list));
8069 }
8070 }
8071 return miss_list;
8072}
8073
8074CLI11_NODISCARD CLI11_INLINE std::vector<std::string> App::remaining_for_passthrough(
8075 bool recurse) const {
8076 std::vector<std::string> miss_list = remaining(recurse);
8077 std::reverse(std::begin(miss_list), std::end(miss_list));
8078 return miss_list;
8079}
8080
8081CLI11_NODISCARD CLI11_INLINE std::size_t App::remaining_size(bool recurse) const {
8082 auto remaining_options = static_cast<std::size_t>(
8083 std::count_if(std::begin(missing_), std::end(missing_),
8084 [](const std::pair<detail::Classifier, std::string> &val) {
8085 return val.first != detail::Classifier::POSITIONAL_MARK;
8086 }));
8087
8088 if (recurse) {
8089 for (const App_p &sub : subcommands_) {
8090 remaining_options += sub->remaining_size(recurse);
8091 }
8092 }
8093 return remaining_options;
8094}
8095
8096CLI11_INLINE void App::_validate() const {
8097 // count the number of positional only args
8098 auto pcount = std::count_if(std::begin(options_), std::end(options_), [](const Option_p &opt) {
8099 return opt->get_items_expected_max() >= detail::expected_max_vector_size &&
8100 !opt->nonpositional();
8101 });
8102 if (pcount > 1) {
8103 auto pcount_req =
8104 std::count_if(std::begin(options_), std::end(options_), [](const Option_p &opt) {
8105 return opt->get_items_expected_max() >= detail::expected_max_vector_size &&
8106 !opt->nonpositional() && opt->get_required();
8107 });
8108 if (pcount - pcount_req > 1) {
8109 throw InvalidError(name_);
8110 }
8111 }
8112
8113 std::size_t nameless_subs{0};
8114 for (const App_p &app : subcommands_) {
8115 app->_validate();
8116 if (app->get_name().empty()) ++nameless_subs;
8117 }
8118
8119 if (require_option_min_ > 0) {
8120 if (require_option_max_ > 0) {
8122 throw(InvalidError("Required min options greater than required max options",
8123 ExitCodes::InvalidError));
8124 }
8125 }
8126 if (require_option_min_ > (options_.size() + nameless_subs)) {
8127 throw(InvalidError("Required min options greater than number of available options",
8128 ExitCodes::InvalidError));
8129 }
8130 }
8131}
8132
8133CLI11_INLINE void App::_configure() {
8134 if (default_startup == startup_mode::enabled) {
8135 disabled_ = false;
8136 } else if (default_startup == startup_mode::disabled) {
8137 disabled_ = true;
8138 }
8139 for (const App_p &app : subcommands_) {
8140 if (app->has_automatic_name_) {
8141 app->name_.clear();
8142 }
8143 if (app->name_.empty()) {
8144 app->fallthrough_ = false; // make sure fallthrough_ is false to prevent infinite loop
8145 app->prefix_command_ = false;
8146 }
8147 // make sure the parent is set to be this object in preparation for parse
8148 app->parent_ = this;
8149 app->_configure();
8150 }
8151}
8152
8153CLI11_INLINE void App::run_callback(bool final_mode, bool suppress_final_callback) {
8154 pre_callback();
8155 // in the main app if immediate_callback_ is set it runs the main callback before the used
8156 // subcommands
8157 if (!final_mode && parse_complete_callback_) {
8159 }
8160 // run the callbacks for the received subcommands
8161 for (App *subc : get_subcommands()) {
8162 if (subc->parent_ == this) {
8163 subc->run_callback(true, suppress_final_callback);
8164 }
8165 }
8166 // now run callbacks for option_groups
8167 for (auto &subc : subcommands_) {
8168 if (subc->name_.empty() && subc->count_all() > 0) {
8169 subc->run_callback(true, suppress_final_callback);
8170 }
8171 }
8172
8173 // finally run the main callback
8174 if (final_callback_ && (parsed_ > 0) && (!suppress_final_callback)) {
8175 if (!name_.empty() || count_all() > 0 || parent_ == nullptr) {
8177 }
8178 }
8179}
8180
8181CLI11_NODISCARD CLI11_INLINE bool App::_valid_subcommand(const std::string &current,
8182 bool ignore_used) const {
8183 // Don't match if max has been reached - but still check parents
8185 return parent_ != nullptr && parent_->_valid_subcommand(current, ignore_used);
8186 }
8187 auto *com = _find_subcommand(current, true, ignore_used);
8188 if (com != nullptr) {
8189 return true;
8190 }
8191 // Check parent if exists, else return false
8192 return parent_ != nullptr && parent_->_valid_subcommand(current, ignore_used);
8193}
8194
8195CLI11_NODISCARD CLI11_INLINE detail::Classifier App::_recognize(
8196 const std::string &current, bool ignore_used_subcommands) const {
8197 std::string dummy1, dummy2;
8198
8199 if (current == "--") return detail::Classifier::POSITIONAL_MARK;
8200 if (_valid_subcommand(current, ignore_used_subcommands)) return detail::Classifier::SUBCOMMAND;
8201 if (detail::split_long(current, dummy1, dummy2)) return detail::Classifier::LONG;
8202 if (detail::split_short(current, dummy1, dummy2)) {
8203 if (dummy1[0] >= '0' && dummy1[0] <= '9') {
8204 if (get_option_no_throw(std::string{'-', dummy1[0]}) == nullptr) {
8205 return detail::Classifier::NONE;
8206 }
8207 }
8208 return detail::Classifier::SHORT;
8209 }
8210 if ((allow_windows_style_options_) && (detail::split_windows_style(current, dummy1, dummy2)))
8211 return detail::Classifier::WINDOWS_STYLE;
8212 if ((current == "++") && !name_.empty() && parent_ != nullptr)
8213 return detail::Classifier::SUBCOMMAND_TERMINATOR;
8214 return detail::Classifier::NONE;
8215}
8216
8217CLI11_INLINE void App::_process_config_file() {
8218 if (config_ptr_ != nullptr) {
8219 bool config_required = config_ptr_->get_required();
8220 auto file_given = config_ptr_->count() > 0;
8221 auto config_files = config_ptr_->as<std::vector<std::string>>();
8222 if (config_files.empty() || config_files.front().empty()) {
8223 if (config_required) {
8224 throw FileError::Missing("no specified config file");
8225 }
8226 return;
8227 }
8228 for (auto rit = config_files.rbegin(); rit != config_files.rend(); ++rit) {
8229 const auto &config_file = *rit;
8230 auto path_result = detail::check_path(config_file.c_str());
8231 if (path_result == detail::path_type::file) {
8232 try {
8233 std::vector<ConfigItem> values = config_formatter_->from_file(config_file);
8234 _parse_config(values);
8235 if (!file_given) {
8236 config_ptr_->add_result(config_file);
8237 }
8238 } catch (const FileError &) {
8239 if (config_required || file_given) throw;
8240 }
8241 } else if (config_required || file_given) {
8242 throw FileError::Missing(config_file);
8243 }
8244 }
8245 }
8246}
8247
8248CLI11_INLINE void App::_process_env() {
8249 for (const Option_p &opt : options_) {
8250 if (opt->count() == 0 && !opt->envname_.empty()) {
8251 char *buffer = nullptr;
8252 std::string ename_string;
8253
8254#ifdef _MSC_VER
8255 // Windows version
8256 std::size_t sz = 0;
8257 if (_dupenv_s(&buffer, &sz, opt->envname_.c_str()) == 0 && buffer != nullptr) {
8258 ename_string = std::string(buffer);
8259 free(buffer);
8260 }
8261#else
8262 // This also works on Windows, but gives a warning
8263 buffer = std::getenv(opt->envname_.c_str());
8264 if (buffer != nullptr) ename_string = std::string(buffer);
8265#endif
8266
8267 if (!ename_string.empty()) {
8268 opt->add_result(ename_string);
8269 }
8270 }
8271 }
8272
8273 for (App_p &sub : subcommands_) {
8274 if (sub->get_name().empty() || !sub->parse_complete_callback_) sub->_process_env();
8275 }
8276}
8277
8278CLI11_INLINE void App::_process_callbacks() {
8279 for (App_p &sub : subcommands_) {
8280 // process the priority option_groups first
8281 if (sub->get_name().empty() && sub->parse_complete_callback_) {
8282 if (sub->count_all() > 0) {
8283 sub->_process_callbacks();
8284 sub->run_callback();
8285 }
8286 }
8287 }
8288
8289 for (const Option_p &opt : options_) {
8290 if ((*opt) && !opt->get_callback_run()) {
8291 opt->run_callback();
8292 }
8293 }
8294 for (App_p &sub : subcommands_) {
8295 if (!sub->parse_complete_callback_) {
8296 sub->_process_callbacks();
8297 }
8298 }
8299}
8300
8301CLI11_INLINE void App::_process_help_flags(bool trigger_help, bool trigger_all_help) const {
8302 const Option *help_ptr = get_help_ptr();
8303 const Option *help_all_ptr = get_help_all_ptr();
8304
8305 if (help_ptr != nullptr && help_ptr->count() > 0) trigger_help = true;
8306 if (help_all_ptr != nullptr && help_all_ptr->count() > 0) trigger_all_help = true;
8307
8308 // If there were parsed subcommands, call those. First subcommand wins if there are multiple
8309 // ones.
8310 if (!parsed_subcommands_.empty()) {
8311 for (const App *sub : parsed_subcommands_)
8312 sub->_process_help_flags(trigger_help, trigger_all_help);
8313
8314 // Only the final subcommand should call for help. All help wins over help.
8315 } else if (trigger_all_help) {
8316 throw CallForAllHelp();
8317 } else if (trigger_help) {
8318 throw CallForHelp();
8319 }
8320}
8321
8322CLI11_INLINE void App::_process_requirements() {
8323 // check excludes
8324 bool excluded{false};
8325 std::string excluder;
8326 for (const auto &opt : exclude_options_) {
8327 if (opt->count() > 0) {
8328 excluded = true;
8329 excluder = opt->get_name();
8330 }
8331 }
8332 for (const auto &subc : exclude_subcommands_) {
8333 if (subc->count_all() > 0) {
8334 excluded = true;
8335 excluder = subc->get_display_name();
8336 }
8337 }
8338 if (excluded) {
8339 if (count_all() > 0) {
8340 throw ExcludesError(get_display_name(), excluder);
8341 }
8342 // if we are excluded but didn't receive anything, just return
8343 return;
8344 }
8345
8346 // check excludes
8347 bool missing_needed{false};
8348 std::string missing_need;
8349 for (const auto &opt : need_options_) {
8350 if (opt->count() == 0) {
8351 missing_needed = true;
8352 missing_need = opt->get_name();
8353 }
8354 }
8355 for (const auto &subc : need_subcommands_) {
8356 if (subc->count_all() == 0) {
8357 missing_needed = true;
8358 missing_need = subc->get_display_name();
8359 }
8360 }
8361 if (missing_needed) {
8362 if (count_all() > 0) {
8363 throw RequiresError(get_display_name(), missing_need);
8364 }
8365 // if we missing something but didn't have any options, just return
8366 return;
8367 }
8368
8369 std::size_t used_options = 0;
8370 for (const Option_p &opt : options_) {
8371 if (opt->count() != 0) {
8372 ++used_options;
8373 }
8374 // Required but empty
8375 if (opt->get_required() && opt->count() == 0) {
8376 throw RequiredError(opt->get_name());
8377 }
8378 // Requires
8379 for (const Option *opt_req : opt->needs_)
8380 if (opt->count() > 0 && opt_req->count() == 0)
8381 throw RequiresError(opt->get_name(), opt_req->get_name());
8382 // Excludes
8383 for (const Option *opt_ex : opt->excludes_)
8384 if (opt->count() > 0 && opt_ex->count() != 0)
8385 throw ExcludesError(opt->get_name(), opt_ex->get_name());
8386 }
8387 // check for the required number of subcommands
8388 if (require_subcommand_min_ > 0) {
8389 auto selected_subcommands = get_subcommands();
8390 if (require_subcommand_min_ > selected_subcommands.size())
8391 throw RequiredError::Subcommand(require_subcommand_min_);
8392 }
8393
8394 // Max error cannot occur, the extra subcommand will parse as an ExtrasError or a remaining
8395 // item.
8396
8397 // run this loop to check how many unnamed subcommands were actually used since they are
8398 // considered options from the perspective of an App
8399 for (App_p &sub : subcommands_) {
8400 if (sub->disabled_) continue;
8401 if (sub->name_.empty() && sub->count_all() > 0) {
8402 ++used_options;
8403 }
8404 }
8405
8406 if (require_option_min_ > used_options ||
8407 (require_option_max_ > 0 && require_option_max_ < used_options)) {
8408 auto option_list = detail::join(options_, [this](const Option_p &ptr) {
8409 if (ptr.get() == help_ptr_ || ptr.get() == help_all_ptr_) {
8410 return std::string{};
8411 }
8412 return ptr->get_name(false, true);
8413 });
8414
8415 auto subc_list = get_subcommands(
8416 [](App *app) { return ((app->get_name().empty()) && (!app->disabled_)); });
8417 if (!subc_list.empty()) {
8418 option_list += "," + detail::join(subc_list, [](const App *app) {
8419 return app->get_display_name();
8420 });
8421 }
8422 throw RequiredError::Option(require_option_min_, require_option_max_, used_options,
8423 option_list);
8424 }
8425
8426 // now process the requirements for subcommands if needed
8427 for (App_p &sub : subcommands_) {
8428 if (sub->disabled_) continue;
8429 if (sub->name_.empty() && sub->required_ == false) {
8430 if (sub->count_all() == 0) {
8431 if (require_option_min_ > 0 && require_option_min_ <= used_options) {
8432 continue;
8433 // if we have met the requirement and there is nothing in this option group skip
8434 // checking requirements
8435 }
8436 if (require_option_max_ > 0 && used_options >= require_option_min_) {
8437 continue;
8438 // if we have met the requirement and there is nothing in this option group skip
8439 // checking requirements
8440 }
8441 }
8442 }
8443 if (sub->count() > 0 || sub->name_.empty()) {
8444 sub->_process_requirements();
8445 }
8446
8447 if (sub->required_ && sub->count_all() == 0) {
8448 throw(CLI::RequiredError(sub->get_display_name()));
8449 }
8450 }
8451}
8452
8453CLI11_INLINE void App::_process() {
8454 try {
8455 // the config file might generate a FileError but that should not be processed until later
8456 // in the process to allow for help, version and other errors to generate first.
8458
8459 // process env shouldn't throw but no reason to process it if config generated an error
8460 _process_env();
8461 } catch (const CLI::FileError &) {
8462 // callbacks and help_flags can generate exceptions which should take priority
8463 // over the config file error if one exists.
8466 throw;
8467 }
8468
8471
8473}
8474
8475CLI11_INLINE void App::_process_extras() {
8476 if (!(allow_extras_ || prefix_command_)) {
8477 std::size_t num_left_over = remaining_size();
8478 if (num_left_over > 0) {
8479 throw ExtrasError(name_, remaining(false));
8480 }
8481 }
8482
8483 for (App_p &sub : subcommands_) {
8484 if (sub->count() > 0) sub->_process_extras();
8485 }
8486}
8487
8488CLI11_INLINE void App::_process_extras(std::vector<std::string> &args) {
8489 if (!(allow_extras_ || prefix_command_)) {
8490 std::size_t num_left_over = remaining_size();
8491 if (num_left_over > 0) {
8492 args = remaining(false);
8493 throw ExtrasError(name_, args);
8494 }
8495 }
8496
8497 for (App_p &sub : subcommands_) {
8498 if (sub->count() > 0) sub->_process_extras(args);
8499 }
8500}
8501
8502CLI11_INLINE void App::increment_parsed() {
8503 ++parsed_;
8504 for (App_p &sub : subcommands_) {
8505 if (sub->get_name().empty()) sub->increment_parsed();
8506 }
8507}
8508
8509CLI11_INLINE void App::_parse(std::vector<std::string> &args) {
8511 _trigger_pre_parse(args.size());
8512 bool positional_only = false;
8513
8514 while (!args.empty()) {
8515 if (!_parse_single(args, positional_only)) {
8516 break;
8517 }
8518 }
8519
8520 if (parent_ == nullptr) {
8521 _process();
8522
8523 // Throw error if any items are left over (depending on settings)
8524 _process_extras(args);
8525
8526 // Convert missing (pairs) to extras (string only) ready for processing in another app
8527 args = remaining_for_passthrough(false);
8528 } else if (parse_complete_callback_) {
8529 _process_env();
8533 run_callback(false, true);
8534 }
8535}
8536
8537CLI11_INLINE void App::_parse(std::vector<std::string> &&args) {
8538 // this can only be called by the top level in which case parent == nullptr by definition
8539 // operation is simplified
8541 _trigger_pre_parse(args.size());
8542 bool positional_only = false;
8543
8544 while (!args.empty()) {
8545 _parse_single(args, positional_only);
8546 }
8547 _process();
8548
8549 // Throw error if any items are left over (depending on settings)
8551}
8552
8553CLI11_INLINE void App::_parse_stream(std::istream &input) {
8554 auto values = config_formatter_->from_config(input);
8555 _parse_config(values);
8557 _trigger_pre_parse(values.size());
8558 _process();
8559
8560 // Throw error if any items are left over (depending on settings)
8562}
8563
8564CLI11_INLINE void App::_parse_config(const std::vector<ConfigItem> &args) {
8565 for (const ConfigItem &item : args) {
8566 if (!_parse_single_config(item) && allow_config_extras_ == config_extras_mode::error)
8567 throw ConfigError::Extras(item.fullname());
8568 }
8569}
8570
8571CLI11_INLINE bool App::_parse_single_config(const ConfigItem &item, std::size_t level) {
8572 if (level < item.parents.size()) {
8573 try {
8574 auto *subcom = get_subcommand(item.parents.at(level));
8575 auto result = subcom->_parse_single_config(item, level + 1);
8576
8577 return result;
8578 } catch (const OptionNotFound &) {
8579 return false;
8580 }
8581 }
8582 // check for section open
8583 if (item.name == "++") {
8584 if (configurable_) {
8587 if (parent_ != nullptr) {
8588 parent_->parsed_subcommands_.push_back(this);
8589 }
8590 }
8591 return true;
8592 }
8593 // check for section close
8594 if (item.name == "--") {
8598 run_callback();
8599 }
8600 return true;
8601 }
8602 Option *op = get_option_no_throw("--" + item.name);
8603 if (op == nullptr) {
8604 if (item.name.size() == 1) {
8605 op = get_option_no_throw("-" + item.name);
8606 }
8607 }
8608 if (op == nullptr) {
8609 op = get_option_no_throw(item.name);
8610 }
8611 if (op == nullptr) {
8612 // If the option was not present
8613 if (get_allow_config_extras() == config_extras_mode::capture)
8614 // Should we worry about classifying the extras properly?
8615 missing_.emplace_back(detail::Classifier::NONE, item.fullname());
8616 return false;
8617 }
8618
8619 if (!op->get_configurable()) {
8620 if (get_allow_config_extras() == config_extras_mode::ignore_all) {
8621 return false;
8622 }
8623 throw ConfigError::NotConfigurable(item.fullname());
8624 }
8625
8626 if (op->empty()) {
8627 if (op->get_expected_min() == 0) {
8628 if (item.inputs.size() <= 1) {
8629 // Flag parsing
8630 auto res = config_formatter_->to_flag(item);
8631 res = op->get_flag_value(item.name, res);
8632
8633 op->add_result(res);
8634 return true;
8635 }
8636 if (static_cast<int>(item.inputs.size()) > op->get_items_expected_max()) {
8637 if (op->get_items_expected_max() > 1) {
8638 throw ArgumentMismatch::AtMost(item.fullname(), op->get_items_expected_max(),
8639 item.inputs.size());
8640 }
8641 throw ConversionError::TooManyInputsFlag(item.fullname());
8642 }
8643 }
8644 op->add_result(item.inputs);
8645 op->run_callback();
8646 }
8647
8648 return true;
8649}
8650
8651CLI11_INLINE bool App::_parse_single(std::vector<std::string> &args, bool &positional_only) {
8652 bool retval = true;
8653 detail::Classifier classifier =
8654 positional_only ? detail::Classifier::NONE : _recognize(args.back());
8655 switch (classifier) {
8656 case detail::Classifier::POSITIONAL_MARK:
8657 args.pop_back();
8658 positional_only = true;
8659 if ((!_has_remaining_positionals()) && (parent_ != nullptr)) {
8660 retval = false;
8661 } else {
8662 _move_to_missing(classifier, "--");
8663 }
8664 break;
8665 case detail::Classifier::SUBCOMMAND_TERMINATOR:
8666 // treat this like a positional mark if in the parent app
8667 args.pop_back();
8668 retval = false;
8669 break;
8670 case detail::Classifier::SUBCOMMAND:
8671 retval = _parse_subcommand(args);
8672 break;
8673 case detail::Classifier::LONG:
8674 case detail::Classifier::SHORT:
8675 case detail::Classifier::WINDOWS_STYLE:
8676 // If already parsed a subcommand, don't accept options_
8677 _parse_arg(args, classifier);
8678 break;
8679 case detail::Classifier::NONE:
8680 // Probably a positional or something for a parent (sub)command
8681 retval = _parse_positional(args, false);
8682 if (retval && positionals_at_end_) {
8683 positional_only = true;
8684 }
8685 break;
8686 // LCOV_EXCL_START
8687 default:
8688 throw HorribleError("unrecognized classifier (you should not see this!)");
8689 // LCOV_EXCL_STOP
8690 }
8691 return retval;
8692}
8693
8694CLI11_NODISCARD CLI11_INLINE std::size_t App::_count_remaining_positionals(
8695 bool required_only) const {
8696 std::size_t retval = 0;
8697 for (const Option_p &opt : options_) {
8698 if (opt->get_positional() && (!required_only || opt->get_required())) {
8699 if (opt->get_items_expected_min() > 0 &&
8700 static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
8701 retval += static_cast<std::size_t>(opt->get_items_expected_min()) - opt->count();
8702 }
8703 }
8704 }
8705 return retval;
8706}
8707
8708CLI11_NODISCARD CLI11_INLINE bool App::_has_remaining_positionals() const {
8709 for (const Option_p &opt : options_) {
8710 if (opt->get_positional() &&
8711 ((static_cast<int>(opt->count()) < opt->get_items_expected_min()))) {
8712 return true;
8713 }
8714 }
8715
8716 return false;
8717}
8718
8719CLI11_INLINE bool App::_parse_positional(std::vector<std::string> &args, bool haltOnSubcommand) {
8720 const std::string &positional = args.back();
8721
8722 if (positionals_at_end_) {
8723 // deal with the case of required arguments at the end which should take precedence over
8724 // other arguments
8725 auto arg_rem = args.size();
8726 auto remreq = _count_remaining_positionals(true);
8727 if (arg_rem <= remreq) {
8728 for (const Option_p &opt : options_) {
8729 if (opt->get_positional() && opt->required_) {
8730 if (static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
8732 std::string pos = positional;
8733 pos = opt->_validate(pos, 0);
8734 if (!pos.empty()) {
8735 continue;
8736 }
8737 }
8738
8739 parse_order_.push_back(opt.get());
8741 if (opt->get_inject_separator()) {
8742 if (!opt->results().empty() && !opt->results().back().empty()) {
8743 opt->add_result(std::string{});
8744 }
8745 }
8746 if (opt->get_trigger_on_parse() &&
8748 opt->clear();
8749 }
8750 opt->add_result(positional);
8751 if (opt->get_trigger_on_parse()) {
8752 opt->run_callback();
8753 }
8754 args.pop_back();
8755 return true;
8756 }
8757 }
8758 }
8759 }
8760 }
8761 for (const Option_p &opt : options_) {
8762 // Eat options, one by one, until done
8763 if (opt->get_positional() &&
8764 (static_cast<int>(opt->count()) < opt->get_items_expected_min() ||
8765 opt->get_allow_extra_args())) {
8767 std::string pos = positional;
8768 pos = opt->_validate(pos, 0);
8769 if (!pos.empty()) {
8770 continue;
8771 }
8772 }
8773 if (opt->get_inject_separator()) {
8774 if (!opt->results().empty() && !opt->results().back().empty()) {
8775 opt->add_result(std::string{});
8776 }
8777 }
8778 if (opt->get_trigger_on_parse() &&
8780 opt->clear();
8781 }
8782 opt->add_result(positional);
8783 if (opt->get_trigger_on_parse()) {
8784 opt->run_callback();
8785 }
8786 parse_order_.push_back(opt.get());
8787 args.pop_back();
8788 return true;
8789 }
8790 }
8791
8792 for (auto &subc : subcommands_) {
8793 if ((subc->name_.empty()) && (!subc->disabled_)) {
8794 if (subc->_parse_positional(args, false)) {
8795 if (!subc->pre_parse_called_) {
8796 subc->_trigger_pre_parse(args.size());
8797 }
8798 return true;
8799 }
8800 }
8801 }
8802 // let the parent deal with it if possible
8803 if (parent_ != nullptr && fallthrough_)
8805 args, static_cast<bool>(parse_complete_callback_));
8806
8808 auto *com = _find_subcommand(args.back(), true, false);
8809 if (com != nullptr &&
8811 if (haltOnSubcommand) {
8812 return false;
8813 }
8814 args.pop_back();
8815 com->_parse(args);
8816 return true;
8817 }
8820 auto *parent_app = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
8821 com = parent_app->_find_subcommand(args.back(), true, false);
8822 if (com != nullptr &&
8823 (com->parent_->require_subcommand_max_ == 0 ||
8824 com->parent_->require_subcommand_max_ > com->parent_->parsed_subcommands_.size())) {
8825 return false;
8826 }
8827
8828 if (positionals_at_end_) {
8829 throw CLI::ExtrasError(name_, args);
8830 }
8832 if (parent_ != nullptr && name_.empty()) {
8833 return false;
8834 }
8836 _move_to_missing(detail::Classifier::NONE, positional);
8837 args.pop_back();
8838 if (prefix_command_) {
8839 while (!args.empty()) {
8840 _move_to_missing(detail::Classifier::NONE, args.back());
8841 args.pop_back();
8842 }
8843 }
8844
8845 return true;
8846}
8847
8848CLI11_NODISCARD CLI11_INLINE App *App::_find_subcommand(const std::string &subc_name,
8849 bool ignore_disabled,
8850 bool ignore_used) const noexcept {
8851 for (const App_p &com : subcommands_) {
8852 if (com->disabled_ && ignore_disabled) continue;
8853 if (com->get_name().empty()) {
8854 auto *subc = com->_find_subcommand(subc_name, ignore_disabled, ignore_used);
8855 if (subc != nullptr) {
8856 return subc;
8857 }
8858 }
8859 if (com->check_name(subc_name)) {
8860 if ((!*com) || !ignore_used) return com.get();
8861 }
8862 }
8863 return nullptr;
8864}
8865
8866CLI11_INLINE bool App::_parse_subcommand(std::vector<std::string> &args) {
8867 if (_count_remaining_positionals(/* required */ true) > 0) {
8868 _parse_positional(args, false);
8869 return true;
8870 }
8871 auto *com = _find_subcommand(args.back(), true, true);
8872 if (com != nullptr) {
8873 args.pop_back();
8874 if (!com->silent_) {
8875 parsed_subcommands_.push_back(com);
8876 }
8877 com->_parse(args);
8878 auto *parent_app = com->parent_;
8879 while (parent_app != this) {
8880 parent_app->_trigger_pre_parse(args.size());
8881 if (!com->silent_) {
8882 parent_app->parsed_subcommands_.push_back(com);
8883 }
8884 parent_app = parent_app->parent_;
8885 }
8886 return true;
8887 }
8888
8889 if (parent_ == nullptr) throw HorribleError("Subcommand " + args.back() + " missing");
8890 return false;
8891}
8892
8893CLI11_INLINE bool App::_parse_arg(std::vector<std::string> &args, detail::Classifier current_type) {
8894 std::string current = args.back();
8895
8896 std::string arg_name;
8897 std::string value;
8898 std::string rest;
8899
8900 switch (current_type) {
8901 case detail::Classifier::LONG:
8902 if (!detail::split_long(current, arg_name, value))
8903 throw HorribleError("Long parsed but missing (you should not see this):" +
8904 args.back());
8905 break;
8906 case detail::Classifier::SHORT:
8907 if (!detail::split_short(current, arg_name, rest))
8908 throw HorribleError("Short parsed but missing! You should not see this");
8909 break;
8910 case detail::Classifier::WINDOWS_STYLE:
8911 if (!detail::split_windows_style(current, arg_name, value))
8912 throw HorribleError("windows option parsed but missing! You should not see this");
8913 break;
8914 case detail::Classifier::SUBCOMMAND:
8915 case detail::Classifier::SUBCOMMAND_TERMINATOR:
8916 case detail::Classifier::POSITIONAL_MARK:
8917 case detail::Classifier::NONE:
8918 default:
8919 throw HorribleError("parsing got called with invalid option! You should not see this");
8920 }
8921
8922 auto op_ptr = std::find_if(std::begin(options_), std::end(options_),
8923 [arg_name, current_type](const Option_p &opt) {
8924 if (current_type == detail::Classifier::LONG)
8925 return opt->check_lname(arg_name);
8926 if (current_type == detail::Classifier::SHORT)
8927 return opt->check_sname(arg_name);
8928 // this will only get called for
8929 // detail::Classifier::WINDOWS_STYLE
8930 return opt->check_lname(arg_name) || opt->check_sname(arg_name);
8931 });
8932
8933 // Option not found
8934 if (op_ptr == std::end(options_)) {
8935 for (auto &subc : subcommands_) {
8936 if (subc->name_.empty() && !subc->disabled_) {
8937 if (subc->_parse_arg(args, current_type)) {
8938 if (!subc->pre_parse_called_) {
8939 subc->_trigger_pre_parse(args.size());
8940 }
8941 return true;
8942 }
8943 }
8944 }
8945
8946 // don't capture missing if this is a nameless subcommand and nameless subcommands can't
8947 // fallthrough
8948 if (parent_ != nullptr && name_.empty()) {
8949 return false;
8950 }
8951
8952 // If a subcommand, try the main command
8953 if (parent_ != nullptr && fallthrough_)
8954 return _get_fallthrough_parent()->_parse_arg(args, current_type);
8955
8956 // Otherwise, add to missing
8957 args.pop_back();
8958 _move_to_missing(current_type, current);
8959 return true;
8960 }
8961
8962 args.pop_back();
8963
8964 // Get a reference to the pointer to make syntax bearable
8965 Option_p &op = *op_ptr;
8967 if (op->get_inject_separator()) {
8968 if (!op->results().empty() && !op->results().back().empty()) {
8969 op->add_result(std::string{});
8970 }
8971 }
8972 if (op->get_trigger_on_parse() &&
8973 op->current_option_state_ == Option::option_state::callback_run) {
8974 op->clear();
8975 }
8976 int min_num = (std::min)(op->get_type_size_min(), op->get_items_expected_min());
8977 int max_num = op->get_items_expected_max();
8978 // check container like options to limit the argument size to a single type if the
8979 // allow_extra_flags argument is set. 16 is somewhat arbitrary (needs to be at least 4)
8980 if (max_num >= detail::expected_max_vector_size / 16 && !op->get_allow_extra_args()) {
8981 auto tmax = op->get_type_size_max();
8982 max_num = detail::checked_multiply(tmax, op->get_expected_min())
8983 ? tmax
8984 : detail::expected_max_vector_size;
8985 }
8986 // Make sure we always eat the minimum for unlimited vectors
8987 int collected = 0; // total number of arguments collected
8988 int result_count = 0; // local variable for number of results in a single arg string
8989 // deal with purely flag like things
8990 if (max_num == 0) {
8991 auto res = op->get_flag_value(arg_name, value);
8992 op->add_result(res);
8993 parse_order_.push_back(op.get());
8994 } else if (!value.empty()) { // --this=value
8995 op->add_result(value, result_count);
8996 parse_order_.push_back(op.get());
8997 collected += result_count;
8998 // -Trest
8999 } else if (!rest.empty()) {
9000 op->add_result(rest, result_count);
9001 parse_order_.push_back(op.get());
9002 rest = "";
9003 collected += result_count;
9004 }
9005
9006 // gather the minimum number of arguments
9007 while (min_num > collected && !args.empty()) {
9008 std::string current_ = args.back();
9009 args.pop_back();
9010 op->add_result(current_, result_count);
9011 parse_order_.push_back(op.get());
9012 collected += result_count;
9013 }
9014
9015 if (min_num > collected) { // if we have run out of arguments and the minimum was not met
9016 throw ArgumentMismatch::TypedAtLeast(op->get_name(), min_num, op->get_type_name());
9017 }
9018
9019 // now check for optional arguments
9020 if (max_num > collected || op->get_allow_extra_args()) { // we allow optional arguments
9021 auto remreqpos = _count_remaining_positionals(true);
9022 // we have met the minimum now optionally check up to the maximum
9023 while ((collected < max_num || op->get_allow_extra_args()) && !args.empty() &&
9024 _recognize(args.back(), false) == detail::Classifier::NONE) {
9025 // If any required positionals remain, don't keep eating
9026 if (remreqpos >= args.size()) {
9027 break;
9028 }
9030 std::string arg = args.back();
9031 arg = op->_validate(arg, 0);
9032 if (!arg.empty()) {
9033 break;
9034 }
9035 }
9036 op->add_result(args.back(), result_count);
9037 parse_order_.push_back(op.get());
9038 args.pop_back();
9039 collected += result_count;
9040 }
9041
9042 // Allow -- to end an unlimited list and "eat" it
9043 if (!args.empty() && _recognize(args.back()) == detail::Classifier::POSITIONAL_MARK)
9044 args.pop_back();
9045 // optional flag that didn't receive anything now get the default value
9046 if (min_num == 0 && max_num > 0 && collected == 0) {
9047 auto res = op->get_flag_value(arg_name, std::string{});
9048 op->add_result(res);
9049 parse_order_.push_back(op.get());
9050 }
9051 }
9052 // if we only partially completed a type then add an empty string if allowed for later
9053 // processing
9054 if (min_num > 0 && (collected % op->get_type_size_max()) != 0) {
9055 if (op->get_type_size_max() != op->get_type_size_min()) {
9056 op->add_result(std::string{});
9057 } else {
9058 throw ArgumentMismatch::PartialType(op->get_name(), op->get_type_size_min(),
9059 op->get_type_name());
9060 }
9061 }
9062 if (op->get_trigger_on_parse()) {
9063 op->run_callback();
9064 }
9065 if (!rest.empty()) {
9066 rest = "-" + rest;
9067 args.push_back(rest);
9068 }
9069 return true;
9070}
9071
9072CLI11_INLINE void App::_trigger_pre_parse(std::size_t remaining_args) {
9073 if (!pre_parse_called_) {
9074 pre_parse_called_ = true;
9075 if (pre_parse_callback_) {
9076 pre_parse_callback_(remaining_args);
9077 }
9078 } else if (immediate_callback_) {
9079 if (!name_.empty()) {
9080 auto pcnt = parsed_;
9081 auto extras = std::move(missing_);
9082 clear();
9083 parsed_ = pcnt;
9084 pre_parse_called_ = true;
9085 missing_ = std::move(extras);
9086 }
9087 }
9088}
9089
9091 if (parent_ == nullptr) {
9092 throw(HorribleError("No Valid parent"));
9093 }
9094 auto *fallthrough_parent = parent_;
9095 while ((fallthrough_parent->parent_ != nullptr) && (fallthrough_parent->get_name().empty())) {
9096 fallthrough_parent = fallthrough_parent->parent_;
9097 }
9098 return fallthrough_parent;
9099}
9100
9101CLI11_NODISCARD CLI11_INLINE const std::string &App::_compare_subcommand_names(
9102 const App &subcom, const App &base) const {
9103 static const std::string estring;
9104 if (subcom.disabled_) {
9105 return estring;
9106 }
9107 for (const auto &subc : base.subcommands_) {
9108 if (subc.get() != &subcom) {
9109 if (subc->disabled_) {
9110 continue;
9111 }
9112 if (!subcom.get_name().empty()) {
9113 if (subc->check_name(subcom.get_name())) {
9114 return subcom.get_name();
9115 }
9116 }
9117 if (!subc->get_name().empty()) {
9118 if (subcom.check_name(subc->get_name())) {
9119 return subc->get_name();
9120 }
9121 }
9122 for (const auto &les : subcom.aliases_) {
9123 if (subc->check_name(les)) {
9124 return les;
9125 }
9126 }
9127 // this loop is needed in case of ignore_underscore or ignore_case on one but not the
9128 // other
9129 for (const auto &les : subc->aliases_) {
9130 if (subcom.check_name(les)) {
9131 return les;
9132 }
9133 }
9134 // if the subcommand is an option group we need to check deeper
9135 if (subc->get_name().empty()) {
9136 const auto &cmpres = _compare_subcommand_names(subcom, *subc);
9137 if (!cmpres.empty()) {
9138 return cmpres;
9139 }
9140 }
9141 // if the test subcommand is an option group we need to check deeper
9142 if (subcom.get_name().empty()) {
9143 const auto &cmpres = _compare_subcommand_names(*subc, subcom);
9144 if (!cmpres.empty()) {
9145 return cmpres;
9146 }
9147 }
9148 }
9149 }
9150 return estring;
9151}
9152
9153CLI11_INLINE void App::_move_to_missing(detail::Classifier val_type, const std::string &val) {
9154 if (allow_extras_ || subcommands_.empty()) {
9155 missing_.emplace_back(val_type, val);
9156 return;
9157 }
9158 // allow extra arguments to be places in an option group if it is allowed there
9159 for (auto &subc : subcommands_) {
9160 if (subc->name_.empty() && subc->allow_extras_) {
9161 subc->missing_.emplace_back(val_type, val);
9162 return;
9163 }
9164 }
9165 // if we haven't found any place to put them yet put them in missing
9166 missing_.emplace_back(val_type, val);
9167}
9168
9169CLI11_INLINE void App::_move_option(Option *opt, App *app) {
9170 if (opt == nullptr) {
9171 throw OptionNotFound("the option is NULL");
9172 }
9173 // verify that the give app is actually a subcommand
9174 bool found = false;
9175 for (auto &subc : subcommands_) {
9176 if (app == subc.get()) {
9177 found = true;
9178 }
9179 }
9180 if (!found) {
9181 throw OptionNotFound("The Given app is not a subcommand");
9182 }
9183
9184 if ((help_ptr_ == opt) || (help_all_ptr_ == opt))
9185 throw OptionAlreadyAdded("cannot move help options");
9186
9187 if (config_ptr_ == opt) throw OptionAlreadyAdded("cannot move config file options");
9188
9189 auto iterator = std::find_if(std::begin(options_), std::end(options_),
9190 [opt](const Option_p &v) { return v.get() == opt; });
9191 if (iterator != std::end(options_)) {
9192 const auto &opt_p = *iterator;
9193 if (std::find_if(std::begin(app->options_), std::end(app->options_),
9194 [&opt_p](const Option_p &v) { return (*v == *opt_p); }) ==
9195 std::end(app->options_)) {
9196 // only erase after the insertion was successful
9197 app->options_.push_back(std::move(*iterator));
9198 options_.erase(iterator);
9199 } else {
9200 throw OptionAlreadyAdded("option was not located: " + opt->get_name());
9201 }
9202 } else {
9203 throw OptionNotFound("could not locate the given Option");
9204 }
9205}
9206
9207CLI11_INLINE void TriggerOn(App *trigger_app, App *app_to_enable) {
9208 app_to_enable->enabled_by_default(false);
9209 app_to_enable->disabled_by_default();
9210 trigger_app->preparse_callback(
9211 [app_to_enable](std::size_t) { app_to_enable->disabled(false); });
9212}
9213
9214CLI11_INLINE void TriggerOn(App *trigger_app, std::vector<App *> apps_to_enable) {
9215 for (auto &app : apps_to_enable) {
9216 app->enabled_by_default(false);
9217 app->disabled_by_default();
9218 }
9219
9220 trigger_app->preparse_callback([apps_to_enable](std::size_t) {
9221 for (const auto &app : apps_to_enable) {
9222 app->disabled(false);
9223 }
9224 });
9225}
9226
9227CLI11_INLINE void TriggerOff(App *trigger_app, App *app_to_enable) {
9228 app_to_enable->disabled_by_default(false);
9229 app_to_enable->enabled_by_default();
9230 trigger_app->preparse_callback([app_to_enable](std::size_t) { app_to_enable->disabled(); });
9231}
9232
9233CLI11_INLINE void TriggerOff(App *trigger_app, std::vector<App *> apps_to_enable) {
9234 for (auto &app : apps_to_enable) {
9235 app->disabled_by_default(false);
9236 app->enabled_by_default();
9237 }
9238
9239 trigger_app->preparse_callback([apps_to_enable](std::size_t) {
9240 for (const auto &app : apps_to_enable) {
9241 app->disabled();
9242 }
9243 });
9244}
9245
9246CLI11_INLINE void deprecate_option(Option *opt, const std::string &replacement) {
9247 Validator deprecate_warning{[opt, replacement](std::string &) {
9248 std::cout << opt->get_name() << " is deprecated please use '"
9249 << replacement << "' instead\n";
9250 return std::string();
9251 },
9252 "DEPRECATED"};
9253 deprecate_warning.application_index(0);
9254 opt->check(deprecate_warning);
9255 if (!replacement.empty()) {
9256 opt->description(opt->get_description() + " DEPRECATED: please use '" + replacement +
9257 "' instead");
9258 }
9259}
9260
9261CLI11_INLINE void retire_option(App *app, Option *opt) {
9262 App temp;
9263 auto *option_copy = temp.add_option(opt->get_name(false, true))
9264 ->type_size(opt->get_type_size_min(), opt->get_type_size_max())
9265 ->expected(opt->get_expected_min(), opt->get_expected_max())
9266 ->allow_extra_args(opt->get_allow_extra_args());
9267
9268 app->remove_option(opt);
9269 auto *opt2 = app->add_option(option_copy->get_name(false, true),
9270 "option has been retired and has no effect")
9271 ->type_name("RETIRED")
9272 ->default_str("RETIRED")
9273 ->type_size(option_copy->get_type_size_min(), option_copy->get_type_size_max())
9274 ->expected(option_copy->get_expected_min(), option_copy->get_expected_max())
9275 ->allow_extra_args(option_copy->get_allow_extra_args());
9276
9277 Validator retired_warning{[opt2](std::string &) {
9278 std::cout << "WARNING " << opt2->get_name()
9279 << " is retired and has no effect\n";
9280 return std::string();
9281 },
9282 ""};
9283 retired_warning.application_index(0);
9284 opt2->check(retired_warning);
9285}
9286
9287CLI11_INLINE void retire_option(App &app, Option *opt) { retire_option(&app, opt); }
9288
9289CLI11_INLINE void retire_option(App *app, const std::string &option_name) {
9290 auto *opt = app->get_option_no_throw(option_name);
9291 if (opt != nullptr) {
9292 retire_option(app, opt);
9293 return;
9294 }
9295 auto *opt2 = app->add_option(option_name, "option has been retired and has no effect")
9296 ->type_name("RETIRED")
9297 ->expected(0, 1)
9298 ->default_str("RETIRED");
9299 Validator retired_warning{[opt2](std::string &) {
9300 std::cout << "WARNING " << opt2->get_name()
9301 << " is retired and has no effect\n";
9302 return std::string();
9303 },
9304 ""};
9305 retired_warning.application_index(0);
9306 opt2->check(retired_warning);
9307}
9308
9309CLI11_INLINE void retire_option(App &app, const std::string &option_name) {
9310 retire_option(&app, option_name);
9311}
9312
9313namespace FailureMessage {
9314
9315CLI11_INLINE std::string simple(const App *app, const Error &e) {
9316 std::string header = std::string(e.what()) + "\n";
9317 std::vector<std::string> names;
9318
9319 // Collect names
9320 if (app->get_help_ptr() != nullptr) names.push_back(app->get_help_ptr()->get_name());
9321
9322 if (app->get_help_all_ptr() != nullptr) names.push_back(app->get_help_all_ptr()->get_name());
9323
9324 // If any names found, suggest those
9325 if (!names.empty())
9326 header += "Run with " + detail::join(names, " or ") + " for more information.\n";
9327
9328 return header;
9329}
9330
9331CLI11_INLINE std::string help(const App *app, const Error &e) {
9332 std::string header = std::string("ERROR: ") + e.get_name() + ": " + e.what() + "\n";
9333 header += app->help();
9334 return header;
9335}
9336
9337} // namespace FailureMessage
9338
9339namespace detail {
9340
9341std::string convert_arg_for_ini(const std::string &arg,
9342 char stringQuote = '"',
9343 char characterQuote = '\'');
9344
9346std::string ini_join(const std::vector<std::string> &args,
9347 char sepChar = ',',
9348 char arrayStart = '[',
9349 char arrayEnd = ']',
9350 char stringQuote = '"',
9351 char characterQuote = '\'');
9352
9353std::vector<std::string> generate_parents(const std::string &section,
9354 std::string &name,
9355 char parentSeparator);
9356
9359void checkParentSegments(std::vector<ConfigItem> &output,
9360 const std::string &currentSection,
9361 char parentSeparator);
9362} // namespace detail
9363
9364namespace detail {
9365
9366CLI11_INLINE std::string convert_arg_for_ini(const std::string &arg,
9367 char stringQuote,
9368 char characterQuote) {
9369 if (arg.empty()) {
9370 return std::string(2, stringQuote);
9371 }
9372 // some specifically supported strings
9373 if (arg == "true" || arg == "false" || arg == "nan" || arg == "inf") {
9374 return arg;
9375 }
9376 // floating point conversion can convert some hex codes, but don't try that here
9377 if (arg.compare(0, 2, "0x") != 0 && arg.compare(0, 2, "0X") != 0) {
9378 double val = 0.0;
9379 if (detail::lexical_cast(arg, val)) {
9380 return arg;
9381 }
9382 }
9383 // just quote a single non numeric character
9384 if (arg.size() == 1) {
9385 return std::string(1, characterQuote) + arg + characterQuote;
9386 }
9387 // handle hex, binary or octal arguments
9388 if (arg.front() == '0') {
9389 if (arg[1] == 'x') {
9390 if (std::all_of(arg.begin() + 2, arg.end(), [](char x) {
9391 return (x >= '0' && x <= '9') || (x >= 'A' && x <= 'F') ||
9392 (x >= 'a' && x <= 'f');
9393 })) {
9394 return arg;
9395 }
9396 } else if (arg[1] == 'o') {
9397 if (std::all_of(arg.begin() + 2, arg.end(),
9398 [](char x) { return (x >= '0' && x <= '7'); })) {
9399 return arg;
9400 }
9401 } else if (arg[1] == 'b') {
9402 if (std::all_of(arg.begin() + 2, arg.end(),
9403 [](char x) { return (x == '0' || x == '1'); })) {
9404 return arg;
9405 }
9406 }
9407 }
9408 if (arg.find_first_of(stringQuote) == std::string::npos) {
9409 return std::string(1, stringQuote) + arg + stringQuote;
9410 }
9411 return characterQuote + arg + characterQuote;
9412}
9413
9414CLI11_INLINE std::string ini_join(const std::vector<std::string> &args,
9415 char sepChar,
9416 char arrayStart,
9417 char arrayEnd,
9418 char stringQuote,
9419 char characterQuote) {
9420 std::string joined;
9421 if (args.size() > 1 && arrayStart != '\0') {
9422 joined.push_back(arrayStart);
9423 }
9424 std::size_t start = 0;
9425 for (const auto &arg : args) {
9426 if (start++ > 0) {
9427 joined.push_back(sepChar);
9428 if (!std::isspace<char>(sepChar, std::locale())) {
9429 joined.push_back(' ');
9430 }
9431 }
9432 joined.append(convert_arg_for_ini(arg, stringQuote, characterQuote));
9433 }
9434 if (args.size() > 1 && arrayEnd != '\0') {
9435 joined.push_back(arrayEnd);
9436 }
9437 return joined;
9438}
9439
9440CLI11_INLINE std::vector<std::string> generate_parents(const std::string &section,
9441 std::string &name,
9442 char parentSeparator) {
9443 std::vector<std::string> parents;
9444 if (detail::to_lower(section) != "default") {
9445 if (section.find(parentSeparator) != std::string::npos) {
9446 parents = detail::split(section, parentSeparator);
9447 } else {
9448 parents = {section};
9449 }
9450 }
9451 if (name.find(parentSeparator) != std::string::npos) {
9452 std::vector<std::string> plist = detail::split(name, parentSeparator);
9453 name = plist.back();
9454 detail::remove_quotes(name);
9455 plist.pop_back();
9456 parents.insert(parents.end(), plist.begin(), plist.end());
9457 }
9458
9459 // clean up quotes on the parents
9460 for (auto &parent : parents) {
9461 detail::remove_quotes(parent);
9462 }
9463 return parents;
9464}
9465
9466CLI11_INLINE void checkParentSegments(std::vector<ConfigItem> &output,
9467 const std::string &currentSection,
9468 char parentSeparator) {
9469 std::string estring;
9470 auto parents = detail::generate_parents(currentSection, estring, parentSeparator);
9471 if (!output.empty() && output.back().name == "--") {
9472 std::size_t msize = (parents.size() > 1U) ? parents.size() : 2;
9473 while (output.back().parents.size() >= msize) {
9474 output.push_back(output.back());
9475 output.back().parents.pop_back();
9476 }
9477
9478 if (parents.size() > 1) {
9479 std::size_t common = 0;
9480 std::size_t mpair = (std::min)(output.back().parents.size(), parents.size() - 1);
9481 for (std::size_t ii = 0; ii < mpair; ++ii) {
9482 if (output.back().parents[ii] != parents[ii]) {
9483 break;
9484 }
9485 ++common;
9486 }
9487 if (common == mpair) {
9488 output.pop_back();
9489 } else {
9490 while (output.back().parents.size() > common + 1) {
9491 output.push_back(output.back());
9492 output.back().parents.pop_back();
9493 }
9494 }
9495 for (std::size_t ii = common; ii < parents.size() - 1; ++ii) {
9496 output.emplace_back();
9497 output.back().parents.assign(parents.begin(),
9498 parents.begin() + static_cast<std::ptrdiff_t>(ii) + 1);
9499 output.back().name = "++";
9500 }
9501 }
9502 } else if (parents.size() > 1) {
9503 for (std::size_t ii = 0; ii < parents.size() - 1; ++ii) {
9504 output.emplace_back();
9505 output.back().parents.assign(parents.begin(),
9506 parents.begin() + static_cast<std::ptrdiff_t>(ii) + 1);
9507 output.back().name = "++";
9508 }
9509 }
9510
9511 // insert a section end which is just an empty items_buffer
9512 output.emplace_back();
9513 output.back().parents = std::move(parents);
9514 output.back().name = "++";
9515}
9516} // namespace detail
9517
9518inline std::vector<ConfigItem> ConfigBase::from_config(std::istream &input) const {
9519 std::string line;
9520 std::string currentSection = "default";
9521 std::string previousSection = "default";
9522 std::vector<ConfigItem> output;
9523 bool isDefaultArray = (arrayStart == '[' && arrayEnd == ']' && arraySeparator == ',');
9524 bool isINIArray = (arrayStart == '\0' || arrayStart == ' ') && arrayStart == arrayEnd;
9525 bool inSection{false};
9526 char aStart = (isINIArray) ? '[' : arrayStart;
9527 char aEnd = (isINIArray) ? ']' : arrayEnd;
9528 char aSep = (isINIArray && arraySeparator == ' ') ? ',' : arraySeparator;
9529 int currentSectionIndex{0};
9530 while (getline(input, line)) {
9531 std::vector<std::string> items_buffer;
9532 std::string name;
9533
9534 detail::trim(line);
9535 std::size_t len = line.length();
9536 // lines have to be at least 3 characters to have any meaning to CLI just skip the rest
9537 if (len < 3) {
9538 continue;
9539 }
9540 if (line.front() == '[' && line.back() == ']') {
9541 if (currentSection != "default") {
9542 // insert a section end which is just an empty items_buffer
9543 output.emplace_back();
9544 output.back().parents =
9545 detail::generate_parents(currentSection, name, parentSeparatorChar);
9546 output.back().name = "--";
9547 }
9548 currentSection = line.substr(1, len - 2);
9549 // deal with double brackets for TOML
9550 if (currentSection.size() > 1 && currentSection.front() == '[' &&
9551 currentSection.back() == ']') {
9552 currentSection = currentSection.substr(1, currentSection.size() - 2);
9553 }
9554 if (detail::to_lower(currentSection) == "default") {
9555 currentSection = "default";
9556 } else {
9557 detail::checkParentSegments(output, currentSection, parentSeparatorChar);
9558 }
9559 inSection = false;
9560 if (currentSection == previousSection) {
9561 ++currentSectionIndex;
9562 } else {
9563 currentSectionIndex = 0;
9564 previousSection = currentSection;
9565 }
9566 continue;
9567 }
9568
9569 // comment lines
9570 if (line.front() == ';' || line.front() == '#' || line.front() == commentChar) {
9571 continue;
9572 }
9573
9574 // Find = in string, split and recombine
9575 auto pos = line.find(valueDelimiter);
9576 if (pos != std::string::npos) {
9577 name = detail::trim_copy(line.substr(0, pos));
9578 std::string item = detail::trim_copy(line.substr(pos + 1));
9579 auto cloc = item.find(commentChar);
9580 if (cloc != std::string::npos) {
9581 item.erase(cloc,
9582 std::string::npos); // NOLINT(readability-suspicious-call-argument)
9583 detail::trim(item);
9584 }
9585 if (item.size() > 1 && item.front() == aStart) {
9586 for (std::string multiline;
9587 item.back() != aEnd && std::getline(input, multiline);) {
9588 detail::trim(multiline);
9589 item += multiline;
9590 }
9591 items_buffer = detail::split_up(item.substr(1, item.length() - 2), aSep);
9592 } else if ((isDefaultArray || isINIArray) &&
9593 item.find_first_of(aSep) != std::string::npos) {
9594 items_buffer = detail::split_up(item, aSep);
9595 } else if ((isDefaultArray || isINIArray) &&
9596 item.find_first_of(' ') != std::string::npos) {
9597 items_buffer = detail::split_up(item);
9598 } else {
9599 items_buffer = {item};
9600 }
9601 } else {
9602 name = detail::trim_copy(line);
9603 auto cloc = name.find(commentChar);
9604 if (cloc != std::string::npos) {
9605 name.erase(cloc,
9606 std::string::npos); // NOLINT(readability-suspicious-call-argument)
9607 detail::trim(name);
9608 }
9609
9610 items_buffer = {"true"};
9611 }
9612 if (name.find(parentSeparatorChar) == std::string::npos) {
9613 detail::remove_quotes(name);
9614 }
9615 // clean up quotes on the items
9616 for (auto &it : items_buffer) {
9617 detail::remove_quotes(it);
9618 }
9619
9620 std::vector<std::string> parents =
9621 detail::generate_parents(currentSection, name, parentSeparatorChar);
9622 if (parents.size() > maximumLayers) {
9623 continue;
9624 }
9625 if (!configSection.empty() && !inSection) {
9626 if (parents.empty() || parents.front() != configSection) {
9627 continue;
9628 }
9629 if (configIndex >= 0 && currentSectionIndex != configIndex) {
9630 continue;
9631 }
9632 parents.erase(parents.begin());
9633 inSection = true;
9634 }
9635 if (!output.empty() && name == output.back().name && parents == output.back().parents) {
9636 output.back().inputs.insert(output.back().inputs.end(), items_buffer.begin(),
9637 items_buffer.end());
9638 } else {
9639 output.emplace_back();
9640 output.back().parents = std::move(parents);
9641 output.back().name = std::move(name);
9642 output.back().inputs = std::move(items_buffer);
9643 }
9644 }
9645 if (currentSection != "default") {
9646 // insert a section end which is just an empty items_buffer
9647 std::string ename;
9648 output.emplace_back();
9649 output.back().parents =
9650 detail::generate_parents(currentSection, ename, parentSeparatorChar);
9651 output.back().name = "--";
9652 while (output.back().parents.size() > 1) {
9653 output.push_back(output.back());
9654 output.back().parents.pop_back();
9655 }
9656 }
9657 return output;
9658}
9659
9660CLI11_INLINE std::string ConfigBase::to_config(const App *app,
9661 bool default_also,
9662 bool write_description,
9663 std::string prefix) const {
9664 std::stringstream out;
9665 std::string commentLead;
9666 commentLead.push_back(commentChar);
9667 commentLead.push_back(' ');
9668
9669 std::vector<std::string> groups = app->get_groups();
9670 bool defaultUsed = false;
9671 groups.insert(groups.begin(), std::string("Options"));
9672 if (write_description &&
9673 (app->get_configurable() || app->get_parent() == nullptr || app->get_name().empty())) {
9674 out << commentLead << detail::fix_newlines(commentLead, app->get_description()) << '\n';
9675 }
9676 for (auto &group : groups) {
9677 if (group == "Options" || group.empty()) {
9678 if (defaultUsed) {
9679 continue;
9680 }
9681 defaultUsed = true;
9682 }
9683 if (write_description && group != "Options" && !group.empty()) {
9684 out << '\n' << commentLead << group << " Options\n";
9685 }
9686 for (const Option *opt : app->get_options({})) {
9687 // Only process options that are configurable
9688 if (opt->get_configurable()) {
9689 if (opt->get_group() != group) {
9690 if (!(group == "Options" && opt->get_group().empty())) {
9691 continue;
9692 }
9693 }
9694 std::string name = prefix + opt->get_single_name();
9695 std::string value =
9696 detail::ini_join(opt->reduced_results(), arraySeparator, arrayStart, arrayEnd,
9698
9699 if (value.empty() && default_also) {
9700 if (!opt->get_default_str().empty()) {
9701 value = detail::convert_arg_for_ini(opt->get_default_str(), stringQuote,
9703 } else if (opt->get_expected_min() == 0) {
9704 value = "false";
9705 } else if (opt->get_run_callback_for_default()) {
9706 value = "\"\""; // empty string default value
9707 }
9708 }
9709
9710 if (!value.empty()) {
9711 if (!opt->get_fnames().empty()) {
9712 value = opt->get_flag_value(name, value);
9713 }
9714 if (write_description && opt->has_description()) {
9715 out << '\n';
9716 out << commentLead
9717 << detail::fix_newlines(commentLead, opt->get_description()) << '\n';
9718 }
9719 out << name << valueDelimiter << value << '\n';
9720 }
9721 }
9722 }
9723 }
9724 auto subcommands = app->get_subcommands({});
9725 for (const App *subcom : subcommands) {
9726 if (subcom->get_name().empty()) {
9727 if (write_description && !subcom->get_group().empty()) {
9728 out << '\n' << commentLead << subcom->get_group() << " Options\n";
9729 }
9730 out << to_config(subcom, default_also, write_description, prefix);
9731 }
9732 }
9733
9734 for (const App *subcom : subcommands) {
9735 if (!subcom->get_name().empty()) {
9736 if (subcom->get_configurable() && app->got_subcommand(subcom)) {
9737 if (!prefix.empty() || app->get_parent() == nullptr) {
9738 out << '[' << prefix << subcom->get_name() << "]\n";
9739 } else {
9740 std::string subname =
9741 app->get_name() + parentSeparatorChar + subcom->get_name();
9742 const auto *p = app->get_parent();
9743 while (p->get_parent() != nullptr) {
9744 subname = p->get_name() + parentSeparatorChar + subname;
9745 p = p->get_parent();
9746 }
9747 out << '[' << subname << "]\n";
9748 }
9749 out << to_config(subcom, default_also, write_description, "");
9750 } else {
9751 out << to_config(subcom, default_also, write_description,
9752 prefix + subcom->get_name() + parentSeparatorChar);
9753 }
9754 }
9755 }
9756
9757 return out.str();
9758}
9759
9760CLI11_INLINE std::string Formatter::make_group(std::string group,
9761 bool is_positional,
9762 std::vector<const Option *> opts) const {
9763 std::stringstream out;
9764
9765 out << "\n" << group << ":\n";
9766 for (const Option *opt : opts) {
9767 out << make_option(opt, is_positional);
9768 }
9769
9770 return out.str();
9771}
9772
9773CLI11_INLINE std::string Formatter::make_positionals(const App *app) const {
9774 std::vector<const Option *> opts = app->get_options(
9775 [](const Option *opt) { return !opt->get_group().empty() && opt->get_positional(); });
9776
9777 if (opts.empty()) return {};
9778
9779 return make_group(get_label("Positionals"), true, opts);
9780}
9781
9782CLI11_INLINE std::string Formatter::make_groups(const App *app, AppFormatMode mode) const {
9783 std::stringstream out;
9784 std::vector<std::string> groups = app->get_groups();
9785
9786 // Options
9787 for (const std::string &group : groups) {
9788 std::vector<const Option *> opts = app->get_options([app, mode, &group](const Option *opt) {
9789 return opt->get_group() == group // Must be in the right group
9790 && opt->nonpositional() // Must not be a positional
9791 && (mode != AppFormatMode::Sub // If mode is Sub, then
9792 || (app->get_help_ptr() != opt // Ignore help pointer
9793 && app->get_help_all_ptr() != opt)); // Ignore help all pointer
9794 });
9795 if (!group.empty() && !opts.empty()) {
9796 out << make_group(group, false, opts);
9797
9798 if (group != groups.back()) out << "\n";
9799 }
9800 }
9801
9802 return out.str();
9803}
9804
9805CLI11_INLINE std::string Formatter::make_description(const App *app) const {
9806 std::string desc = app->get_description();
9807 auto min_options = app->get_require_option_min();
9808 auto max_options = app->get_require_option_max();
9809 if (app->get_required()) {
9810 desc += " REQUIRED ";
9811 }
9812 if ((max_options == min_options) && (min_options > 0)) {
9813 if (min_options == 1) {
9814 desc += " \n[Exactly 1 of the following options is required]";
9815 } else {
9816 desc += " \n[Exactly " + std::to_string(min_options) +
9817 "options from the following list are required]";
9818 }
9819 } else if (max_options > 0) {
9820 if (min_options > 0) {
9821 desc += " \n[Between " + std::to_string(min_options) + " and " +
9822 std::to_string(max_options) + " of the follow options are required]";
9823 } else {
9824 desc += " \n[At most " + std::to_string(max_options) +
9825 " of the following options are allowed]";
9826 }
9827 } else if (min_options > 0) {
9828 desc += " \n[At least " + std::to_string(min_options) +
9829 " of the following options are required]";
9830 }
9831 return (!desc.empty()) ? desc + "\n" : std::string{};
9832}
9833
9834CLI11_INLINE std::string Formatter::make_usage(const App *app, std::string name) const {
9835 std::stringstream out;
9836
9837 out << get_label("Usage") << ":" << (name.empty() ? "" : " ") << name;
9838
9839 std::vector<std::string> groups = app->get_groups();
9840
9841 // Print an Options badge if any options exist
9842 std::vector<const Option *> non_pos_options =
9843 app->get_options([](const Option *opt) { return opt->nonpositional(); });
9844 if (!non_pos_options.empty()) out << " [" << get_label("OPTIONS") << "]";
9845
9846 // Positionals need to be listed here
9847 std::vector<const Option *> positionals =
9848 app->get_options([](const Option *opt) { return opt->get_positional(); });
9849
9850 // Print out positionals if any are left
9851 if (!positionals.empty()) {
9852 // Convert to help names
9853 std::vector<std::string> positional_names(positionals.size());
9854 std::transform(positionals.begin(), positionals.end(), positional_names.begin(),
9855 [this](const Option *opt) { return make_option_usage(opt); });
9856
9857 out << " " << detail::join(positional_names, " ");
9858 }
9859
9860 // Add a marker if subcommands are expected or optional
9861 if (!app->get_subcommands([](const CLI::App *subc) {
9862 return ((!subc->get_disabled()) && (!subc->get_name().empty()));
9863 })
9864 .empty()) {
9865 out << " " << (app->get_require_subcommand_min() == 0 ? "[" : "")
9866 << get_label(app->get_require_subcommand_max() < 2 ||
9868 ? "SUBCOMMAND"
9869 : "SUBCOMMANDS")
9870 << (app->get_require_subcommand_min() == 0 ? "]" : "");
9871 }
9872
9873 out << std::endl;
9874
9875 return out.str();
9876}
9877
9878CLI11_INLINE std::string Formatter::make_footer(const App *app) const {
9879 std::string footer = app->get_footer();
9880 if (footer.empty()) {
9881 return std::string{};
9882 }
9883 return "\n" + footer + "\n";
9884}
9885
9886CLI11_INLINE std::string Formatter::make_help(const App *app,
9887 std::string name,
9888 AppFormatMode mode) const {
9889 // This immediately forwards to the make_expanded method. This is done this way so that
9890 // subcommands can have overridden formatters
9891 if (mode == AppFormatMode::Sub) return make_expanded(app);
9892
9893 std::stringstream out;
9894 if ((app->get_name().empty()) && (app->get_parent() != nullptr)) {
9895 if (app->get_group() != "Subcommands") {
9896 out << app->get_group() << ':';
9897 }
9898 }
9899
9900 out << make_description(app);
9901 out << make_usage(app, name);
9902 if (app->get_aliases().size() > 0) {
9903 out << "or\n";
9904 out << make_usage(app, app->get_aliases()[0]);
9905 }
9906 out << make_positionals(app);
9907 out << make_groups(app, mode);
9908 out << make_subcommands(app, mode);
9909 out << make_footer(app);
9910
9911 return out.str();
9912}
9913
9914CLI11_INLINE std::string Formatter::make_subcommands(const App *app, AppFormatMode mode) const {
9915 std::stringstream out;
9916
9917 std::vector<const App *> subcommands = app->get_subcommands({});
9918
9919 // Make a list in definition order of the groups seen
9920 std::vector<std::string> subcmd_groups_seen;
9921 for (const App *com : subcommands) {
9922 if (com->get_name().empty()) {
9923 if (!com->get_group().empty()) {
9924 out << make_expanded(com);
9925 }
9926 continue;
9927 }
9928 std::string group_key = com->get_group();
9929 if (!group_key.empty() && std::find_if(subcmd_groups_seen.begin(), subcmd_groups_seen.end(),
9930 [&group_key](std::string a) {
9931 return detail::to_lower(a) ==
9932 detail::to_lower(group_key);
9933 }) == subcmd_groups_seen.end())
9934 subcmd_groups_seen.push_back(group_key);
9935 }
9936
9937 // For each group, filter out and print subcommands
9938 for (const std::string &group : subcmd_groups_seen) {
9939 out << "\n" << group << ":\n";
9940 std::vector<const App *> subcommands_group =
9941 app->get_subcommands([&group](const App *sub_app) {
9942 return detail::to_lower(sub_app->get_group()) == detail::to_lower(group);
9943 });
9944 for (const App *new_com : subcommands_group) {
9945 if (new_com->get_name().empty()) continue;
9946 if (mode != AppFormatMode::All) {
9947 out << make_subcommand(new_com);
9948 } else {
9949 out << new_com->help(new_com->get_name(), AppFormatMode::Sub);
9950 out << "\n";
9951 }
9952 }
9953 }
9954
9955 return out.str();
9956}
9957
9958CLI11_INLINE std::string Formatter::make_subcommand(const App *sub) const {
9959 std::stringstream out;
9960 detail::format_help(out, sub->get_display_name(true), sub->get_description(), column_width_);
9961 return out.str();
9962}
9963
9964CLI11_INLINE std::string Formatter::make_expanded(const App *sub) const {
9965 std::stringstream out;
9966 out << sub->get_display_name(true) << "\n";
9967
9968 out << make_description(sub);
9969 if (sub->get_name().empty() && !sub->get_aliases().empty()) {
9970 detail::format_aliases(out, sub->get_aliases(), column_width_ + 2);
9971 }
9972 out << make_positionals(sub);
9973 out << make_groups(sub, AppFormatMode::Sub);
9974 out << make_subcommands(sub, AppFormatMode::Sub);
9975
9976 // Drop blank spaces
9977 std::string tmp = detail::find_and_replace(out.str(), "\n\n", "\n");
9978 tmp = tmp.substr(0, tmp.size() - 1); // Remove the final '\n'
9979
9980 // Indent all but the first line (the name)
9981 return detail::find_and_replace(tmp, "\n", "\n ") + "\n";
9982}
9983
9984CLI11_INLINE std::string Formatter::make_option_name(const Option *opt, bool is_positional) const {
9985 if (is_positional) return opt->get_name(true, false);
9986
9987 return opt->get_name(false, true);
9988}
9989
9990CLI11_INLINE std::string Formatter::make_option_opts(const Option *opt) const {
9991 std::stringstream out;
9992
9993 if (!opt->get_option_text().empty()) {
9994 out << " " << opt->get_option_text();
9995 } else {
9996 if (opt->get_type_size() != 0) {
9997 if (!opt->get_type_name().empty()) out << " " << get_label(opt->get_type_name());
9998 if (!opt->get_default_str().empty()) out << " [" << opt->get_default_str() << "] ";
9999 if (opt->get_expected_max() == detail::expected_max_vector_size)
10000 out << " ...";
10001 else if (opt->get_expected_min() > 1)
10002 out << " x " << opt->get_expected();
10003
10004 if (opt->get_required()) out << " " << get_label("REQUIRED");
10005 }
10006 if (!opt->get_envname().empty())
10007 out << " (" << get_label("Env") << ":" << opt->get_envname() << ")";
10008 if (!opt->get_needs().empty()) {
10009 out << " " << get_label("Needs") << ":";
10010 for (const Option *op : opt->get_needs()) out << " " << op->get_name();
10011 }
10012 if (!opt->get_excludes().empty()) {
10013 out << " " << get_label("Excludes") << ":";
10014 for (const Option *op : opt->get_excludes()) out << " " << op->get_name();
10015 }
10016 }
10017 return out.str();
10018}
10019
10020CLI11_INLINE std::string Formatter::make_option_desc(const Option *opt) const {
10021 return opt->get_description();
10022}
10023
10024CLI11_INLINE std::string Formatter::make_option_usage(const Option *opt) const {
10025 // Note that these are positionals usages
10026 std::stringstream out;
10027 out << make_option_name(opt, true);
10028 if (opt->get_expected_max() >= detail::expected_max_vector_size)
10029 out << "...";
10030 else if (opt->get_expected_max() > 1)
10031 out << "(" << opt->get_expected() << "x)";
10032
10033 return opt->get_required() ? out.str() : "[" + out.str() + "]";
10034}
10035
10036} // namespace CLI
Creates a command line program, with very few defaults.
Definition CLI11.hpp:5883
int exit(const Error &e, std::ostream &out=std::cout, std::ostream &err=std::cerr) const
Print a nice error message and return the exit code.
Definition CLI11.hpp:7800
CLI11_NODISCARD std::string help(std::string prev="", AppFormatMode mode=AppFormatMode::Normal) const
Definition CLI11.hpp:7894
CLI11_NODISCARD std::size_t remaining_size(bool recurse=false) const
This returns the number of remaining options, minus the – separator.
Definition CLI11.hpp:8081
const Option * operator[](const std::string &option_name) const
Shortcut bracket operator for getting a pointer to an option.
Definition CLI11.hpp:6856
CLI11_NODISCARD bool _has_remaining_positionals() const
Count the required remaining positional arguments.
Definition CLI11.hpp:8708
App * configurable(bool value=true)
Specify that the subcommand can be triggered by a config file.
Definition CLI11.hpp:6252
CLI11_NODISCARD detail::Classifier _recognize(const std::string &current, bool ignore_used_subcommands=true) const
Selects a Classifier enum based on the type of the current argument.
Definition CLI11.hpp:8195
App * immediate_callback(bool immediate=true)
Set the subcommand callback to be executed immediately on subcommand completion.
Definition CLI11.hpp:7331
Option * get_option_no_throw(std::string option_name) noexcept
Get an option by name (noexcept non-const version).
Definition CLI11.hpp:7954
Option * set_help_flag(std::string flag_name="", const std::string &help_description="")
Set a help flag, replace the existing one if present.
Definition CLI11.hpp:7410
App * _get_fallthrough_parent()
Definition CLI11.hpp:9090
CLI11_NODISCARD std::string config_to_str(bool default_also=false, bool write_description=false) const
Definition CLI11.hpp:6780
CLI11_NODISCARD bool get_enabled_by_default() const
Get the status of disabled by default.
Definition CLI11.hpp:6931
Option * config_ptr_
Pointer to the config option.
Definition CLI11.hpp:6081
CLI11_NODISCARD bool got_subcommand(std::string subcommand_name) const
Check with name instead of pointer to see if subcommand was selected.
Definition CLI11.hpp:6704
CLI11_NODISCARD bool get_configurable() const
Check the status of the allow windows style options.
Definition CLI11.hpp:6881
Option * add_option_no_stream(std::string option_name, AssignTo &variable, std::string option_description="")
Add option for assigning to a variable.
Definition CLI11.hpp:6337
CLI11_NODISCARD std::shared_ptr< FormatterBase > get_formatter() const
Access the formatter.
Definition CLI11.hpp:6797
Option * add_option(std::string option_name)
Add option with no description or variable assignment.
Definition CLI11.hpp:6377
App * config_formatter(std::shared_ptr< Config > fmt)
Set the config formatter.
Definition CLI11.hpp:6273
App * allow_config_extras(bool allow=true)
ignore extras in config files
Definition CLI11.hpp:6213
App * disabled_by_default(bool disable=true)
Definition CLI11.hpp:6175
void _move_to_missing(detail::Classifier val_type, const std::string &val)
Helper function to place extra values in the most appropriate position.
Definition CLI11.hpp:9153
std::size_t require_option_min_
Minimum required options (not inheritable!).
Definition CLI11.hpp:6062
App * silent(bool silence=true)
silence the subcommand from showing up in the processed list
Definition CLI11.hpp:6168
App * clear_aliases()
clear all the aliases of the current App
Definition CLI11.hpp:6980
CLI11_NODISCARD bool get_ignore_underscore() const
Check the status of ignore_underscore.
Definition CLI11.hpp:6867
App * ignore_underscore(bool value=true)
Ignore underscore. Subcommands inherit value.
Definition CLI11.hpp:7357
App * allow_extras(bool allow=true)
Remove the error when extras are left over on the command line.
Definition CLI11.hpp:6150
App * fallthrough(bool value=true)
Definition CLI11.hpp:6623
std::size_t require_subcommand_max_
Definition CLI11.hpp:6059
Option * get_config_ptr()
Get a pointer to the config option.
Definition CLI11.hpp:6956
std::vector< App_p > subcommands_
Storage for subcommand list.
Definition CLI11.hpp:6009
CLI11_NODISCARD std::vector< std::string > remaining(bool recurse=false) const
This returns the missing options from the current subcommand.
Definition CLI11.hpp:8048
CLI11_NODISCARD bool get_allow_extras() const
Get the status of allow extras.
Definition CLI11.hpp:6911
CLI11_NODISCARD std::vector< std::string > remaining_for_passthrough(bool recurse=false) const
Definition CLI11.hpp:8074
std::uint32_t parsed_
Counts the number of times this command/subcommand was parsed.
Definition CLI11.hpp:6052
CLI11_NODISCARD App * get_option_group(std::string group_name) const
Check to see if an option group is part of this App.
Definition CLI11.hpp:7675
App * require_subcommand()
The argumentless form of require subcommand requires 1 or more subcommands.
Definition CLI11.hpp:6564
Option * get_option(std::string option_name)
Get an option by name (non-const version).
Definition CLI11.hpp:6847
OptionDefaults option_defaults_
The default values for options, customizable and changeable INHERITABLE.
Definition CLI11.hpp:5939
void _process_help_flags(bool trigger_help=false, bool trigger_all_help=false) const
Definition CLI11.hpp:8301
CLI11_NODISCARD const Option * get_version_ptr() const
Get a pointer to the version option. (const).
Definition CLI11.hpp:6965
void _process_requirements()
Verify required options and cross requirements. Subcommands too (only if selected).
Definition CLI11.hpp:8322
CLI11_NODISCARD std::size_t count_all() const
Definition CLI11.hpp:7684
CLI11_NODISCARD bool get_fallthrough() const
Check the status of fallthrough.
Definition CLI11.hpp:6870
bool disabled_
If set to true the subcommand is disabled and cannot be used, ignored for main app.
Definition CLI11.hpp:5916
CLI11_NODISCARD bool get_prefix_command() const
Get the prefix command status.
Definition CLI11.hpp:6908
Option * add_option(std::string option_name, AssignTo &variable, std::string option_description="")
Add option for assigning to a variable.
Definition CLI11.hpp:6312
CLI11_NODISCARD std::size_t get_require_subcommand_max() const
Get the required max subcommand value.
Definition CLI11.hpp:6897
Option * set_version_flag(std::string flag_name="", const std::string &versionString="", const std::string &version_help="Display program version information and exit")
Set a version flag and version display string, replace the existing one if present.
Definition CLI11.hpp:7446
bool required_
If set to true the subcommand is required to be processed and used, ignored for main app.
Definition CLI11.hpp:5913
bool remove_needs(Option *opt)
Removes an option from the needs list of this subcommand.
Definition CLI11.hpp:7876
bool _parse_arg(std::vector< std::string > &args, detail::Classifier current_type)
Definition CLI11.hpp:8893
const Option * operator[](const char *option_name) const
Shortcut bracket operator for getting a pointer to an option.
Definition CLI11.hpp:6861
CLI11_NODISCARD bool get_immediate_callback() const
Get the status of disabled.
Definition CLI11.hpp:6923
Option * get_help_ptr()
Get a pointer to the help flag.
Definition CLI11.hpp:6947
App * require_subcommand(int value)
Definition CLI11.hpp:6573
void _configure()
Definition CLI11.hpp:8133
CLI11_NODISCARD std::size_t _count_remaining_positionals(bool required_only=false) const
Count the required remaining positional arguments.
Definition CLI11.hpp:8694
Option * add_flag_function(std::string flag_name, std::function< void(std::int64_t)> function, std::string flag_description="")
Add option for callback with an integer value.
Definition CLI11.hpp:7526
OptionDefaults * option_defaults()
Get the OptionDefault object, to set option defaults.
Definition CLI11.hpp:6282
void parse(int argc, const char *const *argv)
Definition CLI11.hpp:7713
void _process_config_file()
Read and process a configuration file (main app only).
Definition CLI11.hpp:8217
std::string footer_
Footer to put after all options in the help output INHERITABLE.
Definition CLI11.hpp:5949
void increment_parsed()
Definition CLI11.hpp:8502
config_extras_mode allow_config_extras_
Definition CLI11.hpp:5904
CLI11_NODISCARD bool check_name(std::string name_to_check) const
Check the name, case insensitive and underscore insensitive if set.
Definition CLI11.hpp:8007
CLI11_NODISCARD std::string get_footer() const
Generate and return the footer.
Definition CLI11.hpp:6887
App * required(bool require=true)
Remove the error when extras are left over on the command line.
Definition CLI11.hpp:6156
Option * version_ptr_
A pointer to a version flag if there is one.
Definition CLI11.hpp:5961
CLI11_NODISCARD const Option * get_help_all_ptr() const
Get a pointer to the help all flag. (const).
Definition CLI11.hpp:6953
bool remove_subcommand(App *subcom)
Definition CLI11.hpp:7617
App * parent_
A pointer to the parent if this is a subcommand.
Definition CLI11.hpp:6068
std::set< Option * > exclude_options_
Definition CLI11.hpp:5994
void _trigger_pre_parse(std::size_t remaining_args)
Trigger the pre_parse callback if needed.
Definition CLI11.hpp:9072
App * prefix_command(bool allow=true)
Do not parse anything after the first unrecognized option and return.
Definition CLI11.hpp:6230
App * group(std::string group_name)
Changes the group membership.
Definition CLI11.hpp:6558
CLI::App_p get_subcommand_ptr(App *subcom) const
Check to see if a subcommand is part of this command and get a shared_ptr to it.
Definition CLI11.hpp:7654
std::function< std::string()> footer_callback_
This is a function that generates a footer to put after all other options in help output.
Definition CLI11.hpp:5952
std::function< void()> parse_complete_callback_
This is a function that runs when parsing has finished.
Definition CLI11.hpp:5929
virtual void pre_callback()
Definition CLI11.hpp:6639
T * add_option_group(std::string group_name, std::string group_description="")
creates an option group as part of the given app
Definition CLI11.hpp:6499
App * get_parent()
Get the parent of this subcommand (or nullptr if main app).
Definition CLI11.hpp:6968
Option * add_flag(std::string flag_name)
Add a flag with no description or variable assignment.
Definition CLI11.hpp:6415
void _validate() const
Definition CLI11.hpp:8096
std::string name_
Subcommand name or program name (from parser if name is empty).
Definition CLI11.hpp:5894
std::vector< App * > parsed_subcommands_
This is a list of the subcommands collected, in order.
Definition CLI11.hpp:5987
App(std::string app_description="", std::string app_name="")
Create a new program. Pass in the same arguments as main(), along with a help string.
Definition CLI11.hpp:6096
CLI11_NODISCARD const Option * get_help_ptr() const
Get a pointer to the help flag. (const).
Definition CLI11.hpp:6950
bool ignore_underscore_
If true, the program should ignore underscores INHERITABLE.
Definition CLI11.hpp:6015
App * allow_windows_style_options(bool value=true)
Definition CLI11.hpp:6240
missing_t missing_
Definition CLI11.hpp:5981
CLI11_NODISCARD bool get_validate_positionals() const
Get the status of validating positionals.
Definition CLI11.hpp:6935
Option * add_option_function(std::string option_name, const std::function< void(const ArgType &)> &func, std::string option_description="")
Add option for a callback of a specific type.
Definition CLI11.hpp:6356
void run_callback(bool final_mode=false, bool suppress_final_callback=false)
Internal function to run (App) callback, bottom up.
Definition CLI11.hpp:8153
std::size_t require_subcommand_min_
Minimum required subcommands (not inheritable!).
Definition CLI11.hpp:6055
void _process_env()
Get envname options if not yet passed. Runs on all subcommands.
Definition CLI11.hpp:8248
std::function< std::string(const App *, const Error &e)> failure_message_
The error message printing function INHERITABLE.
Definition CLI11.hpp:5967
void _parse_stream(std::istream &input)
Internal function to parse a stream.
Definition CLI11.hpp:8553
CLI11_NODISCARD std::string get_display_name(bool with_aliases=false) const
Get a display name for an app.
Definition CLI11.hpp:7991
void failure_message(std::function< std::string(const App *, const Error &e)> function)
Definition CLI11.hpp:6669
bool has_automatic_name_
If set to true the name was automatically generated from the command line vs a user set name.
Definition CLI11.hpp:5910
CLI11_NODISCARD const std::string & _compare_subcommand_names(const App &subcom, const App &base) const
Definition CLI11.hpp:9101
void clear()
Reset the parsed data.
Definition CLI11.hpp:7699
CLI11_NODISCARD std::size_t get_require_option_max() const
Get the required max option value.
Definition CLI11.hpp:6905
App * enabled_by_default(bool enable=true)
Definition CLI11.hpp:6187
App * footer(std::string footer_string)
Set footer.
Definition CLI11.hpp:6768
App * get_subcommand(const App *subcom) const
Definition CLI11.hpp:7633
App * require_option(int value)
Definition CLI11.hpp:6602
CLI11_NODISCARD std::string version() const
Displays a version string.
Definition CLI11.hpp:7908
virtual ~App()=default
virtual destructor
CLI11_NODISCARD std::size_t count(std::string option_name) const
Counts the number of times the given option was passed.
Definition CLI11.hpp:6681
std::vector< Option_p > options_
The list of options, stored locally.
Definition CLI11.hpp:5942
Option * help_all_ptr_
A pointer to the help all flag if there is one INHERITABLE.
Definition CLI11.hpp:5958
bool validate_optional_arguments_
If set to true optional vector arguments are validated before assigning INHERITABLE.
Definition CLI11.hpp:6045
std::function< void()> final_callback_
This is a function that runs when all processing has completed.
Definition CLI11.hpp:5932
bool remove_option(Option *opt)
Removes an option from the App. Takes an option pointer. Returns true if found and removed.
Definition CLI11.hpp:7565
App * require_option()
The argumentless form of require option requires 1 or more options be used.
Definition CLI11.hpp:6593
App(std::string app_description, std::string app_name, App *parent)
Special private constructor for subcommand.
Definition CLI11.hpp:7261
App * add_subcommand(std::string subcommand_name="", std::string subcommand_description="")
Add a subcommand. Inherits INHERITABLE and OptionDefaults, and help flag.
Definition CLI11.hpp:7584
App * preparse_callback(std::function< void(std::size_t)> pp_callback)
Definition CLI11.hpp:6138
Option * add_flag_callback(std::string flag_name, std::function< void(void)> function, std::string flag_description="")
Add option for callback that is triggered with a true flag and takes no arguments.
Definition CLI11.hpp:7511
bool positionals_at_end_
specify that positional arguments come at the end of the argument sequence not inheritable
Definition CLI11.hpp:6031
void _process()
Process callbacks and such.
Definition CLI11.hpp:8453
bool immediate_callback_
Definition CLI11.hpp:5923
bool _parse_single(std::vector< std::string > &args, bool &positional_only)
Definition CLI11.hpp:8651
App * name(std::string app_name="")
Set a name for the app (empty will use parser to set the name).
Definition CLI11.hpp:7296
void _move_option(Option *opt, App *app)
function that could be used by subclasses of App to shift options around into subcommands
Definition CLI11.hpp:9169
CLI11_NODISCARD bool get_required() const
Get the status of required.
Definition CLI11.hpp:6914
void _process_extras()
Throw an error if anything is left over and should not be.
Definition CLI11.hpp:8475
CLI11_NODISCARD bool _valid_subcommand(const std::string &current, bool ignore_used=true) const
Definition CLI11.hpp:8181
Option * add_flag(std::string flag_name, T &flag_description)
Definition CLI11.hpp:6425
CLI11_NODISCARD bool get_ignore_case() const
Check the status of ignore_case.
Definition CLI11.hpp:6864
App * parse_complete_callback(std::function< void()> pc_callback)
Definition CLI11.hpp:6131
bool configurable_
if set to true the subcommand can be triggered via configuration files INHERITABLE
Definition CLI11.hpp:6039
CLI11_NODISCARD std::vector< std::string > get_groups() const
Get the groups available directly from this option (in order).
Definition CLI11.hpp:8035
App * formatter_fn(std::function< std::string(const App *, std::string, AppFormatMode)> fmt)
Set the help formatter.
Definition CLI11.hpp:6267
CLI11_NODISCARD const std::vector< std::string > & get_aliases() const
Get the aliases of the current app.
Definition CLI11.hpp:6977
void _parse_config(const std::vector< ConfigItem > &args)
Definition CLI11.hpp:8564
App * description(std::string app_description)
Set the description of the app.
Definition CLI11.hpp:6818
CLI11_NODISCARD std::shared_ptr< ConfigBase > get_config_formatter_base() const
Access the config formatter as a configBase pointer.
Definition CLI11.hpp:6805
std::string description_
Description of the current program/subcommand.
Definition CLI11.hpp:5897
App * excludes(App *app)
Sets excluded subcommands for the subcommand.
Definition CLI11.hpp:6718
CLI11_NODISCARD bool get_positionals_at_end() const
Check the status of the allow windows style options.
Definition CLI11.hpp:6878
Option * get_version_ptr()
Get a pointer to the version option.
Definition CLI11.hpp:6962
CLI11_NODISCARD std::size_t get_require_option_min() const
Get the required min option value.
Definition CLI11.hpp:6902
std::size_t require_option_max_
Max number of options allowed. 0 is unlimited (not inheritable).
Definition CLI11.hpp:6065
CLI11_NODISCARD bool get_disabled() const
Get the status of disabled.
Definition CLI11.hpp:6917
CLI11_NODISCARD bool get_allow_windows_style_options() const
Check the status of the allow windows style options.
Definition CLI11.hpp:6873
std::vector< std::string > aliases_
Alias names for the subcommand.
Definition CLI11.hpp:6074
CLI11_NODISCARD bool parsed() const
Check to see if this subcommand was parsed, true only if received on command line.
Definition CLI11.hpp:6279
std::set< App * > exclude_subcommands_
this is a list of subcommands that are exclusionary to this one
Definition CLI11.hpp:5990
CLI11_NODISCARD bool get_disabled_by_default() const
Get the status of disabled by default.
Definition CLI11.hpp:6926
Option * add_flag(std::string flag_name, std::vector< T > &flag_results, std::string flag_description="")
Vector version to capture multiple flags.
Definition CLI11.hpp:6449
CLI11_NODISCARD std::size_t count() const
Definition CLI11.hpp:6551
bool _parse_positional(std::vector< std::string > &args, bool haltOnSubcommand)
Definition CLI11.hpp:8719
bool ignore_case_
If true, the program name is not case sensitive INHERITABLE.
Definition CLI11.hpp:6012
CLI11_NODISCARD const std::string & get_group() const
Get the group of this subcommand.
Definition CLI11.hpp:6884
bool silent_
Definition CLI11.hpp:6049
CLI11_NODISCARD const App * get_parent() const
Get the parent of this subcommand (or nullptr if main app) (const version).
Definition CLI11.hpp:6971
std::function< void(std::size_t)> pre_parse_callback_
This is a function that runs prior to the start of parsing.
Definition CLI11.hpp:5926
App * final_callback(std::function< void()> app_callback)
Definition CLI11.hpp:6124
std::string group_
The group membership INHERITABLE.
Definition CLI11.hpp:6071
App * alias(std::string app_name)
Set an alias for the app.
Definition CLI11.hpp:7312
bool pre_parse_called_
Flag indicating that the pre_parse_callback has been triggered.
Definition CLI11.hpp:5919
void _process_callbacks()
Process callbacks. Runs on all subcommands.
Definition CLI11.hpp:8278
App * validate_positionals(bool validate=true)
Set the subcommand to validate positional arguments before assigning.
Definition CLI11.hpp:6201
Option * help_ptr_
A pointer to the help flag if there is one INHERITABLE.
Definition CLI11.hpp:5955
Option * set_config(std::string option_name="", std::string default_filename="", const std::string &help_message="Read an ini file", bool config_required=false)
Set a configuration ini file option, or clear it if no name passed.
Definition CLI11.hpp:7540
App * footer(std::function< std::string()> footer_function)
Set footer.
Definition CLI11.hpp:6773
App * ignore_case(bool value=true)
Ignore case. Subcommands inherit value.
Definition CLI11.hpp:7343
App * excludes(Option *opt)
Sets excluded options for the subcommand.
Definition CLI11.hpp:6709
CLI11_NODISCARD std::shared_ptr< Config > get_config_formatter() const
Access the config formatter.
Definition CLI11.hpp:6800
bool remove_excludes(Option *opt)
Removes an option from the excludes list of this subcommand.
Definition CLI11.hpp:7855
CLI11_NODISCARD std::vector< App * > get_subcommands() const
Definition CLI11.hpp:6687
bool got_subcommand(const App *subcom) const
Check to see if given subcommand was selected.
Definition CLI11.hpp:6698
CLI11_NODISCARD config_extras_mode get_allow_config_extras() const
Get the status of allow extras.
Definition CLI11.hpp:6942
bool _parse_subcommand(std::vector< std::string > &args)
Definition CLI11.hpp:8866
App * positionals_at_end(bool value=true)
Specify that the positional arguments are only at the end of the sequence.
Definition CLI11.hpp:6246
bool fallthrough_
Definition CLI11.hpp:6019
std::set< Option * > need_options_
Definition CLI11.hpp:6002
CLI11_NODISCARD bool get_validate_optional_arguments() const
Get the status of validating optional vector arguments.
Definition CLI11.hpp:6937
CLI11_NODISCARD bool get_silent() const
Get the status of silence.
Definition CLI11.hpp:6920
std::vector< const Option * > get_options(const std::function< bool(const Option *)> filter={}) const
Definition CLI11.hpp:7925
std::set< App * > need_subcommands_
Definition CLI11.hpp:5998
App * validate_optional_arguments(bool validate=true)
Set the subcommand to validate optional vector arguments before assigning.
Definition CLI11.hpp:6207
bool prefix_command_
If true, return immediately on an unrecognized option (implies allow_extras) INHERITABLE.
Definition CLI11.hpp:5907
Option * add_option(std::string option_name, callback_t option_callback, std::string option_description="", bool defaulted=false, std::function< std::string()> func={})
Definition CLI11.hpp:7372
App * formatter(std::shared_ptr< FormatterBase > fmt)
Set the help formatter.
Definition CLI11.hpp:6261
std::vector< Option * > parse_order_
This is a list of pointers to options with the original parse order.
Definition CLI11.hpp:5984
Option * add_option(std::string option_name, T &option_description)
Add option with description but with no variable assignment or callback.
Definition CLI11.hpp:6385
CLI11_NODISCARD const std::vector< Option * > & parse_order() const
This gets a vector of pointers with the original parse order.
Definition CLI11.hpp:6995
void _parse(std::vector< std::string > &args)
Internal parse function.
Definition CLI11.hpp:8509
bool validate_positionals_
If set to true positional options are validated before assigning INHERITABLE.
Definition CLI11.hpp:6042
bool _parse_single_config(const ConfigItem &item, std::size_t level=0)
Fill in a single config option.
Definition CLI11.hpp:8571
startup_mode default_startup
Definition CLI11.hpp:6036
App * allow_config_extras(config_extras_mode mode)
ignore extras in config files
Definition CLI11.hpp:6224
Option * add_flag(std::string flag_name, T &flag_result, std::string flag_description="")
Definition CLI11.hpp:6435
bool allow_extras_
If true, allow extra arguments (ie, don't throw an error). INHERITABLE.
Definition CLI11.hpp:5900
CLI11_NODISCARD std::string get_description() const
Get the app or subcommand description.
Definition CLI11.hpp:6815
App * require_option(std::size_t min, std::size_t max)
Definition CLI11.hpp:6615
CLI11_NODISCARD App * _find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept
Definition CLI11.hpp:8848
CLI11_NODISCARD std::size_t get_require_subcommand_min() const
Get the required min subcommand value.
Definition CLI11.hpp:6892
CLI11_NODISCARD const Option * get_config_ptr() const
Get a pointer to the config option. (const).
Definition CLI11.hpp:6959
CLI11_NODISCARD const std::string & get_name() const
Get the name of the current app.
Definition CLI11.hpp:6974
App * disabled(bool disable=true)
Disable the subcommand or option group.
Definition CLI11.hpp:6162
App * callback(std::function< void()> app_callback)
Definition CLI11.hpp:6113
std::shared_ptr< FormatterBase > formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer).
Definition CLI11.hpp:5964
Option * set_help_all_flag(std::string help_name="", const std::string &help_description="")
Set a help all flag, replaced the existing one if present.
Definition CLI11.hpp:7428
App * require_subcommand(std::size_t min, std::size_t max)
Definition CLI11.hpp:6586
CLI11_NODISCARD const Option * get_option(std::string option_name) const
Get an option by name.
Definition CLI11.hpp:6838
bool allow_windows_style_options_
Definition CLI11.hpp:6023
std::shared_ptr< Config > config_formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer).
Definition CLI11.hpp:6084
Thrown when the wrong number of arguments has been received.
Definition CLI11.hpp:886
Definition CLI11.hpp:3721
Options
Definition CLI11.hpp:3727
AsSizeValue(bool kb_is_1000)
Definition CLI11.hpp:4133
Thrown on construction of a bad name.
Definition CLI11.hpp:736
Bound(T min_val, T max_val)
Definition CLI11.hpp:3287
Bound(T max_val)
Range of one value is 0 to value.
Definition CLI11.hpp:3309
Usually something like –help-all on command line.
Definition CLI11.hpp:790
-h or –help on command line
Definition CLI11.hpp:782
-v or –version on command line
Definition CLI11.hpp:798
CheckedTransformer(T mapping)
direct map of std::string to std::string
Definition CLI11.hpp:3621
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 CLI11.hpp:3687
CheckedTransformer(std::initializer_list< std::pair< std::string, std::string > > values, Args &&...args)
This allows in-place construction.
Definition CLI11.hpp:3615
CheckedTransformer(T mapping, F filter_function)
Definition CLI11.hpp:3626
This converter works with INI/TOML files; to write INI files use ConfigINI.
Definition CLI11.hpp:2898
std::vector< ConfigItem > from_config(std::istream &input) const override
Convert a configuration into an app.
Definition CLI11.hpp:9518
std::string configSection
Specify the configuration section that should be used.
Definition CLI11.hpp:2921
ConfigBase * comment(char cchar)
Specify the configuration for comment characters.
Definition CLI11.hpp:2931
ConfigBase * arrayDelimiter(char aSep)
Specify the delimiter character for an array.
Definition CLI11.hpp:2942
char arraySeparator
the character used to separate elements in an array
Definition CLI11.hpp:2907
ConfigBase * quoteCharacter(char qString, char qChar)
Specify the quote characters used around strings and characters.
Definition CLI11.hpp:2952
std::string & sectionRef()
get a reference to the configuration section
Definition CLI11.hpp:2968
ConfigBase * arrayBounds(char aStart, char aEnd)
Specify the start and end characters for an array.
Definition CLI11.hpp:2936
ConfigBase * maxLayers(uint8_t layers)
Specify the maximum number of parents.
Definition CLI11.hpp:2958
char characterQuote
the character to use around single characters
Definition CLI11.hpp:2913
CLI11_NODISCARD const std::string & section() const
get the section
Definition CLI11.hpp:2970
char stringQuote
the character to use around strings
Definition CLI11.hpp:2911
ConfigBase * section(const std::string &sectionName)
specify a particular section of the configuration file to use
Definition CLI11.hpp:2972
ConfigBase * valueSeparator(char vSep)
Specify the delimiter between a name and value.
Definition CLI11.hpp:2947
uint8_t maximumLayers
the maximum number of layers to allow
Definition CLI11.hpp:2915
char valueDelimiter
the character used separate the name from the value
Definition CLI11.hpp:2909
char arrayStart
the character used to start an array '\0' is a default to not use
Definition CLI11.hpp:2903
char parentSeparatorChar
the separator used to separator parent layers
Definition CLI11.hpp:2917
CLI11_NODISCARD int16_t index() const
get the section index
Definition CLI11.hpp:2980
ConfigBase * index(int16_t sectionIndex)
specify a particular index in the section to use (-1) for all sections to use
Definition CLI11.hpp:2982
int16_t & indexRef()
get a reference to the configuration index
Definition CLI11.hpp:2978
char arrayEnd
the character used to end an array '\0' is a default to not use
Definition CLI11.hpp:2905
ConfigBase * parentSeparator(char sep)
Specify the separator to use for parent layers.
Definition CLI11.hpp:2963
int16_t configIndex
Specify the configuration index to use for arrayed sections.
Definition CLI11.hpp:2919
std::string to_config(const App *, bool default_also, bool write_description, std::string prefix) const override
Convert an app into a configuration.
Definition CLI11.hpp:9660
char commentChar
the character used for comments
Definition CLI11.hpp:2901
Thrown when extra values are found in an INI file.
Definition CLI11.hpp:949
This class provides a converter for configuration files.
Definition CLI11.hpp:2863
virtual CLI11_NODISCARD std::string to_flag(const ConfigItem &item) const
Get a flag value.
Definition CLI11.hpp:2875
virtual std::string to_config(const App *, bool, bool, std::string) const =0
Convert an app into a configuration.
CLI11_NODISCARD std::vector< ConfigItem > from_file(const std::string &name) const
Parse a config file, throw an error (ParseError:ConfigParseError or FileError) on failure.
Definition CLI11.hpp:2886
virtual ~Config()=default
Virtual destructor.
virtual std::vector< ConfigItem > from_config(std::istream &) const =0
Convert a configuration into an app.
Construction errors (not in parsing).
Definition CLI11.hpp:700
Thrown when conversion call back fails, such as when an int fails to coerce to a string.
Definition CLI11.hpp:822
Class wrapping some of the accessors of Validator.
Definition CLI11.hpp:3146
All errors derive from this one.
Definition CLI11.hpp:681
Thrown when an excludes option is present.
Definition CLI11.hpp:926
Thrown when too many positionals or options are found.
Definition CLI11.hpp:933
Thrown when parsing an INI file and it is missing.
Definition CLI11.hpp:813
Definition CLI11.hpp:4240
std::size_t column_width_
The width of the first column.
Definition CLI11.hpp:4246
std::map< std::string, std::string > labels_
The required help printout labels (user changeable) Values are Needs, Excludes, etc.
Definition CLI11.hpp:4250
CLI11_NODISCARD std::size_t get_column_width() const
Get the current column width.
Definition CLI11.hpp:4290
CLI11_NODISCARD std::string get_label(std::string key) const
Get the current value of a name (REQUIRED, etc.).
Definition CLI11.hpp:4284
void label(std::string key, std::string val)
Set the "REQUIRED" label.
Definition CLI11.hpp:4274
virtual ~FormatterBase() noexcept
Adding a destructor in this form to work around bug in GCC 4.7.
Definition CLI11.hpp:4264
virtual std::string make_help(const App *, std::string, AppFormatMode) const =0
This is the key method that puts together help.
void column_width(std::size_t val)
Set the column width.
Definition CLI11.hpp:4277
std::string make_help(const App *app, std::string name, AppFormatMode mode) const override
This will simply call the lambda function.
Definition CLI11.hpp:4310
~FormatterLambda() noexcept override
Adding a destructor (mostly to make GCC 4.7 happy).
Definition CLI11.hpp:4307
FormatterLambda(funct_t funct)
Create a FormatterLambda with a lambda function.
Definition CLI11.hpp:4304
Definition CLI11.hpp:4317
std::string make_help(const App *, std::string, AppFormatMode) const override
This puts everything together.
Definition CLI11.hpp:9886
virtual std::string make_option(const Option *opt, bool is_positional) const
This prints out an option help line, either positional or optional form.
Definition CLI11.hpp:4366
std::string make_groups(const App *app, AppFormatMode mode) const
This prints out all the groups of options.
Definition CLI11.hpp:9782
virtual std::string make_usage(const App *app, std::string name) const
This displays the usage line.
Definition CLI11.hpp:9834
virtual std::string make_option_name(const Option *, bool) const
This is the name part of an option, Default: left column.
Definition CLI11.hpp:9984
virtual CLI11_NODISCARD std::string make_group(std::string group, bool is_positional, std::vector< const Option * > opts) const
Definition CLI11.hpp:9760
virtual std::string make_footer(const App *app) const
This prints out all the groups of options.
Definition CLI11.hpp:9878
virtual std::string make_option_usage(const Option *opt) const
This is used to print the name on the USAGE line.
Definition CLI11.hpp:10024
virtual std::string make_subcommand(const App *sub) const
This prints out a subcommand.
Definition CLI11.hpp:9958
virtual std::string make_positionals(const App *app) const
This prints out just the positionals "group".
Definition CLI11.hpp:9773
virtual std::string make_subcommands(const App *app, AppFormatMode mode) const
This prints out all the subcommands.
Definition CLI11.hpp:9914
virtual std::string make_description(const App *app) const
This displays the description line.
Definition CLI11.hpp:9805
virtual std::string make_option_desc(const Option *) const
This is the description. Default: Right column, on new line if left column too large.
Definition CLI11.hpp:10020
virtual std::string make_option_opts(const Option *) const
This is the options part of the name, Default: combined into left column.
Definition CLI11.hpp:9990
virtual std::string make_expanded(const App *sub) const
This prints out a subcommand in help-all.
Definition CLI11.hpp:9964
Definition CLI11.hpp:970
Thrown when an option is set to conflicting values (non-vector and multi args, for example).
Definition CLI11.hpp:705
Thrown when validation fails before parsing.
Definition CLI11.hpp:961
IsMember(T &&set)
This checks to see if an item is in a set (empty function).
Definition CLI11.hpp:3482
IsMember(T set, F filter_function)
Definition CLI11.hpp:3487
IsMember(T &&set, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
You can pass in as many filter functions as you like, they nest (string only currently).
Definition CLI11.hpp:3534
IsMember(std::initializer_list< T > values, Args &&...args)
This allows in-place construction using an initializer list.
Definition CLI11.hpp:3477
Thrown when an option already exists.
Definition CLI11.hpp:754
Definition CLI11.hpp:4410
CRTP * mandatory(bool value=true)
Support Plumbum term.
Definition CLI11.hpp:4464
CRTP * take_all()
Set the multi option policy to take all arguments.
Definition CLI11.hpp:4519
CRTP * group(const std::string &name)
Changes the group membership.
Definition CLI11.hpp:4449
CRTP * join()
Set the multi option policy to join.
Definition CLI11.hpp:4526
bool always_capture_default_
Automatically capture default value.
Definition CLI11.hpp:4436
MultiOptionPolicy multi_option_policy_
Policy for handling multiple arguments beyond the expected Max.
Definition CLI11.hpp:4439
CRTP * join(char delim)
Set the multi option policy to join with a specific delimiter.
Definition CLI11.hpp:4533
CLI11_NODISCARD bool get_always_capture_default() const
Return true if this will automatically capture the default value for help printing.
Definition CLI11.hpp:4495
CLI11_NODISCARD char get_delimiter() const
Get the current delimiter char.
Definition CLI11.hpp:4492
CLI11_NODISCARD bool get_required() const
True if this is a required option.
Definition CLI11.hpp:4477
CRTP * take_first()
Set the multi option policy to take last.
Definition CLI11.hpp:4512
CLI11_NODISCARD bool get_ignore_case() const
The status of ignore case.
Definition CLI11.hpp:4480
bool ignore_case_
Ignore the case when matching (option, not value).
Definition CLI11.hpp:4421
CRTP * configurable(bool value=true)
Allow in a configuration file.
Definition CLI11.hpp:4541
CRTP * delimiter(char value='\0')
Allow in a configuration file.
Definition CLI11.hpp:4547
CLI11_NODISCARD MultiOptionPolicy get_multi_option_policy() const
The status of the multi option policy.
Definition CLI11.hpp:4498
CLI11_NODISCARD bool get_configurable() const
The status of configurable.
Definition CLI11.hpp:4486
bool configurable_
Allow this option to be given in a configuration file.
Definition CLI11.hpp:4427
bool disable_flag_override_
Disable overriding flag values with '=value'.
Definition CLI11.hpp:4430
bool required_
True if this is a required option.
Definition CLI11.hpp:4418
CRTP * take_last()
Set the multi option policy to take last.
Definition CLI11.hpp:4505
char delimiter_
Specify a delimiter character for vector arguments.
Definition CLI11.hpp:4433
std::string group_
The group membership.
Definition CLI11.hpp:4415
CLI11_NODISCARD bool get_ignore_underscore() const
The status of ignore_underscore.
Definition CLI11.hpp:4483
bool ignore_underscore_
Ignore underscores when matching (option, not value).
Definition CLI11.hpp:4424
CLI11_NODISCARD bool get_disable_flag_override() const
The status of configurable.
Definition CLI11.hpp:4489
CLI11_NODISCARD const std::string & get_group() const
Get the group of this option.
Definition CLI11.hpp:4474
void copy_to(T *other) const
Copy the contents to another similar class (one based on OptionBase).
Definition CLI11.hpp:5195
CRTP * required(bool value=true)
Set the option as required.
Definition CLI11.hpp:4458
Definition CLI11.hpp:4555
OptionDefaults * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times.
Definition CLI11.hpp:4562
OptionDefaults * ignore_case(bool value=true)
Ignore the case of the option name.
Definition CLI11.hpp:4568
OptionDefaults * ignore_underscore(bool value=true)
Ignore underscores in the option name.
Definition CLI11.hpp:4574
OptionDefaults * delimiter(char value='\0')
set a delimiter character to split up single arguments to treat as multiple inputs
Definition CLI11.hpp:4586
OptionDefaults * disable_flag_override(bool value=true)
Disable overriding flag values with an '=' segment.
Definition CLI11.hpp:4580
Thrown when counting a non-existent option.
Definition CLI11.hpp:978
Extension of App to better manage groups of options.
Definition CLI11.hpp:7138
App * add_subcommand(App *subcom)
Add an existing subcommand to be a member of an option_group.
Definition CLI11.hpp:7164
Option * add_option(Option *opt)
Add an existing option to the Option_group.
Definition CLI11.hpp:7147
void add_options(Option *opt, Args... args)
Add a bunch of options to the group.
Definition CLI11.hpp:7158
void add_options(Option *opt)
Add an existing option to the Option_group.
Definition CLI11.hpp:7155
Definition CLI11.hpp:4592
Option * type_size(int option_type_size)
Set a custom option size.
Definition CLI11.hpp:5605
Option * expected(int value)
Set the number of expected arguments.
Definition CLI11.hpp:5207
CLI11_NODISCARD bool get_positional() const
True if the argument can be given directly.
Definition CLI11.hpp:4962
std::string default_str_
A human readable default value, either manually set, captured, or captured by default.
Definition CLI11.hpp:4627
bool run_callback_for_default_
Control option to run the callback to set the default.
Definition CLI11.hpp:4696
CLI11_NODISCARD std::string get_envname() const
The environment variable associated to this value.
Definition CLI11.hpp:4907
CLI11_NODISCARD bool check_name(const std::string &name) const
Check a name. Requires "-" or "--" for short / long, supports positional name.
Definition CLI11.hpp:5495
Option * type_name(std::string typeval)
Set a custom option typestring.
Definition CLI11.hpp:5111
std::function< std::string()> type_name_
Definition CLI11.hpp:4635
option_state
enumeration for the option state machine
Definition CLI11.hpp:4683
@ reduced
a subset of results has been generated
Definition CLI11.hpp:4686
@ callback_run
the callback has been executed
Definition CLI11.hpp:4687
@ validated
the results have been validated
Definition CLI11.hpp:4685
@ parsing
The option is currently collecting parsed results.
Definition CLI11.hpp:4684
option_state current_option_state_
Whether the callback has run (needed for INI parsing).
Definition CLI11.hpp:4690
std::string option_text_
If given, replace the text that describes the option type and usage in the help text.
Definition CLI11.hpp:4630
int type_size_min_
The minimum number of arguments an option should be expecting.
Definition CLI11.hpp:4648
CLI11_NODISCARD results_t reduced_results() const
Get a copy of the results.
Definition CLI11.hpp:5587
CLI11_NODISCARD std::string get_type_name() const
Get the full typename for this option.
Definition CLI11.hpp:5647
CLI11_NODISCARD bool check_fname(std::string name) const
Requires "--" to be removed from string.
Definition CLI11.hpp:5026
std::string pname_
A positional name.
Definition CLI11.hpp:4614
int expected_min_
The minimum number of expected values.
Definition CLI11.hpp:4651
Option(std::string option_name, std::string option_description, callback_t callback, App *parent)
Making an option by hand is not defined, it must be made by the App class.
Definition CLI11.hpp:4707
Option * ignore_case(bool value=true)
Definition CLI11.hpp:5350
std::set< Option * > needs_
A list of options that are required with this option.
Definition CLI11.hpp:4659
Option * default_function(const std::function< std::string()> &func)
Set a capture function for the default. Mostly used by App.
Definition CLI11.hpp:5126
CLI11_NODISCARD int get_type_size_min() const
The minimum number of arguments the option expects.
Definition CLI11.hpp:4899
void run_callback()
Process the callback.
Definition CLI11.hpp:5453
CLI11_NODISCARD bool check_sname(std::string name) const
Requires "-" to be removed from string.
Definition CLI11.hpp:5015
bool trigger_on_result_
Definition CLI11.hpp:4701
bool flag_like_
Specify that the option should act like a flag vs regular option.
Definition CLI11.hpp:4694
CLI11_NODISCARD std::string get_name(bool positional=false, bool all_options=false) const
Gets a comma separated list of names. Will include / prefer the positional name if positional is true...
Definition CLI11.hpp:5407
std::set< Option * > excludes_
A list of options that are excluded with this option.
Definition CLI11.hpp:4662
bool force_callback_
flag indicating that the option should force the callback regardless if any results present
Definition CLI11.hpp:4703
CLI11_NODISCARD bool get_callback_run() const
See if the callback has been run already.
Definition CLI11.hpp:5096
CLI11_NODISCARD bool get_force_callback() const
The status of force_callback.
Definition CLI11.hpp:4773
std::vector< std::string > fnames_
a list of flag names with specified default values;
Definition CLI11.hpp:4611
CLI11_NODISCARD bool get_run_callback_for_default() const
Get the current value of run_callback_for_default.
Definition CLI11.hpp:4783
CLI11_NODISCARD std::string get_default_str() const
The default value (for help printing).
Definition CLI11.hpp:4916
CLI11_NODISCARD bool nonpositional() const
True if option has at least one non-positional name.
Definition CLI11.hpp:4965
CLI11_NODISCARD int get_items_expected_min() const
The total min number of expected string values to be used.
Definition CLI11.hpp:4951
CLI11_NODISCARD const std::string & matching_name(const Option &other) const
If options share any of the same names, find it.
Definition CLI11.hpp:5478
CLI11_NODISCARD bool check_lname(std::string name) const
Requires "--" to be removed from string.
Definition CLI11.hpp:5020
CLI11_NODISCARD const results_t & results() const
Get the current complete results set.
Definition CLI11.hpp:5049
Option * disable_flag_override(bool value=true)
Disable flag overrides values, e.g. –flag=is not allowed.
Definition CLI11.hpp:4887
CLI11_NODISCARD int get_items_expected_max() const
Get the maximum number of items expected to be returned and used for the callback.
Definition CLI11.hpp:4954
std::vector< std::string > snames_
A list of the short names (-a) without the leading dashes.
Definition CLI11.hpp:4600
results_t proc_results_
results after reduction
Definition CLI11.hpp:4681
bool remove_excludes(Option *opt)
Remove needs link from an option. Returns true if the option really was in the needs list.
Definition CLI11.hpp:5339
CLI11_NODISCARD std::size_t count() const
Count the total number of times an option was passed.
Definition CLI11.hpp:4725
Option * run_callback_for_default(bool value=true)
Definition CLI11.hpp:4778
void inject_separator(bool value=true)
Set the value of the separator injection flag.
Definition CLI11.hpp:5123
Option * allow_extra_args(bool value=true)
Definition CLI11.hpp:4752
Option * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times (or another policy).
Definition CLI11.hpp:5393
Option * trigger_on_parse(bool value=true)
Definition CLI11.hpp:4760
CLI11_NODISCARD callback_t get_callback() const
Get the callback function.
Definition CLI11.hpp:4919
CLI11_NODISCARD bool get_inject_separator() const
Return the inject_separator flag.
Definition CLI11.hpp:4904
Option * excludes(Option *opt)
Sets excluded options.
Definition CLI11.hpp:5323
App * parent_
link back up to the parent App for fallthrough
Definition CLI11.hpp:4669
CLI11_NODISCARD bool get_trigger_on_parse() const
The status of trigger on parse.
Definition CLI11.hpp:4765
CLI11_NODISCARD const std::vector< std::string > & get_lnames() const
Get the long names.
Definition CLI11.hpp:4922
int expected_max_
The maximum number of expected values.
Definition CLI11.hpp:4653
CLI11_NODISCARD std::set< Option * > get_excludes() const
The set of options excluded.
Definition CLI11.hpp:4913
CLI11_NODISCARD std::string get_flag_value(const std::string &name, std::string input_value) const
Definition CLI11.hpp:5521
Option * excludes(std::string opt_name)
Can find a string if needed.
Definition CLI11.hpp:4845
CLI11_NODISCARD int get_items_expected() const
The total min number of expected string values to be used.
Definition CLI11.hpp:4959
Validator * get_validator(const std::string &Validator_name="")
Get a named Validator.
Definition CLI11.hpp:5293
CLI11_NODISCARD std::set< Option * > get_needs() const
The set of options needed.
Definition CLI11.hpp:4910
std::string description_
The description for help strings.
Definition CLI11.hpp:4624
CLI11_NODISCARD const std::vector< std::string > & get_snames() const
Get the short names.
Definition CLI11.hpp:4925
CLI11_NODISCARD int get_type_size_max() const
The maximum number of arguments the option expects.
Definition CLI11.hpp:4901
bool inject_separator_
flag indicating a separator needs to be injected after each argument call
Definition CLI11.hpp:4698
Option * check(Validator validator, const std::string &validator_name="")
Adds a Validator with a built in type name.
Definition CLI11.hpp:5247
CLI11_NODISCARD const std::string & get_description() const
Get the description.
Definition CLI11.hpp:4971
CLI11_NODISCARD const std::string & get_single_name() const
Get a single name for the option, first of lname, pname, sname, envname.
Definition CLI11.hpp:4930
CLI11_NODISCARD int get_expected() const
The number of times the option expects to be included.
Definition CLI11.hpp:4943
callback_t callback_
Options store a callback to do all the work.
Definition CLI11.hpp:4672
CLI11_NODISCARD bool empty() const
True if the option was not passed.
Definition CLI11.hpp:4728
CLI11_NODISCARD int get_expected_min() const
The number of times the option expects to be included.
Definition CLI11.hpp:4946
void clear()
Clear the parsed results (mostly for testing).
Definition CLI11.hpp:4735
CLI11_NODISCARD int get_expected_max() const
The max number of times the option expects to be included.
Definition CLI11.hpp:4948
Option * capture_default_str()
Capture the default value from the original value (if it can be captured).
Definition CLI11.hpp:5132
void results(T &output) const
Get the results as a specified type.
Definition CLI11.hpp:5056
Option * default_str(std::string val)
Set the default value string representation (does not change the contained value).
Definition CLI11.hpp:5140
CLI11_NODISCARD int get_type_size() const
The number of arguments the option expects.
Definition CLI11.hpp:4896
std::string envname_
If given, check the environment for this option.
Definition CLI11.hpp:4617
std::function< std::string()> default_function_
Run this function to capture a default (ignore if empty).
Definition CLI11.hpp:4638
CLI11_NODISCARD bool get_allow_extra_args() const
Get the current value of allow extra args.
Definition CLI11.hpp:4757
Option * ignore_underscore(bool value=true)
Definition CLI11.hpp:5372
std::vector< std::pair< std::string, std::string > > default_flag_values_
Definition CLI11.hpp:4608
std::vector< Validator > validators_
A list of Validators to run on each value parsed.
Definition CLI11.hpp:4656
Option * envname(std::string name)
Sets environment variable to read if no option given.
Definition CLI11.hpp:4864
Option * type_name_fn(std::function< std::string()> typefun)
Set the type function to run when displayed on this option.
Definition CLI11.hpp:5105
Option * default_val(const X &val)
Definition CLI11.hpp:5148
Option * needs(Option *opt)
Sets required options.
Definition CLI11.hpp:4813
int type_size_max_
Definition CLI11.hpp:4646
Option * needs(A opt, B opt1, ARG... args)
Any number supported, any mix of string and Opt.
Definition CLI11.hpp:4832
bool allow_extra_args_
Specify that extra args beyond type_size_max should be allowed.
Definition CLI11.hpp:4692
Option * description(std::string option_description)
Set the description.
Definition CLI11.hpp:4974
Option * transform(Validator Validator, const std::string &Validator_name="")
Adds a transforming Validator with a built in type name.
Definition CLI11.hpp:5263
std::vector< std::string > lnames_
A list of the long names (--long) without the leading dashes.
Definition CLI11.hpp:4603
Option * force_callback(bool value=true)
Set the value of force_callback.
Definition CLI11.hpp:4768
Option * add_result(std::string s)
Puts a result at the end.
Definition CLI11.hpp:5567
bool remove_needs(Option *opt)
Remove needs link from an option. Returns true if the option really was in the needs list.
Definition CLI11.hpp:5313
bool operator==(const Option &other) const
If options share any of the same names, they are equal (not counting positional).
Definition CLI11.hpp:5009
Option * each(const std::function< void(std::string)> &func)
Definition CLI11.hpp:5283
Option * needs(std::string opt_name)
Can find a string if needed.
Definition CLI11.hpp:4822
CLI11_NODISCARD const std::vector< std::string > & get_fnames() const
Get the flag names with specified default values.
Definition CLI11.hpp:4928
CLI11_NODISCARD bool has_description() const
True if option has description.
Definition CLI11.hpp:4968
results_t results_
complete Results of parsing
Definition CLI11.hpp:4679
CLI11_NODISCARD T as() const
Return the results as the specified type.
Definition CLI11.hpp:5089
Option * excludes(A opt, B opt1, ARG... args)
Any number supported, any mix of string and Opt.
Definition CLI11.hpp:4855
Anything that can error in Parse.
Definition CLI11.hpp:769
Produce a range (factory). Min and max are inclusive.
Definition CLI11.hpp:3236
Range(T min_val, T max_val, const std::string &validator_name=std::string{})
Definition CLI11.hpp:3243
Range(T max_val, const std::string &validator_name=std::string{})
Range of one value is 0 to value.
Definition CLI11.hpp:3266
Thrown when a required option is missing.
Definition CLI11.hpp:846
Thrown when a requires option is missing.
Definition CLI11.hpp:919
This is a successful completion on parsing, supposed to exit.
Definition CLI11.hpp:776
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 CLI11.hpp:3601
Transformer(std::initializer_list< std::pair< std::string, std::string > > values, Args &&...args)
This allows in-place construction.
Definition CLI11.hpp:3552
Transformer(T &&mapping)
direct map of std::string to std::string
Definition CLI11.hpp:3557
Transformer(T mapping, F filter_function)
Definition CLI11.hpp:3562
Validate the input as a particular type.
Definition CLI11.hpp:3211
Thrown when validation of results fails.
Definition CLI11.hpp:838
Some validators that are provided.
Definition CLI11.hpp:3015
Validator operator&(const Validator &other) const
Definition CLI11.hpp:3917
CLI11_NODISCARD int get_application_index() const
Get the current value of the application index.
Definition CLI11.hpp:3120
int application_index_
A Validator will only apply to an indexed value (-1 is all elements).
Definition CLI11.hpp:3026
Validator & non_modifying(bool no_modify=true)
Specify whether the Validator can be modifying or not.
Definition CLI11.hpp:3104
Validator & description(std::string validator_desc)
Specify the type string.
Definition CLI11.hpp:3064
std::string operator()(const std::string &str) const
Definition CLI11.hpp:3058
CLI11_NODISCARD Validator application_index(int app_index) const
Specify the application index of a validator.
Definition CLI11.hpp:3114
Validator operator|(const Validator &other) const
Definition CLI11.hpp:3938
CLI11_NODISCARD bool get_active() const
Get a boolean if the validator is active.
Definition CLI11.hpp:3122
bool active_
Enable for Validator to allow it to be disabled if need be.
Definition CLI11.hpp:3028
bool non_modifying_
specify that a validator should not modify the input
Definition CLI11.hpp:3030
Validator(std::string validator_desc)
Construct a Validator with just the description string.
Definition CLI11.hpp:3038
Validator & name(std::string validator_name)
Specify the type string.
Definition CLI11.hpp:3079
std::function< std::string()> desc_function_
This is the description function, if empty the description_ will be used.
Definition CLI11.hpp:3018
std::function< std::string(std::string &)> func_
Definition CLI11.hpp:3022
CLI11_NODISCARD std::string get_description() const
Generate type description information for the Validator.
Definition CLI11.hpp:3072
CLI11_NODISCARD Validator active(bool active_val=true) const
Specify whether the Validator is active or not.
Definition CLI11.hpp:3097
CLI11_NODISCARD const std::string & get_name() const
Get the name of the Validator.
Definition CLI11.hpp:3090
Validator & active(bool active_val=true)
Specify whether the Validator is active or not.
Definition CLI11.hpp:3092
std::string name_
The name for search purposes of the Validator.
Definition CLI11.hpp:3024
CLI11_NODISCARD bool get_modifying() const
Definition CLI11.hpp:3126
CLI11_NODISCARD Validator name(std::string validator_name) const
Specify the type string.
Definition CLI11.hpp:3084
Validator operator!() const
Create a validator that fails when a given validator succeeds.
Definition CLI11.hpp:3959
std::string operator()(std::string &str) const
Definition CLI11.hpp:3898
Validator & application_index(int app_index)
Specify the application index of a validator.
Definition CLI11.hpp:3109
Validator(std::function< std::string(std::string &)> op, std::string validator_desc, std::string validator_name="")
Construct Validator from basic information.
Definition CLI11.hpp:3041
Validator & operation(std::function< std::string(std::string &)> op)
Set the Validator operation function.
Definition CLI11.hpp:3048
Check for an existing directory (returns error message if check fails).
Definition CLI11.hpp:3167
Check for an existing file (returns error message if check fails).
Definition CLI11.hpp:3161
Check for an existing path.
Definition CLI11.hpp:3173
Validate the given string is a legal ipv4 address.
Definition CLI11.hpp:3185
Check for an non-existing path.
Definition CLI11.hpp:3179
Check for complex.
Definition CLI11.hpp:1204
Definition CLI11.hpp:1144
Check for input streamability.
Definition CLI11.hpp:1190
Definition CLI11.hpp:1177
Definition CLI11.hpp:1276
Definition CLI11.hpp:169
std::ostream & operator<<(std::ostream &in, const T &item)
output streaming for enumerations
Definition CLI11.hpp:173
Holds values to load into Options.
Definition CLI11.hpp:2844
std::vector< std::string > inputs
Listing of inputs.
Definition CLI11.hpp:2852
std::string name
This is the name.
Definition CLI11.hpp:2849
CLI11_NODISCARD std::string fullname() const
The list of parents and name joined by ".".
Definition CLI11.hpp:2855
std::vector< std::string > parents
This is the list of parents.
Definition CLI11.hpp:2846
This can be specialized to override the type deduction for IsMember.
Definition CLI11.hpp:1052
This class is simply to allow tests access to App's protected functions.
Definition CLI11.hpp:7227
static auto parse_subcommand(App *app, Args &&...args) -> typename std::result_of< decltype(&App::_parse_subcommand)(App, Args...)>::type
Wrap _parse_subcommand, perfectly forward arguments and return.
Definition CLI11.hpp:7251
static App * get_fallthrough_parent(App *app)
Wrap the fallthrough parent function to make sure that is working correctly.
Definition CLI11.hpp:7257
static auto parse_arg(App *app, Args &&...args) -> typename std::result_of< decltype(&App::_parse_arg)(App, Args...)>::type
Wrap _parse_short, perfectly forward arguments and return.
Definition CLI11.hpp:7244
not a pointer
Definition CLI11.hpp:1071
Definition CLI11.hpp:1083
Definition CLI11.hpp:3364
Definition CLI11.hpp:1232
Definition CLI11.hpp:1253
Definition CLI11.hpp:1267
static auto first(Q &&pair_value) -> decltype(std::get< 0 >(std::forward< Q >(pair_value)))
Get the first value (really just the underlying value).
Definition CLI11.hpp:1121
static auto second(Q &&pair_value) -> decltype(std::get< 1 >(std::forward< Q >(pair_value)))
Get the second value (really just the underlying value).
Definition CLI11.hpp:1126
Definition CLI11.hpp:1090
static auto second(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the second value (really just the underlying value).
Definition CLI11.hpp:1102
static auto first(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the first value (really just the underlying value).
Definition CLI11.hpp:1097
forward declare the subtype_count_min structure
Definition CLI11.hpp:1430
Set of overloads to get the type size of an object.
Definition CLI11.hpp:1426
This will only trigger for actual void type.
Definition CLI11.hpp:1395
This will only trigger for actual void type.
Definition CLI11.hpp:1434
template to get the underlying value type if it exists or use a default
Definition CLI11.hpp:1383
Check to see if something is bool (fail check by default).
Definition CLI11.hpp:1026
Check to see if something is copyable pointer.
Definition CLI11.hpp:1046
Check to see if something is a shared pointer.
Definition CLI11.hpp:1034
A copy of std::void_t from C++17 (helper for C++11 and C++14).
Definition CLI11.hpp:1011