sisi4s
Loading...
Searching...
No Matches
CLI11.hpp
Go to the documentation of this file.
1// CLI11: Version 2.1.2
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.1.2
7//
8// CLI11 2.1.2 Copyright (c) 2017-2021 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 <memory>
38#include <string>
39#include <cmath>
40#include <functional>
41#include <numeric>
42#include <map>
43#include <fstream>
44#include <tuple>
45#include <utility>
46#include <iomanip>
47#include <locale>
48#include <sstream>
49#include <algorithm>
50#include <cstdint>
51#include <iostream>
52#include <set>
53#include <type_traits>
54#include <iterator>
55#include <stdexcept>
56#include <vector>
57#include <limits>
58#include <exception>
59
60
61#define CLI11_VERSION_MAJOR 2
62#define CLI11_VERSION_MINOR 1
63#define CLI11_VERSION_PATCH 2
64#define CLI11_VERSION "2.1.2"
65
66
67
68
69// The following version macro is very similar to the one in pybind11
70#if !(defined(_MSC_VER) && __cplusplus == 199711L) && !defined(__INTEL_COMPILER)
71#if __cplusplus >= 201402L
72#define CLI11_CPP14
73#if __cplusplus >= 201703L
74#define CLI11_CPP17
75#if __cplusplus > 201703L
76#define CLI11_CPP20
77#endif
78#endif
79#endif
80#elif defined(_MSC_VER) && __cplusplus == 199711L
81// MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully implemented)
82// Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 or newer
83#if _MSVC_LANG >= 201402L
84#define CLI11_CPP14
85#if _MSVC_LANG > 201402L && _MSC_VER >= 1910
86#define CLI11_CPP17
87#if __MSVC_LANG > 201703L && _MSC_VER >= 1910
88#define CLI11_CPP20
89#endif
90#endif
91#endif
92#endif
93
94#if defined(CLI11_CPP14)
95#define CLI11_DEPRECATED(reason) [[deprecated(reason)]]
96#elif defined(_MSC_VER)
97#define CLI11_DEPRECATED(reason) __declspec(deprecated(reason))
98#else
99#define CLI11_DEPRECATED(reason) __attribute__((deprecated(reason)))
100#endif
101
102
103
104
105// C standard library
106// Only needed for existence checking
107#if defined CLI11_CPP17 && defined __has_include && !defined CLI11_HAS_FILESYSTEM
108#if __has_include(<filesystem>)
109// Filesystem cannot be used if targeting macOS < 10.15
110#if defined __MAC_OS_X_VERSION_MIN_REQUIRED && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500
111#define CLI11_HAS_FILESYSTEM 0
112#else
113#include <filesystem>
114#if defined __cpp_lib_filesystem && __cpp_lib_filesystem >= 201703
115#if defined _GLIBCXX_RELEASE && _GLIBCXX_RELEASE >= 9
116#define CLI11_HAS_FILESYSTEM 1
117#elif defined(__GLIBCXX__)
118// if we are using gcc and Version <9 default to no filesystem
119#define CLI11_HAS_FILESYSTEM 0
120#else
121#define CLI11_HAS_FILESYSTEM 1
122#endif
123#else
124#define CLI11_HAS_FILESYSTEM 0
125#endif
126#endif
127#endif
128#endif
129
130#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
131#include <filesystem> // NOLINT(build/include)
132#else
133#include <sys/stat.h>
134#include <sys/types.h>
135#endif
136
137
138
139namespace CLI {
140
141
144namespace enums {
145
147template <typename T, typename = typename std::enable_if<std::is_enum<T>::value>::type>
148std::ostream &operator<<(std::ostream &in, const T &item) {
149 // make sure this is out of the detail namespace otherwise it won't be found when needed
150 return in << static_cast<typename std::underlying_type<T>::type>(item);
151}
152
153} // namespace enums
154
156using enums::operator<<;
157
158namespace detail {
161constexpr int expected_max_vector_size{1 << 29};
162// Based on http://stackoverflow.com/questions/236129/split-a-string-in-c
164inline std::vector<std::string> split(const std::string &s, char delim) {
165 std::vector<std::string> elems;
166 // Check to see if empty string, give consistent result
167 if(s.empty()) {
168 elems.emplace_back();
169 } else {
170 std::stringstream ss;
171 ss.str(s);
172 std::string item;
173 while(std::getline(ss, item, delim)) {
174 elems.push_back(item);
175 }
176 }
177 return elems;
178}
179
181template <typename T> std::string join(const T &v, std::string delim = ",") {
182 std::ostringstream s;
183 auto beg = std::begin(v);
184 auto end = std::end(v);
185 if(beg != end)
186 s << *beg++;
187 while(beg != end) {
188 s << delim << *beg++;
189 }
190 return s.str();
191}
192
194template <typename T,
195 typename Callable,
196 typename = typename std::enable_if<!std::is_constructible<std::string, Callable>::value>::type>
197std::string join(const T &v, Callable func, std::string delim = ",") {
198 std::ostringstream s;
199 auto beg = std::begin(v);
200 auto end = std::end(v);
201 auto loc = s.tellp();
202 while(beg != end) {
203 auto nloc = s.tellp();
204 if(nloc > loc) {
205 s << delim;
206 loc = nloc;
207 }
208 s << func(*beg++);
209 }
210 return s.str();
211}
212
214template <typename T> std::string rjoin(const T &v, std::string delim = ",") {
215 std::ostringstream s;
216 for(std::size_t start = 0; start < v.size(); start++) {
217 if(start > 0)
218 s << delim;
219 s << v[v.size() - start - 1];
220 }
221 return s.str();
222}
223
224// Based roughly on http://stackoverflow.com/questions/25829143/c-trim-whitespace-from-a-string
225
227inline std::string &ltrim(std::string &str) {
228 auto it = std::find_if(str.begin(), str.end(), [](char ch) { return !std::isspace<char>(ch, std::locale()); });
229 str.erase(str.begin(), it);
230 return str;
231}
232
234inline std::string &ltrim(std::string &str, const std::string &filter) {
235 auto it = std::find_if(str.begin(), str.end(), [&filter](char ch) { return filter.find(ch) == std::string::npos; });
236 str.erase(str.begin(), it);
237 return str;
238}
239
241inline std::string &rtrim(std::string &str) {
242 auto it = std::find_if(str.rbegin(), str.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale()); });
243 str.erase(it.base(), str.end());
244 return str;
245}
246
248inline std::string &rtrim(std::string &str, const std::string &filter) {
249 auto it =
250 std::find_if(str.rbegin(), str.rend(), [&filter](char ch) { return filter.find(ch) == std::string::npos; });
251 str.erase(it.base(), str.end());
252 return str;
253}
254
256inline std::string &trim(std::string &str) { return ltrim(rtrim(str)); }
257
259inline std::string &trim(std::string &str, const std::string filter) { return ltrim(rtrim(str, filter), filter); }
260
262inline std::string trim_copy(const std::string &str) {
263 std::string s = str;
264 return trim(s);
265}
266
268inline std::string &remove_quotes(std::string &str) {
269 if(str.length() > 1 && (str.front() == '"' || str.front() == '\'')) {
270 if(str.front() == str.back()) {
271 str.pop_back();
272 str.erase(str.begin(), str.begin() + 1);
273 }
274 }
275 return str;
276}
277
282inline std::string fix_newlines(const std::string &leader, std::string input) {
283 std::string::size_type n = 0;
284 while(n != std::string::npos && n < input.size()) {
285 n = input.find('\n', n);
286 if(n != std::string::npos) {
287 input = input.substr(0, n + 1) + leader + input.substr(n + 1);
288 n += leader.size();
289 }
290 }
291 return input;
292}
293
295inline std::string trim_copy(const std::string &str, const std::string &filter) {
296 std::string s = str;
297 return trim(s, filter);
298}
300inline std::ostream &format_help(std::ostream &out, std::string name, const std::string &description, std::size_t wid) {
301 name = " " + name;
302 out << std::setw(static_cast<int>(wid)) << std::left << name;
303 if(!description.empty()) {
304 if(name.length() >= wid)
305 out << "\n" << std::setw(static_cast<int>(wid)) << "";
306 for(const char c : description) {
307 out.put(c);
308 if(c == '\n') {
309 out << std::setw(static_cast<int>(wid)) << "";
310 }
311 }
312 }
313 out << "\n";
314 return out;
315}
316
318inline std::ostream &format_aliases(std::ostream &out, const std::vector<std::string> &aliases, std::size_t wid) {
319 if(!aliases.empty()) {
320 out << std::setw(static_cast<int>(wid)) << " aliases: ";
321 bool front = true;
322 for(const auto &alias : aliases) {
323 if(!front) {
324 out << ", ";
325 } else {
326 front = false;
327 }
328 out << detail::fix_newlines(" ", alias);
329 }
330 out << "\n";
331 }
332 return out;
333}
334
337template <typename T> bool valid_first_char(T c) { return ((c != '-') && (c != '!') && (c != ' ') && c != '\n'); }
338
340template <typename T> bool valid_later_char(T c) {
341 // = and : are value separators, { has special meaning for option defaults,
342 // and \n would just be annoying to deal with in many places allowing space here has too much potential for
343 // inadvertent entry errors and bugs
344 return ((c != '=') && (c != ':') && (c != '{') && (c != ' ') && c != '\n');
345}
346
348inline bool valid_name_string(const std::string &str) {
349 if(str.empty() || !valid_first_char(str[0])) {
350 return false;
351 }
352 auto e = str.end();
353 for(auto c = str.begin() + 1; c != e; ++c)
354 if(!valid_later_char(*c))
355 return false;
356 return true;
357}
358
360inline bool valid_alias_name_string(const std::string &str) {
361 static const std::string badChars(std::string("\n") + '\0');
362 return (str.find_first_of(badChars) == std::string::npos);
363}
364
366inline bool is_separator(const std::string &str) {
367 static const std::string sep("%%");
368 return (str.empty() || str == sep);
369}
370
372inline bool isalpha(const std::string &str) {
373 return std::all_of(str.begin(), str.end(), [](char c) { return std::isalpha(c, std::locale()); });
374}
375
377inline std::string to_lower(std::string str) {
378 std::transform(std::begin(str), std::end(str), std::begin(str), [](const std::string::value_type &x) {
379 return std::tolower(x, std::locale());
380 });
381 return str;
382}
383
385inline std::string remove_underscore(std::string str) {
386 str.erase(std::remove(std::begin(str), std::end(str), '_'), std::end(str));
387 return str;
388}
389
391inline std::string find_and_replace(std::string str, std::string from, std::string to) {
392
393 std::size_t start_pos = 0;
394
395 while((start_pos = str.find(from, start_pos)) != std::string::npos) {
396 str.replace(start_pos, from.length(), to);
397 start_pos += to.length();
398 }
399
400 return str;
401}
402
404inline bool has_default_flag_values(const std::string &flags) {
405 return (flags.find_first_of("{!") != std::string::npos);
406}
407
408inline void remove_default_flag_values(std::string &flags) {
409 auto loc = flags.find_first_of('{', 2);
410 while(loc != std::string::npos) {
411 auto finish = flags.find_first_of("},", loc + 1);
412 if((finish != std::string::npos) && (flags[finish] == '}')) {
413 flags.erase(flags.begin() + static_cast<std::ptrdiff_t>(loc),
414 flags.begin() + static_cast<std::ptrdiff_t>(finish) + 1);
415 }
416 loc = flags.find_first_of('{', loc + 1);
417 }
418 flags.erase(std::remove(flags.begin(), flags.end(), '!'), flags.end());
419}
420
422inline std::ptrdiff_t find_member(std::string name,
423 const std::vector<std::string> names,
424 bool ignore_case = false,
425 bool ignore_underscore = false) {
426 auto it = std::end(names);
427 if(ignore_case) {
430 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
431 return detail::to_lower(detail::remove_underscore(local_name)) == name;
432 });
433 } else {
434 name = detail::to_lower(name);
435 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
436 return detail::to_lower(local_name) == name;
437 });
438 }
439
440 } else if(ignore_underscore) {
441 name = detail::remove_underscore(name);
442 it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
443 return detail::remove_underscore(local_name) == name;
444 });
445 } else {
446 it = std::find(std::begin(names), std::end(names), name);
447 }
448
449 return (it != std::end(names)) ? (it - std::begin(names)) : (-1);
450}
451
454template <typename Callable> inline std::string find_and_modify(std::string str, std::string trigger, Callable modify) {
455 std::size_t start_pos = 0;
456 while((start_pos = str.find(trigger, start_pos)) != std::string::npos) {
457 start_pos = modify(str, start_pos);
458 }
459 return str;
460}
461
464inline std::vector<std::string> split_up(std::string str, char delimiter = '\0') {
465
466 const std::string delims("\'\"`");
467 auto find_ws = [delimiter](char ch) {
468 return (delimiter == '\0') ? (std::isspace<char>(ch, std::locale()) != 0) : (ch == delimiter);
469 };
470 trim(str);
471
472 std::vector<std::string> output;
473 bool embeddedQuote = false;
474 char keyChar = ' ';
475 while(!str.empty()) {
476 if(delims.find_first_of(str[0]) != std::string::npos) {
477 keyChar = str[0];
478 auto end = str.find_first_of(keyChar, 1);
479 while((end != std::string::npos) && (str[end - 1] == '\\')) { // deal with escaped quotes
480 end = str.find_first_of(keyChar, end + 1);
481 embeddedQuote = true;
482 }
483 if(end != std::string::npos) {
484 output.push_back(str.substr(1, end - 1));
485 if(end + 2 < str.size()) {
486 str = str.substr(end + 2);
487 } else {
488 str.clear();
489 }
490
491 } else {
492 output.push_back(str.substr(1));
493 str = "";
494 }
495 } else {
496 auto it = std::find_if(std::begin(str), std::end(str), find_ws);
497 if(it != std::end(str)) {
498 std::string value = std::string(str.begin(), it);
499 output.push_back(value);
500 str = std::string(it + 1, str.end());
501 } else {
502 output.push_back(str);
503 str = "";
504 }
505 }
506 // transform any embedded quotes into the regular character
507 if(embeddedQuote) {
508 output.back() = find_and_replace(output.back(), std::string("\\") + keyChar, std::string(1, keyChar));
509 embeddedQuote = false;
510 }
511 trim(str);
512 }
513 return output;
514}
515
520inline std::size_t escape_detect(std::string &str, std::size_t offset) {
521 auto next = str[offset + 1];
522 if((next == '\"') || (next == '\'') || (next == '`')) {
523 auto astart = str.find_last_of("-/ \"\'`", offset - 1);
524 if(astart != std::string::npos) {
525 if(str[astart] == ((str[offset] == '=') ? '-' : '/'))
526 str[offset] = ' '; // interpret this as a space so the split_up works properly
527 }
528 }
529 return offset + 1;
530}
531
533inline std::string &add_quotes_if_needed(std::string &str) {
534 if((str.front() != '"' && str.front() != '\'') || str.front() != str.back()) {
535 char quote = str.find('"') < str.find('\'') ? '\'' : '"';
536 if(str.find(' ') != std::string::npos) {
537 str.insert(0, 1, quote);
538 str.append(1, quote);
539 }
540 }
541 return str;
542}
543
544} // namespace detail
545
546
547
548
549// Use one of these on all error classes.
550// These are temporary and are undef'd at the end of this file.
551#define CLI11_ERROR_DEF(parent, name) \
552 protected: \
553 name(std::string ename, std::string msg, int exit_code) : parent(std::move(ename), std::move(msg), exit_code) {} \
554 name(std::string ename, std::string msg, ExitCodes exit_code) \
555 : parent(std::move(ename), std::move(msg), exit_code) {} \
556 \
557 public: \
558 name(std::string msg, ExitCodes exit_code) : parent(#name, std::move(msg), exit_code) {} \
559 name(std::string msg, int exit_code) : parent(#name, std::move(msg), exit_code) {}
560
561// This is added after the one above if a class is used directly and builds its own message
562#define CLI11_ERROR_SIMPLE(name) \
563 explicit name(std::string msg) : name(#name, msg, ExitCodes::name) {}
564
567enum class ExitCodes {
568 Success = 0,
572 FileError,
584 BaseClass = 127
585};
586
587// Error definitions
588
594
596class Error : public std::runtime_error {
597 int actual_exit_code;
598 std::string error_name{"Error"};
599
600 public:
601 int get_exit_code() const { return actual_exit_code; }
602
603 std::string get_name() const { return error_name; }
604
605 Error(std::string name, std::string msg, int exit_code = static_cast<int>(ExitCodes::BaseClass))
606 : runtime_error(msg), actual_exit_code(exit_code), error_name(std::move(name)) {}
607
608 Error(std::string name, std::string msg, ExitCodes exit_code) : Error(name, msg, static_cast<int>(exit_code)) {}
609};
610
611// Note: Using Error::Error constructors does not work on GCC 4.7
612
614class ConstructionError : public Error {
616};
617
622 static IncorrectConstruction PositionalFlag(std::string name) {
623 return IncorrectConstruction(name + ": Flags cannot be positional");
624 }
625 static IncorrectConstruction Set0Opt(std::string name) {
626 return IncorrectConstruction(name + ": Cannot set 0 expected, use a flag instead");
627 }
628 static IncorrectConstruction SetFlag(std::string name) {
629 return IncorrectConstruction(name + ": Cannot set an expected number for flags");
630 }
631 static IncorrectConstruction ChangeNotVector(std::string name) {
632 return IncorrectConstruction(name + ": You can only change the expected arguments for vectors");
633 }
634 static IncorrectConstruction AfterMultiOpt(std::string name) {
636 name + ": You can't change expected arguments after you've changed the multi option policy!");
637 }
638 static IncorrectConstruction MissingOption(std::string name) {
639 return IncorrectConstruction("Option " + name + " is not defined");
640 }
641 static IncorrectConstruction MultiOptionPolicy(std::string name) {
642 return IncorrectConstruction(name + ": multi_option_policy only works for flags and exact value options");
643 }
644};
645
650 static BadNameString OneCharName(std::string name) { return BadNameString("Invalid one char name: " + name); }
651 static BadNameString BadLongName(std::string name) { return BadNameString("Bad long name: " + name); }
652 static BadNameString DashesOnly(std::string name) {
653 return BadNameString("Must have a name, not just dashes: " + name);
654 }
655 static BadNameString MultiPositionalNames(std::string name) {
656 return BadNameString("Only one positional name allowed, remove: " + name);
657 }
658};
659
663 explicit OptionAlreadyAdded(std::string name)
664 : OptionAlreadyAdded(name + " is already added", ExitCodes::OptionAlreadyAdded) {}
665 static OptionAlreadyAdded Requires(std::string name, std::string other) {
666 return OptionAlreadyAdded(name + " requires " + other, ExitCodes::OptionAlreadyAdded);
667 }
668 static OptionAlreadyAdded Excludes(std::string name, std::string other) {
669 return OptionAlreadyAdded(name + " excludes " + other, ExitCodes::OptionAlreadyAdded);
670 }
671};
672
673// Parsing errors
674
676class ParseError : public Error {
678};
679
680// Not really "errors"
681
683class Success : public ParseError {
685 Success() : Success("Successfully completed, should be caught and quit", ExitCodes::Success) {}
686};
687
689class CallForHelp : public Success {
691 CallForHelp() : CallForHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
692};
693
695class CallForAllHelp : public Success {
698 : CallForAllHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
699};
700
702class CallForVersion : public Success {
705 : CallForVersion("This should be caught in your main function, see examples", ExitCodes::Success) {}
706};
707
709class RuntimeError : public ParseError {
711 explicit RuntimeError(int exit_code = 1) : RuntimeError("Runtime error", exit_code) {}
712};
713
715class FileError : public ParseError {
718 static FileError Missing(std::string name) { return FileError(name + " was not readable (missing?)"); }
719};
720
725 ConversionError(std::string member, std::string name)
726 : ConversionError("The value " + member + " is not an allowed value for " + name) {}
727 ConversionError(std::string name, std::vector<std::string> results)
728 : ConversionError("Could not convert: " + name + " = " + detail::join(results)) {}
729 static ConversionError TooManyInputsFlag(std::string name) {
730 return ConversionError(name + ": too many inputs for a flag");
731 }
732 static ConversionError TrueFalse(std::string name) {
733 return ConversionError(name + ": Should be true/false or a number");
734 }
735};
736
741 explicit ValidationError(std::string name, std::string msg) : ValidationError(name + ": " + msg) {}
742};
743
745class RequiredError : public ParseError {
747 explicit RequiredError(std::string name) : RequiredError(name + " is required", ExitCodes::RequiredError) {}
748 static RequiredError Subcommand(std::size_t min_subcom) {
749 if(min_subcom == 1) {
750 return RequiredError("A subcommand");
751 }
752 return RequiredError("Requires at least " + std::to_string(min_subcom) + " subcommands",
754 }
755 static RequiredError
756 Option(std::size_t min_option, std::size_t max_option, std::size_t used, const std::string &option_list) {
757 if((min_option == 1) && (max_option == 1) && (used == 0))
758 return RequiredError("Exactly 1 option from [" + option_list + "]");
759 if((min_option == 1) && (max_option == 1) && (used > 1)) {
760 return RequiredError("Exactly 1 option from [" + option_list + "] is required and " + std::to_string(used) +
761 " were given",
763 }
764 if((min_option == 1) && (used == 0))
765 return RequiredError("At least 1 option from [" + option_list + "]");
766 if(used < min_option) {
767 return RequiredError("Requires at least " + std::to_string(min_option) + " options used and only " +
768 std::to_string(used) + "were given from [" + option_list + "]",
770 }
771 if(max_option == 1)
772 return RequiredError("Requires at most 1 options be given from [" + option_list + "]",
774
775 return RequiredError("Requires at most " + std::to_string(max_option) + " options be used and " +
776 std::to_string(used) + "were given from [" + option_list + "]",
778 }
779};
780
785 ArgumentMismatch(std::string name, int expected, std::size_t received)
786 : ArgumentMismatch(expected > 0 ? ("Expected exactly " + std::to_string(expected) + " arguments to " + name +
787 ", got " + std::to_string(received))
788 : ("Expected at least " + std::to_string(-expected) + " arguments to " + name +
789 ", got " + std::to_string(received)),
791
792 static ArgumentMismatch AtLeast(std::string name, int num, std::size_t received) {
793 return ArgumentMismatch(name + ": At least " + std::to_string(num) + " required but received " +
794 std::to_string(received));
795 }
796 static ArgumentMismatch AtMost(std::string name, int num, std::size_t received) {
797 return ArgumentMismatch(name + ": At Most " + std::to_string(num) + " required but received " +
798 std::to_string(received));
799 }
800 static ArgumentMismatch TypedAtLeast(std::string name, int num, std::string type) {
801 return ArgumentMismatch(name + ": " + std::to_string(num) + " required " + type + " missing");
802 }
803 static ArgumentMismatch FlagOverride(std::string name) {
804 return ArgumentMismatch(name + " was given a disallowed flag override");
805 }
806};
807
809class RequiresError : public ParseError {
811 RequiresError(std::string curname, std::string subname)
812 : RequiresError(curname + " requires " + subname, ExitCodes::RequiresError) {}
813};
814
816class ExcludesError : public ParseError {
818 ExcludesError(std::string curname, std::string subname)
819 : ExcludesError(curname + " excludes " + subname, ExitCodes::ExcludesError) {}
820};
821
823class ExtrasError : public ParseError {
825 explicit ExtrasError(std::vector<std::string> args)
826 : ExtrasError((args.size() > 1 ? "The following arguments were not expected: "
827 : "The following argument was not expected: ") +
828 detail::rjoin(args, " "),
830 ExtrasError(const std::string &name, std::vector<std::string> args)
831 : ExtrasError(name,
832 (args.size() > 1 ? "The following arguments were not expected: "
833 : "The following argument was not expected: ") +
834 detail::rjoin(args, " "),
836};
837
839class ConfigError : public ParseError {
842 static ConfigError Extras(std::string item) { return ConfigError("INI was not able to parse " + item); }
843 static ConfigError NotConfigurable(std::string item) {
844 return ConfigError(item + ": This option is not allowed in a configuration file");
845 }
846};
847
849class InvalidError : public ParseError {
851 explicit InvalidError(std::string name)
852 : InvalidError(name + ": Too many positional arguments with unlimited expected args", ExitCodes::InvalidError) {
853 }
854};
855
858class HorribleError : public ParseError {
861};
862
863// After parsing
864
866class OptionNotFound : public Error {
868 explicit OptionNotFound(std::string name) : OptionNotFound(name + " not found", ExitCodes::OptionNotFound) {}
869};
870
871#undef CLI11_ERROR_DEF
872#undef CLI11_ERROR_SIMPLE
873
875
876
877
878
879// Type tools
880
881// Utilities for type enabling
882namespace detail {
883// Based generally on https://rmf.io/cxx11/almost-static-if
885enum class enabler {};
886
888constexpr enabler dummy = {};
889} // namespace detail
890
896template <bool B, class T = void> using enable_if_t = typename std::enable_if<B, T>::type;
897
899template <typename... Ts> struct make_void { using type = void; };
900
902template <typename... Ts> using void_t = typename make_void<Ts...>::type;
903
905template <bool B, class T, class F> using conditional_t = typename std::conditional<B, T, F>::type;
906
908template <typename T> struct is_bool : std::false_type {};
909
911template <> struct is_bool<bool> : std::true_type {};
912
914template <typename T> struct is_shared_ptr : std::false_type {};
915
917template <typename T> struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
918
920template <typename T> struct is_shared_ptr<const std::shared_ptr<T>> : std::true_type {};
921
923template <typename T> struct is_copyable_ptr {
924 static bool const value = is_shared_ptr<T>::value || std::is_pointer<T>::value;
925};
926
928template <typename T> struct IsMemberType { using type = T; };
929
931template <> struct IsMemberType<const char *> { using type = std::string; };
932
933namespace detail {
934
935// These are utilities for IsMember and other transforming objects
936
939
941template <typename T, typename Enable = void> struct element_type { using type = T; };
942
943template <typename T> struct element_type<T, typename std::enable_if<is_copyable_ptr<T>::value>::type> {
944 using type = typename std::pointer_traits<T>::element_type;
945};
946
949template <typename T> struct element_value_type { using type = typename element_type<T>::type::value_type; };
950
952template <typename T, typename _ = void> struct pair_adaptor : std::false_type {
953 using value_type = typename T::value_type;
954 using first_type = typename std::remove_const<value_type>::type;
955 using second_type = typename std::remove_const<value_type>::type;
956
958 template <typename Q> static auto first(Q &&pair_value) -> decltype(std::forward<Q>(pair_value)) {
959 return std::forward<Q>(pair_value);
960 }
962 template <typename Q> static auto second(Q &&pair_value) -> decltype(std::forward<Q>(pair_value)) {
963 return std::forward<Q>(pair_value);
964 }
965};
966
969template <typename T>
971 T,
972 conditional_t<false, void_t<typename T::value_type::first_type, typename T::value_type::second_type>, void>>
973 : std::true_type {
974 using value_type = typename T::value_type;
975 using first_type = typename std::remove_const<typename value_type::first_type>::type;
976 using second_type = typename std::remove_const<typename value_type::second_type>::type;
977
979 template <typename Q> static auto first(Q &&pair_value) -> decltype(std::get<0>(std::forward<Q>(pair_value))) {
980 return std::get<0>(std::forward<Q>(pair_value));
981 }
983 template <typename Q> static auto second(Q &&pair_value) -> decltype(std::get<1>(std::forward<Q>(pair_value))) {
984 return std::get<1>(std::forward<Q>(pair_value));
985 }
986};
987
988// Warning is suppressed due to "bug" in gcc<5.0 and gcc 7.0 with c++17 enabled that generates a Wnarrowing warning
989// in the unevaluated context even if the function that was using this wasn't used. The standard says narrowing in
990// brace initialization shouldn't be allowed but for backwards compatibility gcc allows it in some contexts. It is a
991// little fuzzy what happens in template constructs and I think that was something GCC took a little while to work out.
992// But regardless some versions of gcc generate a warning when they shouldn't from the following code so that should be
993// suppressed
994#ifdef __GNUC__
995#pragma GCC diagnostic push
996#pragma GCC diagnostic ignored "-Wnarrowing"
997#endif
998// check for constructibility from a specific type and copy assignable used in the parse detection
999template <typename T, typename C> class is_direct_constructible {
1000 template <typename TT, typename CC>
1001 static auto test(int, std::true_type) -> decltype(
1002// NVCC warns about narrowing conversions here
1003#ifdef __CUDACC__
1004#pragma diag_suppress 2361
1005#endif
1006 TT { std::declval<CC>() }
1007#ifdef __CUDACC__
1008#pragma diag_default 2361
1009#endif
1010 ,
1011 std::is_move_assignable<TT>());
1012
1013 template <typename TT, typename CC> static auto test(int, std::false_type) -> std::false_type;
1014
1015 template <typename, typename> static auto test(...) -> std::false_type;
1016
1017 public:
1018 static constexpr bool value = decltype(test<T, C>(0, typename std::is_constructible<T, C>::type()))::value;
1019};
1020#ifdef __GNUC__
1021#pragma GCC diagnostic pop
1022#endif
1023
1024// Check for output streamability
1025// Based on https://stackoverflow.com/questions/22758291/how-can-i-detect-if-a-type-can-be-streamed-to-an-stdostream
1026
1027template <typename T, typename S = std::ostringstream> class is_ostreamable {
1028 template <typename TT, typename SS>
1029 static auto test(int) -> decltype(std::declval<SS &>() << std::declval<TT>(), std::true_type());
1030
1031 template <typename, typename> static auto test(...) -> std::false_type;
1032
1033 public:
1034 static constexpr bool value = decltype(test<T, S>(0))::value;
1035};
1036
1038template <typename T, typename S = std::istringstream> class is_istreamable {
1039 template <typename TT, typename SS>
1040 static auto test(int) -> decltype(std::declval<SS &>() >> std::declval<TT &>(), std::true_type());
1041
1042 template <typename, typename> static auto test(...) -> std::false_type;
1043
1044 public:
1045 static constexpr bool value = decltype(test<T, S>(0))::value;
1046};
1047
1049template <typename T> class is_complex {
1050 template <typename TT>
1051 static auto test(int) -> decltype(std::declval<TT>().real(), std::declval<TT>().imag(), std::true_type());
1052
1053 template <typename> static auto test(...) -> std::false_type;
1054
1055 public:
1056 static constexpr bool value = decltype(test<T>(0))::value;
1057};
1058
1060template <typename T, enable_if_t<is_istreamable<T>::value, detail::enabler> = detail::dummy>
1061bool from_stream(const std::string &istring, T &obj) {
1062 std::istringstream is;
1063 is.str(istring);
1064 is >> obj;
1065 return !is.fail() && !is.rdbuf()->in_avail();
1066}
1067
1068template <typename T, enable_if_t<!is_istreamable<T>::value, detail::enabler> = detail::dummy>
1069bool from_stream(const std::string & /*istring*/, T & /*obj*/) {
1070 return false;
1071}
1072
1073// check to see if an object is a mutable container (fail by default)
1074template <typename T, typename _ = void> struct is_mutable_container : std::false_type {};
1075
1079template <typename T>
1081 T,
1082 conditional_t<false,
1083 void_t<typename T::value_type,
1084 decltype(std::declval<T>().end()),
1085 decltype(std::declval<T>().clear()),
1086 decltype(std::declval<T>().insert(std::declval<decltype(std::declval<T>().end())>(),
1087 std::declval<const typename T::value_type &>()))>,
1088 void>>
1089 : public conditional_t<std::is_constructible<T, std::string>::value, std::false_type, std::true_type> {};
1090
1091// check to see if an object is a mutable container (fail by default)
1092template <typename T, typename _ = void> struct is_readable_container : std::false_type {};
1093
1097template <typename T>
1099 T,
1100 conditional_t<false, void_t<decltype(std::declval<T>().end()), decltype(std::declval<T>().begin())>, void>>
1101 : public std::true_type {};
1102
1103// check to see if an object is a wrapper (fail by default)
1104template <typename T, typename _ = void> struct is_wrapper : std::false_type {};
1105
1106// check if an object is a wrapper (it has a value_type defined)
1107template <typename T>
1108struct is_wrapper<T, conditional_t<false, void_t<typename T::value_type>, void>> : public std::true_type {};
1109
1110// Check for tuple like types, as in classes with a tuple_size type trait
1111template <typename S> class is_tuple_like {
1112 template <typename SS>
1113 // static auto test(int)
1114 // -> decltype(std::conditional<(std::tuple_size<SS>::value > 0), std::true_type, std::false_type>::type());
1115 static auto test(int) -> decltype(std::tuple_size<typename std::decay<SS>::type>::value, std::true_type{});
1116 template <typename> static auto test(...) -> std::false_type;
1117
1118 public:
1119 static constexpr bool value = decltype(test<S>(0))::value;
1120};
1121
1123template <typename T, enable_if_t<std::is_convertible<T, std::string>::value, detail::enabler> = detail::dummy>
1124auto to_string(T &&value) -> decltype(std::forward<T>(value)) {
1125 return std::forward<T>(value);
1126}
1127
1129template <typename T,
1130 enable_if_t<std::is_constructible<std::string, T>::value && !std::is_convertible<T, std::string>::value,
1131 detail::enabler> = detail::dummy>
1132std::string to_string(const T &value) {
1133 return std::string(value);
1134}
1135
1137template <typename T,
1138 enable_if_t<!std::is_convertible<std::string, T>::value && !std::is_constructible<std::string, T>::value &&
1139 is_ostreamable<T>::value,
1140 detail::enabler> = detail::dummy>
1141std::string to_string(T &&value) {
1142 std::stringstream stream;
1143 stream << value;
1144 return stream.str();
1145}
1146
1148template <typename T,
1149 enable_if_t<!std::is_constructible<std::string, T>::value && !is_ostreamable<T>::value &&
1150 !is_readable_container<typename std::remove_const<T>::type>::value,
1151 detail::enabler> = detail::dummy>
1152std::string to_string(T &&) {
1153 return std::string{};
1154}
1155
1157template <typename T,
1158 enable_if_t<!std::is_constructible<std::string, T>::value && !is_ostreamable<T>::value &&
1159 is_readable_container<T>::value,
1160 detail::enabler> = detail::dummy>
1161std::string to_string(T &&variable) {
1162 std::vector<std::string> defaults;
1163 auto cval = variable.begin();
1164 auto end = variable.end();
1165 while(cval != end) {
1166 defaults.emplace_back(CLI::detail::to_string(*cval));
1167 ++cval;
1168 }
1169 return std::string("[" + detail::join(defaults) + "]");
1170}
1171
1173template <typename T1,
1174 typename T2,
1175 typename T,
1176 enable_if_t<std::is_same<T1, T2>::value, detail::enabler> = detail::dummy>
1177auto checked_to_string(T &&value) -> decltype(to_string(std::forward<T>(value))) {
1178 return to_string(std::forward<T>(value));
1179}
1180
1182template <typename T1,
1183 typename T2,
1184 typename T,
1186std::string checked_to_string(T &&) {
1187 return std::string{};
1188}
1190template <typename T, enable_if_t<std::is_arithmetic<T>::value, detail::enabler> = detail::dummy>
1191std::string value_string(const T &value) {
1192 return std::to_string(value);
1193}
1195template <typename T, enable_if_t<std::is_enum<T>::value, detail::enabler> = detail::dummy>
1196std::string value_string(const T &value) {
1197 return std::to_string(static_cast<typename std::underlying_type<T>::type>(value));
1198}
1200template <typename T,
1201 enable_if_t<!std::is_enum<T>::value && !std::is_arithmetic<T>::value, detail::enabler> = detail::dummy>
1202auto value_string(const T &value) -> decltype(to_string(value)) {
1203 return to_string(value);
1204}
1205
1207template <typename T, typename def, typename Enable = void> struct wrapped_type { using type = def; };
1208
1210template <typename T, typename def> struct wrapped_type<T, def, typename std::enable_if<is_wrapper<T>::value>::type> {
1211 using type = typename T::value_type;
1212};
1213
1215template <typename T, typename Enable = void> struct type_count_base { static const int value{0}; };
1216
1218template <typename T>
1220 typename std::enable_if<!is_tuple_like<T>::value && !is_mutable_container<T>::value &&
1221 !std::is_void<T>::value>::type> {
1222 static constexpr int value{1};
1223};
1224
1226template <typename T>
1227struct type_count_base<T, typename std::enable_if<is_tuple_like<T>::value && !is_mutable_container<T>::value>::type> {
1228 static constexpr int value{std::tuple_size<T>::value};
1229};
1230
1232template <typename T> struct type_count_base<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1234};
1235
1237
1239template <typename T> struct subtype_count;
1240
1242template <typename T> struct subtype_count_min;
1243
1245template <typename T, typename Enable = void> struct type_count { static const int value{0}; };
1246
1248template <typename T>
1249struct type_count<T,
1250 typename std::enable_if<!is_wrapper<T>::value && !is_tuple_like<T>::value && !is_complex<T>::value &&
1251 !std::is_void<T>::value>::type> {
1252 static constexpr int value{1};
1253};
1254
1256template <typename T> struct type_count<T, typename std::enable_if<is_complex<T>::value>::type> {
1257 static constexpr int value{2};
1258};
1259
1261template <typename T> struct type_count<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1263};
1264
1266template <typename T>
1267struct type_count<T,
1268 typename std::enable_if<is_wrapper<T>::value && !is_complex<T>::value && !is_tuple_like<T>::value &&
1269 !is_mutable_container<T>::value>::type> {
1271};
1272
1274template <typename T, std::size_t I>
1275constexpr typename std::enable_if<I == type_count_base<T>::value, int>::type tuple_type_size() {
1276 return 0;
1277}
1278
1280template <typename T, std::size_t I>
1281 constexpr typename std::enable_if < I<type_count_base<T>::value, int>::type tuple_type_size() {
1282 return subtype_count<typename std::tuple_element<I, T>::type>::value + tuple_type_size<T, I + 1>();
1283}
1284
1286template <typename T> struct type_count<T, typename std::enable_if<is_tuple_like<T>::value>::type> {
1287 static constexpr int value{tuple_type_size<T, 0>()};
1288};
1289
1291template <typename T> struct subtype_count {
1292 static constexpr int value{is_mutable_container<T>::value ? expected_max_vector_size : type_count<T>::value};
1293};
1294
1296template <typename T, typename Enable = void> struct type_count_min { static const int value{0}; };
1297
1299template <typename T>
1300struct type_count_min<
1301 T,
1302 typename std::enable_if<!is_mutable_container<T>::value && !is_tuple_like<T>::value && !is_wrapper<T>::value &&
1303 !is_complex<T>::value && !std::is_void<T>::value>::type> {
1304 static constexpr int value{type_count<T>::value};
1305};
1306
1308template <typename T> struct type_count_min<T, typename std::enable_if<is_complex<T>::value>::type> {
1309 static constexpr int value{1};
1310};
1311
1313template <typename T>
1314struct type_count_min<
1315 T,
1316 typename std::enable_if<is_wrapper<T>::value && !is_complex<T>::value && !is_tuple_like<T>::value>::type> {
1317 static constexpr int value{subtype_count_min<typename T::value_type>::value};
1318};
1319
1321template <typename T, std::size_t I>
1322constexpr typename std::enable_if<I == type_count_base<T>::value, int>::type tuple_type_size_min() {
1323 return 0;
1324}
1325
1327template <typename T, std::size_t I>
1328 constexpr typename std::enable_if < I<type_count_base<T>::value, int>::type tuple_type_size_min() {
1329 return subtype_count_min<typename std::tuple_element<I, T>::type>::value + tuple_type_size_min<T, I + 1>();
1330}
1331
1333template <typename T> struct type_count_min<T, typename std::enable_if<is_tuple_like<T>::value>::type> {
1334 static constexpr int value{tuple_type_size_min<T, 0>()};
1335};
1336
1338template <typename T> struct subtype_count_min {
1339 static constexpr int value{is_mutable_container<T>::value
1340 ? ((type_count<T>::value < expected_max_vector_size) ? type_count<T>::value : 0)
1341 : type_count_min<T>::value};
1342};
1343
1345template <typename T, typename Enable = void> struct expected_count { static const int value{0}; };
1346
1348template <typename T>
1349struct expected_count<T,
1350 typename std::enable_if<!is_mutable_container<T>::value && !is_wrapper<T>::value &&
1351 !std::is_void<T>::value>::type> {
1352 static constexpr int value{1};
1353};
1355template <typename T> struct expected_count<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1356 static constexpr int value{expected_max_vector_size};
1357};
1358
1360template <typename T>
1361struct expected_count<T, typename std::enable_if<!is_mutable_container<T>::value && is_wrapper<T>::value>::type> {
1362 static constexpr int value{expected_count<typename T::value_type>::value};
1363};
1364
1365// Enumeration of the different supported categorizations of objects
1366enum class object_category : int {
1367 char_value = 1,
1368 integral_value = 2,
1369 unsigned_integral = 4,
1370 enumeration = 6,
1371 boolean_value = 8,
1372 floating_point = 10,
1373 number_constructible = 12,
1374 double_constructible = 14,
1375 integer_constructible = 16,
1376 // string like types
1377 string_assignable = 23,
1378 string_constructible = 24,
1379 other = 45,
1380 // special wrapper or container types
1381 wrapper_value = 50,
1382 complex_number = 60,
1383 tuple_value = 70,
1384 container_value = 80,
1385
1386};
1387
1389
1391template <typename T, typename Enable = void> struct classify_object {
1392 static constexpr object_category value{object_category::other};
1393};
1394
1396template <typename T>
1397struct classify_object<
1398 T,
1399 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, char>::value && std::is_signed<T>::value &&
1400 !is_bool<T>::value && !std::is_enum<T>::value>::type> {
1401 static constexpr object_category value{object_category::integral_value};
1402};
1403
1405template <typename T>
1406struct classify_object<T,
1407 typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value &&
1408 !std::is_same<T, char>::value && !is_bool<T>::value>::type> {
1409 static constexpr object_category value{object_category::unsigned_integral};
1410};
1411
1413template <typename T>
1414struct classify_object<T, typename std::enable_if<std::is_same<T, char>::value && !std::is_enum<T>::value>::type> {
1415 static constexpr object_category value{object_category::char_value};
1416};
1417
1419template <typename T> struct classify_object<T, typename std::enable_if<is_bool<T>::value>::type> {
1420 static constexpr object_category value{object_category::boolean_value};
1421};
1422
1424template <typename T> struct classify_object<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
1425 static constexpr object_category value{object_category::floating_point};
1426};
1427
1429template <typename T>
1430struct classify_object<T,
1431 typename std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1432 std::is_assignable<T &, std::string>::value>::type> {
1433 static constexpr object_category value{object_category::string_assignable};
1434};
1435
1437template <typename T>
1438struct classify_object<
1439 T,
1440 typename std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1441 !std::is_assignable<T &, std::string>::value && (type_count<T>::value == 1) &&
1442 std::is_constructible<T, std::string>::value>::type> {
1443 static constexpr object_category value{object_category::string_constructible};
1444};
1445
1447template <typename T> struct classify_object<T, typename std::enable_if<std::is_enum<T>::value>::type> {
1448 static constexpr object_category value{object_category::enumeration};
1449};
1450
1451template <typename T> struct classify_object<T, typename std::enable_if<is_complex<T>::value>::type> {
1452 static constexpr object_category value{object_category::complex_number};
1453};
1454
1457template <typename T> struct uncommon_type {
1458 using type = typename std::conditional<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1459 !std::is_assignable<T &, std::string>::value &&
1460 !std::is_constructible<T, std::string>::value && !is_complex<T>::value &&
1461 !is_mutable_container<T>::value && !std::is_enum<T>::value,
1462 std::true_type,
1463 std::false_type>::type;
1464 static constexpr bool value = type::value;
1465};
1466
1468template <typename T>
1469struct classify_object<T,
1470 typename std::enable_if<(!is_mutable_container<T>::value && is_wrapper<T>::value &&
1471 !is_tuple_like<T>::value && uncommon_type<T>::value)>::type> {
1472 static constexpr object_category value{object_category::wrapper_value};
1473};
1474
1476template <typename T>
1477struct classify_object<T,
1478 typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1479 !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
1480 is_direct_constructible<T, int>::value>::type> {
1481 static constexpr object_category value{object_category::number_constructible};
1482};
1483
1485template <typename T>
1486struct classify_object<T,
1487 typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1488 !is_wrapper<T>::value && !is_direct_constructible<T, double>::value &&
1489 is_direct_constructible<T, int>::value>::type> {
1490 static constexpr object_category value{object_category::integer_constructible};
1491};
1492
1494template <typename T>
1495struct classify_object<T,
1496 typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1497 !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
1498 !is_direct_constructible<T, int>::value>::type> {
1499 static constexpr object_category value{object_category::double_constructible};
1500};
1501
1503template <typename T>
1504struct classify_object<
1505 T,
1506 typename std::enable_if<is_tuple_like<T>::value &&
1507 ((type_count<T>::value >= 2 && !is_wrapper<T>::value) ||
1508 (uncommon_type<T>::value && !is_direct_constructible<T, double>::value &&
1509 !is_direct_constructible<T, int>::value))>::type> {
1510 static constexpr object_category value{object_category::tuple_value};
1511 // the condition on this class requires it be like a tuple, but on some compilers (like Xcode) tuples can be
1512 // constructed from just the first element so tuples of <string, int,int> can be constructed from a string, which
1513 // could lead to issues so there are two variants of the condition, the first isolates things with a type size >=2
1514 // mainly to get tuples on Xcode with the exception of wrappers, the second is the main one and just separating out
1515 // those cases that are caught by other object classifications
1516};
1517
1519template <typename T> struct classify_object<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1520 static constexpr object_category value{object_category::container_value};
1521};
1522
1523// Type name print
1524
1528
1529template <typename T,
1530 enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> = detail::dummy>
1531constexpr const char *type_name() {
1532 return "CHAR";
1533}
1534
1535template <typename T,
1536 enable_if_t<classify_object<T>::value == object_category::integral_value ||
1537 classify_object<T>::value == object_category::integer_constructible,
1538 detail::enabler> = detail::dummy>
1539constexpr const char *type_name() {
1540 return "INT";
1541}
1542
1543template <typename T,
1544 enable_if_t<classify_object<T>::value == object_category::unsigned_integral, detail::enabler> = detail::dummy>
1545constexpr const char *type_name() {
1546 return "UINT";
1547}
1548
1549template <typename T,
1550 enable_if_t<classify_object<T>::value == object_category::floating_point ||
1551 classify_object<T>::value == object_category::number_constructible ||
1552 classify_object<T>::value == object_category::double_constructible,
1553 detail::enabler> = detail::dummy>
1554constexpr const char *type_name() {
1555 return "FLOAT";
1556}
1557
1559template <typename T,
1560 enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> = detail::dummy>
1561constexpr const char *type_name() {
1562 return "ENUM";
1563}
1564
1566template <typename T,
1567 enable_if_t<classify_object<T>::value == object_category::boolean_value, detail::enabler> = detail::dummy>
1568constexpr const char *type_name() {
1569 return "BOOLEAN";
1570}
1571
1573template <typename T,
1574 enable_if_t<classify_object<T>::value == object_category::complex_number, detail::enabler> = detail::dummy>
1575constexpr const char *type_name() {
1576 return "COMPLEX";
1577}
1578
1580template <typename T,
1581 enable_if_t<classify_object<T>::value >= object_category::string_assignable &&
1582 classify_object<T>::value <= object_category::other,
1583 detail::enabler> = detail::dummy>
1584constexpr const char *type_name() {
1585 return "TEXT";
1586}
1588template <typename T,
1589 enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value >= 2,
1590 detail::enabler> = detail::dummy>
1591std::string type_name(); // forward declaration
1592
1594template <typename T,
1595 enable_if_t<classify_object<T>::value == object_category::container_value ||
1596 classify_object<T>::value == object_category::wrapper_value,
1597 detail::enabler> = detail::dummy>
1598std::string type_name(); // forward declaration
1599
1601template <typename T,
1602 enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value == 1,
1603 detail::enabler> = detail::dummy>
1604inline std::string type_name() {
1605 return type_name<typename std::decay<typename std::tuple_element<0, T>::type>::type>();
1606}
1607
1609template <typename T, std::size_t I>
1610inline typename std::enable_if<I == type_count_base<T>::value, std::string>::type tuple_name() {
1611 return std::string{};
1612}
1613
1615template <typename T, std::size_t I>
1616inline typename std::enable_if<(I < type_count_base<T>::value), std::string>::type tuple_name() {
1617 std::string str = std::string(type_name<typename std::decay<typename std::tuple_element<I, T>::type>::type>()) +
1618 ',' + tuple_name<T, I + 1>();
1619 if(str.back() == ',')
1620 str.pop_back();
1621 return str;
1622}
1623
1625template <typename T,
1626 enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value >= 2,
1628inline std::string type_name() {
1629 auto tname = std::string(1, '[') + tuple_name<T, 0>();
1630 tname.push_back(']');
1631 return tname;
1632}
1633
1635template <typename T,
1636 enable_if_t<classify_object<T>::value == object_category::container_value ||
1637 classify_object<T>::value == object_category::wrapper_value,
1639inline std::string type_name() {
1640 return type_name<typename T::value_type>();
1641}
1642
1643// Lexical cast
1644
1646template <typename T, enable_if_t<std::is_unsigned<T>::value, detail::enabler> = detail::dummy>
1647bool integral_conversion(const std::string &input, T &output) noexcept {
1648 if(input.empty()) {
1649 return false;
1650 }
1651 char *val = nullptr;
1652 std::uint64_t output_ll = std::strtoull(input.c_str(), &val, 0);
1653 output = static_cast<T>(output_ll);
1654 return val == (input.c_str() + input.size()) && static_cast<std::uint64_t>(output) == output_ll;
1655}
1656
1658template <typename T, enable_if_t<std::is_signed<T>::value, detail::enabler> = detail::dummy>
1659bool integral_conversion(const std::string &input, T &output) noexcept {
1660 if(input.empty()) {
1661 return false;
1662 }
1663 char *val = nullptr;
1664 std::int64_t output_ll = std::strtoll(input.c_str(), &val, 0);
1665 output = static_cast<T>(output_ll);
1666 return val == (input.c_str() + input.size()) && static_cast<std::int64_t>(output) == output_ll;
1667}
1668
1670inline std::int64_t to_flag_value(std::string val) {
1671 static const std::string trueString("true");
1672 static const std::string falseString("false");
1673 if(val == trueString) {
1674 return 1;
1675 }
1676 if(val == falseString) {
1677 return -1;
1678 }
1679 val = detail::to_lower(val);
1680 std::int64_t ret;
1681 if(val.size() == 1) {
1682 if(val[0] >= '1' && val[0] <= '9') {
1683 return (static_cast<std::int64_t>(val[0]) - '0');
1684 }
1685 switch(val[0]) {
1686 case '0':
1687 case 'f':
1688 case 'n':
1689 case '-':
1690 ret = -1;
1691 break;
1692 case 't':
1693 case 'y':
1694 case '+':
1695 ret = 1;
1696 break;
1697 default:
1698 throw std::invalid_argument("unrecognized character");
1699 }
1700 return ret;
1701 }
1702 if(val == trueString || val == "on" || val == "yes" || val == "enable") {
1703 ret = 1;
1704 } else if(val == falseString || val == "off" || val == "no" || val == "disable") {
1705 ret = -1;
1706 } else {
1707 ret = std::stoll(val);
1708 }
1709 return ret;
1710}
1711
1713template <typename T,
1714 enable_if_t<classify_object<T>::value == object_category::integral_value ||
1715 classify_object<T>::value == object_category::unsigned_integral,
1716 detail::enabler> = detail::dummy>
1717bool lexical_cast(const std::string &input, T &output) {
1718 return integral_conversion(input, output);
1719}
1720
1722template <typename T,
1723 enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> = detail::dummy>
1724bool lexical_cast(const std::string &input, T &output) {
1725 if(input.size() == 1) {
1726 output = static_cast<T>(input[0]);
1727 return true;
1728 }
1729 return integral_conversion(input, output);
1730}
1731
1733template <typename T,
1734 enable_if_t<classify_object<T>::value == object_category::boolean_value, detail::enabler> = detail::dummy>
1735bool lexical_cast(const std::string &input, T &output) {
1736 try {
1737 auto out = to_flag_value(input);
1738 output = (out > 0);
1739 return true;
1740 } catch(const std::invalid_argument &) {
1741 return false;
1742 } catch(const std::out_of_range &) {
1743 // if the number is out of the range of a 64 bit value then it is still a number and for this purpose is still
1744 // valid all we care about the sign
1745 output = (input[0] != '-');
1746 return true;
1747 }
1748}
1749
1751template <typename T,
1752 enable_if_t<classify_object<T>::value == object_category::floating_point, detail::enabler> = detail::dummy>
1753bool lexical_cast(const std::string &input, T &output) {
1754 if(input.empty()) {
1755 return false;
1756 }
1757 char *val = nullptr;
1758 auto output_ld = std::strtold(input.c_str(), &val);
1759 output = static_cast<T>(output_ld);
1760 return val == (input.c_str() + input.size());
1761}
1762
1764template <typename T,
1765 enable_if_t<classify_object<T>::value == object_category::complex_number, detail::enabler> = detail::dummy>
1766bool lexical_cast(const std::string &input, T &output) {
1767 using XC = typename wrapped_type<T, double>::type;
1768 XC x{0.0}, y{0.0};
1769 auto str1 = input;
1770 bool worked = false;
1771 auto nloc = str1.find_last_of("+-");
1772 if(nloc != std::string::npos && nloc > 0) {
1773 worked = detail::lexical_cast(str1.substr(0, nloc), x);
1774 str1 = str1.substr(nloc);
1775 if(str1.back() == 'i' || str1.back() == 'j')
1776 str1.pop_back();
1777 worked = worked && detail::lexical_cast(str1, y);
1778 } else {
1779 if(str1.back() == 'i' || str1.back() == 'j') {
1780 str1.pop_back();
1781 worked = detail::lexical_cast(str1, y);
1782 x = XC{0};
1783 } else {
1784 worked = detail::lexical_cast(str1, x);
1785 y = XC{0};
1786 }
1787 }
1788 if(worked) {
1789 output = T{x, y};
1790 return worked;
1791 }
1792 return from_stream(input, output);
1793}
1794
1796template <typename T,
1797 enable_if_t<classify_object<T>::value == object_category::string_assignable, detail::enabler> = detail::dummy>
1798bool lexical_cast(const std::string &input, T &output) {
1799 output = input;
1800 return true;
1801}
1802
1804template <
1805 typename T,
1806 enable_if_t<classify_object<T>::value == object_category::string_constructible, detail::enabler> = detail::dummy>
1807bool lexical_cast(const std::string &input, T &output) {
1808 output = T(input);
1809 return true;
1810}
1811
1813template <typename T,
1814 enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> = detail::dummy>
1815bool lexical_cast(const std::string &input, T &output) {
1816 typename std::underlying_type<T>::type val;
1817 if(!integral_conversion(input, val)) {
1818 return false;
1819 }
1820 output = static_cast<T>(val);
1821 return true;
1822}
1823
1825template <typename T,
1826 enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
1827 std::is_assignable<T &, typename T::value_type>::value,
1828 detail::enabler> = detail::dummy>
1829bool lexical_cast(const std::string &input, T &output) {
1830 typename T::value_type val;
1831 if(lexical_cast(input, val)) {
1832 output = val;
1833 return true;
1834 }
1835 return from_stream(input, output);
1836}
1837
1838template <typename T,
1839 enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
1840 !std::is_assignable<T &, typename T::value_type>::value && std::is_assignable<T &, T>::value,
1841 detail::enabler> = detail::dummy>
1842bool lexical_cast(const std::string &input, T &output) {
1843 typename T::value_type val;
1844 if(lexical_cast(input, val)) {
1845 output = T{val};
1846 return true;
1847 }
1848 return from_stream(input, output);
1849}
1850
1852template <
1853 typename T,
1854 enable_if_t<classify_object<T>::value == object_category::number_constructible, detail::enabler> = detail::dummy>
1855bool lexical_cast(const std::string &input, T &output) {
1856 int val;
1857 if(integral_conversion(input, val)) {
1858 output = T(val);
1859 return true;
1860 } else {
1861 double dval;
1862 if(lexical_cast(input, dval)) {
1863 output = T{dval};
1864 return true;
1865 }
1866 }
1867 return from_stream(input, output);
1868}
1869
1871template <
1872 typename T,
1873 enable_if_t<classify_object<T>::value == object_category::integer_constructible, detail::enabler> = detail::dummy>
1874bool lexical_cast(const std::string &input, T &output) {
1875 int val;
1876 if(integral_conversion(input, val)) {
1877 output = T(val);
1878 return true;
1879 }
1880 return from_stream(input, output);
1881}
1882
1884template <
1885 typename T,
1886 enable_if_t<classify_object<T>::value == object_category::double_constructible, detail::enabler> = detail::dummy>
1887bool lexical_cast(const std::string &input, T &output) {
1888 double val;
1889 if(lexical_cast(input, val)) {
1890 output = T{val};
1891 return true;
1892 }
1893 return from_stream(input, output);
1894}
1895
1897template <typename T,
1898 enable_if_t<classify_object<T>::value == object_category::other && std::is_assignable<T &, int>::value,
1899 detail::enabler> = detail::dummy>
1900bool lexical_cast(const std::string &input, T &output) {
1901 int val;
1902 if(integral_conversion(input, val)) {
1903#ifdef _MSC_VER
1904#pragma warning(push)
1905#pragma warning(disable : 4800)
1906#endif
1907 // with Atomic<XX> this could produce a warning due to the conversion but if atomic gets here it is an old style
1908 // so will most likely still work
1909 output = val;
1910#ifdef _MSC_VER
1911#pragma warning(pop)
1912#endif
1913 return true;
1914 }
1915 // LCOV_EXCL_START
1916 // This version of cast is only used for odd cases in an older compilers the fail over
1917 // from_stream is tested elsewhere an not relevant for coverage here
1918 return from_stream(input, output);
1919 // LCOV_EXCL_STOP
1920}
1921
1923template <typename T,
1924 enable_if_t<classify_object<T>::value == object_category::other && !std::is_assignable<T &, int>::value,
1925 detail::enabler> = detail::dummy>
1926bool lexical_cast(const std::string &input, T &output) {
1927 static_assert(is_istreamable<T>::value,
1928 "option object type must have a lexical cast overload or streaming input operator(>>) defined, if it "
1929 "is convertible from another type use the add_option<T, XC>(...) with XC being the known type");
1930 return from_stream(input, output);
1931}
1932
1935template <typename AssignTo,
1936 typename ConvertTo,
1937 enable_if_t<std::is_same<AssignTo, ConvertTo>::value &&
1938 (classify_object<AssignTo>::value == object_category::string_assignable ||
1939 classify_object<AssignTo>::value == object_category::string_constructible),
1940 detail::enabler> = detail::dummy>
1941bool lexical_assign(const std::string &input, AssignTo &output) {
1942 return lexical_cast(input, output);
1943}
1944
1946template <typename AssignTo,
1947 typename ConvertTo,
1948 enable_if_t<std::is_same<AssignTo, ConvertTo>::value && std::is_assignable<AssignTo &, AssignTo>::value &&
1949 classify_object<AssignTo>::value != object_category::string_assignable &&
1950 classify_object<AssignTo>::value != object_category::string_constructible,
1951 detail::enabler> = detail::dummy>
1952bool lexical_assign(const std::string &input, AssignTo &output) {
1953 if(input.empty()) {
1954 output = AssignTo{};
1955 return true;
1956 }
1957
1958 return lexical_cast(input, output);
1959}
1960
1962template <typename AssignTo,
1963 typename ConvertTo,
1964 enable_if_t<std::is_same<AssignTo, ConvertTo>::value && !std::is_assignable<AssignTo &, AssignTo>::value &&
1965 classify_object<AssignTo>::value == object_category::wrapper_value,
1966 detail::enabler> = detail::dummy>
1967bool lexical_assign(const std::string &input, AssignTo &output) {
1968 if(input.empty()) {
1969 typename AssignTo::value_type emptyVal{};
1970 output = emptyVal;
1971 return true;
1972 }
1973 return lexical_cast(input, output);
1974}
1975
1978template <typename AssignTo,
1979 typename ConvertTo,
1980 enable_if_t<std::is_same<AssignTo, ConvertTo>::value && !std::is_assignable<AssignTo &, AssignTo>::value &&
1981 classify_object<AssignTo>::value != object_category::wrapper_value &&
1982 std::is_assignable<AssignTo &, int>::value,
1983 detail::enabler> = detail::dummy>
1984bool lexical_assign(const std::string &input, AssignTo &output) {
1985 if(input.empty()) {
1986 output = 0;
1987 return true;
1988 }
1989 int val;
1990 if(lexical_cast(input, val)) {
1991 output = val;
1992 return true;
1993 }
1994 return false;
1995}
1996
1998template <typename AssignTo,
1999 typename ConvertTo,
2000 enable_if_t<!std::is_same<AssignTo, ConvertTo>::value && std::is_assignable<AssignTo &, ConvertTo &>::value,
2001 detail::enabler> = detail::dummy>
2002bool lexical_assign(const std::string &input, AssignTo &output) {
2003 ConvertTo val{};
2004 bool parse_result = (!input.empty()) ? lexical_cast<ConvertTo>(input, val) : true;
2005 if(parse_result) {
2006 output = val;
2007 }
2008 return parse_result;
2009}
2010
2012template <
2013 typename AssignTo,
2014 typename ConvertTo,
2015 enable_if_t<!std::is_same<AssignTo, ConvertTo>::value && !std::is_assignable<AssignTo &, ConvertTo &>::value &&
2016 std::is_move_assignable<AssignTo>::value,
2017 detail::enabler> = detail::dummy>
2018bool lexical_assign(const std::string &input, AssignTo &output) {
2019 ConvertTo val{};
2020 bool parse_result = input.empty() ? true : lexical_cast<ConvertTo>(input, val);
2021 if(parse_result) {
2022 output = AssignTo(val); // use () form of constructor to allow some implicit conversions
2023 }
2024 return parse_result;
2025}
2026
2028template <typename AssignTo,
2029 typename ConvertTo,
2030 enable_if_t<classify_object<ConvertTo>::value <= object_category::other &&
2031 classify_object<AssignTo>::value <= object_category::wrapper_value,
2032 detail::enabler> = detail::dummy>
2033bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2034 return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2035}
2036
2039template <typename AssignTo,
2040 typename ConvertTo,
2041 enable_if_t<(type_count<AssignTo>::value <= 2) && expected_count<AssignTo>::value == 1 &&
2042 is_tuple_like<ConvertTo>::value && type_count_base<ConvertTo>::value == 2,
2043 detail::enabler> = detail::dummy>
2044bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2045 // the remove const is to handle pair types coming from a container
2046 typename std::remove_const<typename std::tuple_element<0, ConvertTo>::type>::type v1;
2047 typename std::tuple_element<1, ConvertTo>::type v2;
2048 bool retval = lexical_assign<decltype(v1), decltype(v1)>(strings[0], v1);
2049 if(strings.size() > 1) {
2050 retval = retval && lexical_assign<decltype(v2), decltype(v2)>(strings[1], v2);
2051 }
2052 if(retval) {
2053 output = AssignTo{v1, v2};
2054 }
2055 return retval;
2056}
2057
2059template <class AssignTo,
2060 class ConvertTo,
2061 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2062 type_count<ConvertTo>::value == 1,
2063 detail::enabler> = detail::dummy>
2064bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2065 output.erase(output.begin(), output.end());
2066 for(const auto &elem : strings) {
2067 typename AssignTo::value_type out;
2068 bool retval = lexical_assign<typename AssignTo::value_type, typename ConvertTo::value_type>(elem, out);
2069 if(!retval) {
2070 return false;
2071 }
2072 output.insert(output.end(), std::move(out));
2073 }
2074 return (!output.empty());
2075}
2076
2078template <class AssignTo, class ConvertTo, enable_if_t<is_complex<ConvertTo>::value, detail::enabler> = detail::dummy>
2079bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2080
2081 if(strings.size() >= 2 && !strings[1].empty()) {
2082 using XC2 = typename wrapped_type<ConvertTo, double>::type;
2083 XC2 x{0.0}, y{0.0};
2084 auto str1 = strings[1];
2085 if(str1.back() == 'i' || str1.back() == 'j') {
2086 str1.pop_back();
2087 }
2088 auto worked = detail::lexical_cast(strings[0], x) && detail::lexical_cast(str1, y);
2089 if(worked) {
2090 output = ConvertTo{x, y};
2091 }
2092 return worked;
2093 } else {
2094 return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2095 }
2096}
2097
2099template <class AssignTo,
2100 class ConvertTo,
2101 enable_if_t<is_mutable_container<AssignTo>::value && (expected_count<ConvertTo>::value == 1) &&
2102 (type_count<ConvertTo>::value == 1),
2103 detail::enabler> = detail::dummy>
2104bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2105 bool retval = true;
2106 output.clear();
2107 output.reserve(strings.size());
2108 for(const auto &elem : strings) {
2109
2110 output.emplace_back();
2111 retval = retval && lexical_assign<typename AssignTo::value_type, ConvertTo>(elem, output.back());
2112 }
2113 return (!output.empty()) && retval;
2114}
2115
2116// forward declaration
2117
2119template <class AssignTo,
2120 class ConvertTo,
2121 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2122 type_count_base<ConvertTo>::value == 2,
2123 detail::enabler> = detail::dummy>
2124bool lexical_conversion(std::vector<std::string> strings, AssignTo &output);
2125
2127template <class AssignTo,
2128 class ConvertTo,
2129 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2130 type_count_base<ConvertTo>::value != 2 &&
2131 ((type_count<ConvertTo>::value > 2) ||
2132 (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
2133 detail::enabler> = detail::dummy>
2134bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output);
2135
2137template <class AssignTo,
2138 class ConvertTo,
2139 enable_if_t<is_tuple_like<AssignTo>::value && is_tuple_like<ConvertTo>::value &&
2140 (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2141 type_count<ConvertTo>::value > 2),
2142 detail::enabler> = detail::dummy>
2143bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output); // forward declaration
2144
2147template <typename AssignTo,
2148 typename ConvertTo,
2149 enable_if_t<!is_tuple_like<AssignTo>::value && !is_mutable_container<AssignTo>::value &&
2150 classify_object<ConvertTo>::value != object_category::wrapper_value &&
2151 (is_mutable_container<ConvertTo>::value || type_count<ConvertTo>::value > 2),
2152 detail::enabler> = detail::dummy>
2153bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2154
2155 if(strings.size() > 1 || (!strings.empty() && !(strings.front().empty()))) {
2156 ConvertTo val;
2157 auto retval = lexical_conversion<ConvertTo, ConvertTo>(strings, val);
2158 output = AssignTo{val};
2159 return retval;
2160 }
2161 output = AssignTo{};
2162 return true;
2163}
2164
2166template <class AssignTo, class ConvertTo, std::size_t I>
2167inline typename std::enable_if<(I >= type_count_base<AssignTo>::value), bool>::type
2168tuple_conversion(const std::vector<std::string> &, AssignTo &) {
2169 return true;
2170}
2171
2173template <class AssignTo, class ConvertTo>
2174inline typename std::enable_if<!is_mutable_container<ConvertTo>::value && type_count<ConvertTo>::value == 1, bool>::type
2175tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2176 auto retval = lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2177 strings.erase(strings.begin());
2178 return retval;
2179}
2180
2182template <class AssignTo, class ConvertTo>
2183inline typename std::enable_if<!is_mutable_container<ConvertTo>::value && (type_count<ConvertTo>::value > 1) &&
2184 type_count<ConvertTo>::value == type_count_min<ConvertTo>::value,
2185 bool>::type
2186tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2187 auto retval = lexical_conversion<AssignTo, ConvertTo>(strings, output);
2188 strings.erase(strings.begin(), strings.begin() + type_count<ConvertTo>::value);
2189 return retval;
2190}
2191
2193template <class AssignTo, class ConvertTo>
2194inline typename std::enable_if<is_mutable_container<ConvertTo>::value ||
2195 type_count<ConvertTo>::value != type_count_min<ConvertTo>::value,
2196 bool>::type
2197tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2198
2199 std::size_t index{subtype_count_min<ConvertTo>::value};
2200 const std::size_t mx_count{subtype_count<ConvertTo>::value};
2201 const std::size_t mx{(std::max)(mx_count, strings.size())};
2202
2203 while(index < mx) {
2204 if(is_separator(strings[index])) {
2205 break;
2206 }
2207 ++index;
2208 }
2209 bool retval = lexical_conversion<AssignTo, ConvertTo>(
2210 std::vector<std::string>(strings.begin(), strings.begin() + static_cast<std::ptrdiff_t>(index)), output);
2211 strings.erase(strings.begin(), strings.begin() + static_cast<std::ptrdiff_t>(index) + 1);
2212 return retval;
2213}
2214
2216template <class AssignTo, class ConvertTo, std::size_t I>
2217inline typename std::enable_if<(I < type_count_base<AssignTo>::value), bool>::type
2218tuple_conversion(std::vector<std::string> strings, AssignTo &output) {
2219 bool retval = true;
2220 using ConvertToElement = typename std::
2221 conditional<is_tuple_like<ConvertTo>::value, typename std::tuple_element<I, ConvertTo>::type, ConvertTo>::type;
2222 if(!strings.empty()) {
2223 retval = retval && tuple_type_conversion<typename std::tuple_element<I, AssignTo>::type, ConvertToElement>(
2224 strings, std::get<I>(output));
2225 }
2226 retval = retval && tuple_conversion<AssignTo, ConvertTo, I + 1>(std::move(strings), output);
2227 return retval;
2228}
2229
2231template <class AssignTo,
2232 class ConvertTo,
2233 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2234 type_count_base<ConvertTo>::value == 2,
2235 detail::enabler>>
2236bool lexical_conversion(std::vector<std::string> strings, AssignTo &output) {
2237 output.clear();
2238 while(!strings.empty()) {
2239
2240 typename std::remove_const<typename std::tuple_element<0, typename ConvertTo::value_type>::type>::type v1;
2241 typename std::tuple_element<1, typename ConvertTo::value_type>::type v2;
2242 bool retval = tuple_type_conversion<decltype(v1), decltype(v1)>(strings, v1);
2243 if(!strings.empty()) {
2244 retval = retval && tuple_type_conversion<decltype(v2), decltype(v2)>(strings, v2);
2245 }
2246 if(retval) {
2247 output.insert(output.end(), typename AssignTo::value_type{v1, v2});
2248 } else {
2249 return false;
2250 }
2251 }
2252 return (!output.empty());
2253}
2254
2256template <class AssignTo,
2257 class ConvertTo,
2258 enable_if_t<is_tuple_like<AssignTo>::value && is_tuple_like<ConvertTo>::value &&
2259 (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2260 type_count<ConvertTo>::value > 2),
2261 detail::enabler>>
2262bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2263 static_assert(
2264 !is_tuple_like<ConvertTo>::value || type_count_base<AssignTo>::value == type_count_base<ConvertTo>::value,
2265 "if the conversion type is defined as a tuple it must be the same size as the type you are converting to");
2266 return tuple_conversion<AssignTo, ConvertTo, 0>(strings, output);
2267}
2268
2270template <class AssignTo,
2271 class ConvertTo,
2272 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2273 type_count_base<ConvertTo>::value != 2 &&
2274 ((type_count<ConvertTo>::value > 2) ||
2275 (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
2276 detail::enabler>>
2277bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2278 bool retval = true;
2279 output.clear();
2280 std::vector<std::string> temp;
2281 std::size_t ii{0};
2282 std::size_t icount{0};
2283 std::size_t xcm{type_count<ConvertTo>::value};
2284 auto ii_max = strings.size();
2285 while(ii < ii_max) {
2286 temp.push_back(strings[ii]);
2287 ++ii;
2288 ++icount;
2289 if(icount == xcm || is_separator(temp.back()) || ii == ii_max) {
2290 if(static_cast<int>(xcm) > type_count_min<ConvertTo>::value && is_separator(temp.back())) {
2291 temp.pop_back();
2292 }
2293 typename AssignTo::value_type temp_out;
2294 retval = retval &&
2295 lexical_conversion<typename AssignTo::value_type, typename ConvertTo::value_type>(temp, temp_out);
2296 temp.clear();
2297 if(!retval) {
2298 return false;
2299 }
2300 output.insert(output.end(), std::move(temp_out));
2301 icount = 0;
2302 }
2303 }
2304 return retval;
2305}
2306
2308template <typename AssignTo,
2309 class ConvertTo,
2310 enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2311 std::is_assignable<ConvertTo &, ConvertTo>::value,
2312 detail::enabler> = detail::dummy>
2313bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2314 if(strings.empty() || strings.front().empty()) {
2315 output = ConvertTo{};
2316 return true;
2317 }
2318 typename ConvertTo::value_type val;
2319 if(lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings, val)) {
2320 output = ConvertTo{val};
2321 return true;
2322 }
2323 return false;
2324}
2325
2327template <typename AssignTo,
2328 class ConvertTo,
2329 enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2330 !std::is_assignable<AssignTo &, ConvertTo>::value,
2331 detail::enabler> = detail::dummy>
2332bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2333 using ConvertType = typename ConvertTo::value_type;
2334 if(strings.empty() || strings.front().empty()) {
2335 output = ConvertType{};
2336 return true;
2337 }
2338 ConvertType val;
2339 if(lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings, val)) {
2340 output = val;
2341 return true;
2342 }
2343 return false;
2344}
2345
2351template <typename T, enable_if_t<std::is_unsigned<T>::value, detail::enabler> = detail::dummy>
2352void sum_flag_vector(const std::vector<std::string> &flags, T &output) {
2353 std::int64_t count{0};
2354 for(auto &flag : flags) {
2355 count += detail::to_flag_value(flag);
2356 }
2357 output = (count > 0) ? static_cast<T>(count) : T{0};
2358}
2359
2365template <typename T, enable_if_t<std::is_signed<T>::value, detail::enabler> = detail::dummy>
2366void sum_flag_vector(const std::vector<std::string> &flags, T &output) {
2367 std::int64_t count{0};
2368 for(auto &flag : flags) {
2369 count += detail::to_flag_value(flag);
2370 }
2371 output = static_cast<T>(count);
2372}
2373
2374#ifdef _MSC_VER
2375#pragma warning(push)
2376#pragma warning(disable : 4800)
2377#endif
2378// with Atomic<XX> this could produce a warning due to the conversion but if atomic gets here it is an old style so will
2379// most likely still work
2380
2386template <typename T,
2387 enable_if_t<!std::is_signed<T>::value && !std::is_unsigned<T>::value, detail::enabler> = detail::dummy>
2388void sum_flag_vector(const std::vector<std::string> &flags, T &output) {
2389 std::int64_t count{0};
2390 for(auto &flag : flags) {
2391 count += detail::to_flag_value(flag);
2392 }
2393 std::string out = detail::to_string(count);
2394 lexical_cast(out, output);
2395}
2396
2397#ifdef _MSC_VER
2398#pragma warning(pop)
2399#endif
2400
2401} // namespace detail
2402
2403
2404
2405namespace detail {
2406
2407// Returns false if not a short option. Otherwise, sets opt name and rest and returns true
2408inline bool split_short(const std::string &current, std::string &name, std::string &rest) {
2409 if(current.size() > 1 && current[0] == '-' && valid_first_char(current[1])) {
2410 name = current.substr(1, 1);
2411 rest = current.substr(2);
2412 return true;
2413 }
2414 return false;
2415}
2416
2417// Returns false if not a long option. Otherwise, sets opt name and other side of = and returns true
2418inline bool split_long(const std::string &current, std::string &name, std::string &value) {
2419 if(current.size() > 2 && current.substr(0, 2) == "--" && valid_first_char(current[2])) {
2420 auto loc = current.find_first_of('=');
2421 if(loc != std::string::npos) {
2422 name = current.substr(2, loc - 2);
2423 value = current.substr(loc + 1);
2424 } else {
2425 name = current.substr(2);
2426 value = "";
2427 }
2428 return true;
2429 }
2430 return false;
2431}
2432
2433// Returns false if not a windows style option. Otherwise, sets opt name and value and returns true
2434inline bool split_windows_style(const std::string &current, std::string &name, std::string &value) {
2435 if(current.size() > 1 && current[0] == '/' && valid_first_char(current[1])) {
2436 auto loc = current.find_first_of(':');
2437 if(loc != std::string::npos) {
2438 name = current.substr(1, loc - 1);
2439 value = current.substr(loc + 1);
2440 } else {
2441 name = current.substr(1);
2442 value = "";
2443 }
2444 return true;
2445 }
2446 return false;
2447}
2448
2449// Splits a string into multiple long and short names
2450inline std::vector<std::string> split_names(std::string current) {
2451 std::vector<std::string> output;
2452 std::size_t val;
2453 while((val = current.find(",")) != std::string::npos) {
2454 output.push_back(trim_copy(current.substr(0, val)));
2455 current = current.substr(val + 1);
2456 }
2457 output.push_back(trim_copy(current));
2458 return output;
2459}
2460
2462inline std::vector<std::pair<std::string, std::string>> get_default_flag_values(const std::string &str) {
2463 std::vector<std::string> flags = split_names(str);
2464 flags.erase(std::remove_if(flags.begin(),
2465 flags.end(),
2466 [](const std::string &name) {
2467 return ((name.empty()) || (!(((name.find_first_of('{') != std::string::npos) &&
2468 (name.back() == '}')) ||
2469 (name[0] == '!'))));
2470 }),
2471 flags.end());
2472 std::vector<std::pair<std::string, std::string>> output;
2473 output.reserve(flags.size());
2474 for(auto &flag : flags) {
2475 auto def_start = flag.find_first_of('{');
2476 std::string defval = "false";
2477 if((def_start != std::string::npos) && (flag.back() == '}')) {
2478 defval = flag.substr(def_start + 1);
2479 defval.pop_back();
2480 flag.erase(def_start, std::string::npos);
2481 }
2482 flag.erase(0, flag.find_first_not_of("-!"));
2483 output.emplace_back(flag, defval);
2484 }
2485 return output;
2486}
2487
2489inline std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>
2490get_names(const std::vector<std::string> &input) {
2491
2492 std::vector<std::string> short_names;
2493 std::vector<std::string> long_names;
2494 std::string pos_name;
2495
2496 for(std::string name : input) {
2497 if(name.length() == 0) {
2498 continue;
2499 }
2500 if(name.length() > 1 && name[0] == '-' && name[1] != '-') {
2501 if(name.length() == 2 && valid_first_char(name[1]))
2502 short_names.emplace_back(1, name[1]);
2503 else
2504 throw BadNameString::OneCharName(name);
2505 } else if(name.length() > 2 && name.substr(0, 2) == "--") {
2506 name = name.substr(2);
2507 if(valid_name_string(name))
2508 long_names.push_back(name);
2509 else
2510 throw BadNameString::BadLongName(name);
2511 } else if(name == "-" || name == "--") {
2512 throw BadNameString::DashesOnly(name);
2513 } else {
2514 if(pos_name.length() > 0)
2515 throw BadNameString::MultiPositionalNames(name);
2516 pos_name = name;
2517 }
2518 }
2519
2520 return std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>(
2521 short_names, long_names, pos_name);
2522}
2523
2524} // namespace detail
2525
2526
2527
2528class App;
2529
2533 std::vector<std::string> parents{};
2534
2536 std::string name{};
2537
2539 std::vector<std::string> inputs{};
2540
2542 std::string fullname() const {
2543 std::vector<std::string> tmp = parents;
2544 tmp.emplace_back(name);
2545 return detail::join(tmp, ".");
2546 }
2547};
2548
2550class Config {
2551 protected:
2552 std::vector<ConfigItem> items{};
2553
2554 public:
2556 virtual std::string to_config(const App *, bool, bool, std::string) const = 0;
2557
2559 virtual std::vector<ConfigItem> from_config(std::istream &) const = 0;
2560
2562 virtual std::string to_flag(const ConfigItem &item) const {
2563 if(item.inputs.size() == 1) {
2564 return item.inputs.at(0);
2565 }
2566 throw ConversionError::TooManyInputsFlag(item.fullname());
2567 }
2568
2570 std::vector<ConfigItem> from_file(const std::string &name) {
2571 std::ifstream input{name};
2572 if(!input.good())
2573 throw FileError::Missing(name);
2574
2575 return from_config(input);
2576 }
2577
2579 virtual ~Config() = default;
2580};
2581
2583class ConfigBase : public Config {
2584 protected:
2586 char commentChar = '#';
2588 char arrayStart = '[';
2590 char arrayEnd = ']';
2592 char arraySeparator = ',';
2594 char valueDelimiter = '=';
2596 char stringQuote = '"';
2598 char characterQuote = '\'';
2600 uint8_t maximumLayers{255};
2602 char parentSeparatorChar{'.'};
2604 int16_t configIndex{-1};
2606 std::string configSection{};
2607
2608 public:
2609 std::string
2610 to_config(const App * /*app*/, bool default_also, bool write_description, std::string prefix) const override;
2611
2612 std::vector<ConfigItem> from_config(std::istream &input) const override;
2614 ConfigBase *comment(char cchar) {
2615 commentChar = cchar;
2616 return this;
2617 }
2619 ConfigBase *arrayBounds(char aStart, char aEnd) {
2620 arrayStart = aStart;
2621 arrayEnd = aEnd;
2622 return this;
2623 }
2626 arraySeparator = aSep;
2627 return this;
2628 }
2631 valueDelimiter = vSep;
2632 return this;
2633 }
2635 ConfigBase *quoteCharacter(char qString, char qChar) {
2636 stringQuote = qString;
2637 characterQuote = qChar;
2638 return this;
2639 }
2641 ConfigBase *maxLayers(uint8_t layers) {
2642 maximumLayers = layers;
2643 return this;
2644 }
2647 parentSeparatorChar = sep;
2648 return this;
2649 }
2651 std::string &sectionRef() { return configSection; }
2653 const std::string &section() const { return configSection; }
2655 ConfigBase *section(const std::string &sectionName) {
2656 configSection = sectionName;
2657 return this;
2658 }
2659
2661 int16_t &indexRef() { return configIndex; }
2663 int16_t index() const { return configIndex; }
2665 ConfigBase *index(int16_t sectionIndex) {
2666 configIndex = sectionIndex;
2667 return this;
2668 }
2669};
2670
2673
2675class ConfigINI : public ConfigTOML {
2676
2677 public:
2679 commentChar = ';';
2680 arrayStart = '\0';
2681 arrayEnd = '\0';
2682 arraySeparator = ' ';
2683 valueDelimiter = '=';
2684 }
2685};
2686
2687
2688
2689class Option;
2690
2692
2699
2702 protected:
2704 std::function<std::string()> desc_function_{[]() { return std::string{}; }};
2705
2708 std::function<std::string(std::string &)> func_{[](std::string &) { return std::string{}; }};
2710 std::string name_{};
2712 int application_index_ = -1;
2714 bool active_{true};
2716 bool non_modifying_{false};
2717
2718 public:
2719 Validator() = default;
2721 explicit Validator(std::string validator_desc) : desc_function_([validator_desc]() { return validator_desc; }) {}
2723 Validator(std::function<std::string(std::string &)> op, std::string validator_desc, std::string validator_name = "")
2724 : desc_function_([validator_desc]() { return validator_desc; }), func_(std::move(op)),
2725 name_(std::move(validator_name)) {}
2727 Validator &operation(std::function<std::string(std::string &)> op) {
2728 func_ = std::move(op);
2729 return *this;
2730 }
2733 std::string operator()(std::string &str) const {
2734 std::string retstring;
2735 if(active_) {
2736 if(non_modifying_) {
2737 std::string value = str;
2738 retstring = func_(value);
2739 } else {
2740 retstring = func_(str);
2741 }
2742 }
2743 return retstring;
2744 }
2745
2748 std::string operator()(const std::string &str) const {
2749 std::string value = str;
2750 return (active_) ? func_(value) : std::string{};
2751 }
2752
2754 Validator &description(std::string validator_desc) {
2755 desc_function_ = [validator_desc]() { return validator_desc; };
2756 return *this;
2757 }
2759 Validator description(std::string validator_desc) const {
2760 Validator newval(*this);
2761 newval.desc_function_ = [validator_desc]() { return validator_desc; };
2762 return newval;
2763 }
2765 std::string get_description() const {
2766 if(active_) {
2767 return desc_function_();
2768 }
2769 return std::string{};
2770 }
2772 Validator &name(std::string validator_name) {
2773 name_ = std::move(validator_name);
2774 return *this;
2775 }
2777 Validator name(std::string validator_name) const {
2778 Validator newval(*this);
2779 newval.name_ = std::move(validator_name);
2780 return newval;
2781 }
2783 const std::string &get_name() const { return name_; }
2785 Validator &active(bool active_val = true) {
2786 active_ = active_val;
2787 return *this;
2788 }
2790 Validator active(bool active_val = true) const {
2791 Validator newval(*this);
2792 newval.active_ = active_val;
2793 return newval;
2794 }
2795
2797 Validator &non_modifying(bool no_modify = true) {
2798 non_modifying_ = no_modify;
2799 return *this;
2800 }
2803 application_index_ = app_index;
2804 return *this;
2805 }
2807 Validator application_index(int app_index) const {
2808 Validator newval(*this);
2809 newval.application_index_ = app_index;
2810 return newval;
2811 }
2813 int get_application_index() const { return application_index_; }
2815 bool get_active() const { return active_; }
2816
2818 bool get_modifying() const { return !non_modifying_; }
2819
2822 Validator operator&(const Validator &other) const {
2823 Validator newval;
2824
2825 newval._merge_description(*this, other, " AND ");
2826
2827 // Give references (will make a copy in lambda function)
2828 const std::function<std::string(std::string & filename)> &f1 = func_;
2829 const std::function<std::string(std::string & filename)> &f2 = other.func_;
2830
2831 newval.func_ = [f1, f2](std::string &input) {
2832 std::string s1 = f1(input);
2833 std::string s2 = f2(input);
2834 if(!s1.empty() && !s2.empty())
2835 return std::string("(") + s1 + ") AND (" + s2 + ")";
2836 else
2837 return s1 + s2;
2838 };
2839
2840 newval.active_ = (active_ & other.active_);
2841 newval.application_index_ = application_index_;
2842 return newval;
2843 }
2844
2847 Validator operator|(const Validator &other) const {
2848 Validator newval;
2849
2850 newval._merge_description(*this, other, " OR ");
2851
2852 // Give references (will make a copy in lambda function)
2853 const std::function<std::string(std::string &)> &f1 = func_;
2854 const std::function<std::string(std::string &)> &f2 = other.func_;
2855
2856 newval.func_ = [f1, f2](std::string &input) {
2857 std::string s1 = f1(input);
2858 std::string s2 = f2(input);
2859 if(s1.empty() || s2.empty())
2860 return std::string();
2861
2862 return std::string("(") + s1 + ") OR (" + s2 + ")";
2863 };
2864 newval.active_ = (active_ & other.active_);
2865 newval.application_index_ = application_index_;
2866 return newval;
2867 }
2868
2871 Validator newval;
2872 const std::function<std::string()> &dfunc1 = desc_function_;
2873 newval.desc_function_ = [dfunc1]() {
2874 auto str = dfunc1();
2875 return (!str.empty()) ? std::string("NOT ") + str : std::string{};
2876 };
2877 // Give references (will make a copy in lambda function)
2878 const std::function<std::string(std::string & res)> &f1 = func_;
2879
2880 newval.func_ = [f1, dfunc1](std::string &test) -> std::string {
2881 std::string s1 = f1(test);
2882 if(s1.empty()) {
2883 return std::string("check ") + dfunc1() + " succeeded improperly";
2884 }
2885 return std::string{};
2886 };
2887 newval.active_ = active_;
2888 newval.application_index_ = application_index_;
2889 return newval;
2890 }
2891
2892 private:
2893 void _merge_description(const Validator &val1, const Validator &val2, const std::string &merger) {
2894
2895 const std::function<std::string()> &dfunc1 = val1.desc_function_;
2896 const std::function<std::string()> &dfunc2 = val2.desc_function_;
2897
2898 desc_function_ = [=]() {
2899 std::string f1 = dfunc1();
2900 std::string f2 = dfunc2();
2901 if((f1.empty()) || (f2.empty())) {
2902 return f1 + f2;
2903 }
2904 return std::string(1, '(') + f1 + ')' + merger + '(' + f2 + ')';
2905 };
2906 }
2907}; // namespace CLI
2908
2911 public:
2912};
2913// The implementation of the built in validators is using the Validator class;
2914// the user is only expected to use the const (static) versions (since there's no setup).
2915// Therefore, this is in detail.
2916namespace detail {
2917
2920
2921#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
2923inline path_type check_path(const char *file) noexcept {
2924 std::error_code ec;
2925 auto stat = std::filesystem::status(file, ec);
2926 if(ec) {
2927 return path_type::nonexistent;
2928 }
2929 switch(stat.type()) {
2930 case std::filesystem::file_type::none:
2931 case std::filesystem::file_type::not_found:
2932 return path_type::nonexistent;
2933 case std::filesystem::file_type::directory:
2934 return path_type::directory;
2935 case std::filesystem::file_type::symlink:
2936 case std::filesystem::file_type::block:
2937 case std::filesystem::file_type::character:
2938 case std::filesystem::file_type::fifo:
2939 case std::filesystem::file_type::socket:
2940 case std::filesystem::file_type::regular:
2941 case std::filesystem::file_type::unknown:
2942 default:
2943 return path_type::file;
2944 }
2945}
2946#else
2948inline path_type check_path(const char *file) noexcept {
2949#if defined(_MSC_VER)
2950 struct __stat64 buffer;
2951 if(_stat64(file, &buffer) == 0) {
2952 return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
2953 }
2954#else
2955 struct stat buffer;
2956 if(stat(file, &buffer) == 0) {
2957 return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
2958 }
2959#endif
2960 return path_type::nonexistent;
2961}
2962#endif
2965 public:
2967 func_ = [](std::string &filename) {
2968 auto path_result = check_path(filename.c_str());
2969 if(path_result == path_type::nonexistent) {
2970 return "File does not exist: " + filename;
2971 }
2972 if(path_result == path_type::directory) {
2973 return "File is actually a directory: " + filename;
2974 }
2975 return std::string();
2976 };
2977 }
2978};
2979
2982 public:
2984 func_ = [](std::string &filename) {
2985 auto path_result = check_path(filename.c_str());
2986 if(path_result == path_type::nonexistent) {
2987 return "Directory does not exist: " + filename;
2988 }
2989 if(path_result == path_type::file) {
2990 return "Directory is actually a file: " + filename;
2991 }
2992 return std::string();
2993 };
2994 }
2995};
2996
2999 public:
3000 ExistingPathValidator() : Validator("PATH(existing)") {
3001 func_ = [](std::string &filename) {
3002 auto path_result = check_path(filename.c_str());
3003 if(path_result == path_type::nonexistent) {
3004 return "Path does not exist: " + filename;
3005 }
3006 return std::string();
3007 };
3008 }
3009};
3010
3013 public:
3014 NonexistentPathValidator() : Validator("PATH(non-existing)") {
3015 func_ = [](std::string &filename) {
3016 auto path_result = check_path(filename.c_str());
3017 if(path_result != path_type::nonexistent) {
3018 return "Path already exists: " + filename;
3019 }
3020 return std::string();
3021 };
3022 }
3023};
3024
3026class IPV4Validator : public Validator {
3027 public:
3029 func_ = [](std::string &ip_addr) {
3030 auto result = CLI::detail::split(ip_addr, '.');
3031 if(result.size() != 4) {
3032 return std::string("Invalid IPV4 address must have four parts (") + ip_addr + ')';
3033 }
3034 int num;
3035 for(const auto &var : result) {
3036 bool retval = detail::lexical_cast(var, num);
3037 if(!retval) {
3038 return std::string("Failed parsing number (") + var + ')';
3039 }
3040 if(num < 0 || num > 255) {
3041 return std::string("Each IP number must be between 0 and 255 ") + var;
3042 }
3043 }
3044 return std::string();
3045 };
3046 }
3047};
3048
3049} // namespace detail
3050
3051// Static is not needed here, because global const implies static.
3052
3055
3058
3061
3064
3067
3069template <typename DesiredType> class TypeValidator : public Validator {
3070 public:
3071 explicit TypeValidator(const std::string &validator_name) : Validator(validator_name) {
3072 func_ = [](std::string &input_string) {
3073 auto val = DesiredType();
3074 if(!detail::lexical_cast(input_string, val)) {
3075 return std::string("Failed parsing ") + input_string + " as a " + detail::type_name<DesiredType>();
3076 }
3077 return std::string();
3078 };
3079 }
3080 TypeValidator() : TypeValidator(detail::type_name<DesiredType>()) {}
3081};
3082
3085
3087class Range : public Validator {
3088 public:
3093 template <typename T>
3094 Range(T min_val, T max_val, const std::string &validator_name = std::string{}) : Validator(validator_name) {
3095 if(validator_name.empty()) {
3096 std::stringstream out;
3097 out << detail::type_name<T>() << " in [" << min_val << " - " << max_val << "]";
3098 description(out.str());
3099 }
3100
3101 func_ = [min_val, max_val](std::string &input) {
3102 T val;
3103 bool converted = detail::lexical_cast(input, val);
3104 if((!converted) || (val < min_val || val > max_val))
3105 return std::string("Value ") + input + " not in range " + std::to_string(min_val) + " to " +
3106 std::to_string(max_val);
3107
3108 return std::string{};
3109 };
3110 }
3111
3113 template <typename T>
3114 explicit Range(T max_val, const std::string &validator_name = std::string{})
3115 : Range(static_cast<T>(0), max_val, validator_name) {}
3116};
3117
3119const Range NonNegativeNumber((std::numeric_limits<double>::max)(), "NONNEGATIVE");
3120
3122const Range PositiveNumber((std::numeric_limits<double>::min)(), (std::numeric_limits<double>::max)(), "POSITIVE");
3123
3125class Bound : public Validator {
3126 public:
3131 template <typename T> Bound(T min_val, T max_val) {
3132 std::stringstream out;
3133 out << detail::type_name<T>() << " bounded to [" << min_val << " - " << max_val << "]";
3134 description(out.str());
3135
3136 func_ = [min_val, max_val](std::string &input) {
3137 T val;
3138 bool converted = detail::lexical_cast(input, val);
3139 if(!converted) {
3140 return std::string("Value ") + input + " could not be converted";
3141 }
3142 if(val < min_val)
3143 input = detail::to_string(min_val);
3144 else if(val > max_val)
3145 input = detail::to_string(max_val);
3146
3147 return std::string{};
3148 };
3149 }
3150
3152 template <typename T> explicit Bound(T max_val) : Bound(static_cast<T>(0), max_val) {}
3153};
3154
3155namespace detail {
3156template <typename T,
3157 enable_if_t<is_copyable_ptr<typename std::remove_reference<T>::type>::value, detail::enabler> = detail::dummy>
3158auto smart_deref(T value) -> decltype(*value) {
3159 return *value;
3160}
3161
3162template <
3163 typename T,
3165typename std::remove_reference<T>::type &smart_deref(T &value) {
3166 return value;
3167}
3169template <typename T> std::string generate_set(const T &set) {
3170 using element_t = typename detail::element_type<T>::type;
3171 using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3172 std::string out(1, '{');
3173 out.append(detail::join(
3174 detail::smart_deref(set),
3175 [](const iteration_type_t &v) { return detail::pair_adaptor<element_t>::first(v); },
3176 ","));
3177 out.push_back('}');
3178 return out;
3179}
3180
3182template <typename T> std::string generate_map(const T &map, bool key_only = false) {
3183 using element_t = typename detail::element_type<T>::type;
3184 using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3185 std::string out(1, '{');
3186 out.append(detail::join(
3187 detail::smart_deref(map),
3188 [key_only](const iteration_type_t &v) {
3189 std::string res{detail::to_string(detail::pair_adaptor<element_t>::first(v))};
3190
3191 if(!key_only) {
3192 res.append("->");
3193 res += detail::to_string(detail::pair_adaptor<element_t>::second(v));
3194 }
3195 return res;
3196 },
3197 ","));
3198 out.push_back('}');
3199 return out;
3200}
3201
3202template <typename C, typename V> struct has_find {
3203 template <typename CC, typename VV>
3204 static auto test(int) -> decltype(std::declval<CC>().find(std::declval<VV>()), std::true_type());
3205 template <typename, typename> static auto test(...) -> decltype(std::false_type());
3206
3207 static const auto value = decltype(test<C, V>(0))::value;
3208 using type = std::integral_constant<bool, value>;
3209};
3210
3212template <typename T, typename V, enable_if_t<!has_find<T, V>::value, detail::enabler> = detail::dummy>
3213auto search(const T &set, const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3214 using element_t = typename detail::element_type<T>::type;
3215 auto &setref = detail::smart_deref(set);
3216 auto it = std::find_if(std::begin(setref), std::end(setref), [&val](decltype(*std::begin(setref)) v) {
3217 return (detail::pair_adaptor<element_t>::first(v) == val);
3218 });
3219 return {(it != std::end(setref)), it};
3220}
3221
3223template <typename T, typename V, enable_if_t<has_find<T, V>::value, detail::enabler> = detail::dummy>
3224auto search(const T &set, const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3225 auto &setref = detail::smart_deref(set);
3226 auto it = setref.find(val);
3227 return {(it != std::end(setref)), it};
3228}
3229
3231template <typename T, typename V>
3232auto search(const T &set, const V &val, const std::function<V(V)> &filter_function)
3233 -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3234 using element_t = typename detail::element_type<T>::type;
3235 // do the potentially faster first search
3236 auto res = search(set, val);
3237 if((res.first) || (!(filter_function))) {
3238 return res;
3239 }
3240 // if we haven't found it do the longer linear search with all the element translations
3241 auto &setref = detail::smart_deref(set);
3242 auto it = std::find_if(std::begin(setref), std::end(setref), [&](decltype(*std::begin(setref)) v) {
3244 a = filter_function(a);
3245 return (a == val);
3246 });
3247 return {(it != std::end(setref)), it};
3248}
3249
3250// the following suggestion was made by Nikita Ofitserov(@himikof)
3251// done in templates to prevent compiler warnings on negation of unsigned numbers
3252
3254template <typename T>
3255inline typename std::enable_if<std::is_signed<T>::value, T>::type overflowCheck(const T &a, const T &b) {
3256 if((a > 0) == (b > 0)) {
3257 return ((std::numeric_limits<T>::max)() / (std::abs)(a) < (std::abs)(b));
3258 } else {
3259 return ((std::numeric_limits<T>::min)() / (std::abs)(a) > -(std::abs)(b));
3260 }
3261}
3263template <typename T>
3264inline typename std::enable_if<!std::is_signed<T>::value, T>::type overflowCheck(const T &a, const T &b) {
3265 return ((std::numeric_limits<T>::max)() / a < b);
3266}
3267
3269template <typename T> typename std::enable_if<std::is_integral<T>::value, bool>::type checked_multiply(T &a, T b) {
3270 if(a == 0 || b == 0 || a == 1 || b == 1) {
3271 a *= b;
3272 return true;
3273 }
3274 if(a == (std::numeric_limits<T>::min)() || b == (std::numeric_limits<T>::min)()) {
3275 return false;
3276 }
3277 if(overflowCheck(a, b)) {
3278 return false;
3279 }
3280 a *= b;
3281 return true;
3282}
3283
3285template <typename T>
3286typename std::enable_if<std::is_floating_point<T>::value, bool>::type checked_multiply(T &a, T b) {
3287 T c = a * b;
3288 if(std::isinf(c) && !std::isinf(a) && !std::isinf(b)) {
3289 return false;
3290 }
3291 a = c;
3292 return true;
3293}
3294
3295} // namespace detail
3297class IsMember : public Validator {
3298 public:
3299 using filter_fn_t = std::function<std::string(std::string)>;
3300
3302 template <typename T, typename... Args>
3303 IsMember(std::initializer_list<T> values, Args &&...args)
3304 : IsMember(std::vector<T>(values), std::forward<Args>(args)...) {}
3305
3307 template <typename T> explicit IsMember(T &&set) : IsMember(std::forward<T>(set), nullptr) {}
3308
3311 template <typename T, typename F> explicit IsMember(T set, F filter_function) {
3312
3313 // Get the type of the contained item - requires a container have ::value_type
3314 // if the type does not have first_type and second_type, these are both value_type
3315 using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3316 using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3317
3318 using local_item_t = typename IsMemberType<item_t>::type; // This will convert bad types to good ones
3319 // (const char * to std::string)
3320
3321 // Make a local copy of the filter function, using a std::function if not one already
3322 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3323
3324 // This is the type name for help, it will take the current version of the set contents
3325 desc_function_ = [set]() { return detail::generate_set(detail::smart_deref(set)); };
3326
3327 // This is the function that validates
3328 // It stores a copy of the set pointer-like, so shared_ptr will stay alive
3329 func_ = [set, filter_fn](std::string &input) {
3330 local_item_t b;
3331 if(!detail::lexical_cast(input, b)) {
3332 throw ValidationError(input); // name is added later
3333 }
3334 if(filter_fn) {
3335 b = filter_fn(b);
3336 }
3337 auto res = detail::search(set, b, filter_fn);
3338 if(res.first) {
3339 // Make sure the version in the input string is identical to the one in the set
3340 if(filter_fn) {
3341 input = detail::value_string(detail::pair_adaptor<element_t>::first(*(res.second)));
3342 }
3343
3344 // Return empty error string (success)
3345 return std::string{};
3346 }
3347
3348 // If you reach this point, the result was not found
3349 return input + " not in " + detail::generate_set(detail::smart_deref(set));
3350 };
3351 }
3352
3354 template <typename T, typename... Args>
3355 IsMember(T &&set, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3356 : IsMember(
3357 std::forward<T>(set),
3358 [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3359 other...) {}
3360};
3361
3363template <typename T> using TransformPairs = std::vector<std::pair<std::string, T>>;
3364
3366class Transformer : public Validator {
3367 public:
3368 using filter_fn_t = std::function<std::string(std::string)>;
3369
3371 template <typename... Args>
3372 Transformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
3373 : Transformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
3374
3376 template <typename T> explicit Transformer(T &&mapping) : Transformer(std::forward<T>(mapping), nullptr) {}
3377
3380 template <typename T, typename F> explicit Transformer(T mapping, F filter_function) {
3381
3383 "mapping must produce value pairs");
3384 // Get the type of the contained item - requires a container have ::value_type
3385 // if the type does not have first_type and second_type, these are both value_type
3386 using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3387 using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3388 using local_item_t = typename IsMemberType<item_t>::type; // Will convert bad types to good ones
3389 // (const char * to std::string)
3390
3391 // Make a local copy of the filter function, using a std::function if not one already
3392 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3393
3394 // This is the type name for help, it will take the current version of the set contents
3395 desc_function_ = [mapping]() { return detail::generate_map(detail::smart_deref(mapping)); };
3396
3397 func_ = [mapping, filter_fn](std::string &input) {
3398 local_item_t b;
3399 if(!detail::lexical_cast(input, b)) {
3400 return std::string();
3401 // there is no possible way we can match anything in the mapping if we can't convert so just return
3402 }
3403 if(filter_fn) {
3404 b = filter_fn(b);
3405 }
3406 auto res = detail::search(mapping, b, filter_fn);
3407 if(res.first) {
3408 input = detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
3409 }
3410 return std::string{};
3411 };
3412 }
3413
3415 template <typename T, typename... Args>
3416 Transformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3417 : Transformer(
3418 std::forward<T>(mapping),
3419 [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3420 other...) {}
3421};
3422
3425 public:
3426 using filter_fn_t = std::function<std::string(std::string)>;
3427
3429 template <typename... Args>
3430 CheckedTransformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
3431 : CheckedTransformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
3432
3434 template <typename T> explicit CheckedTransformer(T mapping) : CheckedTransformer(std::move(mapping), nullptr) {}
3435
3438 template <typename T, typename F> explicit CheckedTransformer(T mapping, F filter_function) {
3439
3441 "mapping must produce value pairs");
3442 // Get the type of the contained item - requires a container have ::value_type
3443 // if the type does not have first_type and second_type, these are both value_type
3444 using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3445 using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3446 using local_item_t = typename IsMemberType<item_t>::type; // Will convert bad types to good ones
3447 // (const char * to std::string)
3448 using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3449
3450 // Make a local copy of the filter function, using a std::function if not one already
3451 std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3452
3453 auto tfunc = [mapping]() {
3454 std::string out("value in ");
3455 out += detail::generate_map(detail::smart_deref(mapping)) + " OR {";
3456 out += detail::join(
3457 detail::smart_deref(mapping),
3458 [](const iteration_type_t &v) { return detail::to_string(detail::pair_adaptor<element_t>::second(v)); },
3459 ",");
3460 out.push_back('}');
3461 return out;
3462 };
3463
3464 desc_function_ = tfunc;
3465
3466 func_ = [mapping, tfunc, filter_fn](std::string &input) {
3467 local_item_t b;
3468 bool converted = detail::lexical_cast(input, b);
3469 if(converted) {
3470 if(filter_fn) {
3471 b = filter_fn(b);
3472 }
3473 auto res = detail::search(mapping, b, filter_fn);
3474 if(res.first) {
3475 input = detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
3476 return std::string{};
3477 }
3478 }
3479 for(const auto &v : detail::smart_deref(mapping)) {
3480 auto output_string = detail::value_string(detail::pair_adaptor<element_t>::second(v));
3481 if(output_string == input) {
3482 return std::string();
3483 }
3484 }
3485
3486 return "Check " + input + " " + tfunc() + " FAILED";
3487 };
3488 }
3489
3491 template <typename T, typename... Args>
3492 CheckedTransformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3494 std::forward<T>(mapping),
3495 [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3496 other...) {}
3497};
3498
3500inline std::string ignore_case(std::string item) { return detail::to_lower(item); }
3501
3503inline std::string ignore_underscore(std::string item) { return detail::remove_underscore(item); }
3504
3506inline std::string ignore_space(std::string item) {
3507 item.erase(std::remove(std::begin(item), std::end(item), ' '), std::end(item));
3508 item.erase(std::remove(std::begin(item), std::end(item), '\t'), std::end(item));
3509 return item;
3510}
3511
3524 public:
3529 enum Options {
3530 CASE_SENSITIVE = 0,
3531 CASE_INSENSITIVE = 1,
3532 UNIT_OPTIONAL = 0,
3533 UNIT_REQUIRED = 2,
3534 DEFAULT = CASE_INSENSITIVE | UNIT_OPTIONAL
3536
3537 template <typename Number>
3538 explicit AsNumberWithUnit(std::map<std::string, Number> mapping,
3539 Options opts = DEFAULT,
3540 const std::string &unit_name = "UNIT") {
3541 description(generate_description<Number>(unit_name, opts));
3542 validate_mapping(mapping, opts);
3543
3544 // transform function
3545 func_ = [mapping, opts](std::string &input) -> std::string {
3546 Number num;
3547
3548 detail::rtrim(input);
3549 if(input.empty()) {
3550 throw ValidationError("Input is empty");
3551 }
3552
3553 // Find split position between number and prefix
3554 auto unit_begin = input.end();
3555 while(unit_begin > input.begin() && std::isalpha(*(unit_begin - 1), std::locale())) {
3556 --unit_begin;
3557 }
3558
3559 std::string unit{unit_begin, input.end()};
3560 input.resize(static_cast<std::size_t>(std::distance(input.begin(), unit_begin)));
3561 detail::trim(input);
3562
3563 if(opts & UNIT_REQUIRED && unit.empty()) {
3564 throw ValidationError("Missing mandatory unit");
3565 }
3566 if(opts & CASE_INSENSITIVE) {
3567 unit = detail::to_lower(unit);
3568 }
3569 if(unit.empty()) {
3570 if(!detail::lexical_cast(input, num)) {
3571 throw ValidationError(std::string("Value ") + input + " could not be converted to " +
3572 detail::type_name<Number>());
3573 }
3574 // No need to modify input if no unit passed
3575 return {};
3576 }
3577
3578 // find corresponding factor
3579 auto it = mapping.find(unit);
3580 if(it == mapping.end()) {
3581 throw ValidationError(unit +
3582 " unit not recognized. "
3583 "Allowed values: " +
3584 detail::generate_map(mapping, true));
3585 }
3586
3587 if(!input.empty()) {
3588 bool converted = detail::lexical_cast(input, num);
3589 if(!converted) {
3590 throw ValidationError(std::string("Value ") + input + " could not be converted to " +
3591 detail::type_name<Number>());
3592 }
3593 // perform safe multiplication
3594 bool ok = detail::checked_multiply(num, it->second);
3595 if(!ok) {
3596 throw ValidationError(detail::to_string(num) + " multiplied by " + unit +
3597 " factor would cause number overflow. Use smaller value.");
3598 }
3599 } else {
3600 num = static_cast<Number>(it->second);
3601 }
3602
3603 input = detail::to_string(num);
3604
3605 return {};
3606 };
3607 }
3608
3609 private:
3612 template <typename Number> static void validate_mapping(std::map<std::string, Number> &mapping, Options opts) {
3613 for(auto &kv : mapping) {
3614 if(kv.first.empty()) {
3615 throw ValidationError("Unit must not be empty.");
3616 }
3617 if(!detail::isalpha(kv.first)) {
3618 throw ValidationError("Unit must contain only letters.");
3619 }
3620 }
3621
3622 // make all units lowercase if CASE_INSENSITIVE
3623 if(opts & CASE_INSENSITIVE) {
3624 std::map<std::string, Number> lower_mapping;
3625 for(auto &kv : mapping) {
3626 auto s = detail::to_lower(kv.first);
3627 if(lower_mapping.count(s)) {
3628 throw ValidationError(std::string("Several matching lowercase unit representations are found: ") +
3629 s);
3630 }
3631 lower_mapping[detail::to_lower(kv.first)] = kv.second;
3632 }
3633 mapping = std::move(lower_mapping);
3634 }
3635 }
3636
3638 template <typename Number> static std::string generate_description(const std::string &name, Options opts) {
3639 std::stringstream out;
3640 out << detail::type_name<Number>() << ' ';
3641 if(opts & UNIT_REQUIRED) {
3642 out << name;
3643 } else {
3644 out << '[' << name << ']';
3645 }
3646 return out.str();
3647 }
3648};
3649
3662 public:
3663 using result_t = std::uint64_t;
3664
3672 explicit AsSizeValue(bool kb_is_1000) : AsNumberWithUnit(get_mapping(kb_is_1000)) {
3673 if(kb_is_1000) {
3674 description("SIZE [b, kb(=1000b), kib(=1024b), ...]");
3675 } else {
3676 description("SIZE [b, kb(=1024b), ...]");
3677 }
3678 }
3679
3680 private:
3682 static std::map<std::string, result_t> init_mapping(bool kb_is_1000) {
3683 std::map<std::string, result_t> m;
3684 result_t k_factor = kb_is_1000 ? 1000 : 1024;
3685 result_t ki_factor = 1024;
3686 result_t k = 1;
3687 result_t ki = 1;
3688 m["b"] = 1;
3689 for(std::string p : {"k", "m", "g", "t", "p", "e"}) {
3690 k *= k_factor;
3691 ki *= ki_factor;
3692 m[p] = k;
3693 m[p + "b"] = k;
3694 m[p + "i"] = ki;
3695 m[p + "ib"] = ki;
3696 }
3697 return m;
3698 }
3699
3701 static std::map<std::string, result_t> get_mapping(bool kb_is_1000) {
3702 if(kb_is_1000) {
3703 static auto m = init_mapping(true);
3704 return m;
3705 } else {
3706 static auto m = init_mapping(false);
3707 return m;
3708 }
3709 }
3710};
3711
3712namespace detail {
3717inline std::pair<std::string, std::string> split_program_name(std::string commandline) {
3718 // try to determine the programName
3719 std::pair<std::string, std::string> vals;
3720 trim(commandline);
3721 auto esp = commandline.find_first_of(' ', 1);
3722 while(detail::check_path(commandline.substr(0, esp).c_str()) != path_type::file) {
3723 esp = commandline.find_first_of(' ', esp + 1);
3724 if(esp == std::string::npos) {
3725 // if we have reached the end and haven't found a valid file just assume the first argument is the
3726 // program name
3727 if(commandline[0] == '"' || commandline[0] == '\'' || commandline[0] == '`') {
3728 bool embeddedQuote = false;
3729 auto keyChar = commandline[0];
3730 auto end = commandline.find_first_of(keyChar, 1);
3731 while((end != std::string::npos) && (commandline[end - 1] == '\\')) { // deal with escaped quotes
3732 end = commandline.find_first_of(keyChar, end + 1);
3733 embeddedQuote = true;
3734 }
3735 if(end != std::string::npos) {
3736 vals.first = commandline.substr(1, end - 1);
3737 esp = end + 1;
3738 if(embeddedQuote) {
3739 vals.first = find_and_replace(vals.first, std::string("\\") + keyChar, std::string(1, keyChar));
3740 }
3741 } else {
3742 esp = commandline.find_first_of(' ', 1);
3743 }
3744 } else {
3745 esp = commandline.find_first_of(' ', 1);
3746 }
3747
3748 break;
3749 }
3750 }
3751 if(vals.first.empty()) {
3752 vals.first = commandline.substr(0, esp);
3753 rtrim(vals.first);
3754 }
3755
3756 // strip the program name
3757 vals.second = (esp != std::string::npos) ? commandline.substr(esp + 1) : std::string{};
3758 ltrim(vals.second);
3759 return vals;
3760}
3761
3762} // namespace detail
3764
3765
3766
3767
3768class Option;
3769class App;
3770
3775
3776enum class AppFormatMode {
3777 Normal,
3778 All,
3779 Sub,
3780};
3781
3787 protected:
3790
3792 std::size_t column_width_{30};
3793
3796 std::map<std::string, std::string> labels_{};
3797
3801
3802 public:
3803 FormatterBase() = default;
3804 FormatterBase(const FormatterBase &) = default;
3806
3808 virtual ~FormatterBase() noexcept {} // NOLINT(modernize-use-equals-default)
3809
3811 virtual std::string make_help(const App *, std::string, AppFormatMode) const = 0;
3812
3816
3818 void label(std::string key, std::string val) { labels_[key] = val; }
3819
3821 void column_width(std::size_t val) { column_width_ = val; }
3822
3826
3828 std::string get_label(std::string key) const {
3829 if(labels_.find(key) == labels_.end())
3830 return key;
3831 else
3832 return labels_.at(key);
3833 }
3834
3836 std::size_t get_column_width() const { return column_width_; }
3837
3839};
3840
3842class FormatterLambda final : public FormatterBase {
3843 using funct_t = std::function<std::string(const App *, std::string, AppFormatMode)>;
3844
3846 funct_t lambda_;
3847
3848 public:
3850 explicit FormatterLambda(funct_t funct) : lambda_(std::move(funct)) {}
3851
3853 ~FormatterLambda() noexcept override {} // NOLINT(modernize-use-equals-default)
3854
3856 std::string make_help(const App *app, std::string name, AppFormatMode mode) const override {
3857 return lambda_(app, name, mode);
3858 }
3859};
3860
3863class Formatter : public FormatterBase {
3864 public:
3865 Formatter() = default;
3866 Formatter(const Formatter &) = default;
3867 Formatter(Formatter &&) = default;
3868
3871
3874 virtual std::string make_group(std::string group, bool is_positional, std::vector<const Option *> opts) const;
3875
3877 virtual std::string make_positionals(const App *app) const;
3878
3880 std::string make_groups(const App *app, AppFormatMode mode) const;
3881
3883 virtual std::string make_subcommands(const App *app, AppFormatMode mode) const;
3884
3886 virtual std::string make_subcommand(const App *sub) const;
3887
3889 virtual std::string make_expanded(const App *sub) const;
3890
3892 virtual std::string make_footer(const App *app) const;
3893
3895 virtual std::string make_description(const App *app) const;
3896
3898 virtual std::string make_usage(const App *app, std::string name) const;
3899
3901 std::string make_help(const App * /*app*/, std::string, AppFormatMode) const override;
3902
3906
3908 virtual std::string make_option(const Option *opt, bool is_positional) const {
3909 std::stringstream out;
3910 detail::format_help(
3911 out, make_option_name(opt, is_positional) + make_option_opts(opt), make_option_desc(opt), column_width_);
3912 return out.str();
3913 }
3914
3916 virtual std::string make_option_name(const Option *, bool) const;
3917
3919 virtual std::string make_option_opts(const Option *) const;
3920
3922 virtual std::string make_option_desc(const Option *) const;
3923
3925 virtual std::string make_option_usage(const Option *opt) const;
3926
3928};
3929
3930
3931
3932
3933using results_t = std::vector<std::string>;
3935using callback_t = std::function<bool(const results_t &)>;
3936
3937class Option;
3938class App;
3939
3940using Option_p = std::unique_ptr<Option>;
3942enum class MultiOptionPolicy : char {
3943 Throw,
3944 TakeLast,
3945 TakeFirst,
3946 Join,
3947 TakeAll
3948};
3949
3952template <typename CRTP> class OptionBase {
3953 friend App;
3954
3955 protected:
3957 std::string group_ = std::string("Options");
3958
3960 bool required_{false};
3961
3963 bool ignore_case_{false};
3964
3966 bool ignore_underscore_{false};
3967
3969 bool configurable_{true};
3970
3972 bool disable_flag_override_{false};
3973
3975 char delimiter_{'\0'};
3976
3978 bool always_capture_default_{false};
3979
3981 MultiOptionPolicy multi_option_policy_{MultiOptionPolicy::Throw};
3982
3984 template <typename T> void copy_to(T *other) const {
3985 other->group(group_);
3986 other->required(required_);
3987 other->ignore_case(ignore_case_);
3988 other->ignore_underscore(ignore_underscore_);
3989 other->configurable(configurable_);
3990 other->disable_flag_override(disable_flag_override_);
3991 other->delimiter(delimiter_);
3992 other->always_capture_default(always_capture_default_);
3993 other->multi_option_policy(multi_option_policy_);
3994 }
3995
3996 public:
3997 // setters
3998
4000 CRTP *group(const std::string &name) {
4001 if(!detail::valid_alias_name_string(name)) {
4002 throw IncorrectConstruction("Group names may not contain newlines or null characters");
4003 }
4004 group_ = name;
4005 return static_cast<CRTP *>(this);
4006 }
4007
4009 CRTP *required(bool value = true) {
4010 required_ = value;
4011 return static_cast<CRTP *>(this);
4012 }
4013
4015 CRTP *mandatory(bool value = true) { return required(value); }
4016
4017 CRTP *always_capture_default(bool value = true) {
4018 always_capture_default_ = value;
4019 return static_cast<CRTP *>(this);
4020 }
4021
4022 // Getters
4023
4025 const std::string &get_group() const { return group_; }
4026
4028 bool get_required() const { return required_; }
4029
4031 bool get_ignore_case() const { return ignore_case_; }
4032
4034 bool get_ignore_underscore() const { return ignore_underscore_; }
4035
4037 bool get_configurable() const { return configurable_; }
4038
4040 bool get_disable_flag_override() const { return disable_flag_override_; }
4041
4043 char get_delimiter() const { return delimiter_; }
4044
4046 bool get_always_capture_default() const { return always_capture_default_; }
4047
4049 MultiOptionPolicy get_multi_option_policy() const { return multi_option_policy_; }
4050
4051 // Shortcuts for multi option policy
4052
4054 CRTP *take_last() {
4055 auto self = static_cast<CRTP *>(this);
4056 self->multi_option_policy(MultiOptionPolicy::TakeLast);
4057 return self;
4058 }
4059
4061 CRTP *take_first() {
4062 auto self = static_cast<CRTP *>(this);
4063 self->multi_option_policy(MultiOptionPolicy::TakeFirst);
4064 return self;
4065 }
4066
4068 CRTP *take_all() {
4069 auto self = static_cast<CRTP *>(this);
4070 self->multi_option_policy(MultiOptionPolicy::TakeAll);
4071 return self;
4072 }
4073
4075 CRTP *join() {
4076 auto self = static_cast<CRTP *>(this);
4077 self->multi_option_policy(MultiOptionPolicy::Join);
4078 return self;
4079 }
4080
4082 CRTP *join(char delim) {
4083 auto self = static_cast<CRTP *>(this);
4084 self->delimiter_ = delim;
4085 self->multi_option_policy(MultiOptionPolicy::Join);
4086 return self;
4087 }
4088
4090 CRTP *configurable(bool value = true) {
4091 configurable_ = value;
4092 return static_cast<CRTP *>(this);
4093 }
4094
4096 CRTP *delimiter(char value = '\0') {
4097 delimiter_ = value;
4098 return static_cast<CRTP *>(this);
4099 }
4100};
4101
4104class OptionDefaults : public OptionBase<OptionDefaults> {
4105 public:
4106 OptionDefaults() = default;
4107
4108 // Methods here need a different implementation if they are Option vs. OptionDefault
4109
4111 OptionDefaults *multi_option_policy(MultiOptionPolicy value = MultiOptionPolicy::Throw) {
4112 multi_option_policy_ = value;
4113 return this;
4114 }
4115
4117 OptionDefaults *ignore_case(bool value = true) {
4118 ignore_case_ = value;
4119 return this;
4120 }
4121
4123 OptionDefaults *ignore_underscore(bool value = true) {
4124 ignore_underscore_ = value;
4125 return this;
4126 }
4127
4130 disable_flag_override_ = value;
4131 return this;
4132 }
4133
4135 OptionDefaults *delimiter(char value = '\0') {
4136 delimiter_ = value;
4137 return this;
4138 }
4139};
4140
4141class Option : public OptionBase<Option> {
4142 friend App;
4143
4144 protected:
4147
4149 std::vector<std::string> snames_{};
4150
4152 std::vector<std::string> lnames_{};
4153
4156 std::vector<std::pair<std::string, std::string>> default_flag_values_{};
4157
4159 std::vector<std::string> fnames_{};
4160
4162 std::string pname_{};
4163
4165 std::string envname_{};
4166
4170
4172 std::string description_{};
4173
4175 std::string default_str_{};
4176
4178 std::string option_text_{};
4179
4183 std::function<std::string()> type_name_{[]() { return std::string(); }};
4184
4186 std::function<std::string()> default_function_{};
4187
4191
4194 int type_size_max_{1};
4196 int type_size_min_{1};
4197
4199 int expected_min_{1};
4201 int expected_max_{1};
4202
4204 std::vector<Validator> validators_{};
4205
4207 std::set<Option *> needs_{};
4208
4210 std::set<Option *> excludes_{};
4211
4215
4217 App *parent_{nullptr};
4218
4220 callback_t callback_{};
4221
4225
4227 results_t results_{};
4229 results_t proc_results_{};
4231 enum class option_state : char {
4232 parsing = 0,
4233 validated = 2,
4234 reduced = 4,
4235 callback_run = 6,
4236 };
4238 option_state current_option_state_{option_state::parsing};
4240 bool allow_extra_args_{false};
4242 bool flag_like_{false};
4244 bool run_callback_for_default_{false};
4246 bool inject_separator_{false};
4248 bool trigger_on_result_{false};
4250 bool force_callback_{false};
4252
4254 Option(std::string option_name, std::string option_description, callback_t callback, App *parent)
4255 : description_(std::move(option_description)), parent_(parent), callback_(std::move(callback)) {
4256 std::tie(snames_, lnames_, pname_) = detail::get_names(detail::split_names(option_name));
4257 }
4258
4259 public:
4262
4263 Option(const Option &) = delete;
4264 Option &operator=(const Option &) = delete;
4265
4267 std::size_t count() const { return results_.size(); }
4268
4270 bool empty() const { return results_.empty(); }
4271
4273 explicit operator bool() const { return !empty() || force_callback_; }
4274
4276 void clear() {
4277 results_.clear();
4278 current_option_state_ = option_state::parsing;
4279 }
4280
4284
4286 Option *expected(int value) {
4287 if(value < 0) {
4288 expected_min_ = -value;
4289 if(expected_max_ < expected_min_) {
4290 expected_max_ = expected_min_;
4291 }
4292 allow_extra_args_ = true;
4293 flag_like_ = false;
4294 } else if(value == detail::expected_max_vector_size) {
4295 expected_min_ = 1;
4296 expected_max_ = detail::expected_max_vector_size;
4297 allow_extra_args_ = true;
4298 flag_like_ = false;
4299 } else {
4300 expected_min_ = value;
4301 expected_max_ = value;
4302 flag_like_ = (expected_min_ == 0);
4303 }
4304 return this;
4305 }
4306
4308 Option *expected(int value_min, int value_max) {
4309 if(value_min < 0) {
4310 value_min = -value_min;
4311 }
4312
4313 if(value_max < 0) {
4314 value_max = detail::expected_max_vector_size;
4315 }
4316 if(value_max < value_min) {
4317 expected_min_ = value_max;
4318 expected_max_ = value_min;
4319 } else {
4320 expected_max_ = value_max;
4321 expected_min_ = value_min;
4322 }
4323
4324 return this;
4325 }
4328 Option *allow_extra_args(bool value = true) {
4329 allow_extra_args_ = value;
4330 return this;
4331 }
4333 bool get_allow_extra_args() const { return allow_extra_args_; }
4335 Option *trigger_on_parse(bool value = true) {
4336 trigger_on_result_ = value;
4337 return this;
4338 }
4340 bool get_trigger_on_parse() const { return trigger_on_result_; }
4341
4343 Option *force_callback(bool value = true) {
4344 force_callback_ = value;
4345 return this;
4346 }
4348 bool get_force_callback() const { return force_callback_; }
4349
4352 Option *run_callback_for_default(bool value = true) {
4353 run_callback_for_default_ = value;
4354 return this;
4355 }
4357 bool get_run_callback_for_default() const { return run_callback_for_default_; }
4358
4360 Option *check(Validator validator, const std::string &validator_name = "") {
4361 validator.non_modifying();
4362 validators_.push_back(std::move(validator));
4363 if(!validator_name.empty())
4364 validators_.back().name(validator_name);
4365 return this;
4366 }
4367
4369 Option *check(std::function<std::string(const std::string &)> Validator,
4370 std::string Validator_description = "",
4371 std::string Validator_name = "") {
4372 validators_.emplace_back(Validator, std::move(Validator_description), std::move(Validator_name));
4373 validators_.back().non_modifying();
4374 return this;
4375 }
4376
4378 Option *transform(Validator Validator, const std::string &Validator_name = "") {
4379 validators_.insert(validators_.begin(), std::move(Validator));
4380 if(!Validator_name.empty())
4381 validators_.front().name(Validator_name);
4382 return this;
4383 }
4384
4386 Option *transform(const std::function<std::string(std::string)> &func,
4387 std::string transform_description = "",
4388 std::string transform_name = "") {
4389 validators_.insert(validators_.begin(),
4390 Validator(
4391 [func](std::string &val) {
4392 val = func(val);
4393 return std::string{};
4394 },
4395 std::move(transform_description),
4396 std::move(transform_name)));
4397
4398 return this;
4399 }
4400
4402 Option *each(const std::function<void(std::string)> &func) {
4403 validators_.emplace_back(
4404 [func](std::string &inout) {
4405 func(inout);
4406 return std::string{};
4407 },
4408 std::string{});
4409 return this;
4410 }
4412 Validator *get_validator(const std::string &Validator_name = "") {
4413 for(auto &Validator : validators_) {
4414 if(Validator_name == Validator.get_name()) {
4415 return &Validator;
4416 }
4417 }
4418 if((Validator_name.empty()) && (!validators_.empty())) {
4419 return &(validators_.front());
4420 }
4421 throw OptionNotFound(std::string{"Validator "} + Validator_name + " Not Found");
4422 }
4423
4426 // This is an signed int so that it is not equivalent to a pointer.
4427 if(index >= 0 && index < static_cast<int>(validators_.size())) {
4428 return &(validators_[static_cast<decltype(validators_)::size_type>(index)]);
4429 }
4430 throw OptionNotFound("Validator index is not valid");
4431 }
4432
4435 if(opt != this) {
4436 needs_.insert(opt);
4437 }
4438 return this;
4439 }
4440
4442 template <typename T = App> Option *needs(std::string opt_name) {
4443 auto opt = static_cast<T *>(parent_)->get_option_no_throw(opt_name);
4444 if(opt == nullptr) {
4445 throw IncorrectConstruction::MissingOption(opt_name);
4446 }
4447 return needs(opt);
4448 }
4449
4451 template <typename A, typename B, typename... ARG> Option *needs(A opt, B opt1, ARG... args) {
4452 needs(opt);
4453 return needs(opt1, args...);
4454 }
4455
4458 auto iterator = std::find(std::begin(needs_), std::end(needs_), opt);
4459
4460 if(iterator == std::end(needs_)) {
4461 return false;
4462 }
4463 needs_.erase(iterator);
4464 return true;
4465 }
4466
4469 if(opt == this) {
4470 throw(IncorrectConstruction("and option cannot exclude itself"));
4471 }
4472 excludes_.insert(opt);
4473
4474 // Help text should be symmetric - excluding a should exclude b
4475 opt->excludes_.insert(this);
4476
4477 // Ignoring the insert return value, excluding twice is now allowed.
4478 // (Mostly to allow both directions to be excluded by user, even though the library does it for you.)
4479
4480 return this;
4481 }
4482
4484 template <typename T = App> Option *excludes(std::string opt_name) {
4485 auto opt = static_cast<T *>(parent_)->get_option_no_throw(opt_name);
4486 if(opt == nullptr) {
4487 throw IncorrectConstruction::MissingOption(opt_name);
4488 }
4489 return excludes(opt);
4490 }
4491
4493 template <typename A, typename B, typename... ARG> Option *excludes(A opt, B opt1, ARG... args) {
4494 excludes(opt);
4495 return excludes(opt1, args...);
4496 }
4497
4500 auto iterator = std::find(std::begin(excludes_), std::end(excludes_), opt);
4501
4502 if(iterator == std::end(excludes_)) {
4503 return false;
4504 }
4505 excludes_.erase(iterator);
4506 return true;
4507 }
4508
4510 Option *envname(std::string name) {
4511 envname_ = std::move(name);
4512 return this;
4513 }
4514
4519 template <typename T = App> Option *ignore_case(bool value = true) {
4520 if(!ignore_case_ && value) {
4521 ignore_case_ = value;
4522 auto *parent = static_cast<T *>(parent_);
4523 for(const Option_p &opt : parent->options_) {
4524 if(opt.get() == this) {
4525 continue;
4526 }
4527 auto &omatch = opt->matching_name(*this);
4528 if(!omatch.empty()) {
4529 ignore_case_ = false;
4530 throw OptionAlreadyAdded("adding ignore case caused a name conflict with " + omatch);
4531 }
4532 }
4533 } else {
4534 ignore_case_ = value;
4535 }
4536 return this;
4537 }
4538
4543 template <typename T = App> Option *ignore_underscore(bool value = true) {
4544
4545 if(!ignore_underscore_ && value) {
4546 ignore_underscore_ = value;
4547 auto *parent = static_cast<T *>(parent_);
4548 for(const Option_p &opt : parent->options_) {
4549 if(opt.get() == this) {
4550 continue;
4551 }
4552 auto &omatch = opt->matching_name(*this);
4553 if(!omatch.empty()) {
4554 ignore_underscore_ = false;
4555 throw OptionAlreadyAdded("adding ignore underscore caused a name conflict with " + omatch);
4556 }
4557 }
4558 } else {
4559 ignore_underscore_ = value;
4560 }
4561 return this;
4562 }
4563
4565 Option *multi_option_policy(MultiOptionPolicy value = MultiOptionPolicy::Throw) {
4566 if(value != multi_option_policy_) {
4567 if(multi_option_policy_ == MultiOptionPolicy::Throw && expected_max_ == detail::expected_max_vector_size &&
4568 expected_min_ > 1) { // this bizarre condition is to maintain backwards compatibility
4569 // with the previous behavior of expected_ with vectors
4570 expected_max_ = expected_min_;
4571 }
4572 multi_option_policy_ = value;
4573 current_option_state_ = option_state::parsing;
4574 }
4575 return this;
4576 }
4577
4579 Option *disable_flag_override(bool value = true) {
4580 disable_flag_override_ = value;
4581 return this;
4582 }
4586
4588 int get_type_size() const { return type_size_min_; }
4589
4591 int get_type_size_min() const { return type_size_min_; }
4593 int get_type_size_max() const { return type_size_max_; }
4594
4596 int get_inject_separator() const { return inject_separator_; }
4597
4599 std::string get_envname() const { return envname_; }
4600
4602 std::set<Option *> get_needs() const { return needs_; }
4603
4605 std::set<Option *> get_excludes() const { return excludes_; }
4606
4608 std::string get_default_str() const { return default_str_; }
4609
4611 callback_t get_callback() const { return callback_; }
4612
4614 const std::vector<std::string> &get_lnames() const { return lnames_; }
4615
4617 const std::vector<std::string> &get_snames() const { return snames_; }
4618
4620 const std::vector<std::string> &get_fnames() const { return fnames_; }
4622 const std::string &get_single_name() const {
4623 if(!lnames_.empty()) {
4624 return lnames_[0];
4625 }
4626 if(!pname_.empty()) {
4627 return pname_;
4628 }
4629 if(!snames_.empty()) {
4630 return snames_[0];
4631 }
4632 return envname_;
4633 }
4635 int get_expected() const { return expected_min_; }
4636
4638 int get_expected_min() const { return expected_min_; }
4640 int get_expected_max() const { return expected_max_; }
4641
4643 int get_items_expected_min() const { return type_size_min_ * expected_min_; }
4644
4647 int t = type_size_max_;
4648 return detail::checked_multiply(t, expected_max_) ? t : detail::expected_max_vector_size;
4649 }
4651 int get_items_expected() const { return get_items_expected_min(); }
4652
4654 bool get_positional() const { return pname_.length() > 0; }
4655
4657 bool nonpositional() const { return (snames_.size() + lnames_.size()) > 0; }
4658
4660 bool has_description() const { return description_.length() > 0; }
4661
4663 const std::string &get_description() const { return description_; }
4664
4666 Option *description(std::string option_description) {
4667 description_ = std::move(option_description);
4668 return this;
4669 }
4670
4671 Option *option_text(std::string text) {
4672 option_text_ = std::move(text);
4673 return this;
4674 }
4675
4676 const std::string &get_option_text() const { return option_text_; }
4677
4681
4686 std::string get_name(bool positional = false,
4687 bool all_options = false
4688 ) const {
4689 if(get_group().empty())
4690 return {}; // Hidden
4691
4692 if(all_options) {
4693
4694 std::vector<std::string> name_list;
4695
4697 if((positional && (!pname_.empty())) || (snames_.empty() && lnames_.empty())) {
4698 name_list.push_back(pname_);
4699 }
4700 if((get_items_expected() == 0) && (!fnames_.empty())) {
4701 for(const std::string &sname : snames_) {
4702 name_list.push_back("-" + sname);
4703 if(check_fname(sname)) {
4704 name_list.back() += "{" + get_flag_value(sname, "") + "}";
4705 }
4706 }
4707
4708 for(const std::string &lname : lnames_) {
4709 name_list.push_back("--" + lname);
4710 if(check_fname(lname)) {
4711 name_list.back() += "{" + get_flag_value(lname, "") + "}";
4712 }
4713 }
4714 } else {
4715 for(const std::string &sname : snames_)
4716 name_list.push_back("-" + sname);
4717
4718 for(const std::string &lname : lnames_)
4719 name_list.push_back("--" + lname);
4720 }
4721
4722 return detail::join(name_list);
4723 }
4724
4725 // This returns the positional name no matter what
4726 if(positional)
4727 return pname_;
4728
4729 // Prefer long name
4730 if(!lnames_.empty())
4731 return std::string(2, '-') + lnames_[0];
4732
4733 // Or short name if no long name
4734 if(!snames_.empty())
4735 return std::string(1, '-') + snames_[0];
4736
4737 // If positional is the only name, it's okay to use that
4738 return pname_;
4739 }
4740
4744
4747 if(force_callback_ && results_.empty()) {
4748 add_result(default_str_);
4749 }
4750 if(current_option_state_ == option_state::parsing) {
4751 _validate_results(results_);
4752 current_option_state_ = option_state::validated;
4753 }
4754
4755 if(current_option_state_ < option_state::reduced) {
4756 _reduce_results(proc_results_, results_);
4757 current_option_state_ = option_state::reduced;
4758 }
4759 if(current_option_state_ >= option_state::reduced) {
4760 current_option_state_ = option_state::callback_run;
4761 if(!(callback_)) {
4762 return;
4763 }
4764 const results_t &send_results = proc_results_.empty() ? results_ : proc_results_;
4765 bool local_result = callback_(send_results);
4766
4767 if(!local_result)
4768 throw ConversionError(get_name(), results_);
4769 }
4770 }
4771
4773 const std::string &matching_name(const Option &other) const {
4774 static const std::string estring;
4775 for(const std::string &sname : snames_)
4776 if(other.check_sname(sname))
4777 return sname;
4778 for(const std::string &lname : lnames_)
4779 if(other.check_lname(lname))
4780 return lname;
4781
4782 if(ignore_case_ ||
4783 ignore_underscore_) { // We need to do the inverse, in case we are ignore_case or ignore underscore
4784 for(const std::string &sname : other.snames_)
4785 if(check_sname(sname))
4786 return sname;
4787 for(const std::string &lname : other.lnames_)
4788 if(check_lname(lname))
4789 return lname;
4790 }
4791 return estring;
4792 }
4794 bool operator==(const Option &other) const { return !matching_name(other).empty(); }
4795
4797 bool check_name(const std::string &name) const {
4798
4799 if(name.length() > 2 && name[0] == '-' && name[1] == '-')
4800 return check_lname(name.substr(2));
4801 if(name.length() > 1 && name.front() == '-')
4802 return check_sname(name.substr(1));
4803 if(!pname_.empty()) {
4804 std::string local_pname = pname_;
4805 std::string local_name = name;
4806 if(ignore_underscore_) {
4807 local_pname = detail::remove_underscore(local_pname);
4808 local_name = detail::remove_underscore(local_name);
4809 }
4810 if(ignore_case_) {
4811 local_pname = detail::to_lower(local_pname);
4812 local_name = detail::to_lower(local_name);
4813 }
4814 if(local_name == local_pname) {
4815 return true;
4816 }
4817 }
4818
4819 if(!envname_.empty()) {
4820 // this needs to be the original since envname_ shouldn't match on case insensitivity
4821 return (name == envname_);
4822 }
4823 return false;
4824 }
4825
4827 bool check_sname(std::string name) const {
4828 return (detail::find_member(std::move(name), snames_, ignore_case_) >= 0);
4829 }
4830
4832 bool check_lname(std::string name) const {
4833 return (detail::find_member(std::move(name), lnames_, ignore_case_, ignore_underscore_) >= 0);
4834 }
4835
4837 bool check_fname(std::string name) const {
4838 if(fnames_.empty()) {
4839 return false;
4840 }
4841 return (detail::find_member(std::move(name), fnames_, ignore_case_, ignore_underscore_) >= 0);
4842 }
4843
4846 std::string get_flag_value(const std::string &name, std::string input_value) const {
4847 static const std::string trueString{"true"};
4848 static const std::string falseString{"false"};
4849 static const std::string emptyString{"{}"};
4850 // check for disable flag override_
4851 if(disable_flag_override_) {
4852 if(!((input_value.empty()) || (input_value == emptyString))) {
4853 auto default_ind = detail::find_member(name, fnames_, ignore_case_, ignore_underscore_);
4854 if(default_ind >= 0) {
4855 // We can static cast this to std::size_t because it is more than 0 in this block
4856 if(default_flag_values_[static_cast<std::size_t>(default_ind)].second != input_value) {
4857 throw(ArgumentMismatch::FlagOverride(name));
4858 }
4859 } else {
4860 if(input_value != trueString) {
4861 throw(ArgumentMismatch::FlagOverride(name));
4862 }
4863 }
4864 }
4865 }
4866 auto ind = detail::find_member(name, fnames_, ignore_case_, ignore_underscore_);
4867 if((input_value.empty()) || (input_value == emptyString)) {
4868 if(flag_like_) {
4869 return (ind < 0) ? trueString : default_flag_values_[static_cast<std::size_t>(ind)].second;
4870 } else {
4871 return (ind < 0) ? default_str_ : default_flag_values_[static_cast<std::size_t>(ind)].second;
4872 }
4873 }
4874 if(ind < 0) {
4875 return input_value;
4876 }
4877 if(default_flag_values_[static_cast<std::size_t>(ind)].second == falseString) {
4878 try {
4879 auto val = detail::to_flag_value(input_value);
4880 return (val == 1) ? falseString : (val == (-1) ? trueString : std::to_string(-val));
4881 } catch(const std::invalid_argument &) {
4882 return input_value;
4883 }
4884 } else {
4885 return input_value;
4886 }
4887 }
4888
4890 Option *add_result(std::string s) {
4891 _add_result(std::move(s), results_);
4892 current_option_state_ = option_state::parsing;
4893 return this;
4894 }
4895
4897 Option *add_result(std::string s, int &results_added) {
4898 results_added = _add_result(std::move(s), results_);
4899 current_option_state_ = option_state::parsing;
4900 return this;
4901 }
4902
4904 Option *add_result(std::vector<std::string> s) {
4905 current_option_state_ = option_state::parsing;
4906 for(auto &str : s) {
4907 _add_result(std::move(str), results_);
4908 }
4909 return this;
4910 }
4911
4913 const results_t &results() const { return results_; }
4914
4917 results_t res = proc_results_.empty() ? results_ : proc_results_;
4918 if(current_option_state_ < option_state::reduced) {
4919 if(current_option_state_ == option_state::parsing) {
4920 res = results_;
4921 _validate_results(res);
4922 }
4923 if(!res.empty()) {
4924 results_t extra;
4925 _reduce_results(extra, res);
4926 if(!extra.empty()) {
4927 res = std::move(extra);
4928 }
4929 }
4930 }
4931 return res;
4932 }
4933
4935 template <typename T> void results(T &output) const {
4936 bool retval;
4937 if(current_option_state_ >= option_state::reduced || (results_.size() == 1 && validators_.empty())) {
4938 const results_t &res = (proc_results_.empty()) ? results_ : proc_results_;
4939 retval = detail::lexical_conversion<T, T>(res, output);
4940 } else {
4941 results_t res;
4942 if(results_.empty()) {
4943 if(!default_str_.empty()) {
4944 // _add_results takes an rvalue only
4945 _add_result(std::string(default_str_), res);
4946 _validate_results(res);
4947 results_t extra;
4948 _reduce_results(extra, res);
4949 if(!extra.empty()) {
4950 res = std::move(extra);
4951 }
4952 } else {
4953 res.emplace_back();
4954 }
4955 } else {
4956 res = reduced_results();
4957 }
4958 retval = detail::lexical_conversion<T, T>(res, output);
4959 }
4960 if(!retval) {
4961 throw ConversionError(get_name(), results_);
4962 }
4963 }
4964
4966 template <typename T> T as() const {
4967 T output;
4968 results(output);
4969 return output;
4970 }
4971
4973 bool get_callback_run() const { return (current_option_state_ == option_state::callback_run); }
4974
4978
4980 Option *type_name_fn(std::function<std::string()> typefun) {
4981 type_name_ = std::move(typefun);
4982 return this;
4983 }
4984
4986 Option *type_name(std::string typeval) {
4987 type_name_fn([typeval]() { return typeval; });
4988 return this;
4989 }
4990
4992 Option *type_size(int option_type_size) {
4993 if(option_type_size < 0) {
4994 // this section is included for backwards compatibility
4995 type_size_max_ = -option_type_size;
4996 type_size_min_ = -option_type_size;
4997 expected_max_ = detail::expected_max_vector_size;
4998 } else {
4999 type_size_max_ = option_type_size;
5000 if(type_size_max_ < detail::expected_max_vector_size) {
5001 type_size_min_ = option_type_size;
5002 } else {
5003 inject_separator_ = true;
5004 }
5005 if(type_size_max_ == 0)
5006 required_ = false;
5007 }
5008 return this;
5009 }
5011 Option *type_size(int option_type_size_min, int option_type_size_max) {
5012 if(option_type_size_min < 0 || option_type_size_max < 0) {
5013 // this section is included for backwards compatibility
5014 expected_max_ = detail::expected_max_vector_size;
5015 option_type_size_min = (std::abs)(option_type_size_min);
5016 option_type_size_max = (std::abs)(option_type_size_max);
5017 }
5018
5019 if(option_type_size_min > option_type_size_max) {
5020 type_size_max_ = option_type_size_min;
5021 type_size_min_ = option_type_size_max;
5022 } else {
5023 type_size_min_ = option_type_size_min;
5024 type_size_max_ = option_type_size_max;
5025 }
5026 if(type_size_max_ == 0) {
5027 required_ = false;
5028 }
5029 if(type_size_max_ >= detail::expected_max_vector_size) {
5030 inject_separator_ = true;
5031 }
5032 return this;
5033 }
5034
5036 void inject_separator(bool value = true) { inject_separator_ = value; }
5037
5039 Option *default_function(const std::function<std::string()> &func) {
5040 default_function_ = func;
5041 return this;
5042 }
5043
5046 if(default_function_) {
5047 default_str_ = default_function_();
5048 }
5049 return this;
5050 }
5051
5053 Option *default_str(std::string val) {
5054 default_str_ = std::move(val);
5055 return this;
5056 }
5057
5060 template <typename X> Option *default_val(const X &val) {
5061 std::string val_str = detail::to_string(val);
5062 auto old_option_state = current_option_state_;
5063 results_t old_results{std::move(results_)};
5064 results_.clear();
5065 try {
5066 add_result(val_str);
5067 // if trigger_on_result_ is set the callback already ran
5068 if(run_callback_for_default_ && !trigger_on_result_) {
5069 run_callback(); // run callback sets the state we need to reset it again
5070 current_option_state_ = option_state::parsing;
5071 } else {
5072 _validate_results(results_);
5073 current_option_state_ = old_option_state;
5074 }
5075 } catch(const CLI::Error &) {
5076 // this should be done
5077 results_ = std::move(old_results);
5078 current_option_state_ = old_option_state;
5079 throw;
5080 }
5081 results_ = std::move(old_results);
5082 default_str_ = std::move(val_str);
5083 return this;
5084 }
5085
5087 std::string get_type_name() const {
5088 std::string full_type_name = type_name_();
5089 if(!validators_.empty()) {
5090 for(auto &Validator : validators_) {
5091 std::string vtype = Validator.get_description();
5092 if(!vtype.empty()) {
5093 full_type_name += ":" + vtype;
5094 }
5095 }
5096 }
5097 return full_type_name;
5098 }
5099
5100 private:
5102 void _validate_results(results_t &res) const {
5103 // Run the Validators (can change the string)
5104 if(!validators_.empty()) {
5105 if(type_size_max_ > 1) { // in this context index refers to the index in the type
5106 int index = 0;
5107 if(get_items_expected_max() < static_cast<int>(res.size()) &&
5108 multi_option_policy_ == CLI::MultiOptionPolicy::TakeLast) {
5109 // create a negative index for the earliest ones
5110 index = get_items_expected_max() - static_cast<int>(res.size());
5111 }
5112
5113 for(std::string &result : res) {
5114 if(detail::is_separator(result) && type_size_max_ != type_size_min_ && index >= 0) {
5115 index = 0; // reset index for variable size chunks
5116 continue;
5117 }
5118 auto err_msg = _validate(result, (index >= 0) ? (index % type_size_max_) : index);
5119 if(!err_msg.empty())
5120 throw ValidationError(get_name(), err_msg);
5121 ++index;
5122 }
5123 } else {
5124 int index = 0;
5125 if(expected_max_ < static_cast<int>(res.size()) &&
5126 multi_option_policy_ == CLI::MultiOptionPolicy::TakeLast) {
5127 // create a negative index for the earliest ones
5128 index = expected_max_ - static_cast<int>(res.size());
5129 }
5130 for(std::string &result : res) {
5131 auto err_msg = _validate(result, index);
5132 ++index;
5133 if(!err_msg.empty())
5134 throw ValidationError(get_name(), err_msg);
5135 }
5136 }
5137 }
5138 }
5139
5143 void _reduce_results(results_t &res, const results_t &original) const {
5144
5145 // max num items expected or length of vector, always at least 1
5146 // Only valid for a trimming policy
5147
5148 res.clear();
5149 // Operation depends on the policy setting
5150 switch(multi_option_policy_) {
5151 case MultiOptionPolicy::TakeAll:
5152 break;
5153 case MultiOptionPolicy::TakeLast: {
5154 // Allow multi-option sizes (including 0)
5155 std::size_t trim_size = std::min<std::size_t>(
5156 static_cast<std::size_t>(std::max<int>(get_items_expected_max(), 1)), original.size());
5157 if(original.size() != trim_size) {
5158 res.assign(original.end() - static_cast<results_t::difference_type>(trim_size), original.end());
5159 }
5160 } break;
5161 case MultiOptionPolicy::TakeFirst: {
5162 std::size_t trim_size = std::min<std::size_t>(
5163 static_cast<std::size_t>(std::max<int>(get_items_expected_max(), 1)), original.size());
5164 if(original.size() != trim_size) {
5165 res.assign(original.begin(), original.begin() + static_cast<results_t::difference_type>(trim_size));
5166 }
5167 } break;
5168 case MultiOptionPolicy::Join:
5169 if(results_.size() > 1) {
5170 res.push_back(detail::join(original, std::string(1, (delimiter_ == '\0') ? '\n' : delimiter_)));
5171 }
5172 break;
5173 case MultiOptionPolicy::Throw:
5174 default: {
5175 auto num_min = static_cast<std::size_t>(get_items_expected_min());
5176 auto num_max = static_cast<std::size_t>(get_items_expected_max());
5177 if(num_min == 0) {
5178 num_min = 1;
5179 }
5180 if(num_max == 0) {
5181 num_max = 1;
5182 }
5183 if(original.size() < num_min) {
5184 throw ArgumentMismatch::AtLeast(get_name(), static_cast<int>(num_min), original.size());
5185 }
5186 if(original.size() > num_max) {
5187 throw ArgumentMismatch::AtMost(get_name(), static_cast<int>(num_max), original.size());
5188 }
5189 break;
5190 }
5191 }
5192 }
5193
5194 // Run a result through the Validators
5195 std::string _validate(std::string &result, int index) const {
5196 std::string err_msg;
5197 if(result.empty() && expected_min_ == 0) {
5198 // an empty with nothing expected is allowed
5199 return err_msg;
5200 }
5201 for(const auto &vali : validators_) {
5202 auto v = vali.get_application_index();
5203 if(v == -1 || v == index) {
5204 try {
5205 err_msg = vali(result);
5206 } catch(const ValidationError &err) {
5207 err_msg = err.what();
5208 }
5209 if(!err_msg.empty())
5210 break;
5211 }
5212 }
5213
5214 return err_msg;
5215 }
5216
5218 int _add_result(std::string &&result, std::vector<std::string> &res) const {
5219 int result_count = 0;
5220 if(allow_extra_args_ && !result.empty() && result.front() == '[' &&
5221 result.back() == ']') { // this is now a vector string likely from the default or user entry
5222 result.pop_back();
5223
5224 for(auto &var : CLI::detail::split(result.substr(1), ',')) {
5225 if(!var.empty()) {
5226 result_count += _add_result(std::move(var), res);
5227 }
5228 }
5229 return result_count;
5230 }
5231 if(delimiter_ == '\0') {
5232 res.push_back(std::move(result));
5233 ++result_count;
5234 } else {
5235 if((result.find_first_of(delimiter_) != std::string::npos)) {
5236 for(const auto &var : CLI::detail::split(result, delimiter_)) {
5237 if(!var.empty()) {
5238 res.push_back(var);
5239 ++result_count;
5240 }
5241 }
5242 } else {
5243 res.push_back(std::move(result));
5244 ++result_count;
5245 }
5246 }
5247 return result_count;
5248 }
5249}; // namespace CLI
5250
5251
5252
5253
5254#ifndef CLI11_PARSE
5255#define CLI11_PARSE(app, argc, argv) \
5256 try { \
5257 (app).parse((argc), (argv)); \
5258 } catch(const CLI::ParseError &e) { \
5259 return (app).exit(e); \
5260 }
5261#endif
5262
5263namespace detail {
5265struct AppFriend;
5266} // namespace detail
5267
5268namespace FailureMessage {
5269std::string simple(const App *app, const Error &e);
5270std::string help(const App *app, const Error &e);
5271} // namespace FailureMessage
5272
5274
5275enum class config_extras_mode : char { error = 0, ignore, ignore_all, capture };
5276
5277class App;
5278
5279using App_p = std::shared_ptr<App>;
5280
5281class Option_group;
5283
5286class App {
5287 friend Option;
5288 friend detail::AppFriend;
5289
5290 protected:
5291 // This library follows the Google style guide for member names ending in underscores
5292
5295
5297 std::string name_{};
5298
5300 std::string description_{};
5301
5303 bool allow_extras_{false};
5304
5307 config_extras_mode allow_config_extras_{config_extras_mode::ignore};
5308
5310 bool prefix_command_{false};
5311
5313 bool has_automatic_name_{false};
5314
5316 bool required_{false};
5317
5319 bool disabled_{false};
5320
5322 bool pre_parse_called_{false};
5323
5326 bool immediate_callback_{false};
5327
5329 std::function<void(std::size_t)> pre_parse_callback_{};
5330
5332 std::function<void()> parse_complete_callback_{};
5333
5335 std::function<void()> final_callback_{};
5336
5340
5342 OptionDefaults option_defaults_{};
5343
5345 std::vector<Option_p> options_{};
5346
5350
5352 std::string footer_{};
5353
5355 std::function<std::string()> footer_callback_{};
5356
5358 Option *help_ptr_{nullptr};
5359
5361 Option *help_all_ptr_{nullptr};
5362
5364 Option *version_ptr_{nullptr};
5365
5367 std::shared_ptr<FormatterBase> formatter_{new Formatter()};
5368
5370 std::function<std::string(const App *, const Error &e)> failure_message_{FailureMessage::simple};
5371
5375
5376 using missing_t = std::vector<std::pair<detail::Classifier, std::string>>;
5377
5381 missing_t missing_{};
5382
5384 std::vector<Option *> parse_order_{};
5385
5387 std::vector<App *> parsed_subcommands_{};
5388
5390 std::set<App *> exclude_subcommands_{};
5391
5394 std::set<Option *> exclude_options_{};
5395
5398 std::set<App *> need_subcommands_{};
5399
5402 std::set<Option *> need_options_{};
5403
5407
5409 std::vector<App_p> subcommands_{};
5410
5412 bool ignore_case_{false};
5413
5415 bool ignore_underscore_{false};
5416
5418 bool fallthrough_{false};
5419
5421 bool allow_windows_style_options_{
5422#ifdef _WIN32
5423 true
5424#else
5425 false
5426#endif
5427 };
5429 bool positionals_at_end_{false};
5430
5431 enum class startup_mode : char { stable, enabled, disabled };
5434 startup_mode default_startup{startup_mode::stable};
5435
5437 bool configurable_{false};
5438
5440 bool validate_positionals_{false};
5441
5444 bool silent_{false};
5445
5447 std::uint32_t parsed_{0U};
5448
5450 std::size_t require_subcommand_min_{0};
5451
5453 std::size_t require_subcommand_max_{0};
5454
5456 std::size_t require_option_min_{0};
5457
5459 std::size_t require_option_max_{0};
5460
5462 App *parent_{nullptr};
5463
5465 std::string group_{"Subcommands"};
5466
5468 std::vector<std::string> aliases_{};
5469
5473
5475 Option *config_ptr_{nullptr};
5476
5478 std::shared_ptr<Config> config_formatter_{new ConfigTOML()};
5479
5481
5483 App(std::string app_description, std::string app_name, App *parent)
5484 : name_(std::move(app_name)), description_(std::move(app_description)), parent_(parent) {
5485 // Inherit if not from a nullptr
5486 if(parent_ != nullptr) {
5487 if(parent_->help_ptr_ != nullptr)
5488 set_help_flag(parent_->help_ptr_->get_name(false, true), parent_->help_ptr_->get_description());
5489 if(parent_->help_all_ptr_ != nullptr)
5490 set_help_all_flag(parent_->help_all_ptr_->get_name(false, true),
5491 parent_->help_all_ptr_->get_description());
5492
5494 option_defaults_ = parent_->option_defaults_;
5495
5496 // INHERITABLE
5497 failure_message_ = parent_->failure_message_;
5498 allow_extras_ = parent_->allow_extras_;
5499 allow_config_extras_ = parent_->allow_config_extras_;
5500 prefix_command_ = parent_->prefix_command_;
5501 immediate_callback_ = parent_->immediate_callback_;
5502 ignore_case_ = parent_->ignore_case_;
5503 ignore_underscore_ = parent_->ignore_underscore_;
5504 fallthrough_ = parent_->fallthrough_;
5505 validate_positionals_ = parent_->validate_positionals_;
5506 configurable_ = parent_->configurable_;
5507 allow_windows_style_options_ = parent_->allow_windows_style_options_;
5508 group_ = parent_->group_;
5509 footer_ = parent_->footer_;
5510 formatter_ = parent_->formatter_;
5511 config_formatter_ = parent_->config_formatter_;
5512 require_subcommand_max_ = parent_->require_subcommand_max_;
5513 }
5514 }
5515
5516 public:
5519
5521 explicit App(std::string app_description = "", std::string app_name = "")
5522 : App(app_description, app_name, nullptr) {
5523 set_help_flag("-h,--help", "Print this help message and exit");
5524 }
5525
5526 App(const App &) = delete;
5527 App &operator=(const App &) = delete;
5528
5530 virtual ~App() = default;
5531
5538 App *callback(std::function<void()> app_callback) {
5539 if(immediate_callback_) {
5540 parse_complete_callback_ = std::move(app_callback);
5541 } else {
5542 final_callback_ = std::move(app_callback);
5543 }
5544 return this;
5545 }
5546
5549 App *final_callback(std::function<void()> app_callback) {
5550 final_callback_ = std::move(app_callback);
5551 return this;
5552 }
5553
5556 App *parse_complete_callback(std::function<void()> pc_callback) {
5557 parse_complete_callback_ = std::move(pc_callback);
5558 return this;
5559 }
5560
5563 App *preparse_callback(std::function<void(std::size_t)> pp_callback) {
5564 pre_parse_callback_ = std::move(pp_callback);
5565 return this;
5566 }
5567
5569 App *name(std::string app_name = "") {
5570
5571 if(parent_ != nullptr) {
5572 auto oname = name_;
5573 name_ = app_name;
5574 auto &res = _compare_subcommand_names(*this, *_get_fallthrough_parent());
5575 if(!res.empty()) {
5576 name_ = oname;
5577 throw(OptionAlreadyAdded(app_name + " conflicts with existing subcommand names"));
5578 }
5579 } else {
5580 name_ = app_name;
5581 }
5582 has_automatic_name_ = false;
5583 return this;
5584 }
5585
5587 App *alias(std::string app_name) {
5588 if(app_name.empty() || !detail::valid_alias_name_string(app_name)) {
5589 throw IncorrectConstruction("Aliases may not be empty or contain newlines or null characters");
5590 }
5591 if(parent_ != nullptr) {
5592 aliases_.push_back(app_name);
5593 auto &res = _compare_subcommand_names(*this, *_get_fallthrough_parent());
5594 if(!res.empty()) {
5595 aliases_.pop_back();
5596 throw(OptionAlreadyAdded("alias already matches an existing subcommand: " + app_name));
5597 }
5598 } else {
5599 aliases_.push_back(app_name);
5600 }
5601
5602 return this;
5603 }
5604
5606 App *allow_extras(bool allow = true) {
5607 allow_extras_ = allow;
5608 return this;
5609 }
5610
5612 App *required(bool require = true) {
5613 required_ = require;
5614 return this;
5615 }
5616
5618 App *disabled(bool disable = true) {
5619 disabled_ = disable;
5620 return this;
5621 }
5622
5624 App *silent(bool silence = true) {
5625 silent_ = silence;
5626 return this;
5627 }
5628
5630 App *disabled_by_default(bool disable = true) {
5631 if(disable) {
5632 default_startup = startup_mode::disabled;
5633 } else {
5634 default_startup = (default_startup == startup_mode::enabled) ? startup_mode::enabled : startup_mode::stable;
5635 }
5636 return this;
5637 }
5638
5641 App *enabled_by_default(bool enable = true) {
5642 if(enable) {
5643 default_startup = startup_mode::enabled;
5644 } else {
5645 default_startup =
5646 (default_startup == startup_mode::disabled) ? startup_mode::disabled : startup_mode::stable;
5647 }
5648 return this;
5649 }
5650
5652 App *immediate_callback(bool immediate = true) {
5653 immediate_callback_ = immediate;
5654 if(immediate_callback_) {
5655 if(final_callback_ && !(parse_complete_callback_)) {
5656 std::swap(final_callback_, parse_complete_callback_);
5657 }
5658 } else if(!(final_callback_) && parse_complete_callback_) {
5659 std::swap(final_callback_, parse_complete_callback_);
5660 }
5661 return this;
5662 }
5663
5665 App *validate_positionals(bool validate = true) {
5666 validate_positionals_ = validate;
5667 return this;
5668 }
5669
5671 App *allow_config_extras(bool allow = true) {
5672 if(allow) {
5673 allow_config_extras_ = config_extras_mode::capture;
5674 allow_extras_ = true;
5675 } else {
5676 allow_config_extras_ = config_extras_mode::error;
5677 }
5678 return this;
5679 }
5680
5683 allow_config_extras_ = mode;
5684 return this;
5685 }
5686
5688 App *prefix_command(bool allow = true) {
5689 prefix_command_ = allow;
5690 return this;
5691 }
5692
5694 App *ignore_case(bool value = true) {
5695 if(value && !ignore_case_) {
5696 ignore_case_ = true;
5697 auto *p = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
5698 auto &match = _compare_subcommand_names(*this, *p);
5699 if(!match.empty()) {
5700 ignore_case_ = false; // we are throwing so need to be exception invariant
5701 throw OptionAlreadyAdded("ignore case would cause subcommand name conflicts: " + match);
5702 }
5703 }
5704 ignore_case_ = value;
5705 return this;
5706 }
5707
5710 App *allow_windows_style_options(bool value = true) {
5711 allow_windows_style_options_ = value;
5712 return this;
5713 }
5714
5716 App *positionals_at_end(bool value = true) {
5717 positionals_at_end_ = value;
5718 return this;
5719 }
5720
5722 App *configurable(bool value = true) {
5723 configurable_ = value;
5724 return this;
5725 }
5726
5728 App *ignore_underscore(bool value = true) {
5729 if(value && !ignore_underscore_) {
5730 ignore_underscore_ = true;
5731 auto *p = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
5732 auto &match = _compare_subcommand_names(*this, *p);
5733 if(!match.empty()) {
5734 ignore_underscore_ = false;
5735 throw OptionAlreadyAdded("ignore underscore would cause subcommand name conflicts: " + match);
5736 }
5737 }
5738 ignore_underscore_ = value;
5739 return this;
5740 }
5741
5743 App *formatter(std::shared_ptr<FormatterBase> fmt) {
5744 formatter_ = fmt;
5745 return this;
5746 }
5747
5749 App *formatter_fn(std::function<std::string(const App *, std::string, AppFormatMode)> fmt) {
5750 formatter_ = std::make_shared<FormatterLambda>(fmt);
5751 return this;
5752 }
5753
5755 App *config_formatter(std::shared_ptr<Config> fmt) {
5756 config_formatter_ = fmt;
5757 return this;
5758 }
5759
5761 bool parsed() const { return parsed_ > 0; }
5762
5764 OptionDefaults *option_defaults() { return &option_defaults_; }
5765
5769
5784 Option *add_option(std::string option_name,
5785 callback_t option_callback,
5786 std::string option_description = "",
5787 bool defaulted = false,
5788 std::function<std::string()> func = {}) {
5789 Option myopt{option_name, option_description, option_callback, this};
5790
5791 if(std::find_if(std::begin(options_), std::end(options_), [&myopt](const Option_p &v) {
5792 return *v == myopt;
5793 }) == std::end(options_)) {
5794 options_.emplace_back();
5795 Option_p &option = options_.back();
5796 option.reset(new Option(option_name, option_description, option_callback, this));
5797
5798 // Set the default string capture function
5799 option->default_function(func);
5800
5801 // For compatibility with CLI11 1.7 and before, capture the default string here
5802 if(defaulted)
5803 option->capture_default_str();
5804
5805 // Transfer defaults to the new option
5806 option_defaults_.copy_to(option.get());
5807
5808 // Don't bother to capture if we already did
5809 if(!defaulted && option->get_always_capture_default())
5810 option->capture_default_str();
5811
5812 return option.get();
5813 }
5814 // we know something matches now find what it is so we can produce more error information
5815 for(auto &opt : options_) {
5816 auto &matchname = opt->matching_name(myopt);
5817 if(!matchname.empty()) {
5818 throw(OptionAlreadyAdded("added option matched existing option name: " + matchname));
5819 }
5820 }
5821 // this line should not be reached the above loop should trigger the throw
5822 throw(OptionAlreadyAdded("added option matched existing option name")); // LCOV_EXCL_LINE
5823 }
5824
5826 template <typename AssignTo,
5827 typename ConvertTo = AssignTo,
5828 enable_if_t<!std::is_const<ConvertTo>::value, detail::enabler> = detail::dummy>
5829 Option *add_option(std::string option_name,
5830 AssignTo &variable,
5831 std::string option_description = "") {
5832
5833 auto fun = [&variable](const CLI::results_t &res) { // comment for spacing
5834 return detail::lexical_conversion<AssignTo, ConvertTo>(res, variable);
5835 };
5836
5837 Option *opt = add_option(option_name, fun, option_description, false, [&variable]() {
5838 return CLI::detail::checked_to_string<AssignTo, ConvertTo>(variable);
5839 });
5840 opt->type_name(detail::type_name<ConvertTo>());
5841 // these must be actual lvalues since (std::max) sometimes is defined in terms of references and references
5842 // to structs used in the evaluation can be temporary so that would cause issues.
5845 opt->type_size(detail::type_count_min<ConvertTo>::value, (std::max)(Tcount, XCcount));
5846 opt->expected(detail::expected_count<ConvertTo>::value);
5848 return opt;
5849 }
5850
5852 template <typename AssignTo, enable_if_t<!std::is_const<AssignTo>::value, detail::enabler> = detail::dummy>
5853 Option *add_option_no_stream(std::string option_name,
5854 AssignTo &variable,
5855 std::string option_description = "") {
5856
5857 auto fun = [&variable](const CLI::results_t &res) { // comment for spacing
5858 return detail::lexical_conversion<AssignTo, AssignTo>(res, variable);
5859 };
5860
5861 Option *opt = add_option(option_name, fun, option_description, false, []() { return std::string{}; });
5862 opt->type_name(detail::type_name<AssignTo>());
5863 opt->type_size(detail::type_count_min<AssignTo>::value, detail::type_count<AssignTo>::value);
5864 opt->expected(detail::expected_count<AssignTo>::value);
5866 return opt;
5867 }
5868
5870 template <typename ArgType>
5871 Option *add_option_function(std::string option_name,
5872 const std::function<void(const ArgType &)> &func,
5873 std::string option_description = "") {
5874
5875 auto fun = [func](const CLI::results_t &res) {
5876 ArgType variable;
5877 bool result = detail::lexical_conversion<ArgType, ArgType>(res, variable);
5878 if(result) {
5879 func(variable);
5880 }
5881 return result;
5882 };
5883
5884 Option *opt = add_option(option_name, std::move(fun), option_description, false);
5885 opt->type_name(detail::type_name<ArgType>());
5886 opt->type_size(detail::type_count_min<ArgType>::value, detail::type_count<ArgType>::value);
5887 opt->expected(detail::expected_count<ArgType>::value);
5888 return opt;
5889 }
5890
5892 Option *add_option(std::string option_name) {
5893 return add_option(option_name, CLI::callback_t{}, std::string{}, false);
5894 }
5895
5897 template <typename T,
5898 enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value, detail::enabler> =
5899 detail::dummy>
5900 Option *add_option(std::string option_name, T &option_description) {
5901 return add_option(option_name, CLI::callback_t(), option_description, false);
5902 }
5903
5905 Option *set_help_flag(std::string flag_name = "", const std::string &help_description = "") {
5906 // take flag_description by const reference otherwise add_flag tries to assign to help_description
5907 if(help_ptr_ != nullptr) {
5908 remove_option(help_ptr_);
5909 help_ptr_ = nullptr;
5910 }
5911
5912 // Empty name will simply remove the help flag
5913 if(!flag_name.empty()) {
5914 help_ptr_ = add_flag(flag_name, help_description);
5915 help_ptr_->configurable(false);
5916 }
5917
5918 return help_ptr_;
5919 }
5920
5922 Option *set_help_all_flag(std::string help_name = "", const std::string &help_description = "") {
5923 // take flag_description by const reference otherwise add_flag tries to assign to flag_description
5924 if(help_all_ptr_ != nullptr) {
5925 remove_option(help_all_ptr_);
5926 help_all_ptr_ = nullptr;
5927 }
5928
5929 // Empty name will simply remove the help all flag
5930 if(!help_name.empty()) {
5931 help_all_ptr_ = add_flag(help_name, help_description);
5932 help_all_ptr_->configurable(false);
5933 }
5934
5935 return help_all_ptr_;
5936 }
5937
5939 Option *set_version_flag(std::string flag_name = "",
5940 const std::string &versionString = "",
5941 const std::string &version_help = "Display program version information and exit") {
5942 // take flag_description by const reference otherwise add_flag tries to assign to version_description
5943 if(version_ptr_ != nullptr) {
5944 remove_option(version_ptr_);
5945 version_ptr_ = nullptr;
5946 }
5947
5948 // Empty name will simply remove the version flag
5949 if(!flag_name.empty()) {
5950 version_ptr_ = add_flag_callback(
5951 flag_name, [versionString]() { throw(CLI::CallForVersion(versionString, 0)); }, version_help);
5952 version_ptr_->configurable(false);
5953 }
5954
5955 return version_ptr_;
5956 }
5958 Option *set_version_flag(std::string flag_name,
5959 std::function<std::string()> vfunc,
5960 const std::string &version_help = "Display program version information and exit") {
5961 if(version_ptr_ != nullptr) {
5962 remove_option(version_ptr_);
5963 version_ptr_ = nullptr;
5964 }
5965
5966 // Empty name will simply remove the version flag
5967 if(!flag_name.empty()) {
5968 version_ptr_ = add_flag_callback(
5969 flag_name, [vfunc]() { throw(CLI::CallForVersion(vfunc(), 0)); }, version_help);
5970 version_ptr_->configurable(false);
5971 }
5972
5973 return version_ptr_;
5974 }
5975
5976 private:
5978 Option *_add_flag_internal(std::string flag_name, CLI::callback_t fun, std::string flag_description) {
5979 Option *opt;
5980 if(detail::has_default_flag_values(flag_name)) {
5981 // check for default values and if it has them
5982 auto flag_defaults = detail::get_default_flag_values(flag_name);
5983 detail::remove_default_flag_values(flag_name);
5984 opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description), false);
5985 for(const auto &fname : flag_defaults)
5986 opt->fnames_.push_back(fname.first);
5987 opt->default_flag_values_ = std::move(flag_defaults);
5988 } else {
5989 opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description), false);
5990 }
5991 // flags cannot have positional values
5992 if(opt->get_positional()) {
5993 auto pos_name = opt->get_name(true);
5994 remove_option(opt);
5995 throw IncorrectConstruction::PositionalFlag(pos_name);
5996 }
5997 opt->multi_option_policy(MultiOptionPolicy::TakeLast);
5998 opt->expected(0);
5999 opt->required(false);
6000 return opt;
6001 }
6002
6003 public:
6005 Option *add_flag(std::string flag_name) { return _add_flag_internal(flag_name, CLI::callback_t(), std::string{}); }
6006
6010 template <typename T,
6011 enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value, detail::enabler> =
6012 detail::dummy>
6013 Option *add_flag(std::string flag_name, T &flag_description) {
6014 return _add_flag_internal(flag_name, CLI::callback_t(), flag_description);
6015 }
6016
6019 template <typename T,
6021 detail::dummy>
6022 Option *add_flag(std::string flag_name,
6023 T &flag_count,
6024 std::string flag_description = "") {
6025 flag_count = 0;
6026 CLI::callback_t fun = [&flag_count](const CLI::results_t &res) {
6027 try {
6028 detail::sum_flag_vector(res, flag_count);
6029 } catch(const std::invalid_argument &) {
6030 return false;
6031 }
6032 return true;
6033 };
6034 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
6035 ->multi_option_policy(MultiOptionPolicy::TakeAll);
6036 }
6037
6040 template <typename T,
6041 enable_if_t<!detail::is_mutable_container<T>::value && !std::is_const<T>::value &&
6042 (!std::is_constructible<T, std::int64_t>::value || is_bool<T>::value) &&
6043 !std::is_constructible<std::function<void(int)>, T>::value,
6044 detail::enabler> = detail::dummy>
6045 Option *add_flag(std::string flag_name,
6046 T &flag_result,
6047 std::string flag_description = "") {
6048
6049 CLI::callback_t fun = [&flag_result](const CLI::results_t &res) {
6050 return CLI::detail::lexical_cast(res[0], flag_result);
6051 };
6052 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))->run_callback_for_default();
6053 }
6054
6056 template <typename T,
6057 enable_if_t<!std::is_assignable<std::function<void(std::int64_t)> &, T>::value, detail::enabler> =
6058 detail::dummy>
6059 Option *add_flag(std::string flag_name,
6060 std::vector<T> &flag_results,
6061 std::string flag_description = "") {
6062 CLI::callback_t fun = [&flag_results](const CLI::results_t &res) {
6063 bool retval = true;
6064 for(const auto &elem : res) {
6065 flag_results.emplace_back();
6066 retval &= detail::lexical_cast(elem, flag_results.back());
6067 }
6068 return retval;
6069 };
6070 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
6071 ->multi_option_policy(MultiOptionPolicy::TakeAll)
6072 ->run_callback_for_default();
6073 }
6074
6076 Option *add_flag_callback(std::string flag_name,
6077 std::function<void(void)> function,
6078 std::string flag_description = "") {
6079
6080 CLI::callback_t fun = [function](const CLI::results_t &res) {
6081 bool trigger{false};
6082 auto result = CLI::detail::lexical_cast(res[0], trigger);
6083 if(result && trigger) {
6084 function();
6085 }
6086 return result;
6087 };
6088 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
6089 }
6090
6092 Option *add_flag_function(std::string flag_name,
6093 std::function<void(std::int64_t)> function,
6094 std::string flag_description = "") {
6095
6096 CLI::callback_t fun = [function](const CLI::results_t &res) {
6097 std::int64_t flag_count = 0;
6098 detail::sum_flag_vector(res, flag_count);
6099 function(flag_count);
6100 return true;
6101 };
6102 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
6103 ->multi_option_policy(MultiOptionPolicy::TakeAll);
6104 }
6105
6106#ifdef CLI11_CPP14
6108 Option *add_flag(std::string flag_name,
6109 std::function<void(std::int64_t)> function,
6110 std::string flag_description = "") {
6111 return add_flag_function(std::move(flag_name), std::move(function), std::move(flag_description));
6112 }
6113#endif
6114
6116 Option *set_config(std::string option_name = "",
6117 std::string default_filename = "",
6118 const std::string &help_message = "Read an ini file",
6119 bool config_required = false) {
6120
6121 // Remove existing config if present
6122 if(config_ptr_ != nullptr) {
6123 remove_option(config_ptr_);
6124 config_ptr_ = nullptr; // need to remove the config_ptr completely
6125 }
6126
6127 // Only add config if option passed
6128 if(!option_name.empty()) {
6129 config_ptr_ = add_option(option_name, help_message);
6130 if(config_required) {
6131 config_ptr_->required();
6132 }
6133 if(!default_filename.empty()) {
6134 config_ptr_->default_str(std::move(default_filename));
6135 }
6136 config_ptr_->configurable(false);
6137 }
6138
6139 return config_ptr_;
6140 }
6141
6144 // Make sure no links exist
6145 for(Option_p &op : options_) {
6146 op->remove_needs(opt);
6147 op->remove_excludes(opt);
6148 }
6149
6150 if(help_ptr_ == opt)
6151 help_ptr_ = nullptr;
6152 if(help_all_ptr_ == opt)
6153 help_all_ptr_ = nullptr;
6154
6155 auto iterator =
6156 std::find_if(std::begin(options_), std::end(options_), [opt](const Option_p &v) { return v.get() == opt; });
6157 if(iterator != std::end(options_)) {
6158 options_.erase(iterator);
6159 return true;
6160 }
6161 return false;
6162 }
6163
6165 template <typename T = Option_group>
6166 T *add_option_group(std::string group_name, std::string group_description = "") {
6167 if(!detail::valid_alias_name_string(group_name)) {
6168 throw IncorrectConstruction("option group names may not contain newlines or null characters");
6169 }
6170 auto option_group = std::make_shared<T>(std::move(group_description), group_name, this);
6171 auto ptr = option_group.get();
6172 // move to App_p for overload resolution on older gcc versions
6173 App_p app_ptr = std::dynamic_pointer_cast<App>(option_group);
6174 add_subcommand(std::move(app_ptr));
6175 return ptr;
6176 }
6177
6181
6183 App *add_subcommand(std::string subcommand_name = "", std::string subcommand_description = "") {
6184 if(!subcommand_name.empty() && !detail::valid_name_string(subcommand_name)) {
6185 if(!detail::valid_first_char(subcommand_name[0])) {
6187 "Subcommand name starts with invalid character, '!' and '-' are not allowed");
6188 }
6189 for(auto c : subcommand_name) {
6190 if(!detail::valid_later_char(c)) {
6191 throw IncorrectConstruction(std::string("Subcommand name contains invalid character ('") + c +
6192 "'), all characters are allowed except"
6193 "'=',':','{','}', and ' '");
6194 }
6195 }
6196 }
6197 CLI::App_p subcom = std::shared_ptr<App>(new App(std::move(subcommand_description), subcommand_name, this));
6198 return add_subcommand(std::move(subcom));
6199 }
6200
6203 if(!subcom)
6204 throw IncorrectConstruction("passed App is not valid");
6205 auto ckapp = (name_.empty() && parent_ != nullptr) ? _get_fallthrough_parent() : this;
6206 auto &mstrg = _compare_subcommand_names(*subcom, *ckapp);
6207 if(!mstrg.empty()) {
6208 throw(OptionAlreadyAdded("subcommand name or alias matches existing subcommand: " + mstrg));
6209 }
6210 subcom->parent_ = this;
6211 subcommands_.push_back(std::move(subcom));
6212 return subcommands_.back().get();
6213 }
6214
6216 bool remove_subcommand(App *subcom) {
6217 // Make sure no links exist
6218 for(App_p &sub : subcommands_) {
6219 sub->remove_excludes(subcom);
6220 sub->remove_needs(subcom);
6221 }
6222
6223 auto iterator = std::find_if(
6224 std::begin(subcommands_), std::end(subcommands_), [subcom](const App_p &v) { return v.get() == subcom; });
6225 if(iterator != std::end(subcommands_)) {
6226 subcommands_.erase(iterator);
6227 return true;
6228 }
6229 return false;
6230 }
6233 App *get_subcommand(const App *subcom) const {
6234 if(subcom == nullptr)
6235 throw OptionNotFound("nullptr passed");
6236 for(const App_p &subcomptr : subcommands_)
6237 if(subcomptr.get() == subcom)
6238 return subcomptr.get();
6239 throw OptionNotFound(subcom->get_name());
6240 }
6241
6243 App *get_subcommand(std::string subcom) const {
6244 auto subc = _find_subcommand(subcom, false, false);
6245 if(subc == nullptr)
6246 throw OptionNotFound(subcom);
6247 return subc;
6248 }
6250 App *get_subcommand(int index = 0) const {
6251 if(index >= 0) {
6252 auto uindex = static_cast<unsigned>(index);
6253 if(uindex < subcommands_.size())
6254 return subcommands_[uindex].get();
6255 }
6256 throw OptionNotFound(std::to_string(index));
6257 }
6258
6261 if(subcom == nullptr)
6262 throw OptionNotFound("nullptr passed");
6263 for(const App_p &subcomptr : subcommands_)
6264 if(subcomptr.get() == subcom)
6265 return subcomptr;
6266 throw OptionNotFound(subcom->get_name());
6267 }
6268
6270 CLI::App_p get_subcommand_ptr(std::string subcom) const {
6271 for(const App_p &subcomptr : subcommands_)
6272 if(subcomptr->check_name(subcom))
6273 return subcomptr;
6274 throw OptionNotFound(subcom);
6275 }
6276
6278 CLI::App_p get_subcommand_ptr(int index = 0) const {
6279 if(index >= 0) {
6280 auto uindex = static_cast<unsigned>(index);
6281 if(uindex < subcommands_.size())
6282 return subcommands_[uindex];
6283 }
6284 throw OptionNotFound(std::to_string(index));
6285 }
6286
6288 App *get_option_group(std::string group_name) const {
6289 for(const App_p &app : subcommands_) {
6290 if(app->name_.empty() && app->group_ == group_name) {
6291 return app.get();
6292 }
6293 }
6294 throw OptionNotFound(group_name);
6295 }
6296
6300 std::size_t count() const { return parsed_; }
6301
6304 std::size_t count_all() const {
6305 std::size_t cnt{0};
6306 for(auto &opt : options_) {
6307 cnt += opt->count();
6308 }
6309 for(auto &sub : subcommands_) {
6310 cnt += sub->count_all();
6311 }
6312 if(!get_name().empty()) { // for named subcommands add the number of times the subcommand was called
6313 cnt += parsed_;
6314 }
6315 return cnt;
6316 }
6317
6319 App *group(std::string group_name) {
6320 group_ = group_name;
6321 return this;
6322 }
6323
6326 require_subcommand_min_ = 1;
6327 require_subcommand_max_ = 0;
6328 return this;
6329 }
6330
6335 if(value < 0) {
6336 require_subcommand_min_ = 0;
6337 require_subcommand_max_ = static_cast<std::size_t>(-value);
6338 } else {
6339 require_subcommand_min_ = static_cast<std::size_t>(value);
6340 require_subcommand_max_ = static_cast<std::size_t>(value);
6341 }
6342 return this;
6343 }
6344
6347 App *require_subcommand(std::size_t min, std::size_t max) {
6348 require_subcommand_min_ = min;
6349 require_subcommand_max_ = max;
6350 return this;
6351 }
6352
6355 require_option_min_ = 1;
6356 require_option_max_ = 0;
6357 return this;
6358 }
6359
6363 App *require_option(int value) {
6364 if(value < 0) {
6365 require_option_min_ = 0;
6366 require_option_max_ = static_cast<std::size_t>(-value);
6367 } else {
6368 require_option_min_ = static_cast<std::size_t>(value);
6369 require_option_max_ = static_cast<std::size_t>(value);
6370 }
6371 return this;
6372 }
6373
6376 App *require_option(std::size_t min, std::size_t max) {
6377 require_option_min_ = min;
6378 require_option_max_ = max;
6379 return this;
6380 }
6381
6384 App *fallthrough(bool value = true) {
6385 fallthrough_ = value;
6386 return this;
6387 }
6388
6391 explicit operator bool() const { return parsed_ > 0; }
6392
6396
6400 virtual void pre_callback() {}
6401
6405 //
6407 void clear() {
6408
6409 parsed_ = 0;
6410 pre_parse_called_ = false;
6411
6412 missing_.clear();
6413 parsed_subcommands_.clear();
6414 for(const Option_p &opt : options_) {
6415 opt->clear();
6416 }
6417 for(const App_p &subc : subcommands_) {
6418 subc->clear();
6419 }
6420 }
6421
6424 void parse(int argc, const char *const *argv) {
6425 // If the name is not set, read from command line
6426 if(name_.empty() || has_automatic_name_) {
6427 has_automatic_name_ = true;
6428 name_ = argv[0];
6429 }
6430
6431 std::vector<std::string> args;
6432 args.reserve(static_cast<std::size_t>(argc) - 1);
6433 for(int i = argc - 1; i > 0; i--)
6434 args.emplace_back(argv[i]);
6435 parse(std::move(args));
6436 }
6437
6442 void parse(std::string commandline, bool program_name_included = false) {
6443
6444 if(program_name_included) {
6445 auto nstr = detail::split_program_name(commandline);
6446 if((name_.empty()) || (has_automatic_name_)) {
6447 has_automatic_name_ = true;
6448 name_ = nstr.first;
6449 }
6450 commandline = std::move(nstr.second);
6451 } else {
6452 detail::trim(commandline);
6453 }
6454 // the next section of code is to deal with quoted arguments after an '=' or ':' for windows like operations
6455 if(!commandline.empty()) {
6456 commandline = detail::find_and_modify(commandline, "=", detail::escape_detect);
6457 if(allow_windows_style_options_)
6458 commandline = detail::find_and_modify(commandline, ":", detail::escape_detect);
6459 }
6460
6461 auto args = detail::split_up(std::move(commandline));
6462 // remove all empty strings
6463 args.erase(std::remove(args.begin(), args.end(), std::string{}), args.end());
6464 std::reverse(args.begin(), args.end());
6465
6466 parse(std::move(args));
6467 }
6468
6471 void parse(std::vector<std::string> &args) {
6472 // Clear if parsed
6473 if(parsed_ > 0)
6474 clear();
6475
6476 // parsed_ is incremented in commands/subcommands,
6477 // but placed here to make sure this is cleared when
6478 // running parse after an error is thrown, even by _validate or _configure.
6479 parsed_ = 1;
6480 _validate();
6481 _configure();
6482 // set the parent as nullptr as this object should be the top now
6483 parent_ = nullptr;
6484 parsed_ = 0;
6485
6486 _parse(args);
6487 run_callback();
6488 }
6489
6491 void parse(std::vector<std::string> &&args) {
6492 // Clear if parsed
6493 if(parsed_ > 0)
6494 clear();
6495
6496 // parsed_ is incremented in commands/subcommands,
6497 // but placed here to make sure this is cleared when
6498 // running parse after an error is thrown, even by _validate or _configure.
6499 parsed_ = 1;
6500 _validate();
6501 _configure();
6502 // set the parent as nullptr as this object should be the top now
6503 parent_ = nullptr;
6504 parsed_ = 0;
6505
6506 _parse(std::move(args));
6507 run_callback();
6508 }
6509
6510 void parse_from_stream(std::istream &input) {
6511 if(parsed_ == 0) {
6512 _validate();
6513 _configure();
6514 // set the parent as nullptr as this object should be the top now
6515 }
6516
6517 _parse_stream(input);
6518 run_callback();
6519 }
6521 void failure_message(std::function<std::string(const App *, const Error &e)> function) {
6522 failure_message_ = function;
6523 }
6524
6526 int exit(const Error &e, std::ostream &out = std::cout, std::ostream &err = std::cerr) const {
6527
6529 if(e.get_name() == "RuntimeError")
6530 return e.get_exit_code();
6531
6532 if(e.get_name() == "CallForHelp") {
6533 out << help();
6534 return e.get_exit_code();
6535 }
6536
6537 if(e.get_name() == "CallForAllHelp") {
6538 out << help("", AppFormatMode::All);
6539 return e.get_exit_code();
6540 }
6541
6542 if(e.get_name() == "CallForVersion") {
6543 out << e.what() << std::endl;
6544 return e.get_exit_code();
6545 }
6546
6547 if(e.get_exit_code() != static_cast<int>(ExitCodes::Success)) {
6548 if(failure_message_)
6549 err << failure_message_(this, e) << std::flush;
6550 }
6551
6552 return e.get_exit_code();
6553 }
6554
6558
6560 std::size_t count(std::string option_name) const { return get_option(option_name)->count(); }
6561
6564 std::vector<App *> get_subcommands() const { return parsed_subcommands_; }
6565
6568 std::vector<const App *> get_subcommands(const std::function<bool(const App *)> &filter) const {
6569 std::vector<const App *> subcomms(subcommands_.size());
6570 std::transform(std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](const App_p &v) {
6571 return v.get();
6572 });
6573
6574 if(filter) {
6575 subcomms.erase(std::remove_if(std::begin(subcomms),
6576 std::end(subcomms),
6577 [&filter](const App *app) { return !filter(app); }),
6578 std::end(subcomms));
6579 }
6580
6581 return subcomms;
6582 }
6583
6586 std::vector<App *> get_subcommands(const std::function<bool(App *)> &filter) {
6587 std::vector<App *> subcomms(subcommands_.size());
6588 std::transform(std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](const App_p &v) {
6589 return v.get();
6590 });
6591
6592 if(filter) {
6593 subcomms.erase(
6594 std::remove_if(std::begin(subcomms), std::end(subcomms), [&filter](App *app) { return !filter(app); }),
6595 std::end(subcomms));
6596 }
6597
6598 return subcomms;
6599 }
6600
6602 bool got_subcommand(const App *subcom) const {
6603 // get subcom needed to verify that this was a real subcommand
6604 return get_subcommand(subcom)->parsed_ > 0;
6605 }
6606
6608 bool got_subcommand(std::string subcommand_name) const { return get_subcommand(subcommand_name)->parsed_ > 0; }
6609
6612 if(opt == nullptr) {
6613 throw OptionNotFound("nullptr passed");
6614 }
6615 exclude_options_.insert(opt);
6616 return this;
6617 }
6618
6621 if(app == nullptr) {
6622 throw OptionNotFound("nullptr passed");
6623 }
6624 if(app == this) {
6625 throw OptionNotFound("cannot self reference in needs");
6626 }
6627 auto res = exclude_subcommands_.insert(app);
6628 // subcommand exclusion should be symmetric
6629 if(res.second) {
6630 app->exclude_subcommands_.insert(this);
6631 }
6632 return this;
6633 }
6634
6636 if(opt == nullptr) {
6637 throw OptionNotFound("nullptr passed");
6638 }
6639 need_options_.insert(opt);
6640 return this;
6641 }
6642
6643 App *needs(App *app) {
6644 if(app == nullptr) {
6645 throw OptionNotFound("nullptr passed");
6646 }
6647 if(app == this) {
6648 throw OptionNotFound("cannot self reference in needs");
6649 }
6650 need_subcommands_.insert(app);
6651 return this;
6652 }
6653
6656 auto iterator = std::find(std::begin(exclude_options_), std::end(exclude_options_), opt);
6657 if(iterator == std::end(exclude_options_)) {
6658 return false;
6659 }
6660 exclude_options_.erase(iterator);
6661 return true;
6662 }
6663
6666 auto iterator = std::find(std::begin(exclude_subcommands_), std::end(exclude_subcommands_), app);
6667 if(iterator == std::end(exclude_subcommands_)) {
6668 return false;
6669 }
6670 auto other_app = *iterator;
6671 exclude_subcommands_.erase(iterator);
6672 other_app->remove_excludes(this);
6673 return true;
6674 }
6675
6678 auto iterator = std::find(std::begin(need_options_), std::end(need_options_), opt);
6679 if(iterator == std::end(need_options_)) {
6680 return false;
6681 }
6682 need_options_.erase(iterator);
6683 return true;
6684 }
6685
6687 bool remove_needs(App *app) {
6688 auto iterator = std::find(std::begin(need_subcommands_), std::end(need_subcommands_), app);
6689 if(iterator == std::end(need_subcommands_)) {
6690 return false;
6691 }
6692 need_subcommands_.erase(iterator);
6693 return true;
6694 }
6695
6699
6701 App *footer(std::string footer_string) {
6702 footer_ = std::move(footer_string);
6703 return this;
6704 }
6706 App *footer(std::function<std::string()> footer_function) {
6707 footer_callback_ = std::move(footer_function);
6708 return this;
6709 }
6712 std::string config_to_str(bool default_also = false, bool write_description = false) const {
6713 return config_formatter_->to_config(this, default_also, write_description, "");
6714 }
6715
6718 std::string help(std::string prev = "", AppFormatMode mode = AppFormatMode::Normal) const {
6719 if(prev.empty())
6720 prev = get_name();
6721 else
6722 prev += " " + get_name();
6723
6724 // Delegate to subcommand if needed
6725 auto selected_subcommands = get_subcommands();
6726 if(!selected_subcommands.empty()) {
6727 return selected_subcommands.at(0)->help(prev, mode);
6728 }
6729 return formatter_->make_help(this, prev, mode);
6730 }
6731
6733 std::string version() const {
6734 std::string val;
6735 if(version_ptr_ != nullptr) {
6736 auto rv = version_ptr_->results();
6737 version_ptr_->clear();
6738 version_ptr_->add_result("true");
6739 try {
6740 version_ptr_->run_callback();
6741 } catch(const CLI::CallForVersion &cfv) {
6742 val = cfv.what();
6743 }
6744 version_ptr_->clear();
6745 version_ptr_->add_result(rv);
6746 }
6747 return val;
6748 }
6752
6754 std::shared_ptr<FormatterBase> get_formatter() const { return formatter_; }
6755
6757 std::shared_ptr<Config> get_config_formatter() const { return config_formatter_; }
6758
6760 std::shared_ptr<ConfigBase> get_config_formatter_base() const {
6761 // This is safer as a dynamic_cast if we have RTTI, as Config -> ConfigBase
6762#if defined(__cpp_rtti) || (defined(__GXX_RTTI) && __GXX_RTTI) || (defined(_HAS_STATIC_RTTI) && (_HAS_STATIC_RTTI == 0))
6763 return std::dynamic_pointer_cast<ConfigBase>(config_formatter_);
6764#else
6765 return std::static_pointer_cast<ConfigBase>(config_formatter_);
6766#endif
6767 }
6768
6770 std::string get_description() const { return description_; }
6771
6773 App *description(std::string app_description) {
6774 description_ = std::move(app_description);
6775 return this;
6776 }
6777
6779 std::vector<const Option *> get_options(const std::function<bool(const Option *)> filter = {}) const {
6780 std::vector<const Option *> options(options_.size());
6781 std::transform(std::begin(options_), std::end(options_), std::begin(options), [](const Option_p &val) {
6782 return val.get();
6783 });
6784
6785 if(filter) {
6786 options.erase(std::remove_if(std::begin(options),
6787 std::end(options),
6788 [&filter](const Option *opt) { return !filter(opt); }),
6789 std::end(options));
6790 }
6791
6792 return options;
6793 }
6794
6796 std::vector<Option *> get_options(const std::function<bool(Option *)> filter = {}) {
6797 std::vector<Option *> options(options_.size());
6798 std::transform(std::begin(options_), std::end(options_), std::begin(options), [](const Option_p &val) {
6799 return val.get();
6800 });
6801
6802 if(filter) {
6803 options.erase(
6804 std::remove_if(std::begin(options), std::end(options), [&filter](Option *opt) { return !filter(opt); }),
6805 std::end(options));
6806 }
6807
6808 return options;
6809 }
6810
6812 Option *get_option_no_throw(std::string option_name) noexcept {
6813 for(Option_p &opt : options_) {
6814 if(opt->check_name(option_name)) {
6815 return opt.get();
6816 }
6817 }
6818 for(auto &subc : subcommands_) {
6819 // also check down into nameless subcommands
6820 if(subc->get_name().empty()) {
6821 auto opt = subc->get_option_no_throw(option_name);
6822 if(opt != nullptr) {
6823 return opt;
6824 }
6825 }
6826 }
6827 return nullptr;
6828 }
6829
6831 const Option *get_option_no_throw(std::string option_name) const noexcept {
6832 for(const Option_p &opt : options_) {
6833 if(opt->check_name(option_name)) {
6834 return opt.get();
6835 }
6836 }
6837 for(const auto &subc : subcommands_) {
6838 // also check down into nameless subcommands
6839 if(subc->get_name().empty()) {
6840 auto opt = subc->get_option_no_throw(option_name);
6841 if(opt != nullptr) {
6842 return opt;
6843 }
6844 }
6845 }
6846 return nullptr;
6847 }
6848
6850 const Option *get_option(std::string option_name) const {
6851 auto opt = get_option_no_throw(option_name);
6852 if(opt == nullptr) {
6853 throw OptionNotFound(option_name);
6854 }
6855 return opt;
6856 }
6857
6859 Option *get_option(std::string option_name) {
6860 auto opt = get_option_no_throw(option_name);
6861 if(opt == nullptr) {
6862 throw OptionNotFound(option_name);
6863 }
6864 return opt;
6865 }
6866
6868 const Option *operator[](const std::string &option_name) const { return get_option(option_name); }
6869
6871 const Option *operator[](const char *option_name) const { return get_option(option_name); }
6872
6874 bool get_ignore_case() const { return ignore_case_; }
6875
6877 bool get_ignore_underscore() const { return ignore_underscore_; }
6878
6880 bool get_fallthrough() const { return fallthrough_; }
6881
6883 bool get_allow_windows_style_options() const { return allow_windows_style_options_; }
6884
6886 bool get_positionals_at_end() const { return positionals_at_end_; }
6887
6889 bool get_configurable() const { return configurable_; }
6890
6892 const std::string &get_group() const { return group_; }
6893
6895 std::string get_footer() const { return (footer_callback_) ? footer_callback_() + '\n' + footer_ : footer_; }
6896
6898 std::size_t get_require_subcommand_min() const { return require_subcommand_min_; }
6899
6901 std::size_t get_require_subcommand_max() const { return require_subcommand_max_; }
6902
6904 std::size_t get_require_option_min() const { return require_option_min_; }
6905
6907 std::size_t get_require_option_max() const { return require_option_max_; }
6908
6910 bool get_prefix_command() const { return prefix_command_; }
6911
6913 bool get_allow_extras() const { return allow_extras_; }
6914
6916 bool get_required() const { return required_; }
6917
6919 bool get_disabled() const { return disabled_; }
6920
6922 bool get_silent() const { return silent_; }
6923
6925 bool get_immediate_callback() const { return immediate_callback_; }
6926
6928 bool get_disabled_by_default() const { return (default_startup == startup_mode::disabled); }
6929
6931 bool get_enabled_by_default() const { return (default_startup == startup_mode::enabled); }
6933 bool get_validate_positionals() const { return validate_positionals_; }
6934
6936 config_extras_mode get_allow_config_extras() const { return allow_config_extras_; }
6937
6939 Option *get_help_ptr() { return help_ptr_; }
6940
6942 const Option *get_help_ptr() const { return help_ptr_; }
6943
6945 const Option *get_help_all_ptr() const { return help_all_ptr_; }
6946
6948 Option *get_config_ptr() { return config_ptr_; }
6949
6951 const Option *get_config_ptr() const { return config_ptr_; }
6952
6954 Option *get_version_ptr() { return version_ptr_; }
6955
6957 const Option *get_version_ptr() const { return version_ptr_; }
6958
6960 App *get_parent() { return parent_; }
6961
6963 const App *get_parent() const { return parent_; }
6964
6966 const std::string &get_name() const { return name_; }
6967
6969 const std::vector<std::string> &get_aliases() const { return aliases_; }
6970
6973 aliases_.clear();
6974 return this;
6975 }
6976
6978 std::string get_display_name(bool with_aliases = false) const {
6979 if(name_.empty()) {
6980 return std::string("[Option Group: ") + get_group() + "]";
6981 }
6982 if(aliases_.empty() || !with_aliases) {
6983 return name_;
6984 }
6985 std::string dispname = name_;
6986 for(const auto &lalias : aliases_) {
6987 dispname.push_back(',');
6988 dispname.push_back(' ');
6989 dispname.append(lalias);
6990 }
6991 return dispname;
6992 }
6993
6995 bool check_name(std::string name_to_check) const {
6996 std::string local_name = name_;
6997 if(ignore_underscore_) {
6998 local_name = detail::remove_underscore(name_);
6999 name_to_check = detail::remove_underscore(name_to_check);
7000 }
7001 if(ignore_case_) {
7002 local_name = detail::to_lower(name_);
7003 name_to_check = detail::to_lower(name_to_check);
7004 }
7005
7006 if(local_name == name_to_check) {
7007 return true;
7008 }
7009 for(auto les : aliases_) {
7010 if(ignore_underscore_) {
7011 les = detail::remove_underscore(les);
7012 }
7013 if(ignore_case_) {
7014 les = detail::to_lower(les);
7015 }
7016 if(les == name_to_check) {
7017 return true;
7018 }
7019 }
7020 return false;
7021 }
7022
7024 std::vector<std::string> get_groups() const {
7025 std::vector<std::string> groups;
7026
7027 for(const Option_p &opt : options_) {
7028 // Add group if it is not already in there
7029 if(std::find(groups.begin(), groups.end(), opt->get_group()) == groups.end()) {
7030 groups.push_back(opt->get_group());
7031 }
7032 }
7033
7034 return groups;
7035 }
7036
7038 const std::vector<Option *> &parse_order() const { return parse_order_; }
7039
7041 std::vector<std::string> remaining(bool recurse = false) const {
7042 std::vector<std::string> miss_list;
7043 for(const std::pair<detail::Classifier, std::string> &miss : missing_) {
7044 miss_list.push_back(std::get<1>(miss));
7045 }
7046 // Get from a subcommand that may allow extras
7047 if(recurse) {
7048 if(!allow_extras_) {
7049 for(const auto &sub : subcommands_) {
7050 if(sub->name_.empty() && !sub->missing_.empty()) {
7051 for(const std::pair<detail::Classifier, std::string> &miss : sub->missing_) {
7052 miss_list.push_back(std::get<1>(miss));
7053 }
7054 }
7055 }
7056 }
7057 // Recurse into subcommands
7058
7059 for(const App *sub : parsed_subcommands_) {
7060 std::vector<std::string> output = sub->remaining(recurse);
7061 std::copy(std::begin(output), std::end(output), std::back_inserter(miss_list));
7062 }
7063 }
7064 return miss_list;
7065 }
7066
7068 std::vector<std::string> remaining_for_passthrough(bool recurse = false) const {
7069 std::vector<std::string> miss_list = remaining(recurse);
7070 std::reverse(std::begin(miss_list), std::end(miss_list));
7071 return miss_list;
7072 }
7073
7075 std::size_t remaining_size(bool recurse = false) const {
7076 auto remaining_options = static_cast<std::size_t>(std::count_if(
7077 std::begin(missing_), std::end(missing_), [](const std::pair<detail::Classifier, std::string> &val) {
7078 return val.first != detail::Classifier::POSITIONAL_MARK;
7079 }));
7080
7081 if(recurse) {
7082 for(const App_p &sub : subcommands_) {
7083 remaining_options += sub->remaining_size(recurse);
7084 }
7085 }
7086 return remaining_options;
7087 }
7088
7090
7091 protected:
7096 void _validate() const {
7097 // count the number of positional only args
7098 auto pcount = std::count_if(std::begin(options_), std::end(options_), [](const Option_p &opt) {
7099 return opt->get_items_expected_max() >= detail::expected_max_vector_size && !opt->nonpositional();
7100 });
7101 if(pcount > 1) {
7102 auto pcount_req = std::count_if(std::begin(options_), std::end(options_), [](const Option_p &opt) {
7103 return opt->get_items_expected_max() >= detail::expected_max_vector_size && !opt->nonpositional() &&
7104 opt->get_required();
7105 });
7106 if(pcount - pcount_req > 1) {
7107 throw InvalidError(name_);
7108 }
7109 }
7110
7111 std::size_t nameless_subs{0};
7112 for(const App_p &app : subcommands_) {
7113 app->_validate();
7114 if(app->get_name().empty())
7115 ++nameless_subs;
7116 }
7117
7118 if(require_option_min_ > 0) {
7119 if(require_option_max_ > 0) {
7120 if(require_option_max_ < require_option_min_) {
7121 throw(InvalidError("Required min options greater than required max options",
7122 ExitCodes::InvalidError));
7123 }
7124 }
7125 if(require_option_min_ > (options_.size() + nameless_subs)) {
7126 throw(InvalidError("Required min options greater than number of available options",
7127 ExitCodes::InvalidError));
7128 }
7129 }
7130 }
7131
7135 void _configure() {
7136 if(default_startup == startup_mode::enabled) {
7137 disabled_ = false;
7138 } else if(default_startup == startup_mode::disabled) {
7139 disabled_ = true;
7140 }
7141 for(const App_p &app : subcommands_) {
7142 if(app->has_automatic_name_) {
7143 app->name_.clear();
7144 }
7145 if(app->name_.empty()) {
7146 app->fallthrough_ = false; // make sure fallthrough_ is false to prevent infinite loop
7147 app->prefix_command_ = false;
7148 }
7149 // make sure the parent is set to be this object in preparation for parse
7150 app->parent_ = this;
7151 app->_configure();
7152 }
7153 }
7154
7156 void run_callback(bool final_mode = false, bool suppress_final_callback = false) {
7157 pre_callback();
7158 // in the main app if immediate_callback_ is set it runs the main callback before the used subcommands
7159 if(!final_mode && parse_complete_callback_) {
7160 parse_complete_callback_();
7161 }
7162 // run the callbacks for the received subcommands
7163 for(App *subc : get_subcommands()) {
7164 subc->run_callback(true, suppress_final_callback);
7165 }
7166 // now run callbacks for option_groups
7167 for(auto &subc : subcommands_) {
7168 if(subc->name_.empty() && subc->count_all() > 0) {
7169 subc->run_callback(true, suppress_final_callback);
7170 }
7171 }
7172
7173 // finally run the main callback
7174 if(final_callback_ && (parsed_ > 0) && (!suppress_final_callback)) {
7175 if(!name_.empty() || count_all() > 0 || parent_ == nullptr) {
7176 final_callback_();
7177 }
7178 }
7179 }
7180
7182 bool _valid_subcommand(const std::string &current, bool ignore_used = true) const {
7183 // Don't match if max has been reached - but still check parents
7184 if(require_subcommand_max_ != 0 && parsed_subcommands_.size() >= require_subcommand_max_) {
7185 return parent_ != nullptr && parent_->_valid_subcommand(current, ignore_used);
7186 }
7187 auto com = _find_subcommand(current, true, ignore_used);
7188 if(com != nullptr) {
7189 return true;
7190 }
7191 // Check parent if exists, else return false
7192 return parent_ != nullptr && parent_->_valid_subcommand(current, ignore_used);
7193 }
7194
7196 detail::Classifier _recognize(const std::string &current, bool ignore_used_subcommands = true) const {
7197 std::string dummy1, dummy2;
7198
7199 if(current == "--")
7200 return detail::Classifier::POSITIONAL_MARK;
7201 if(_valid_subcommand(current, ignore_used_subcommands))
7202 return detail::Classifier::SUBCOMMAND;
7203 if(detail::split_long(current, dummy1, dummy2))
7204 return detail::Classifier::LONG;
7205 if(detail::split_short(current, dummy1, dummy2)) {
7206 if(dummy1[0] >= '0' && dummy1[0] <= '9') {
7207 if(get_option_no_throw(std::string{'-', dummy1[0]}) == nullptr) {
7208 return detail::Classifier::NONE;
7209 }
7210 }
7211 return detail::Classifier::SHORT;
7212 }
7213 if((allow_windows_style_options_) && (detail::split_windows_style(current, dummy1, dummy2)))
7214 return detail::Classifier::WINDOWS_STYLE;
7215 if((current == "++") && !name_.empty() && parent_ != nullptr)
7216 return detail::Classifier::SUBCOMMAND_TERMINATOR;
7217 return detail::Classifier::NONE;
7218 }
7219
7220 // The parse function is now broken into several parts, and part of process
7221
7224 if(config_ptr_ != nullptr) {
7225 bool config_required = config_ptr_->get_required();
7226 auto file_given = config_ptr_->count() > 0;
7227 auto config_files = config_ptr_->as<std::vector<std::string>>();
7228 if(config_files.empty() || config_files.front().empty()) {
7229 if(config_required) {
7230 throw FileError::Missing("no specified config file");
7231 }
7232 return;
7233 }
7234 for(auto rit = config_files.rbegin(); rit != config_files.rend(); ++rit) {
7235 const auto &config_file = *rit;
7236 auto path_result = detail::check_path(config_file.c_str());
7237 if(path_result == detail::path_type::file) {
7238 try {
7239 std::vector<ConfigItem> values = config_formatter_->from_file(config_file);
7240 _parse_config(values);
7241 if(!file_given) {
7242 config_ptr_->add_result(config_file);
7243 }
7244 } catch(const FileError &) {
7245 if(config_required || file_given)
7246 throw;
7247 }
7248 } else if(config_required || file_given) {
7249 throw FileError::Missing(config_file);
7250 }
7251 }
7252 }
7253 }
7254
7257 for(const Option_p &opt : options_) {
7258 if(opt->count() == 0 && !opt->envname_.empty()) {
7259 char *buffer = nullptr;
7260 std::string ename_string;
7261
7262#ifdef _MSC_VER
7263 // Windows version
7264 std::size_t sz = 0;
7265 if(_dupenv_s(&buffer, &sz, opt->envname_.c_str()) == 0 && buffer != nullptr) {
7266 ename_string = std::string(buffer);
7267 free(buffer);
7268 }
7269#else
7270 // This also works on Windows, but gives a warning
7271 buffer = std::getenv(opt->envname_.c_str());
7272 if(buffer != nullptr)
7273 ename_string = std::string(buffer);
7274#endif
7275
7276 if(!ename_string.empty()) {
7277 opt->add_result(ename_string);
7278 }
7279 }
7280 }
7281
7282 for(App_p &sub : subcommands_) {
7283 if(sub->get_name().empty() || !sub->parse_complete_callback_)
7284 sub->_process_env();
7285 }
7286 }
7287
7290
7291 for(App_p &sub : subcommands_) {
7292 // process the priority option_groups first
7293 if(sub->get_name().empty() && sub->parse_complete_callback_) {
7294 if(sub->count_all() > 0) {
7295 sub->_process_callbacks();
7296 sub->run_callback();
7297 }
7298 }
7299 }
7300
7301 for(const Option_p &opt : options_) {
7302 if((*opt) && !opt->get_callback_run()) {
7303 opt->run_callback();
7304 }
7305 }
7306 for(App_p &sub : subcommands_) {
7307 if(!sub->parse_complete_callback_) {
7308 sub->_process_callbacks();
7309 }
7310 }
7311 }
7312
7316 void _process_help_flags(bool trigger_help = false, bool trigger_all_help = false) const {
7317 const Option *help_ptr = get_help_ptr();
7318 const Option *help_all_ptr = get_help_all_ptr();
7319
7320 if(help_ptr != nullptr && help_ptr->count() > 0)
7321 trigger_help = true;
7322 if(help_all_ptr != nullptr && help_all_ptr->count() > 0)
7323 trigger_all_help = true;
7324
7325 // If there were parsed subcommands, call those. First subcommand wins if there are multiple ones.
7326 if(!parsed_subcommands_.empty()) {
7327 for(const App *sub : parsed_subcommands_)
7328 sub->_process_help_flags(trigger_help, trigger_all_help);
7329
7330 // Only the final subcommand should call for help. All help wins over help.
7331 } else if(trigger_all_help) {
7332 throw CallForAllHelp();
7333 } else if(trigger_help) {
7334 throw CallForHelp();
7335 }
7336 }
7337
7340 // check excludes
7341 bool excluded{false};
7342 std::string excluder;
7343 for(auto &opt : exclude_options_) {
7344 if(opt->count() > 0) {
7345 excluded = true;
7346 excluder = opt->get_name();
7347 }
7348 }
7349 for(auto &subc : exclude_subcommands_) {
7350 if(subc->count_all() > 0) {
7351 excluded = true;
7352 excluder = subc->get_display_name();
7353 }
7354 }
7355 if(excluded) {
7356 if(count_all() > 0) {
7357 throw ExcludesError(get_display_name(), excluder);
7358 }
7359 // if we are excluded but didn't receive anything, just return
7360 return;
7361 }
7362
7363 // check excludes
7364 bool missing_needed{false};
7365 std::string missing_need;
7366 for(auto &opt : need_options_) {
7367 if(opt->count() == 0) {
7368 missing_needed = true;
7369 missing_need = opt->get_name();
7370 }
7371 }
7372 for(auto &subc : need_subcommands_) {
7373 if(subc->count_all() == 0) {
7374 missing_needed = true;
7375 missing_need = subc->get_display_name();
7376 }
7377 }
7378 if(missing_needed) {
7379 if(count_all() > 0) {
7380 throw RequiresError(get_display_name(), missing_need);
7381 }
7382 // if we missing something but didn't have any options, just return
7383 return;
7384 }
7385
7386 std::size_t used_options = 0;
7387 for(const Option_p &opt : options_) {
7388
7389 if(opt->count() != 0) {
7390 ++used_options;
7391 }
7392 // Required but empty
7393 if(opt->get_required() && opt->count() == 0) {
7394 throw RequiredError(opt->get_name());
7395 }
7396 // Requires
7397 for(const Option *opt_req : opt->needs_)
7398 if(opt->count() > 0 && opt_req->count() == 0)
7399 throw RequiresError(opt->get_name(), opt_req->get_name());
7400 // Excludes
7401 for(const Option *opt_ex : opt->excludes_)
7402 if(opt->count() > 0 && opt_ex->count() != 0)
7403 throw ExcludesError(opt->get_name(), opt_ex->get_name());
7404 }
7405 // check for the required number of subcommands
7406 if(require_subcommand_min_ > 0) {
7407 auto selected_subcommands = get_subcommands();
7408 if(require_subcommand_min_ > selected_subcommands.size())
7409 throw RequiredError::Subcommand(require_subcommand_min_);
7410 }
7411
7412 // Max error cannot occur, the extra subcommand will parse as an ExtrasError or a remaining item.
7413
7414 // run this loop to check how many unnamed subcommands were actually used since they are considered options
7415 // from the perspective of an App
7416 for(App_p &sub : subcommands_) {
7417 if(sub->disabled_)
7418 continue;
7419 if(sub->name_.empty() && sub->count_all() > 0) {
7420 ++used_options;
7421 }
7422 }
7423
7424 if(require_option_min_ > used_options || (require_option_max_ > 0 && require_option_max_ < used_options)) {
7425 auto option_list = detail::join(options_, [this](const Option_p &ptr) {
7426 if(ptr.get() == help_ptr_ || ptr.get() == help_all_ptr_) {
7427 return std::string{};
7428 }
7429 return ptr->get_name(false, true);
7430 });
7431
7432 auto subc_list = get_subcommands([](App *app) { return ((app->get_name().empty()) && (!app->disabled_)); });
7433 if(!subc_list.empty()) {
7434 option_list += "," + detail::join(subc_list, [](const App *app) { return app->get_display_name(); });
7435 }
7436 throw RequiredError::Option(require_option_min_, require_option_max_, used_options, option_list);
7437 }
7438
7439 // now process the requirements for subcommands if needed
7440 for(App_p &sub : subcommands_) {
7441 if(sub->disabled_)
7442 continue;
7443 if(sub->name_.empty() && sub->required_ == false) {
7444 if(sub->count_all() == 0) {
7445 if(require_option_min_ > 0 && require_option_min_ <= used_options) {
7446 continue;
7447 // if we have met the requirement and there is nothing in this option group skip checking
7448 // requirements
7449 }
7450 if(require_option_max_ > 0 && used_options >= require_option_min_) {
7451 continue;
7452 // if we have met the requirement and there is nothing in this option group skip checking
7453 // requirements
7454 }
7455 }
7456 }
7457 if(sub->count() > 0 || sub->name_.empty()) {
7458 sub->_process_requirements();
7459 }
7460
7461 if(sub->required_ && sub->count_all() == 0) {
7462 throw(CLI::RequiredError(sub->get_display_name()));
7463 }
7464 }
7465 }
7466
7468 void _process() {
7469 CLI::FileError fe("ne");
7470 bool caught_error{false};
7471 try {
7472 // the config file might generate a FileError but that should not be processed until later in the process
7473 // to allow for help, version and other errors to generate first.
7474 _process_config_file();
7475 // process env shouldn't throw but no reason to process it if config generated an error
7476 _process_env();
7477 } catch(const CLI::FileError &fe2) {
7478 fe = fe2;
7479 caught_error = true;
7480 }
7481 // callbacks and help_flags can generate exceptions which should take priority over the config file error if one
7482 // exists
7483 _process_callbacks();
7484 _process_help_flags();
7485
7486 if(caught_error) {
7487 throw CLI::FileError(std::move(fe));
7488 }
7489
7490 _process_requirements();
7491 }
7492
7495 if(!(allow_extras_ || prefix_command_)) {
7496 std::size_t num_left_over = remaining_size();
7497 if(num_left_over > 0) {
7498 throw ExtrasError(name_, remaining(false));
7499 }
7500 }
7501
7502 for(App_p &sub : subcommands_) {
7503 if(sub->count() > 0)
7504 sub->_process_extras();
7505 }
7506 }
7507
7510 void _process_extras(std::vector<std::string> &args) {
7511 if(!(allow_extras_ || prefix_command_)) {
7512 std::size_t num_left_over = remaining_size();
7513 if(num_left_over > 0) {
7514 args = remaining(false);
7515 throw ExtrasError(name_, args);
7516 }
7517 }
7518
7519 for(App_p &sub : subcommands_) {
7520 if(sub->count() > 0)
7521 sub->_process_extras(args);
7522 }
7523 }
7524
7527 ++parsed_;
7528 for(App_p &sub : subcommands_) {
7529 if(sub->get_name().empty())
7530 sub->increment_parsed();
7531 }
7532 }
7534 void _parse(std::vector<std::string> &args) {
7535 increment_parsed();
7536 _trigger_pre_parse(args.size());
7537 bool positional_only = false;
7538
7539 while(!args.empty()) {
7540 if(!_parse_single(args, positional_only)) {
7541 break;
7542 }
7543 }
7544
7545 if(parent_ == nullptr) {
7546 _process();
7547
7548 // Throw error if any items are left over (depending on settings)
7549 _process_extras(args);
7550
7551 // Convert missing (pairs) to extras (string only) ready for processing in another app
7552 args = remaining_for_passthrough(false);
7553 } else if(parse_complete_callback_) {
7554 _process_env();
7555 _process_callbacks();
7556 _process_help_flags();
7557 _process_requirements();
7558 run_callback(false, true);
7559 }
7560 }
7561
7563 void _parse(std::vector<std::string> &&args) {
7564 // this can only be called by the top level in which case parent == nullptr by definition
7565 // operation is simplified
7566 increment_parsed();
7567 _trigger_pre_parse(args.size());
7568 bool positional_only = false;
7569
7570 while(!args.empty()) {
7571 _parse_single(args, positional_only);
7572 }
7573 _process();
7574
7575 // Throw error if any items are left over (depending on settings)
7576 _process_extras();
7577 }
7578
7580 void _parse_stream(std::istream &input) {
7581 auto values = config_formatter_->from_config(input);
7582 _parse_config(values);
7583 increment_parsed();
7584 _trigger_pre_parse(values.size());
7585 _process();
7586
7587 // Throw error if any items are left over (depending on settings)
7588 _process_extras();
7589 }
7590
7595 void _parse_config(const std::vector<ConfigItem> &args) {
7596 for(const ConfigItem &item : args) {
7597 if(!_parse_single_config(item) && allow_config_extras_ == config_extras_mode::error)
7598 throw ConfigError::Extras(item.fullname());
7599 }
7600 }
7601
7603 bool _parse_single_config(const ConfigItem &item, std::size_t level = 0) {
7604 if(level < item.parents.size()) {
7605 try {
7606 auto subcom = get_subcommand(item.parents.at(level));
7607 auto result = subcom->_parse_single_config(item, level + 1);
7608
7609 return result;
7610 } catch(const OptionNotFound &) {
7611 return false;
7612 }
7613 }
7614 // check for section open
7615 if(item.name == "++") {
7616 if(configurable_) {
7617 increment_parsed();
7618 _trigger_pre_parse(2);
7619 if(parent_ != nullptr) {
7620 parent_->parsed_subcommands_.push_back(this);
7621 }
7622 }
7623 return true;
7624 }
7625 // check for section close
7626 if(item.name == "--") {
7627 if(configurable_) {
7628 _process_callbacks();
7629 _process_requirements();
7630 run_callback();
7631 }
7632 return true;
7633 }
7634 Option *op = get_option_no_throw("--" + item.name);
7635 if(op == nullptr) {
7636 if(item.name.size() == 1) {
7637 op = get_option_no_throw("-" + item.name);
7638 }
7639 }
7640 if(op == nullptr) {
7641 op = get_option_no_throw(item.name);
7642 }
7643 if(op == nullptr) {
7644 // If the option was not present
7645 if(get_allow_config_extras() == config_extras_mode::capture)
7646 // Should we worry about classifying the extras properly?
7647 missing_.emplace_back(detail::Classifier::NONE, item.fullname());
7648 return false;
7649 }
7650
7651 if(!op->get_configurable()) {
7652 if(get_allow_config_extras() == config_extras_mode::ignore_all) {
7653 return false;
7654 }
7655 throw ConfigError::NotConfigurable(item.fullname());
7656 }
7657
7658 if(op->empty()) {
7659 // Flag parsing
7660 if(op->get_expected_min() == 0) {
7661 auto res = config_formatter_->to_flag(item);
7662 res = op->get_flag_value(item.name, res);
7663
7664 op->add_result(res);
7665
7666 } else {
7667 op->add_result(item.inputs);
7668 op->run_callback();
7669 }
7670 }
7671
7672 return true;
7673 }
7674
7677 bool _parse_single(std::vector<std::string> &args, bool &positional_only) {
7678 bool retval = true;
7679 detail::Classifier classifier = positional_only ? detail::Classifier::NONE : _recognize(args.back());
7680 switch(classifier) {
7681 case detail::Classifier::POSITIONAL_MARK:
7682 args.pop_back();
7683 positional_only = true;
7684 if((!_has_remaining_positionals()) && (parent_ != nullptr)) {
7685 retval = false;
7686 } else {
7687 _move_to_missing(classifier, "--");
7688 }
7689 break;
7690 case detail::Classifier::SUBCOMMAND_TERMINATOR:
7691 // treat this like a positional mark if in the parent app
7692 args.pop_back();
7693 retval = false;
7694 break;
7695 case detail::Classifier::SUBCOMMAND:
7696 retval = _parse_subcommand(args);
7697 break;
7698 case detail::Classifier::LONG:
7699 case detail::Classifier::SHORT:
7700 case detail::Classifier::WINDOWS_STYLE:
7701 // If already parsed a subcommand, don't accept options_
7702 _parse_arg(args, classifier);
7703 break;
7704 case detail::Classifier::NONE:
7705 // Probably a positional or something for a parent (sub)command
7706 retval = _parse_positional(args, false);
7707 if(retval && positionals_at_end_) {
7708 positional_only = true;
7709 }
7710 break;
7711 // LCOV_EXCL_START
7712 default:
7713 throw HorribleError("unrecognized classifier (you should not see this!)");
7714 // LCOV_EXCL_STOP
7715 }
7716 return retval;
7717 }
7718
7720 std::size_t _count_remaining_positionals(bool required_only = false) const {
7721 std::size_t retval = 0;
7722 for(const Option_p &opt : options_) {
7723 if(opt->get_positional() && (!required_only || opt->get_required())) {
7724 if(opt->get_items_expected_min() > 0 &&
7725 static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
7726 retval += static_cast<std::size_t>(opt->get_items_expected_min()) - opt->count();
7727 }
7728 }
7729 }
7730 return retval;
7731 }
7732
7735 for(const Option_p &opt : options_) {
7736 if(opt->get_positional() && ((static_cast<int>(opt->count()) < opt->get_items_expected_min()))) {
7737 return true;
7738 }
7739 }
7740
7741 return false;
7742 }
7743
7747 bool _parse_positional(std::vector<std::string> &args, bool haltOnSubcommand) {
7748
7749 const std::string &positional = args.back();
7750
7751 if(positionals_at_end_) {
7752 // deal with the case of required arguments at the end which should take precedence over other arguments
7753 auto arg_rem = args.size();
7754 auto remreq = _count_remaining_positionals(true);
7755 if(arg_rem <= remreq) {
7756 for(const Option_p &opt : options_) {
7757 if(opt->get_positional() && opt->required_) {
7758 if(static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
7759 if(validate_positionals_) {
7760 std::string pos = positional;
7761 pos = opt->_validate(pos, 0);
7762 if(!pos.empty()) {
7763 continue;
7764 }
7765 }
7766 opt->add_result(positional);
7767 parse_order_.push_back(opt.get());
7768 args.pop_back();
7769 return true;
7770 }
7771 }
7772 }
7773 }
7774 }
7775 for(const Option_p &opt : options_) {
7776 // Eat options, one by one, until done
7777 if(opt->get_positional() &&
7778 (static_cast<int>(opt->count()) < opt->get_items_expected_min() || opt->get_allow_extra_args())) {
7779 if(validate_positionals_) {
7780 std::string pos = positional;
7781 pos = opt->_validate(pos, 0);
7782 if(!pos.empty()) {
7783 continue;
7784 }
7785 }
7786 opt->add_result(positional);
7787 parse_order_.push_back(opt.get());
7788 args.pop_back();
7789 return true;
7790 }
7791 }
7792
7793 for(auto &subc : subcommands_) {
7794 if((subc->name_.empty()) && (!subc->disabled_)) {
7795 if(subc->_parse_positional(args, false)) {
7796 if(!subc->pre_parse_called_) {
7797 subc->_trigger_pre_parse(args.size());
7798 }
7799 return true;
7800 }
7801 }
7802 }
7803 // let the parent deal with it if possible
7804 if(parent_ != nullptr && fallthrough_)
7805 return _get_fallthrough_parent()->_parse_positional(args, static_cast<bool>(parse_complete_callback_));
7806
7808 auto com = _find_subcommand(args.back(), true, false);
7809 if(com != nullptr && (require_subcommand_max_ == 0 || require_subcommand_max_ > parsed_subcommands_.size())) {
7810 if(haltOnSubcommand) {
7811 return false;
7812 }
7813 args.pop_back();
7814 com->_parse(args);
7815 return true;
7816 }
7819 auto parent_app = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
7820 com = parent_app->_find_subcommand(args.back(), true, false);
7821 if(com != nullptr && (com->parent_->require_subcommand_max_ == 0 ||
7822 com->parent_->require_subcommand_max_ > com->parent_->parsed_subcommands_.size())) {
7823 return false;
7824 }
7825
7826 if(positionals_at_end_) {
7827 throw CLI::ExtrasError(name_, args);
7828 }
7830 if(parent_ != nullptr && name_.empty()) {
7831 return false;
7832 }
7834 _move_to_missing(detail::Classifier::NONE, positional);
7835 args.pop_back();
7836 if(prefix_command_) {
7837 while(!args.empty()) {
7838 _move_to_missing(detail::Classifier::NONE, args.back());
7839 args.pop_back();
7840 }
7841 }
7842
7843 return true;
7844 }
7845
7848 App *_find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept {
7849 for(const App_p &com : subcommands_) {
7850 if(com->disabled_ && ignore_disabled)
7851 continue;
7852 if(com->get_name().empty()) {
7853 auto subc = com->_find_subcommand(subc_name, ignore_disabled, ignore_used);
7854 if(subc != nullptr) {
7855 return subc;
7856 }
7857 }
7858 if(com->check_name(subc_name)) {
7859 if((!*com) || !ignore_used)
7860 return com.get();
7861 }
7862 }
7863 return nullptr;
7864 }
7865
7870 bool _parse_subcommand(std::vector<std::string> &args) {
7871 if(_count_remaining_positionals(/* required */ true) > 0) {
7872 _parse_positional(args, false);
7873 return true;
7874 }
7875 auto com = _find_subcommand(args.back(), true, true);
7876 if(com != nullptr) {
7877 args.pop_back();
7878 if(!com->silent_) {
7879 parsed_subcommands_.push_back(com);
7880 }
7881 com->_parse(args);
7882 auto parent_app = com->parent_;
7883 while(parent_app != this) {
7884 parent_app->_trigger_pre_parse(args.size());
7885 if(!com->silent_) {
7886 parent_app->parsed_subcommands_.push_back(com);
7887 }
7888 parent_app = parent_app->parent_;
7889 }
7890 return true;
7891 }
7892
7893 if(parent_ == nullptr)
7894 throw HorribleError("Subcommand " + args.back() + " missing");
7895 return false;
7896 }
7897
7900 bool _parse_arg(std::vector<std::string> &args, detail::Classifier current_type) {
7901
7902 std::string current = args.back();
7903
7904 std::string arg_name;
7905 std::string value;
7906 std::string rest;
7907
7908 switch(current_type) {
7909 case detail::Classifier::LONG:
7910 if(!detail::split_long(current, arg_name, value))
7911 throw HorribleError("Long parsed but missing (you should not see this):" + args.back());
7912 break;
7913 case detail::Classifier::SHORT:
7914 if(!detail::split_short(current, arg_name, rest))
7915 throw HorribleError("Short parsed but missing! You should not see this");
7916 break;
7917 case detail::Classifier::WINDOWS_STYLE:
7918 if(!detail::split_windows_style(current, arg_name, value))
7919 throw HorribleError("windows option parsed but missing! You should not see this");
7920 break;
7921 case detail::Classifier::SUBCOMMAND:
7922 case detail::Classifier::SUBCOMMAND_TERMINATOR:
7923 case detail::Classifier::POSITIONAL_MARK:
7924 case detail::Classifier::NONE:
7925 default:
7926 throw HorribleError("parsing got called with invalid option! You should not see this");
7927 }
7928
7929 auto op_ptr =
7930 std::find_if(std::begin(options_), std::end(options_), [arg_name, current_type](const Option_p &opt) {
7931 if(current_type == detail::Classifier::LONG)
7932 return opt->check_lname(arg_name);
7933 if(current_type == detail::Classifier::SHORT)
7934 return opt->check_sname(arg_name);
7935 // this will only get called for detail::Classifier::WINDOWS_STYLE
7936 return opt->check_lname(arg_name) || opt->check_sname(arg_name);
7937 });
7938
7939 // Option not found
7940 if(op_ptr == std::end(options_)) {
7941 for(auto &subc : subcommands_) {
7942 if(subc->name_.empty() && !subc->disabled_) {
7943 if(subc->_parse_arg(args, current_type)) {
7944 if(!subc->pre_parse_called_) {
7945 subc->_trigger_pre_parse(args.size());
7946 }
7947 return true;
7948 }
7949 }
7950 }
7951 // If a subcommand, try the main command
7952 if(parent_ != nullptr && fallthrough_)
7953 return _get_fallthrough_parent()->_parse_arg(args, current_type);
7954 // don't capture missing if this is a nameless subcommand
7955 if(parent_ != nullptr && name_.empty()) {
7956 return false;
7957 }
7958 // Otherwise, add to missing
7959 args.pop_back();
7960 _move_to_missing(current_type, current);
7961 return true;
7962 }
7963
7964 args.pop_back();
7965
7966 // Get a reference to the pointer to make syntax bearable
7967 Option_p &op = *op_ptr;
7969 if(op->get_inject_separator()) {
7970 if(!op->results().empty() && !op->results().back().empty()) {
7971 op->add_result(std::string{});
7972 }
7973 }
7974 if(op->get_trigger_on_parse() && op->current_option_state_ == Option::option_state::callback_run) {
7975 op->clear();
7976 }
7977 int min_num = (std::min)(op->get_type_size_min(), op->get_items_expected_min());
7978 int max_num = op->get_items_expected_max();
7979 // check container like options to limit the argument size to a single type if the allow_extra_flags argument is
7980 // set. 16 is somewhat arbitrary (needs to be at least 4)
7981 if(max_num >= detail::expected_max_vector_size / 16 && !op->get_allow_extra_args()) {
7982 auto tmax = op->get_type_size_max();
7983 max_num = detail::checked_multiply(tmax, op->get_expected_min()) ? tmax : detail::expected_max_vector_size;
7984 }
7985 // Make sure we always eat the minimum for unlimited vectors
7986 int collected = 0; // total number of arguments collected
7987 int result_count = 0; // local variable for number of results in a single arg string
7988 // deal with purely flag like things
7989 if(max_num == 0) {
7990 auto res = op->get_flag_value(arg_name, value);
7991 op->add_result(res);
7992 parse_order_.push_back(op.get());
7993 } else if(!value.empty()) { // --this=value
7994 op->add_result(value, result_count);
7995 parse_order_.push_back(op.get());
7996 collected += result_count;
7997 // -Trest
7998 } else if(!rest.empty()) {
7999 op->add_result(rest, result_count);
8000 parse_order_.push_back(op.get());
8001 rest = "";
8002 collected += result_count;
8003 }
8004
8005 // gather the minimum number of arguments
8006 while(min_num > collected && !args.empty()) {
8007 std::string current_ = args.back();
8008 args.pop_back();
8009 op->add_result(current_, result_count);
8010 parse_order_.push_back(op.get());
8011 collected += result_count;
8012 }
8013
8014 if(min_num > collected) { // if we have run out of arguments and the minimum was not met
8015 throw ArgumentMismatch::TypedAtLeast(op->get_name(), min_num, op->get_type_name());
8016 }
8017
8018 if(max_num > collected || op->get_allow_extra_args()) { // we allow optional arguments
8019 auto remreqpos = _count_remaining_positionals(true);
8020 // we have met the minimum now optionally check up to the maximum
8021 while((collected < max_num || op->get_allow_extra_args()) && !args.empty() &&
8022 _recognize(args.back(), false) == detail::Classifier::NONE) {
8023 // If any required positionals remain, don't keep eating
8024 if(remreqpos >= args.size()) {
8025 break;
8026 }
8027
8028 op->add_result(args.back(), result_count);
8029 parse_order_.push_back(op.get());
8030 args.pop_back();
8031 collected += result_count;
8032 }
8033
8034 // Allow -- to end an unlimited list and "eat" it
8035 if(!args.empty() && _recognize(args.back()) == detail::Classifier::POSITIONAL_MARK)
8036 args.pop_back();
8037 // optional flag that didn't receive anything now get the default value
8038 if(min_num == 0 && max_num > 0 && collected == 0) {
8039 auto res = op->get_flag_value(arg_name, std::string{});
8040 op->add_result(res);
8041 parse_order_.push_back(op.get());
8042 }
8043 }
8044
8045 // if we only partially completed a type then add an empty string for later processing
8046 if(min_num > 0 && op->get_type_size_max() != min_num && (collected % op->get_type_size_max()) != 0) {
8047 op->add_result(std::string{});
8048 }
8049 if(op->get_trigger_on_parse()) {
8050 op->run_callback();
8051 }
8052 if(!rest.empty()) {
8053 rest = "-" + rest;
8054 args.push_back(rest);
8055 }
8056 return true;
8057 }
8058
8060 void _trigger_pre_parse(std::size_t remaining_args) {
8061 if(!pre_parse_called_) {
8062 pre_parse_called_ = true;
8063 if(pre_parse_callback_) {
8064 pre_parse_callback_(remaining_args);
8065 }
8066 } else if(immediate_callback_) {
8067 if(!name_.empty()) {
8068 auto pcnt = parsed_;
8069 auto extras = std::move(missing_);
8070 clear();
8071 parsed_ = pcnt;
8072 pre_parse_called_ = true;
8073 missing_ = std::move(extras);
8074 }
8075 }
8076 }
8077
8080 if(parent_ == nullptr) {
8081 throw(HorribleError("No Valid parent"));
8082 }
8083 auto fallthrough_parent = parent_;
8084 while((fallthrough_parent->parent_ != nullptr) && (fallthrough_parent->get_name().empty())) {
8085 fallthrough_parent = fallthrough_parent->parent_;
8086 }
8087 return fallthrough_parent;
8088 }
8089
8091 const std::string &_compare_subcommand_names(const App &subcom, const App &base) const {
8092 static const std::string estring;
8093 if(subcom.disabled_) {
8094 return estring;
8095 }
8096 for(auto &subc : base.subcommands_) {
8097 if(subc.get() != &subcom) {
8098 if(subc->disabled_) {
8099 continue;
8100 }
8101 if(!subcom.get_name().empty()) {
8102 if(subc->check_name(subcom.get_name())) {
8103 return subcom.get_name();
8104 }
8105 }
8106 if(!subc->get_name().empty()) {
8107 if(subcom.check_name(subc->get_name())) {
8108 return subc->get_name();
8109 }
8110 }
8111 for(const auto &les : subcom.aliases_) {
8112 if(subc->check_name(les)) {
8113 return les;
8114 }
8115 }
8116 // this loop is needed in case of ignore_underscore or ignore_case on one but not the other
8117 for(const auto &les : subc->aliases_) {
8118 if(subcom.check_name(les)) {
8119 return les;
8120 }
8121 }
8122 // if the subcommand is an option group we need to check deeper
8123 if(subc->get_name().empty()) {
8124 auto &cmpres = _compare_subcommand_names(subcom, *subc);
8125 if(!cmpres.empty()) {
8126 return cmpres;
8127 }
8128 }
8129 // if the test subcommand is an option group we need to check deeper
8130 if(subcom.get_name().empty()) {
8131 auto &cmpres = _compare_subcommand_names(*subc, subcom);
8132 if(!cmpres.empty()) {
8133 return cmpres;
8134 }
8135 }
8136 }
8137 }
8138 return estring;
8139 }
8141 void _move_to_missing(detail::Classifier val_type, const std::string &val) {
8142 if(allow_extras_ || subcommands_.empty()) {
8143 missing_.emplace_back(val_type, val);
8144 return;
8145 }
8146 // allow extra arguments to be places in an option group if it is allowed there
8147 for(auto &subc : subcommands_) {
8148 if(subc->name_.empty() && subc->allow_extras_) {
8149 subc->missing_.emplace_back(val_type, val);
8150 return;
8151 }
8152 }
8153 // if we haven't found any place to put them yet put them in missing
8154 missing_.emplace_back(val_type, val);
8155 }
8156
8157 public:
8159 void _move_option(Option *opt, App *app) {
8160 if(opt == nullptr) {
8161 throw OptionNotFound("the option is NULL");
8162 }
8163 // verify that the give app is actually a subcommand
8164 bool found = false;
8165 for(auto &subc : subcommands_) {
8166 if(app == subc.get()) {
8167 found = true;
8168 }
8169 }
8170 if(!found) {
8171 throw OptionNotFound("The Given app is not a subcommand");
8172 }
8173
8174 if((help_ptr_ == opt) || (help_all_ptr_ == opt))
8175 throw OptionAlreadyAdded("cannot move help options");
8176
8177 if(config_ptr_ == opt)
8178 throw OptionAlreadyAdded("cannot move config file options");
8179
8180 auto iterator =
8181 std::find_if(std::begin(options_), std::end(options_), [opt](const Option_p &v) { return v.get() == opt; });
8182 if(iterator != std::end(options_)) {
8183 const auto &opt_p = *iterator;
8184 if(std::find_if(std::begin(app->options_), std::end(app->options_), [&opt_p](const Option_p &v) {
8185 return (*v == *opt_p);
8186 }) == std::end(app->options_)) {
8187 // only erase after the insertion was successful
8188 app->options_.push_back(std::move(*iterator));
8189 options_.erase(iterator);
8190 } else {
8191 throw OptionAlreadyAdded("option was not located: " + opt->get_name());
8192 }
8193 } else {
8194 throw OptionNotFound("could not locate the given Option");
8195 }
8196 }
8197}; // namespace CLI
8198
8200class Option_group : public App {
8201 public:
8202 Option_group(std::string group_description, std::string group_name, App *parent)
8203 : App(std::move(group_description), "", parent) {
8204 group(group_name);
8205 // option groups should have automatic fallthrough
8206 }
8207 using App::add_option;
8210 if(get_parent() == nullptr) {
8211 throw OptionNotFound("Unable to locate the specified option");
8212 }
8213 get_parent()->_move_option(opt, this);
8214 return opt;
8215 }
8217 void add_options(Option *opt) { add_option(opt); }
8219 template <typename... Args> void add_options(Option *opt, Args... args) {
8220 add_option(opt);
8221 add_options(args...);
8222 }
8223 using App::add_subcommand;
8226 App_p subc = subcom->get_parent()->get_subcommand_ptr(subcom);
8227 subc->get_parent()->remove_subcommand(subcom);
8228 add_subcommand(std::move(subc));
8229 return subcom;
8230 }
8231};
8233inline void TriggerOn(App *trigger_app, App *app_to_enable) {
8234 app_to_enable->enabled_by_default(false);
8235 app_to_enable->disabled_by_default();
8236 trigger_app->preparse_callback([app_to_enable](std::size_t) { app_to_enable->disabled(false); });
8237}
8238
8240inline void TriggerOn(App *trigger_app, std::vector<App *> apps_to_enable) {
8241 for(auto &app : apps_to_enable) {
8242 app->enabled_by_default(false);
8243 app->disabled_by_default();
8244 }
8245
8246 trigger_app->preparse_callback([apps_to_enable](std::size_t) {
8247 for(auto &app : apps_to_enable) {
8248 app->disabled(false);
8249 }
8250 });
8251}
8252
8254inline void TriggerOff(App *trigger_app, App *app_to_enable) {
8255 app_to_enable->disabled_by_default(false);
8256 app_to_enable->enabled_by_default();
8257 trigger_app->preparse_callback([app_to_enable](std::size_t) { app_to_enable->disabled(); });
8258}
8259
8261inline void TriggerOff(App *trigger_app, std::vector<App *> apps_to_enable) {
8262 for(auto &app : apps_to_enable) {
8263 app->disabled_by_default(false);
8264 app->enabled_by_default();
8265 }
8266
8267 trigger_app->preparse_callback([apps_to_enable](std::size_t) {
8268 for(auto &app : apps_to_enable) {
8269 app->disabled();
8270 }
8271 });
8272}
8273
8275inline void deprecate_option(Option *opt, const std::string &replacement = "") {
8276 Validator deprecate_warning{[opt, replacement](std::string &) {
8277 std::cout << opt->get_name() << " is deprecated please use '" << replacement
8278 << "' instead\n";
8279 return std::string();
8280 },
8281 "DEPRECATED"};
8282 deprecate_warning.application_index(0);
8283 opt->check(deprecate_warning);
8284 if(!replacement.empty()) {
8285 opt->description(opt->get_description() + " DEPRECATED: please use '" + replacement + "' instead");
8286 }
8287}
8288
8290inline void deprecate_option(App *app, const std::string &option_name, const std::string &replacement = "") {
8291 auto opt = app->get_option(option_name);
8292 deprecate_option(opt, replacement);
8293}
8294
8296inline void deprecate_option(App &app, const std::string &option_name, const std::string &replacement = "") {
8297 auto opt = app.get_option(option_name);
8298 deprecate_option(opt, replacement);
8299}
8300
8302inline void retire_option(App *app, Option *opt) {
8303 App temp;
8304 auto option_copy = temp.add_option(opt->get_name(false, true))
8308
8309 app->remove_option(opt);
8310 auto opt2 = app->add_option(option_copy->get_name(false, true), "option has been retired and has no effect")
8311 ->type_name("RETIRED")
8312 ->default_str("RETIRED")
8313 ->type_size(option_copy->get_type_size_min(), option_copy->get_type_size_max())
8314 ->expected(option_copy->get_expected_min(), option_copy->get_expected_max())
8315 ->allow_extra_args(option_copy->get_allow_extra_args());
8316
8317 Validator retired_warning{[opt2](std::string &) {
8318 std::cout << "WARNING " << opt2->get_name() << " is retired and has no effect\n";
8319 return std::string();
8320 },
8321 ""};
8322 retired_warning.application_index(0);
8323 opt2->check(retired_warning);
8324}
8325
8327inline void retire_option(App &app, Option *opt) { retire_option(&app, opt); }
8328
8330inline void retire_option(App *app, const std::string &option_name) {
8331
8332 auto opt = app->get_option_no_throw(option_name);
8333 if(opt != nullptr) {
8334 retire_option(app, opt);
8335 return;
8336 }
8337 auto opt2 = app->add_option(option_name, "option has been retired and has no effect")
8338 ->type_name("RETIRED")
8339 ->expected(0, 1)
8340 ->default_str("RETIRED");
8341 Validator retired_warning{[opt2](std::string &) {
8342 std::cout << "WARNING " << opt2->get_name() << " is retired and has no effect\n";
8343 return std::string();
8344 },
8345 ""};
8346 retired_warning.application_index(0);
8347 opt2->check(retired_warning);
8348}
8349
8351inline void retire_option(App &app, const std::string &option_name) { retire_option(&app, option_name); }
8352
8353namespace FailureMessage {
8354
8356inline std::string simple(const App *app, const Error &e) {
8357 std::string header = std::string(e.what()) + "\n";
8358 std::vector<std::string> names;
8359
8360 // Collect names
8361 if(app->get_help_ptr() != nullptr)
8362 names.push_back(app->get_help_ptr()->get_name());
8363
8364 if(app->get_help_all_ptr() != nullptr)
8365 names.push_back(app->get_help_all_ptr()->get_name());
8366
8367 // If any names found, suggest those
8368 if(!names.empty())
8369 header += "Run with " + detail::join(names, " or ") + " for more information.\n";
8370
8371 return header;
8372}
8373
8375inline std::string help(const App *app, const Error &e) {
8376 std::string header = std::string("ERROR: ") + e.get_name() + ": " + e.what() + "\n";
8377 header += app->help();
8378 return header;
8379}
8380
8381} // namespace FailureMessage
8382
8383namespace detail {
8386#ifdef CLI11_CPP14
8387
8389 template <typename... Args> static decltype(auto) parse_arg(App *app, Args &&...args) {
8390 return app->_parse_arg(std::forward<Args>(args)...);
8391 }
8392
8394 template <typename... Args> static decltype(auto) parse_subcommand(App *app, Args &&...args) {
8395 return app->_parse_subcommand(std::forward<Args>(args)...);
8396 }
8397#else
8399 template <typename... Args>
8400 static auto parse_arg(App *app, Args &&...args) ->
8401 typename std::result_of<decltype (&App::_parse_arg)(App, Args...)>::type {
8402 return app->_parse_arg(std::forward<Args>(args)...);
8403 }
8404
8406 template <typename... Args>
8407 static auto parse_subcommand(App *app, Args &&...args) ->
8408 typename std::result_of<decltype (&App::_parse_subcommand)(App, Args...)>::type {
8409 return app->_parse_subcommand(std::forward<Args>(args)...);
8410 }
8411#endif
8414};
8415} // namespace detail
8416
8417
8418
8419
8420namespace detail {
8421
8422inline std::string convert_arg_for_ini(const std::string &arg, char stringQuote = '"', char characterQuote = '\'') {
8423 if(arg.empty()) {
8424 return std::string(2, stringQuote);
8425 }
8426 // some specifically supported strings
8427 if(arg == "true" || arg == "false" || arg == "nan" || arg == "inf") {
8428 return arg;
8429 }
8430 // floating point conversion can convert some hex codes, but don't try that here
8431 if(arg.compare(0, 2, "0x") != 0 && arg.compare(0, 2, "0X") != 0) {
8432 double val;
8433 if(detail::lexical_cast(arg, val)) {
8434 return arg;
8435 }
8436 }
8437 // just quote a single non numeric character
8438 if(arg.size() == 1) {
8439 return std::string(1, characterQuote) + arg + characterQuote;
8440 }
8441 // handle hex, binary or octal arguments
8442 if(arg.front() == '0') {
8443 if(arg[1] == 'x') {
8444 if(std::all_of(arg.begin() + 2, arg.end(), [](char x) {
8445 return (x >= '0' && x <= '9') || (x >= 'A' && x <= 'F') || (x >= 'a' && x <= 'f');
8446 })) {
8447 return arg;
8448 }
8449 } else if(arg[1] == 'o') {
8450 if(std::all_of(arg.begin() + 2, arg.end(), [](char x) { return (x >= '0' && x <= '7'); })) {
8451 return arg;
8452 }
8453 } else if(arg[1] == 'b') {
8454 if(std::all_of(arg.begin() + 2, arg.end(), [](char x) { return (x == '0' || x == '1'); })) {
8455 return arg;
8456 }
8457 }
8458 }
8459 if(arg.find_first_of(stringQuote) == std::string::npos) {
8460 return std::string(1, stringQuote) + arg + stringQuote;
8461 } else {
8462 return characterQuote + arg + characterQuote;
8463 }
8464}
8465
8467inline std::string ini_join(const std::vector<std::string> &args,
8468 char sepChar = ',',
8469 char arrayStart = '[',
8470 char arrayEnd = ']',
8471 char stringQuote = '"',
8472 char characterQuote = '\'') {
8473 std::string joined;
8474 if(args.size() > 1 && arrayStart != '\0') {
8475 joined.push_back(arrayStart);
8476 }
8477 std::size_t start = 0;
8478 for(const auto &arg : args) {
8479 if(start++ > 0) {
8480 joined.push_back(sepChar);
8481 if(isspace(sepChar) == 0) {
8482 joined.push_back(' ');
8483 }
8484 }
8485 joined.append(convert_arg_for_ini(arg, stringQuote, characterQuote));
8486 }
8487 if(args.size() > 1 && arrayEnd != '\0') {
8488 joined.push_back(arrayEnd);
8489 }
8490 return joined;
8491}
8492
8493inline std::vector<std::string> generate_parents(const std::string &section, std::string &name, char parentSeparator) {
8494 std::vector<std::string> parents;
8495 if(detail::to_lower(section) != "default") {
8496 if(section.find(parentSeparator) != std::string::npos) {
8497 parents = detail::split(section, parentSeparator);
8498 } else {
8499 parents = {section};
8500 }
8501 }
8502 if(name.find(parentSeparator) != std::string::npos) {
8503 std::vector<std::string> plist = detail::split(name, parentSeparator);
8504 name = plist.back();
8505 detail::remove_quotes(name);
8506 plist.pop_back();
8507 parents.insert(parents.end(), plist.begin(), plist.end());
8508 }
8509
8510 // clean up quotes on the parents
8511 for(auto &parent : parents) {
8512 detail::remove_quotes(parent);
8513 }
8514 return parents;
8515}
8516
8518inline void
8519checkParentSegments(std::vector<ConfigItem> &output, const std::string &currentSection, char parentSeparator) {
8520
8521 std::string estring;
8522 auto parents = detail::generate_parents(currentSection, estring, parentSeparator);
8523 if(!output.empty() && output.back().name == "--") {
8524 std::size_t msize = (parents.size() > 1U) ? parents.size() : 2;
8525 while(output.back().parents.size() >= msize) {
8526 output.push_back(output.back());
8527 output.back().parents.pop_back();
8528 }
8529
8530 if(parents.size() > 1) {
8531 std::size_t common = 0;
8532 std::size_t mpair = (std::min)(output.back().parents.size(), parents.size() - 1);
8533 for(std::size_t ii = 0; ii < mpair; ++ii) {
8534 if(output.back().parents[ii] != parents[ii]) {
8535 break;
8536 }
8537 ++common;
8538 }
8539 if(common == mpair) {
8540 output.pop_back();
8541 } else {
8542 while(output.back().parents.size() > common + 1) {
8543 output.push_back(output.back());
8544 output.back().parents.pop_back();
8545 }
8546 }
8547 for(std::size_t ii = common; ii < parents.size() - 1; ++ii) {
8548 output.emplace_back();
8549 output.back().parents.assign(parents.begin(), parents.begin() + static_cast<std::ptrdiff_t>(ii) + 1);
8550 output.back().name = "++";
8551 }
8552 }
8553 } else if(parents.size() > 1) {
8554 for(std::size_t ii = 0; ii < parents.size() - 1; ++ii) {
8555 output.emplace_back();
8556 output.back().parents.assign(parents.begin(), parents.begin() + static_cast<std::ptrdiff_t>(ii) + 1);
8557 output.back().name = "++";
8558 }
8559 }
8560
8561 // insert a section end which is just an empty items_buffer
8562 output.emplace_back();
8563 output.back().parents = std::move(parents);
8564 output.back().name = "++";
8565}
8566} // namespace detail
8567
8568inline std::vector<ConfigItem> ConfigBase::from_config(std::istream &input) const {
8569 std::string line;
8570 std::string currentSection = "default";
8571 std::string previousSection = "default";
8572 std::vector<ConfigItem> output;
8573 bool isDefaultArray = (arrayStart == '[' && arrayEnd == ']' && arraySeparator == ',');
8574 bool isINIArray = (arrayStart == '\0' || arrayStart == ' ') && arrayStart == arrayEnd;
8575 bool inSection{false};
8576 char aStart = (isINIArray) ? '[' : arrayStart;
8577 char aEnd = (isINIArray) ? ']' : arrayEnd;
8578 char aSep = (isINIArray && arraySeparator == ' ') ? ',' : arraySeparator;
8579 int currentSectionIndex{0};
8580 while(getline(input, line)) {
8581 std::vector<std::string> items_buffer;
8582 std::string name;
8583
8584 detail::trim(line);
8585 std::size_t len = line.length();
8586 // lines have to be at least 3 characters to have any meaning to CLI just skip the rest
8587 if(len < 3) {
8588 continue;
8589 }
8590 if(line.front() == '[' && line.back() == ']') {
8591 if(currentSection != "default") {
8592 // insert a section end which is just an empty items_buffer
8593 output.emplace_back();
8594 output.back().parents = detail::generate_parents(currentSection, name, parentSeparatorChar);
8595 output.back().name = "--";
8596 }
8597 currentSection = line.substr(1, len - 2);
8598 // deal with double brackets for TOML
8599 if(currentSection.size() > 1 && currentSection.front() == '[' && currentSection.back() == ']') {
8600 currentSection = currentSection.substr(1, currentSection.size() - 2);
8601 }
8602 if(detail::to_lower(currentSection) == "default") {
8603 currentSection = "default";
8604 } else {
8605 detail::checkParentSegments(output, currentSection, parentSeparatorChar);
8606 }
8607 inSection = false;
8608 if(currentSection == previousSection) {
8609 ++currentSectionIndex;
8610 } else {
8611 currentSectionIndex = 0;
8612 previousSection = currentSection;
8613 }
8614 continue;
8615 }
8616
8617 // comment lines
8618 if(line.front() == ';' || line.front() == '#' || line.front() == commentChar) {
8619 continue;
8620 }
8621
8622 // Find = in string, split and recombine
8623 auto pos = line.find(valueDelimiter);
8624 if(pos != std::string::npos) {
8625 name = detail::trim_copy(line.substr(0, pos));
8626 std::string item = detail::trim_copy(line.substr(pos + 1));
8627 auto cloc = item.find(commentChar);
8628 if(cloc != std::string::npos) {
8629 item.erase(cloc, std::string::npos);
8630 detail::trim(item);
8631 }
8632 if(item.size() > 1 && item.front() == aStart) {
8633 for(std::string multiline; item.back() != aEnd && std::getline(input, multiline);) {
8634 detail::trim(multiline);
8635 item += multiline;
8636 }
8637 items_buffer = detail::split_up(item.substr(1, item.length() - 2), aSep);
8638 } else if((isDefaultArray || isINIArray) && item.find_first_of(aSep) != std::string::npos) {
8639 items_buffer = detail::split_up(item, aSep);
8640 } else if((isDefaultArray || isINIArray) && item.find_first_of(' ') != std::string::npos) {
8641 items_buffer = detail::split_up(item);
8642 } else {
8643 items_buffer = {item};
8644 }
8645 } else {
8646 name = detail::trim_copy(line);
8647 auto cloc = name.find(commentChar);
8648 if(cloc != std::string::npos) {
8649 name.erase(cloc, std::string::npos);
8650 detail::trim(name);
8651 }
8652
8653 items_buffer = {"true"};
8654 }
8655 if(name.find(parentSeparatorChar) == std::string::npos) {
8657 }
8658 // clean up quotes on the items
8659 for(auto &it : items_buffer) {
8661 }
8662
8663 std::vector<std::string> parents = detail::generate_parents(currentSection, name, parentSeparatorChar);
8664 if(parents.size() > maximumLayers) {
8665 continue;
8666 }
8667 if(!configSection.empty() && !inSection) {
8668 if(parents.empty() || parents.front() != configSection) {
8669 continue;
8670 }
8671 if(configIndex >= 0 && currentSectionIndex != configIndex) {
8672 continue;
8673 }
8674 parents.erase(parents.begin());
8675 inSection = true;
8676 }
8677 if(!output.empty() && name == output.back().name && parents == output.back().parents) {
8678 output.back().inputs.insert(output.back().inputs.end(), items_buffer.begin(), items_buffer.end());
8679 } else {
8680 output.emplace_back();
8681 output.back().parents = std::move(parents);
8682 output.back().name = std::move(name);
8683 output.back().inputs = std::move(items_buffer);
8684 }
8685 }
8686 if(currentSection != "default") {
8687 // insert a section end which is just an empty items_buffer
8688 std::string ename;
8689 output.emplace_back();
8690 output.back().parents = detail::generate_parents(currentSection, ename, parentSeparatorChar);
8691 output.back().name = "--";
8692 while(output.back().parents.size() > 1) {
8693 output.push_back(output.back());
8694 output.back().parents.pop_back();
8695 }
8696 }
8697 return output;
8698}
8699
8700inline std::string
8701ConfigBase::to_config(const App *app, bool default_also, bool write_description, std::string prefix) const {
8702 std::stringstream out;
8703 std::string commentLead;
8704 commentLead.push_back(commentChar);
8705 commentLead.push_back(' ');
8706
8707 std::vector<std::string> groups = app->get_groups();
8708 bool defaultUsed = false;
8709 groups.insert(groups.begin(), std::string("Options"));
8710 if(write_description && (app->get_configurable() || app->get_parent() == nullptr || app->get_name().empty())) {
8711 out << commentLead << detail::fix_newlines(commentLead, app->get_description()) << '\n';
8712 }
8713 for(auto &group : groups) {
8714 if(group == "Options" || group.empty()) {
8715 if(defaultUsed) {
8716 continue;
8717 }
8718 defaultUsed = true;
8719 }
8720 if(write_description && group != "Options" && !group.empty()) {
8721 out << '\n' << commentLead << group << " Options\n";
8722 }
8723 for(const Option *opt : app->get_options({})) {
8724
8725 // Only process options that are configurable
8726 if(opt->get_configurable()) {
8727 if(opt->get_group() != group) {
8728 if(!(group == "Options" && opt->get_group().empty())) {
8729 continue;
8730 }
8731 }
8732 std::string name = prefix + opt->get_single_name();
8733 std::string value = detail::ini_join(
8734 opt->reduced_results(), arraySeparator, arrayStart, arrayEnd, stringQuote, characterQuote);
8735
8736 if(value.empty() && default_also) {
8737 if(!opt->get_default_str().empty()) {
8738 value = detail::convert_arg_for_ini(opt->get_default_str(), stringQuote, characterQuote);
8739 } else if(opt->get_expected_min() == 0) {
8740 value = "false";
8741 } else if(opt->get_run_callback_for_default()) {
8742 value = "\"\""; // empty string default value
8743 }
8744 }
8745
8746 if(!value.empty()) {
8747 if(write_description && opt->has_description()) {
8748 out << '\n';
8749 out << commentLead << detail::fix_newlines(commentLead, opt->get_description()) << '\n';
8750 }
8751 out << name << valueDelimiter << value << '\n';
8752 }
8753 }
8754 }
8755 }
8756 auto subcommands = app->get_subcommands({});
8757 for(const App *subcom : subcommands) {
8758 if(subcom->get_name().empty()) {
8759 if(write_description && !subcom->get_group().empty()) {
8760 out << '\n' << commentLead << subcom->get_group() << " Options\n";
8761 }
8762 out << to_config(subcom, default_also, write_description, prefix);
8763 }
8764 }
8765
8766 for(const App *subcom : subcommands) {
8767 if(!subcom->get_name().empty()) {
8768 if(subcom->get_configurable() && app->got_subcommand(subcom)) {
8769 if(!prefix.empty() || app->get_parent() == nullptr) {
8770 out << '[' << prefix << subcom->get_name() << "]\n";
8771 } else {
8772 std::string subname = app->get_name() + parentSeparatorChar + subcom->get_name();
8773 auto p = app->get_parent();
8774 while(p->get_parent() != nullptr) {
8775 subname = p->get_name() + parentSeparatorChar + subname;
8776 p = p->get_parent();
8777 }
8778 out << '[' << subname << "]\n";
8779 }
8780 out << to_config(subcom, default_also, write_description, "");
8781 } else {
8782 out << to_config(
8783 subcom, default_also, write_description, prefix + subcom->get_name() + parentSeparatorChar);
8784 }
8785 }
8786 }
8787
8788 return out.str();
8789}
8790
8791
8792
8793
8794inline std::string
8795Formatter::make_group(std::string group, bool is_positional, std::vector<const Option *> opts) const {
8796 std::stringstream out;
8797
8798 out << "\n" << group << ":\n";
8799 for(const Option *opt : opts) {
8800 out << make_option(opt, is_positional);
8801 }
8802
8803 return out.str();
8804}
8805
8806inline std::string Formatter::make_positionals(const App *app) const {
8807 std::vector<const Option *> opts =
8808 app->get_options([](const Option *opt) { return !opt->get_group().empty() && opt->get_positional(); });
8809
8810 if(opts.empty())
8811 return std::string();
8812
8813 return make_group(get_label("Positionals"), true, opts);
8814}
8815
8816inline std::string Formatter::make_groups(const App *app, AppFormatMode mode) const {
8817 std::stringstream out;
8818 std::vector<std::string> groups = app->get_groups();
8819
8820 // Options
8821 for(const std::string &group : groups) {
8822 std::vector<const Option *> opts = app->get_options([app, mode, &group](const Option *opt) {
8823 return opt->get_group() == group // Must be in the right group
8824 && opt->nonpositional() // Must not be a positional
8825 && (mode != AppFormatMode::Sub // If mode is Sub, then
8826 || (app->get_help_ptr() != opt // Ignore help pointer
8827 && app->get_help_all_ptr() != opt)); // Ignore help all pointer
8828 });
8829 if(!group.empty() && !opts.empty()) {
8830 out << make_group(group, false, opts);
8831
8832 if(group != groups.back())
8833 out << "\n";
8834 }
8835 }
8836
8837 return out.str();
8838}
8839
8840inline std::string Formatter::make_description(const App *app) const {
8841 std::string desc = app->get_description();
8842 auto min_options = app->get_require_option_min();
8843 auto max_options = app->get_require_option_max();
8844 if(app->get_required()) {
8845 desc += " REQUIRED ";
8846 }
8847 if((max_options == min_options) && (min_options > 0)) {
8848 if(min_options == 1) {
8849 desc += " \n[Exactly 1 of the following options is required]";
8850 } else {
8851 desc += " \n[Exactly " + std::to_string(min_options) + "options from the following list are required]";
8852 }
8853 } else if(max_options > 0) {
8854 if(min_options > 0) {
8855 desc += " \n[Between " + std::to_string(min_options) + " and " + std::to_string(max_options) +
8856 " of the follow options are required]";
8857 } else {
8858 desc += " \n[At most " + std::to_string(max_options) + " of the following options are allowed]";
8859 }
8860 } else if(min_options > 0) {
8861 desc += " \n[At least " + std::to_string(min_options) + " of the following options are required]";
8862 }
8863 return (!desc.empty()) ? desc + "\n" : std::string{};
8864}
8865
8866inline std::string Formatter::make_usage(const App *app, std::string name) const {
8867 std::stringstream out;
8868
8869 out << get_label("Usage") << ":" << (name.empty() ? "" : " ") << name;
8870
8871 std::vector<std::string> groups = app->get_groups();
8872
8873 // Print an Options badge if any options exist
8874 std::vector<const Option *> non_pos_options =
8875 app->get_options([](const Option *opt) { return opt->nonpositional(); });
8876 if(!non_pos_options.empty())
8877 out << " [" << get_label("OPTIONS") << "]";
8878
8879 // Positionals need to be listed here
8880 std::vector<const Option *> positionals = app->get_options([](const Option *opt) { return opt->get_positional(); });
8881
8882 // Print out positionals if any are left
8883 if(!positionals.empty()) {
8884 // Convert to help names
8885 std::vector<std::string> positional_names(positionals.size());
8886 std::transform(positionals.begin(), positionals.end(), positional_names.begin(), [this](const Option *opt) {
8887 return make_option_usage(opt);
8888 });
8889
8890 out << " " << detail::join(positional_names, " ");
8891 }
8892
8893 // Add a marker if subcommands are expected or optional
8894 if(!app->get_subcommands(
8895 [](const CLI::App *subc) { return ((!subc->get_disabled()) && (!subc->get_name().empty())); })
8896 .empty()) {
8897 out << " " << (app->get_require_subcommand_min() == 0 ? "[" : "")
8898 << get_label(app->get_require_subcommand_max() < 2 || app->get_require_subcommand_min() > 1 ? "SUBCOMMAND"
8899 : "SUBCOMMANDS")
8900 << (app->get_require_subcommand_min() == 0 ? "]" : "");
8901 }
8902
8903 out << std::endl;
8904
8905 return out.str();
8906}
8907
8908inline std::string Formatter::make_footer(const App *app) const {
8909 std::string footer = app->get_footer();
8910 if(footer.empty()) {
8911 return std::string{};
8912 }
8913 return footer + "\n";
8914}
8915
8916inline std::string Formatter::make_help(const App *app, std::string name, AppFormatMode mode) const {
8917
8918 // This immediately forwards to the make_expanded method. This is done this way so that subcommands can
8919 // have overridden formatters
8920 if(mode == AppFormatMode::Sub)
8921 return make_expanded(app);
8922
8923 std::stringstream out;
8924 if((app->get_name().empty()) && (app->get_parent() != nullptr)) {
8925 if(app->get_group() != "Subcommands") {
8926 out << app->get_group() << ':';
8927 }
8928 }
8929
8930 out << make_description(app);
8931 out << make_usage(app, name);
8932 out << make_positionals(app);
8933 out << make_groups(app, mode);
8934 out << make_subcommands(app, mode);
8935 out << '\n' << make_footer(app);
8936
8937 return out.str();
8938}
8939
8940inline std::string Formatter::make_subcommands(const App *app, AppFormatMode mode) const {
8941 std::stringstream out;
8942
8943 std::vector<const App *> subcommands = app->get_subcommands({});
8944
8945 // Make a list in definition order of the groups seen
8946 std::vector<std::string> subcmd_groups_seen;
8947 for(const App *com : subcommands) {
8948 if(com->get_name().empty()) {
8949 if(!com->get_group().empty()) {
8950 out << make_expanded(com);
8951 }
8952 continue;
8953 }
8954 std::string group_key = com->get_group();
8955 if(!group_key.empty() &&
8956 std::find_if(subcmd_groups_seen.begin(), subcmd_groups_seen.end(), [&group_key](std::string a) {
8957 return detail::to_lower(a) == detail::to_lower(group_key);
8958 }) == subcmd_groups_seen.end())
8959 subcmd_groups_seen.push_back(group_key);
8960 }
8961
8962 // For each group, filter out and print subcommands
8963 for(const std::string &group : subcmd_groups_seen) {
8964 out << "\n" << group << ":\n";
8965 std::vector<const App *> subcommands_group = app->get_subcommands(
8966 [&group](const App *sub_app) { return detail::to_lower(sub_app->get_group()) == detail::to_lower(group); });
8967 for(const App *new_com : subcommands_group) {
8968 if(new_com->get_name().empty())
8969 continue;
8970 if(mode != AppFormatMode::All) {
8971 out << make_subcommand(new_com);
8972 } else {
8973 out << new_com->help(new_com->get_name(), AppFormatMode::Sub);
8974 out << "\n";
8975 }
8976 }
8977 }
8978
8979 return out.str();
8980}
8981
8982inline std::string Formatter::make_subcommand(const App *sub) const {
8983 std::stringstream out;
8984 detail::format_help(out, sub->get_display_name(true), sub->get_description(), column_width_);
8985 return out.str();
8986}
8987
8988inline std::string Formatter::make_expanded(const App *sub) const {
8989 std::stringstream out;
8990 out << sub->get_display_name(true) << "\n";
8991
8992 out << make_description(sub);
8993 if(sub->get_name().empty() && !sub->get_aliases().empty()) {
8994 detail::format_aliases(out, sub->get_aliases(), column_width_ + 2);
8995 }
8996 out << make_positionals(sub);
8997 out << make_groups(sub, AppFormatMode::Sub);
8998 out << make_subcommands(sub, AppFormatMode::Sub);
8999
9000 // Drop blank spaces
9001 std::string tmp = detail::find_and_replace(out.str(), "\n\n", "\n");
9002 tmp = tmp.substr(0, tmp.size() - 1); // Remove the final '\n'
9003
9004 // Indent all but the first line (the name)
9005 return detail::find_and_replace(tmp, "\n", "\n ") + "\n";
9006}
9007
9008inline std::string Formatter::make_option_name(const Option *opt, bool is_positional) const {
9009 if(is_positional)
9010 return opt->get_name(true, false);
9011
9012 return opt->get_name(false, true);
9013}
9014
9015inline std::string Formatter::make_option_opts(const Option *opt) const {
9016 std::stringstream out;
9017
9018 if(!opt->get_option_text().empty()) {
9019 out << " " << opt->get_option_text();
9020 } else {
9021 if(opt->get_type_size() != 0) {
9022 if(!opt->get_type_name().empty())
9023 out << " " << get_label(opt->get_type_name());
9024 if(!opt->get_default_str().empty())
9025 out << "=" << opt->get_default_str();
9027 out << " ...";
9028 else if(opt->get_expected_min() > 1)
9029 out << " x " << opt->get_expected();
9030
9031 if(opt->get_required())
9032 out << " " << get_label("REQUIRED");
9033 }
9034 if(!opt->get_envname().empty())
9035 out << " (" << get_label("Env") << ":" << opt->get_envname() << ")";
9036 if(!opt->get_needs().empty()) {
9037 out << " " << get_label("Needs") << ":";
9038 for(const Option *op : opt->get_needs())
9039 out << " " << op->get_name();
9040 }
9041 if(!opt->get_excludes().empty()) {
9042 out << " " << get_label("Excludes") << ":";
9043 for(const Option *op : opt->get_excludes())
9044 out << " " << op->get_name();
9045 }
9046 }
9047 return out.str();
9048}
9049
9050inline std::string Formatter::make_option_desc(const Option *opt) const { return opt->get_description(); }
9051
9052inline std::string Formatter::make_option_usage(const Option *opt) const {
9053 // Note that these are positionals usages
9054 std::stringstream out;
9055 out << make_option_name(opt, true);
9057 out << "...";
9058 else if(opt->get_expected_max() > 1)
9059 out << "(" << opt->get_expected() << "x)";
9060
9061 return opt->get_required() ? out.str() : "[" + out.str() + "]";
9062}
9063
9064
9065
9066} // namespace CLI
const Regex sep
Definition BasisParser.cxx:13
#define CLI11_ERROR_SIMPLE(name)
Definition CLI11.hpp:562
#define CLI11_ERROR_DEF(parent, name)
Definition CLI11.hpp:551
std::ostream & operator<<(std::ostream &s, const FcidumpReader::FcidumpHeader &h)
Definition FcidumpWriter.cxx:25
int main(int argumentCount, char **arguments)
Definition Sisi4s.cxx:278
Creates a command line program, with very few defaults.
Definition CLI11.hpp:5286
bool _parse_single(std::vector< std::string > &args, bool &positional_only)
Definition CLI11.hpp:7677
bool get_disabled_by_default() const
Get the status of disabled by default.
Definition CLI11.hpp:6928
const Option * operator[](const std::string &option_name) const
Shortcut bracket operator for getting a pointer to an option.
Definition CLI11.hpp:6868
App * configurable(bool value=true)
Specify that the subcommand can be triggered by a config file.
Definition CLI11.hpp:5722
void _process_env()
Get envname options if not yet passed. Runs on all subcommands.
Definition CLI11.hpp:7256
App * _get_fallthrough_parent()
Get the appropriate parent to fallthrough to which is the first one that has a name or the main app.
Definition CLI11.hpp:8079
void _process()
Process callbacks and such.
Definition CLI11.hpp:7468
Option * set_version_flag(std::string flag_name, std::function< std::string()> vfunc, const std::string &version_help="Display program version information and exit")
Generate the version string through a callback function.
Definition CLI11.hpp:5958
void parse(std::string commandline, bool program_name_included=false)
Definition CLI11.hpp:6442
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:5853
Option * add_option(std::string option_name)
Add option with no description or variable assignment.
Definition CLI11.hpp:5892
App * get_option_group(std::string group_name) const
Check to see if an option group is part of this App.
Definition CLI11.hpp:6288
App * config_formatter(std::shared_ptr< Config > fmt)
Set the config formatter.
Definition CLI11.hpp:5755
bool remove_excludes(App *app)
Removes a subcommand from the excludes list of this subcommand.
Definition CLI11.hpp:6665
App * allow_config_extras(bool allow=true)
ignore extras in config files
Definition CLI11.hpp:5671
App * disabled_by_default(bool disable=true)
Set the subcommand to be disabled by default, so on clear(), at the start of each parse it is disable...
Definition CLI11.hpp:5630
App * ignore_case(bool value=true)
Ignore case. Subcommands inherit value.
Definition CLI11.hpp:5694
bool _parse_single_config(const ConfigItem &item, std::size_t level=0)
Fill in a single config option.
Definition CLI11.hpp:7603
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:5939
void _parse(std::vector< std::string > &args)
Internal parse function.
Definition CLI11.hpp:7534
std::size_t get_require_option_min() const
Get the required min option value.
Definition CLI11.hpp:6904
void _parse(std::vector< std::string > &&args)
Internal parse function.
Definition CLI11.hpp:7563
App * silent(bool silence=true)
silence the subcommand from showing up in the processed list
Definition CLI11.hpp:5624
bool get_configurable() const
Check the status of the allow windows style options.
Definition CLI11.hpp:6889
App * clear_aliases()
clear all the aliases of the current App
Definition CLI11.hpp:6972
App * allow_extras(bool allow=true)
Remove the error when extras are left over on the command line.
Definition CLI11.hpp:5606
App * fallthrough(bool value=true)
Definition CLI11.hpp:6384
Option * get_config_ptr()
Get a pointer to the config option.
Definition CLI11.hpp:6948
bool _valid_subcommand(const std::string &current, bool ignore_used=true) const
Check to see if a subcommand is valid. Give up immediately if subcommand max has been reached.
Definition CLI11.hpp:7182
std::vector< App_p > subcommands_
Storage for subcommand list.
Definition CLI11.hpp:5409
std::string help(std::string prev="", AppFormatMode mode=AppFormatMode::Normal) const
Definition CLI11.hpp:6718
bool remove_option(Option *opt)
Removes an option from the App. Takes an option pointer. Returns true if found and removed.
Definition CLI11.hpp:6143
bool parsed() const
Check to see if this subcommand was parsed, true only if received on command line.
Definition CLI11.hpp:5761
App * require_subcommand()
The argumentless form of require subcommand requires 1 or more subcommands.
Definition CLI11.hpp:6325
Option * get_option(std::string option_name)
Get an option by name (non-const version)
Definition CLI11.hpp:6859
bool get_allow_windows_style_options() const
Check the status of the allow windows style options.
Definition CLI11.hpp:6883
const Option * get_help_all_ptr() const
Get a pointer to the help all flag. (const)
Definition CLI11.hpp:6945
bool _parse_positional(std::vector< std::string > &args, bool haltOnSubcommand)
Definition CLI11.hpp:7747
bool check_name(std::string name_to_check) const
Check the name, case insensitive and underscore insensitive if set.
Definition CLI11.hpp:6995
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:5905
void _process_help_flags(bool trigger_help=false, bool trigger_all_help=false) const
Definition CLI11.hpp:7316
bool disabled_
If set to true the subcommand is disabled and cannot be used, ignored for main app.
Definition CLI11.hpp:5319
Option * add_option(std::string option_name, AssignTo &variable, std::string option_description="")
Add option for assigning to a variable.
Definition CLI11.hpp:5829
startup_mode
Definition CLI11.hpp:5431
const Option * operator[](const char *option_name) const
Shortcut bracket operator for getting a pointer to an option.
Definition CLI11.hpp:6871
Option * add_flag(std::string flag_name, T &flag_count, std::string flag_description="")
Definition CLI11.hpp:6022
Option * get_help_ptr()
Get a pointer to the help flag.
Definition CLI11.hpp:6939
App * require_subcommand(int value)
Definition CLI11.hpp:6334
CLI::App_p get_subcommand_ptr(std::string subcom) const
Check to see if a subcommand is part of this command (text version)
Definition CLI11.hpp:6270
std::size_t count_all() const
Definition CLI11.hpp:6304
CLI::App_p get_subcommand_ptr(int index=0) const
Get an owning pointer to subcommand by index.
Definition CLI11.hpp:6278
OptionDefaults * option_defaults()
Get the OptionDefault object, to set option defaults.
Definition CLI11.hpp:5764
void _process_extras()
Throw an error if anything is left over and should not be.
Definition CLI11.hpp:7494
void _process_requirements()
Verify required options and cross requirements. Subcommands too (only if selected).
Definition CLI11.hpp:7339
App * get_subcommand(std::string subcom) const
Check to see if a subcommand is part of this command (text version)
Definition CLI11.hpp:6243
Option * get_option_no_throw(std::string option_name) noexcept
Get an option by name (noexcept non-const version)
Definition CLI11.hpp:6812
std::vector< std::pair< detail::Classifier, std::string > > missing_t
Definition CLI11.hpp:5376
std::vector< std::string > remaining_for_passthrough(bool recurse=false) const
This returns the missing options in a form ready for processing by another command line program.
Definition CLI11.hpp:7068
App * required(bool require=true)
Remove the error when extras are left over on the command line.
Definition CLI11.hpp:5612
App * parent_
A pointer to the parent if this is a subcommand.
Definition CLI11.hpp:5462
App * prefix_command(bool allow=true)
Do not parse anything after the first unrecognized option and return.
Definition CLI11.hpp:5688
App * group(std::string group_name)
Changes the group membership.
Definition CLI11.hpp:6319
void run_callback(bool final_mode=false, bool suppress_final_callback=false)
Internal function to run (App) callback, bottom up.
Definition CLI11.hpp:7156
bool get_ignore_case() const
Check the status of ignore_case.
Definition CLI11.hpp:6874
App(const App &)=delete
bool got_subcommand(std::string subcommand_name) const
Check with name instead of pointer to see if subcommand was selected.
Definition CLI11.hpp:6608
virtual void pre_callback()
Definition CLI11.hpp:6400
void parse(int argc, const char *const *argv)
Definition CLI11.hpp:6424
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:6166
App * get_parent()
Get the parent of this subcommand (or nullptr if main app)
Definition CLI11.hpp:6960
Option * add_flag(std::string flag_name)
Add a flag with no description or variable assignment.
Definition CLI11.hpp:6005
bool get_prefix_command() const
Get the prefix command status.
Definition CLI11.hpp:6910
const std::vector< Option * > & parse_order() const
This gets a vector of pointers with the original parse order.
Definition CLI11.hpp:7038
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:5521
const std::vector< std::string > & get_aliases() const
Get the aliases of the current app.
Definition CLI11.hpp:6969
const Option * get_config_ptr() const
Get a pointer to the config option. (const)
Definition CLI11.hpp:6951
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:6260
App * allow_windows_style_options(bool value=true)
Definition CLI11.hpp:5710
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:5871
std::vector< App * > get_subcommands() const
Definition CLI11.hpp:6564
void clear()
Reset the parsed data.
Definition CLI11.hpp:6407
std::size_t _count_remaining_positionals(bool required_only=false) const
Count the required remaining positional arguments.
Definition CLI11.hpp:7720
App * _find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept
Definition CLI11.hpp:7848
const std::string & get_group() const
Get the group of this subcommand.
Definition CLI11.hpp:6892
bool remove_needs(App *app)
Removes a subcommand from the needs list of this subcommand.
Definition CLI11.hpp:6687
bool _parse_arg(std::vector< std::string > &args, detail::Classifier current_type)
Definition CLI11.hpp:7900
bool get_required() const
Get the status of required.
Definition CLI11.hpp:6916
bool get_validate_positionals() const
Get the status of validating positionals.
Definition CLI11.hpp:6933
void failure_message(std::function< std::string(const App *, const Error &e)> function)
Provide a function to print a help message. The function gets access to the App pointer and error.
Definition CLI11.hpp:6521
const Option * get_version_ptr() const
Get a pointer to the version option. (const)
Definition CLI11.hpp:6957
App * name(std::string app_name="")
Set a name for the app (empty will use parser to set the name)
Definition CLI11.hpp:5569
std::size_t get_require_subcommand_max() const
Get the required max subcommand value.
Definition CLI11.hpp:6901
bool get_disabled() const
Get the status of disabled.
Definition CLI11.hpp:6919
void _process_config_file()
Read and process a configuration file (main app only)
Definition CLI11.hpp:7223
std::size_t remaining_size(bool recurse=false) const
This returns the number of remaining options, minus the – separator.
Definition CLI11.hpp:7075
App * enabled_by_default(bool enable=true)
Definition CLI11.hpp:5641
void _process_extras(std::vector< std::string > &args)
Definition CLI11.hpp:7510
App * footer(std::string footer_string)
Set footer.
Definition CLI11.hpp:6701
App * needs(Option *opt)
Definition CLI11.hpp:6635
App * require_option(int value)
Definition CLI11.hpp:6363
std::vector< App * > get_subcommands(const std::function< bool(App *)> &filter)
Definition CLI11.hpp:6586
virtual ~App()=default
virtual destructor
bool get_allow_extras() const
Get the status of allow extras.
Definition CLI11.hpp:6913
std::vector< Option_p > options_
The list of options, stored locally.
Definition CLI11.hpp:5345
void parse(std::vector< std::string > &args)
Definition CLI11.hpp:6471
std::shared_ptr< FormatterBase > get_formatter() const
Access the formatter.
Definition CLI11.hpp:6754
std::size_t count(std::string option_name) const
Counts the number of times the given option was passed.
Definition CLI11.hpp:6560
App * add_subcommand(std::string subcommand_name="", std::string subcommand_description="")
Add a subcommand. Inherits INHERITABLE and OptionDefaults, and help flag.
Definition CLI11.hpp:6183
App * get_subcommand(int index=0) const
Get a pointer to subcommand by index.
Definition CLI11.hpp:6250
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:5784
App * require_option()
The argumentless form of require option requires 1 or more options be used.
Definition CLI11.hpp:6354
void parse(std::vector< std::string > &&args)
The real work is done here. Expects a reversed vector.
Definition CLI11.hpp:6491
App * preparse_callback(std::function< void(std::size_t)> pp_callback)
Definition CLI11.hpp:5563
App * add_subcommand(CLI::App_p subcom)
Add a previously created app as a subcommand.
Definition CLI11.hpp:6202
Option * add_flag(std::string flag_name, T &flag_description)
Definition CLI11.hpp:6013
bool remove_excludes(Option *opt)
Removes an option from the excludes list of this subcommand.
Definition CLI11.hpp:6655
void parse_from_stream(std::istream &input)
Definition CLI11.hpp:6510
App * parse_complete_callback(std::function< void()> pc_callback)
Definition CLI11.hpp:5556
App * formatter_fn(std::function< std::string(const App *, std::string, AppFormatMode)> fmt)
Set the help formatter.
Definition CLI11.hpp:5749
App * description(std::string app_description)
Set the description of the app.
Definition CLI11.hpp:6773
const Option * get_option_no_throw(std::string option_name) const noexcept
Get an option by name (noexcept const version)
Definition CLI11.hpp:6831
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:5922
std::string get_display_name(bool with_aliases=false) const
Get a display name for an app.
Definition CLI11.hpp:6978
App * excludes(App *app)
Sets excluded subcommands for the subcommand.
Definition CLI11.hpp:6620
App(std::string app_description, std::string app_name, App *parent)
Special private constructor for subcommand.
Definition CLI11.hpp:5483
bool remove_needs(Option *opt)
Removes an option from the needs list of this subcommand.
Definition CLI11.hpp:6677
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:8159
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:6526
const std::string & _compare_subcommand_names(const App &subcom, const App &base) const
Helper function to run through all possible comparisons of subcommand names to check there is no over...
Definition CLI11.hpp:8091
std::vector< const App * > get_subcommands(const std::function< bool(const App *)> &filter) const
Definition CLI11.hpp:6568
Option * get_version_ptr()
Get a pointer to the version option.
Definition CLI11.hpp:6954
const Option * get_help_ptr() const
Get a pointer to the help flag. (const)
Definition CLI11.hpp:6942
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:6076
std::vector< const Option * > get_options(const std::function< bool(const Option *)> filter={}) const
Get the list of options (user facing function, so returns raw pointers), has optional filter function...
Definition CLI11.hpp:6779
bool get_silent() const
Get the status of silence.
Definition CLI11.hpp:6922
std::vector< std::string > aliases_
Alias names for the subcommand.
Definition CLI11.hpp:5468
void _parse_stream(std::istream &input)
Internal function to parse a stream.
Definition CLI11.hpp:7580
std::string get_description() const
Get the app or subcommand description.
Definition CLI11.hpp:6770
bool get_fallthrough() const
Check the status of fallthrough.
Definition CLI11.hpp:6880
std::set< App * > exclude_subcommands_
this is a list of subcommands that are exclusionary to this one
Definition CLI11.hpp:5390
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:6059
std::shared_ptr< Config > get_config_formatter() const
Access the config formatter.
Definition CLI11.hpp:6757
std::size_t get_require_option_max() const
Get the required max option value.
Definition CLI11.hpp:6907
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:6116
App * final_callback(std::function< void()> app_callback)
Definition CLI11.hpp:5549
App * validate_positionals(bool validate=true)
Set the subcommand to validate positional arguments before assigning.
Definition CLI11.hpp:5665
std::size_t count() const
Definition CLI11.hpp:6300
App * footer(std::function< std::string()> footer_function)
Set footer.
Definition CLI11.hpp:6706
App * excludes(Option *opt)
Sets excluded options for the subcommand.
Definition CLI11.hpp:6611
App * ignore_underscore(bool value=true)
Ignore underscore. Subcommands inherit value.
Definition CLI11.hpp:5728
std::string config_to_str(bool default_also=false, bool write_description=false) const
Definition CLI11.hpp:6712
std::string version() const
Displays a version string.
Definition CLI11.hpp:6733
void _configure()
Definition CLI11.hpp:7135
const App * get_parent() const
Get the parent of this subcommand (or nullptr if main app) (const version)
Definition CLI11.hpp:6963
bool remove_subcommand(App *subcom)
Removes a subcommand from the App. Takes a subcommand pointer. Returns true if found and removed.
Definition CLI11.hpp:6216
App * get_subcommand(const App *subcom) const
Definition CLI11.hpp:6233
std::shared_ptr< ConfigBase > get_config_formatter_base() const
Access the config formatter as a configBase pointer.
Definition CLI11.hpp:6760
bool got_subcommand(const App *subcom) const
Check to see if given subcommand was selected.
Definition CLI11.hpp:6602
const Option * get_option(std::string option_name) const
Get an option by name.
Definition CLI11.hpp:6850
std::string get_footer() const
Generate and return the footer.
Definition CLI11.hpp:6895
App * positionals_at_end(bool value=true)
Specify that the positional arguments are only at the end of the sequence.
Definition CLI11.hpp:5716
App * alias(std::string app_name)
Set an alias for the app.
Definition CLI11.hpp:5587
bool get_ignore_underscore() const
Check the status of ignore_underscore.
Definition CLI11.hpp:6877
std::vector< std::string > remaining(bool recurse=false) const
This returns the missing options from the current subcommand.
Definition CLI11.hpp:7041
void _process_callbacks()
Process callbacks. Runs on all subcommands.
Definition CLI11.hpp:7289
App * formatter(std::shared_ptr< FormatterBase > fmt)
Set the help formatter.
Definition CLI11.hpp:5743
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:7196
Option * add_option(std::string option_name, T &option_description)
Add option with description but with no variable assignment or callback.
Definition CLI11.hpp:5900
const std::string & get_name() const
Get the name of the current app.
Definition CLI11.hpp:6966
void _trigger_pre_parse(std::size_t remaining_args)
Trigger the pre_parse callback if needed.
Definition CLI11.hpp:8060
void _validate() const
Definition CLI11.hpp:7096
App * allow_config_extras(config_extras_mode mode)
ignore extras in config files
Definition CLI11.hpp:5682
Option * add_flag(std::string flag_name, T &flag_result, std::string flag_description="")
Definition CLI11.hpp:6045
void increment_parsed()
Internal function to recursively increment the parsed counter on the current app as well unnamed subc...
Definition CLI11.hpp:7526
config_extras_mode get_allow_config_extras() const
Get the status of allow extras.
Definition CLI11.hpp:6936
App & operator=(const App &)=delete
App * require_option(std::size_t min, std::size_t max)
Definition CLI11.hpp:6376
App * immediate_callback(bool immediate=true)
Set the subcommand callback to be executed immediately on subcommand completion.
Definition CLI11.hpp:5652
std::vector< Option * > get_options(const std::function< bool(Option *)> filter={})
Non-const version of the above.
Definition CLI11.hpp:6796
std::vector< std::string > get_groups() const
Get the groups available directly from this option (in order)
Definition CLI11.hpp:7024
bool _has_remaining_positionals() const
Count the required remaining positional arguments.
Definition CLI11.hpp:7734
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:6092
bool _parse_subcommand(std::vector< std::string > &args)
Definition CLI11.hpp:7870
bool get_enabled_by_default() const
Get the status of disabled by default.
Definition CLI11.hpp:6931
void _parse_config(const std::vector< ConfigItem > &args)
Definition CLI11.hpp:7595
App * disabled(bool disable=true)
Disable the subcommand or option group.
Definition CLI11.hpp:5618
App * callback(std::function< void()> app_callback)
Definition CLI11.hpp:5538
bool get_positionals_at_end() const
Check the status of the allow windows style options.
Definition CLI11.hpp:6886
std::size_t get_require_subcommand_min() const
Get the required min subcommand value.
Definition CLI11.hpp:6898
App * needs(App *app)
Definition CLI11.hpp:6643
App * require_subcommand(std::size_t min, std::size_t max)
Definition CLI11.hpp:6347
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:8141
bool get_immediate_callback() const
Get the status of disabled.
Definition CLI11.hpp:6925
Thrown when the wrong number of arguments has been received.
Definition CLI11.hpp:782
static ArgumentMismatch AtLeast(std::string name, int num, std::size_t received)
Definition CLI11.hpp:792
static ArgumentMismatch TypedAtLeast(std::string name, int num, std::string type)
Definition CLI11.hpp:800
static ArgumentMismatch AtMost(std::string name, int num, std::size_t received)
Definition CLI11.hpp:796
static ArgumentMismatch FlagOverride(std::string name)
Definition CLI11.hpp:803
Definition CLI11.hpp:3523
Options
Definition CLI11.hpp:3529
AsNumberWithUnit(std::map< std::string, Number > mapping, Options opts=DEFAULT, const std::string &unit_name="UNIT")
Definition CLI11.hpp:3538
Definition CLI11.hpp:3661
AsSizeValue(bool kb_is_1000)
Definition CLI11.hpp:3672
std::uint64_t result_t
Definition CLI11.hpp:3663
Thrown on construction of a bad name.
Definition CLI11.hpp:647
static BadNameString BadLongName(std::string name)
Definition CLI11.hpp:651
static BadNameString OneCharName(std::string name)
Definition CLI11.hpp:650
static BadNameString DashesOnly(std::string name)
Definition CLI11.hpp:652
static BadNameString MultiPositionalNames(std::string name)
Definition CLI11.hpp:655
Produce a bounded range (factory). Min and max are inclusive.
Definition CLI11.hpp:3125
Bound(T min_val, T max_val)
Definition CLI11.hpp:3131
Bound(T max_val)
Range of one value is 0 to value.
Definition CLI11.hpp:3152
Usually something like –help-all on command line.
Definition CLI11.hpp:695
-h or –help on command line
Definition CLI11.hpp:689
-v or –version on command line
Definition CLI11.hpp:702
translate named items to other or a value set
Definition CLI11.hpp:3424
CheckedTransformer(T mapping)
direct map of std::string to std::string
Definition CLI11.hpp:3434
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:3492
std::function< std::string(std::string)> filter_fn_t
Definition CLI11.hpp:3426
CheckedTransformer(std::initializer_list< std::pair< std::string, std::string > > values, Args &&...args)
This allows in-place construction.
Definition CLI11.hpp:3430
CheckedTransformer(T mapping, F filter_function)
Definition CLI11.hpp:3438
This converter works with INI/TOML files; to write INI files use ConfigINI.
Definition CLI11.hpp:2583
const std::string & section() const
get the section
Definition CLI11.hpp:2653
std::vector< ConfigItem > from_config(std::istream &input) const override
Convert a configuration into an app.
Definition CLI11.hpp:8568
ConfigBase * comment(char cchar)
Specify the configuration for comment characters.
Definition CLI11.hpp:2614
ConfigBase * arrayDelimiter(char aSep)
Specify the delimiter character for an array.
Definition CLI11.hpp:2625
ConfigBase * quoteCharacter(char qString, char qChar)
Specify the quote characters used around strings and characters.
Definition CLI11.hpp:2635
std::string & sectionRef()
get a reference to the configuration section
Definition CLI11.hpp:2651
ConfigBase * arrayBounds(char aStart, char aEnd)
Specify the start and end characters for an array.
Definition CLI11.hpp:2619
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:8701
int16_t index() const
get the section index
Definition CLI11.hpp:2663
ConfigBase * maxLayers(uint8_t layers)
Specify the maximum number of parents.
Definition CLI11.hpp:2641
ConfigBase * section(const std::string &sectionName)
specify a particular section of the configuration file to use
Definition CLI11.hpp:2655
ConfigBase * valueSeparator(char vSep)
Specify the delimiter between a name and value.
Definition CLI11.hpp:2630
ConfigBase * index(int16_t sectionIndex)
specify a particular index in the section to use (-1) for all sections to use
Definition CLI11.hpp:2665
int16_t & indexRef()
get a reference to the configuration index
Definition CLI11.hpp:2661
ConfigBase * parentSeparator(char sep)
Specify the separator to use for parent layers.
Definition CLI11.hpp:2646
Thrown when extra values are found in an INI file.
Definition CLI11.hpp:839
static ConfigError NotConfigurable(std::string item)
Definition CLI11.hpp:843
static ConfigError Extras(std::string item)
Definition CLI11.hpp:842
ConfigINI generates a "standard" INI compliant output.
Definition CLI11.hpp:2675
ConfigINI()
Definition CLI11.hpp:2678
This class provides a converter for configuration files.
Definition CLI11.hpp:2550
std::vector< ConfigItem > from_file(const std::string &name)
Parse a config file, throw an error (ParseError:ConfigParseError or FileError) on failure.
Definition CLI11.hpp:2570
virtual std::string to_config(const App *, bool, bool, std::string) const =0
Convert an app into a configuration.
virtual ~Config()=default
Virtual destructor.
virtual std::vector< ConfigItem > from_config(std::istream &) const =0
Convert a configuration into an app.
virtual std::string to_flag(const ConfigItem &item) const
Get a flag value.
Definition CLI11.hpp:2562
Construction errors (not in parsing)
Definition CLI11.hpp:614
Thrown when conversion call back fails, such as when an int fails to coerce to a string.
Definition CLI11.hpp:722
static ConversionError TrueFalse(std::string name)
Definition CLI11.hpp:732
ConversionError(std::string name, std::vector< std::string > results)
Definition CLI11.hpp:727
static ConversionError TooManyInputsFlag(std::string name)
Definition CLI11.hpp:729
Class wrapping some of the accessors of Validator.
Definition CLI11.hpp:2910
All errors derive from this one.
Definition CLI11.hpp:596
int get_exit_code() const
Definition CLI11.hpp:601
Error(std::string name, std::string msg, ExitCodes exit_code)
Definition CLI11.hpp:608
std::string get_name() const
Definition CLI11.hpp:603
Error(std::string name, std::string msg, int exit_code=static_cast< int >(ExitCodes::BaseClass))
Definition CLI11.hpp:605
Thrown when an excludes option is present.
Definition CLI11.hpp:816
Thrown when too many positionals or options are found.
Definition CLI11.hpp:823
ExtrasError(const std::string &name, std::vector< std::string > args)
Definition CLI11.hpp:830
Thrown when parsing an INI file and it is missing.
Definition CLI11.hpp:715
static FileError Missing(std::string name)
Definition CLI11.hpp:718
Definition CLI11.hpp:3786
std::size_t get_column_width() const
Get the current column width.
Definition CLI11.hpp:3836
FormatterBase(FormatterBase &&)=default
void label(std::string key, std::string val)
Set the "REQUIRED" label.
Definition CLI11.hpp:3818
std::string get_label(std::string key) const
Get the current value of a name (REQUIRED, etc.)
Definition CLI11.hpp:3828
FormatterBase()=default
FormatterBase(const FormatterBase &)=default
virtual ~FormatterBase() noexcept
Adding a destructor in this form to work around bug in GCC 4.7.
Definition CLI11.hpp:3808
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:3821
This is a specialty override for lambda functions.
Definition CLI11.hpp:3842
std::string make_help(const App *app, std::string name, AppFormatMode mode) const override
This will simply call the lambda function.
Definition CLI11.hpp:3856
~FormatterLambda() noexcept override
Adding a destructor (mostly to make GCC 4.7 happy)
Definition CLI11.hpp:3853
FormatterLambda(funct_t funct)
Create a FormatterLambda with a lambda function.
Definition CLI11.hpp:3850
Definition CLI11.hpp:3863
virtual std::string make_description(const App *app) const
This displays the description line.
Definition CLI11.hpp:8840
Formatter(Formatter &&)=default
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:3908
virtual std::string make_usage(const App *app, std::string name) const
This displays the usage line.
Definition CLI11.hpp:8866
Formatter(const Formatter &)=default
virtual std::string make_subcommand(const App *sub) const
This prints out a subcommand.
Definition CLI11.hpp:8982
std::string make_help(const App *, std::string, AppFormatMode) const override
This puts everything together.
Definition CLI11.hpp:8916
virtual std::string make_subcommands(const App *app, AppFormatMode mode) const
This prints out all the subcommands.
Definition CLI11.hpp:8940
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:9015
virtual std::string make_positionals(const App *app) const
This prints out just the positionals "group".
Definition CLI11.hpp:8806
Formatter()=default
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:9050
virtual std::string make_option_name(const Option *, bool) const
This is the name part of an option, Default: left column.
Definition CLI11.hpp:9008
virtual std::string make_footer(const App *app) const
This prints out all the groups of options.
Definition CLI11.hpp:8908
std::string make_groups(const App *app, AppFormatMode mode) const
This prints out all the groups of options.
Definition CLI11.hpp:8816
virtual std::string make_expanded(const App *sub) const
This prints out a subcommand in help-all.
Definition CLI11.hpp:8988
virtual std::string make_group(std::string group, bool is_positional, std::vector< const Option * > opts) const
Definition CLI11.hpp:8795
virtual std::string make_option_usage(const Option *opt) const
This is used to print the name on the USAGE line.
Definition CLI11.hpp:9052
Definition CLI11.hpp:858
Thrown when an option is set to conflicting values (non-vector and multi args, for example)
Definition CLI11.hpp:619
static IncorrectConstruction SetFlag(std::string name)
Definition CLI11.hpp:628
static IncorrectConstruction MultiOptionPolicy(std::string name)
Definition CLI11.hpp:641
static IncorrectConstruction AfterMultiOpt(std::string name)
Definition CLI11.hpp:634
static IncorrectConstruction MissingOption(std::string name)
Definition CLI11.hpp:638
static IncorrectConstruction PositionalFlag(std::string name)
Definition CLI11.hpp:622
static IncorrectConstruction Set0Opt(std::string name)
Definition CLI11.hpp:625
static IncorrectConstruction ChangeNotVector(std::string name)
Definition CLI11.hpp:631
Thrown when validation fails before parsing.
Definition CLI11.hpp:849
Verify items are in a set.
Definition CLI11.hpp:3297
IsMember(T &&set)
This checks to see if an item is in a set (empty function)
Definition CLI11.hpp:3307
IsMember(T set, F filter_function)
Definition CLI11.hpp:3311
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:3355
IsMember(std::initializer_list< T > values, Args &&...args)
This allows in-place construction using an initializer list.
Definition CLI11.hpp:3303
std::function< std::string(std::string)> filter_fn_t
Definition CLI11.hpp:3299
Thrown when an option already exists.
Definition CLI11.hpp:661
static OptionAlreadyAdded Excludes(std::string name, std::string other)
Definition CLI11.hpp:668
static OptionAlreadyAdded Requires(std::string name, std::string other)
Definition CLI11.hpp:665
Definition CLI11.hpp:3952
bool get_disable_flag_override() const
The status of configurable.
Definition CLI11.hpp:4040
CRTP * mandatory(bool value=true)
Support Plumbum term.
Definition CLI11.hpp:4015
CRTP * take_all()
Set the multi option policy to take all arguments.
Definition CLI11.hpp:4068
bool get_ignore_case() const
The status of ignore case.
Definition CLI11.hpp:4031
bool get_configurable() const
The status of configurable.
Definition CLI11.hpp:4037
CRTP * group(const std::string &name)
Changes the group membership.
Definition CLI11.hpp:4000
CRTP * join()
Set the multi option policy to join.
Definition CLI11.hpp:4075
CRTP * join(char delim)
Set the multi option policy to join with a specific delimiter.
Definition CLI11.hpp:4082
bool get_ignore_underscore() const
The status of ignore_underscore.
Definition CLI11.hpp:4034
CRTP * take_first()
Set the multi option policy to take last.
Definition CLI11.hpp:4061
CRTP * configurable(bool value=true)
Allow in a configuration file.
Definition CLI11.hpp:4090
CRTP * delimiter(char value='\0')
Allow in a configuration file.
Definition CLI11.hpp:4096
MultiOptionPolicy get_multi_option_policy() const
The status of the multi option policy.
Definition CLI11.hpp:4049
bool get_required() const
True if this is a required option.
Definition CLI11.hpp:4028
bool required_
True if this is a required option.
Definition CLI11.hpp:3960
CRTP * take_last()
Set the multi option policy to take last.
Definition CLI11.hpp:4054
CRTP * always_capture_default(bool value=true)
Definition CLI11.hpp:4017
bool get_always_capture_default() const
Return true if this will automatically capture the default value for help printing.
Definition CLI11.hpp:4046
char get_delimiter() const
Get the current delimiter char.
Definition CLI11.hpp:4043
const std::string & get_group() const
Get the group of this option.
Definition CLI11.hpp:4025
void copy_to(T *other) const
Copy the contents to another similar class (one based on OptionBase)
Definition CLI11.hpp:3984
CRTP * required(bool value=true)
Set the option as required.
Definition CLI11.hpp:4009
Definition CLI11.hpp:4104
OptionDefaults * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times.
Definition CLI11.hpp:4111
OptionDefaults * ignore_case(bool value=true)
Ignore the case of the option name.
Definition CLI11.hpp:4117
OptionDefaults * ignore_underscore(bool value=true)
Ignore underscores in the option name.
Definition CLI11.hpp:4123
OptionDefaults()=default
OptionDefaults * delimiter(char value='\0')
set a delimiter character to split up single arguments to treat as multiple inputs
Definition CLI11.hpp:4135
OptionDefaults * disable_flag_override(bool value=true)
Disable overriding flag values with an '=' segment.
Definition CLI11.hpp:4129
Thrown when counting a non-existent option.
Definition CLI11.hpp:866
Extension of App to better manage groups of options.
Definition CLI11.hpp:8200
App * add_subcommand(App *subcom)
Add an existing subcommand to be a member of an option_group.
Definition CLI11.hpp:8225
Option * add_option(Option *opt)
Add an existing option to the Option_group.
Definition CLI11.hpp:8209
Option_group(std::string group_description, std::string group_name, App *parent)
Definition CLI11.hpp:8202
void add_options(Option *opt, Args... args)
Add a bunch of options to the group.
Definition CLI11.hpp:8219
void add_options(Option *opt)
Add an existing option to the Option_group.
Definition CLI11.hpp:8217
Definition CLI11.hpp:4141
const std::string & get_option_text() const
Definition CLI11.hpp:4676
const std::vector< std::string > & get_lnames() const
Get the long names.
Definition CLI11.hpp:4614
int get_type_size_max() const
The maximum number of arguments the option expects.
Definition CLI11.hpp:4593
std::size_t count() const
Count the total number of times an option was passed.
Definition CLI11.hpp:4267
int get_expected_min() const
The number of times the option expects to be included.
Definition CLI11.hpp:4638
Option * excludes(Option *opt)
Sets excluded options.
Definition CLI11.hpp:4468
bool get_run_callback_for_default() const
Get the current value of run_callback_for_default.
Definition CLI11.hpp:4357
Option * type_name(std::string typeval)
Set a custom option typestring.
Definition CLI11.hpp:4986
int get_expected_max() const
The max number of times the option expects to be included.
Definition CLI11.hpp:4640
option_state
enumeration for the option state machine
Definition CLI11.hpp:4231
bool get_trigger_on_parse() const
The status of trigger on parse.
Definition CLI11.hpp:4340
int get_expected() const
The number of times the option expects to be included.
Definition CLI11.hpp:4635
const results_t & results() const
Get the current complete results set.
Definition CLI11.hpp:4913
results_t reduced_results() const
Get a copy of the results.
Definition CLI11.hpp:4916
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:4254
Option * expected(int value_min, int value_max)
Set the range of expected arguments.
Definition CLI11.hpp:4308
int get_type_size_min() const
The minimum number of arguments the option expects.
Definition CLI11.hpp:4591
Option * ignore_case(bool value=true)
Definition CLI11.hpp:4519
std::string get_default_str() const
The default value (for help printing)
Definition CLI11.hpp:4608
std::set< Option * > needs_
A list of options that are required with this option.
Definition CLI11.hpp:4207
Option * default_function(const std::function< std::string()> &func)
Set a capture function for the default. Mostly used by App.
Definition CLI11.hpp:5039
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:4499
Option * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times (or another policy)
Definition CLI11.hpp:4565
bool check_lname(std::string name) const
Requires "--" to be removed from string.
Definition CLI11.hpp:4832
Option * add_result(std::string s)
Puts a result at the end.
Definition CLI11.hpp:4890
std::set< Option * > excludes_
A list of options that are excluded with this option.
Definition CLI11.hpp:4210
Option & operator=(const Option &)=delete
bool check_fname(std::string name) const
Requires "--" to be removed from string.
Definition CLI11.hpp:4837
std::string get_flag_value(const std::string &name, std::string input_value) const
Definition CLI11.hpp:4846
const std::vector< std::string > & get_fnames() const
Get the flag names with specified default values.
Definition CLI11.hpp:4620
Option * each(const std::function< void(std::string)> &func)
Adds a user supplied function to run on each item passed in (communicate though lambda capture)
Definition CLI11.hpp:4402
Validator * get_validator(const std::string &Validator_name="")
Get a named Validator.
Definition CLI11.hpp:4412
Option * option_text(std::string text)
Definition CLI11.hpp:4671
Option * check(std::function< std::string(const std::string &)> Validator, std::string Validator_description="", std::string Validator_name="")
Adds a Validator. Takes a const string& and returns an error message (empty if conversion/check is ok...
Definition CLI11.hpp:4369
const std::string & get_description() const
Get the description.
Definition CLI11.hpp:4663
Option * expected(int value)
Set the number of expected arguments.
Definition CLI11.hpp:4286
bool has_description() const
True if option has description.
Definition CLI11.hpp:4660
bool check_name(const std::string &name) const
Check a name. Requires "-" or "--" for short / long, supports positional name.
Definition CLI11.hpp:4797
Option(const Option &)=delete
bool get_force_callback() const
The status of force_callback.
Definition CLI11.hpp:4348
bool get_allow_extra_args() const
Get the current value of allow extra args.
Definition CLI11.hpp:4333
Option * disable_flag_override(bool value=true)
Disable flag overrides values, e.g. –flag=is not allowed.
Definition CLI11.hpp:4579
std::vector< std::string > snames_
A list of the short names (-a) without the leading dashes.
Definition CLI11.hpp:4149
Option * run_callback_for_default(bool value=true)
Definition CLI11.hpp:4352
Option * type_size(int option_type_size_min, int option_type_size_max)
Set a custom option type size range.
Definition CLI11.hpp:5011
void inject_separator(bool value=true)
Set the value of the separator injection flag.
Definition CLI11.hpp:5036
Option * allow_extra_args(bool value=true)
Definition CLI11.hpp:4328
std::set< Option * > get_excludes() const
The set of options excluded.
Definition CLI11.hpp:4605
Option * trigger_on_parse(bool value=true)
Set the value of trigger_on_parse which specifies that the option callback should be triggered on eve...
Definition CLI11.hpp:4335
int get_type_size() const
The number of arguments the option expects.
Definition CLI11.hpp:4588
Option * type_size(int option_type_size)
Set a custom option size.
Definition CLI11.hpp:4992
callback_t get_callback() const
Get the callback function.
Definition CLI11.hpp:4611
std::string get_type_name() const
Get the full typename for this option.
Definition CLI11.hpp:5087
bool nonpositional() const
True if option has at least one non-positional name.
Definition CLI11.hpp:4657
std::string get_envname() const
The environment variable associated to this value.
Definition CLI11.hpp:4599
int get_items_expected_max() const
Get the maximum number of items expected to be returned and used for the callback.
Definition CLI11.hpp:4646
Option * transform(const std::function< std::string(std::string)> &func, std::string transform_description="", std::string transform_name="")
Adds a Validator-like function that can change result.
Definition CLI11.hpp:4386
Option * excludes(std::string opt_name)
Can find a string if needed.
Definition CLI11.hpp:4484
int get_inject_separator() const
Return the inject_separator flag.
Definition CLI11.hpp:4596
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:4457
bool get_callback_run() const
See if the callback has been run already.
Definition CLI11.hpp:4973
T as() const
Return the results as the specified type.
Definition CLI11.hpp:4966
void run_callback()
Process the callback.
Definition CLI11.hpp:4746
Option * transform(Validator Validator, const std::string &Validator_name="")
Adds a transforming Validator with a built in type name.
Definition CLI11.hpp:4378
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:4686
void clear()
Clear the parsed results (mostly for testing)
Definition CLI11.hpp:4276
Option * add_result(std::vector< std::string > s)
Puts a result at the end.
Definition CLI11.hpp:4904
Option * capture_default_str()
Capture the default value from the original value (if it can be captured)
Definition CLI11.hpp:5045
void results(T &output) const
Get the results as a specified type.
Definition CLI11.hpp:4935
Option * default_str(std::string val)
Set the default value string representation (does not change the contained value)
Definition CLI11.hpp:5053
bool get_positional() const
True if the argument can be given directly.
Definition CLI11.hpp:4654
std::string envname_
If given, check the environment for this option.
Definition CLI11.hpp:4165
std::set< Option * > get_needs() const
The set of options needed.
Definition CLI11.hpp:4602
bool check_sname(std::string name) const
Requires "-" to be removed from string.
Definition CLI11.hpp:4827
Option * ignore_underscore(bool value=true)
Definition CLI11.hpp:4543
std::vector< std::pair< std::string, std::string > > default_flag_values_
Definition CLI11.hpp:4156
Option * envname(std::string name)
Sets environment variable to read if no option given.
Definition CLI11.hpp:4510
Option * type_name_fn(std::function< std::string()> typefun)
Set the type function to run when displayed on this option.
Definition CLI11.hpp:4980
Option * default_val(const X &val)
Definition CLI11.hpp:5060
Option * add_result(std::string s, int &results_added)
Puts a result at the end and get a count of the number of arguments actually added.
Definition CLI11.hpp:4897
const std::string & get_single_name() const
Get a single name for the option, first of lname, pname, sname, envname.
Definition CLI11.hpp:4622
Option * needs(Option *opt)
Sets required options.
Definition CLI11.hpp:4434
const std::string & matching_name(const Option &other) const
If options share any of the same names, find it.
Definition CLI11.hpp:4773
Option * needs(A opt, B opt1, ARG... args)
Any number supported, any mix of string and Opt.
Definition CLI11.hpp:4451
Option * description(std::string option_description)
Set the description.
Definition CLI11.hpp:4666
std::vector< std::string > lnames_
A list of the long names (--long) without the leading dashes.
Definition CLI11.hpp:4152
Option * force_callback(bool value=true)
Set the value of force_callback.
Definition CLI11.hpp:4343
Validator * get_validator(int index)
Get a Validator by index NOTE: this may not be the order of definition.
Definition CLI11.hpp:4425
bool operator==(const Option &other) const
If options share any of the same names, they are equal (not counting positional)
Definition CLI11.hpp:4794
Option * check(Validator validator, const std::string &validator_name="")
Adds a Validator with a built in type name.
Definition CLI11.hpp:4360
Option * needs(std::string opt_name)
Can find a string if needed.
Definition CLI11.hpp:4442
bool empty() const
True if the option was not passed.
Definition CLI11.hpp:4270
int get_items_expected_min() const
The total min number of expected string values to be used.
Definition CLI11.hpp:4643
Option * excludes(A opt, B opt1, ARG... args)
Any number supported, any mix of string and Opt.
Definition CLI11.hpp:4493
const std::vector< std::string > & get_snames() const
Get the short names.
Definition CLI11.hpp:4617
int get_items_expected() const
The total min number of expected string values to be used.
Definition CLI11.hpp:4651
Anything that can error in Parse.
Definition CLI11.hpp:676
Produce a range (factory). Min and max are inclusive.
Definition CLI11.hpp:3087
Range(T min_val, T max_val, const std::string &validator_name=std::string{})
Definition CLI11.hpp:3094
Range(T max_val, const std::string &validator_name=std::string{})
Range of one value is 0 to value.
Definition CLI11.hpp:3114
Thrown when a required option is missing.
Definition CLI11.hpp:745
static RequiredError Option(std::size_t min_option, std::size_t max_option, std::size_t used, const std::string &option_list)
Definition CLI11.hpp:756
static RequiredError Subcommand(std::size_t min_subcom)
Definition CLI11.hpp:748
Thrown when a requires option is missing.
Definition CLI11.hpp:809
Does not output a diagnostic in CLI11_PARSE, but allows main() to return with a specific error code.
Definition CLI11.hpp:709
This is a successful completion on parsing, supposed to exit.
Definition CLI11.hpp:683
Translate named items to other or a value set.
Definition CLI11.hpp:3366
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:3416
Transformer(std::initializer_list< std::pair< std::string, std::string > > values, Args &&...args)
This allows in-place construction.
Definition CLI11.hpp:3372
std::function< std::string(std::string)> filter_fn_t
Definition CLI11.hpp:3368
Transformer(T &&mapping)
direct map of std::string to std::string
Definition CLI11.hpp:3376
Transformer(T mapping, F filter_function)
Definition CLI11.hpp:3380
Validate the input as a particular type.
Definition CLI11.hpp:3069
TypeValidator()
Definition CLI11.hpp:3080
TypeValidator(const std::string &validator_name)
Definition CLI11.hpp:3071
Thrown when validation of results fails.
Definition CLI11.hpp:738
Some validators that are provided.
Definition CLI11.hpp:2701
bool get_active() const
Get a boolean if the validator is active.
Definition CLI11.hpp:2815
int application_index_
A Validator will only apply to an indexed value (-1 is all elements)
Definition CLI11.hpp:2712
Validator & non_modifying(bool no_modify=true)
Specify whether the Validator can be modifying or not.
Definition CLI11.hpp:2797
Validator & description(std::string validator_desc)
Specify the type string.
Definition CLI11.hpp:2754
std::string operator()(const std::string &str) const
Definition CLI11.hpp:2748
Validator operator&(const Validator &other) const
Definition CLI11.hpp:2822
bool active_
Enable for Validator to allow it to be disabled if need be.
Definition CLI11.hpp:2714
Validator name(std::string validator_name) const
Specify the type string.
Definition CLI11.hpp:2777
Validator application_index(int app_index) const
Specify the application index of a validator.
Definition CLI11.hpp:2807
const std::string & get_name() const
Get the name of the Validator.
Definition CLI11.hpp:2783
Validator(std::string validator_desc)
Construct a Validator with just the description string.
Definition CLI11.hpp:2721
std::string get_description() const
Generate type description information for the Validator.
Definition CLI11.hpp:2765
Validator & name(std::string validator_name)
Specify the type string.
Definition CLI11.hpp:2772
Validator()=default
std::string operator()(std::string &str) const
Definition CLI11.hpp:2733
Validator active(bool active_val=true) const
Specify whether the Validator is active or not.
Definition CLI11.hpp:2790
std::function< std::string()> desc_function_
This is the description function, if empty the description_ will be used.
Definition CLI11.hpp:2704
int get_application_index() const
Get the current value of the application index.
Definition CLI11.hpp:2813
std::function< std::string(std::string &)> func_
Definition CLI11.hpp:2708
Validator operator!() const
Create a validator that fails when a given validator succeeds.
Definition CLI11.hpp:2870
Validator operator|(const Validator &other) const
Definition CLI11.hpp:2847
Validator & active(bool active_val=true)
Specify whether the Validator is active or not.
Definition CLI11.hpp:2785
std::string name_
The name for search purposes of the Validator.
Definition CLI11.hpp:2710
Validator description(std::string validator_desc) const
Specify the type string.
Definition CLI11.hpp:2759
bool get_modifying() const
Get a boolean if the validator is allowed to modify the input returns true if it can modify the input...
Definition CLI11.hpp:2818
Validator & application_index(int app_index)
Specify the application index of a validator.
Definition CLI11.hpp:2802
Validator(std::function< std::string(std::string &)> op, std::string validator_desc, std::string validator_name="")
Construct Validator from basic information.
Definition CLI11.hpp:2723
Validator & operation(std::function< std::string(std::string &)> op)
Set the Validator operation function.
Definition CLI11.hpp:2727
Check for an existing directory (returns error message if check fails)
Definition CLI11.hpp:2981
ExistingDirectoryValidator()
Definition CLI11.hpp:2983
Check for an existing file (returns error message if check fails)
Definition CLI11.hpp:2964
ExistingFileValidator()
Definition CLI11.hpp:2966
Check for an existing path.
Definition CLI11.hpp:2998
ExistingPathValidator()
Definition CLI11.hpp:3000
Validate the given string is a legal ipv4 address.
Definition CLI11.hpp:3026
IPV4Validator()
Definition CLI11.hpp:3028
Check for an non-existing path.
Definition CLI11.hpp:3012
NonexistentPathValidator()
Definition CLI11.hpp:3014
Check for complex.
Definition CLI11.hpp:1049
Definition CLI11.hpp:999
Check for input streamability.
Definition CLI11.hpp:1038
Definition CLI11.hpp:1027
Definition CLI11.hpp:1111
std::string help(const App *app, const Error &e)
Printout the full help string on error (if this fn is set, the old default for CLI11)
Definition CLI11.hpp:8375
std::string simple(const App *app, const Error &e)
Printout a clean, simple message on error (the default in CLI11 1.5+)
Definition CLI11.hpp:8356
std::vector< std::string > split_names(std::string current)
Definition CLI11.hpp:2450
std::string & remove_quotes(std::string &str)
remove quotes at the front and back of a string either '"' or '\''
Definition CLI11.hpp:268
constexpr enabler dummy
An instance to use in EnableIf.
Definition CLI11.hpp:888
std::string & add_quotes_if_needed(std::string &str)
Add quotes if the string contains spaces.
Definition CLI11.hpp:533
std::string ini_join(const std::vector< std::string > &args, char sepChar=',', char arrayStart='[', char arrayEnd=']', char stringQuote='"', char characterQuote = '\'')
Comma separated join, adds quotes if needed.
Definition CLI11.hpp:8467
auto smart_deref(T value) -> decltype(*value)
Definition CLI11.hpp:3158
bool split_long(const std::string &current, std::string &name, std::string &value)
Definition CLI11.hpp:2418
auto to_string(T &&value) -> decltype(std::forward< T >(value))
Convert an object to a string (directly forward if this can become a string)
Definition CLI11.hpp:1124
path_type check_path(const char *file) noexcept
get the type of the path from a file name
Definition CLI11.hpp:2948
auto checked_to_string(T &&value) -> decltype(to_string(std::forward< T >(value)))
special template overload
Definition CLI11.hpp:1177
bool split_short(const std::string &current, std::string &name, std::string &rest)
Definition CLI11.hpp:2408
path_type
CLI enumeration of different file types.
Definition CLI11.hpp:2919
std::string convert_arg_for_ini(const std::string &arg, char stringQuote='"', char characterQuote = '\'')
Definition CLI11.hpp:8422
std::tuple< std::vector< std::string >, std::vector< std::string >, std::string > get_names(const std::vector< std::string > &input)
Get a vector of short names, one of long names, and a single name.
Definition CLI11.hpp:2490
std::string generate_map(const T &map, bool key_only=false)
Generate a string representation of a map.
Definition CLI11.hpp:3182
std::string & rtrim(std::string &str)
Trim whitespace from right of string.
Definition CLI11.hpp:241
std::ptrdiff_t find_member(std::string name, const std::vector< std::string > names, bool ignore_case=false, bool ignore_underscore=false)
Check if a string is a member of a list of strings and optionally ignore case or ignore underscores.
Definition CLI11.hpp:422
bool valid_first_char(T c)
Definition CLI11.hpp:337
bool valid_name_string(const std::string &str)
Verify an option/subcommand name.
Definition CLI11.hpp:348
std::ostream & format_help(std::ostream &out, std::string name, const std::string &description, std::size_t wid)
Print a two part "help" string.
Definition CLI11.hpp:300
std::string remove_underscore(std::string str)
remove underscores from a string
Definition CLI11.hpp:385
bool is_separator(const std::string &str)
check if a string is a container segment separator (empty or "%%")
Definition CLI11.hpp:366
std::vector< std::string > split_up(std::string str, char delimiter='\0')
Definition CLI11.hpp:464
std::enable_if< std::is_signed< T >::value, T >::type overflowCheck(const T &a, const T &b)
Do a check for overflow on signed numbers.
Definition CLI11.hpp:3255
std::enable_if< std::is_integral< T >::value, bool >::type checked_multiply(T &a, T b)
Performs a *= b; if it doesn't cause integer overflow. Returns false otherwise.
Definition CLI11.hpp:3269
std::string find_and_modify(std::string str, std::string trigger, Callable modify)
Definition CLI11.hpp:454
std::string trim_copy(const std::string &str)
Make a copy of the string and then trim it.
Definition CLI11.hpp:262
std::string & trim(std::string &str)
Trim whitespace from string.
Definition CLI11.hpp:256
bool from_stream(const std::string &istring, T &obj)
Templated operation to get a value from a stream.
Definition CLI11.hpp:1061
std::string fix_newlines(const std::string &leader, std::string input)
Definition CLI11.hpp:282
void remove_default_flag_values(std::string &flags)
Definition CLI11.hpp:408
std::string generate_set(const T &set)
Generate a string representation of a set.
Definition CLI11.hpp:3169
std::ostream & format_aliases(std::ostream &out, const std::vector< std::string > &aliases, std::size_t wid)
Print subcommand aliases.
Definition CLI11.hpp:318
bool valid_later_char(T c)
Verify following characters of an option.
Definition CLI11.hpp:340
std::pair< std::string, std::string > split_program_name(std::string commandline)
Definition CLI11.hpp:3717
constexpr int expected_max_vector_size
Definition CLI11.hpp:161
std::string value_string(const T &value)
get a string as a convertible value for arithmetic types
Definition CLI11.hpp:1191
std::string & ltrim(std::string &str)
Trim whitespace from left of string.
Definition CLI11.hpp:227
auto search(const T &set, const V &val) -> std::pair< bool, decltype(std::begin(detail::smart_deref(set)))>
A search function.
Definition CLI11.hpp:3213
bool split_windows_style(const std::string &current, std::string &name, std::string &value)
Definition CLI11.hpp:2434
std::string type_name()
Print type name for tuples with 2 or more elements.
Definition CLI11.hpp:1628
std::string join(const T &v, std::string delim=",")
Simple function to join a string.
Definition CLI11.hpp:181
std::string find_and_replace(std::string str, std::string from, std::string to)
Find and replace a substring with another substring.
Definition CLI11.hpp:391
return str
Definition CLI11.hpp:1621
bool lexical_assign(const std::string &input, AssignTo &output)
Assign a value through lexical cast operations.
Definition CLI11.hpp:1941
Classifier
Definition CLI11.hpp:5264
std::vector< std::string > generate_parents(const std::string &section, std::string &name, char parentSeparator)
Definition CLI11.hpp:8493
std::vector< std::string > split(const std::string &s, char delim)
Split a string by a delim.
Definition CLI11.hpp:164
std::size_t escape_detect(std::string &str, std::size_t offset)
Definition CLI11.hpp:520
bool valid_alias_name_string(const std::string &str)
Verify an app name.
Definition CLI11.hpp:360
bool isalpha(const std::string &str)
Verify that str consists of letters only.
Definition CLI11.hpp:372
std::string to_lower(std::string str)
Return a lower case version of a string.
Definition CLI11.hpp:377
bool has_default_flag_values(const std::string &flags)
check if the flag definitions has possible false flags
Definition CLI11.hpp:404
std::vector< std::pair< std::string, std::string > > get_default_flag_values(const std::string &str)
extract default flag values either {def} or starting with a !
Definition CLI11.hpp:2462
enabler
Simple empty scoped class.
Definition CLI11.hpp:885
bool lexical_cast(const std::string &input, T &output)
Integer conversion.
Definition CLI11.hpp:1717
void checkParentSegments(std::vector< ConfigItem > &output, const std::string &currentSection, char parentSeparator)
assuming non default segments do a check on the close and open of the segments in a configItem struct...
Definition CLI11.hpp:8519
std::int64_t to_flag_value(std::string val)
Convert a flag into an integer value typically binary flags.
Definition CLI11.hpp:1670
bool integral_conversion(const std::string &input, T &output) noexcept
Convert to an unsigned integral.
Definition CLI11.hpp:1647
constexpr std::enable_if< I==type_count_base< T >::value, int >::type tuple_type_size()
0 if the index > tuple size
Definition CLI11.hpp:1275
std::string rjoin(const T &v, std::string delim=",")
Join a string in reverse order.
Definition CLI11.hpp:214
Definition CLI11.hpp:139
std::string ignore_case(std::string item)
Helper function to allow ignore_case to be passed to IsMember or Transform.
Definition CLI11.hpp:3500
std::string ignore_underscore(std::string item)
Helper function to allow ignore_underscore to be passed to IsMember or Transform.
Definition CLI11.hpp:3503
typename std::enable_if< B, T >::type enable_if_t
Definition CLI11.hpp:896
ExitCodes
Definition CLI11.hpp:567
const detail::ExistingDirectoryValidator ExistingDirectory
Check for an existing directory (returns error message if check fails)
Definition CLI11.hpp:3057
void retire_option(App *app, Option *opt)
Helper function to mark an option as retired.
Definition CLI11.hpp:8302
config_extras_mode
enumeration of modes of how to deal with extras in config files
Definition CLI11.hpp:5275
void TriggerOn(App *trigger_app, App *app_to_enable)
Helper function to enable one option group/subcommand when another is used.
Definition CLI11.hpp:8233
typename std::conditional< B, T, F >::type conditional_t
A copy of std::conditional_t from C++14 - same reasoning as enable_if_t, it does not hurt to redefine...
Definition CLI11.hpp:905
std::unique_ptr< Option > Option_p
Definition CLI11.hpp:3940
void deprecate_option(Option *opt, const std::string &replacement="")
Helper function to mark an option as deprecated.
Definition CLI11.hpp:8275
std::vector< std::string > results_t
Definition CLI11.hpp:3933
const detail::NonexistentPathValidator NonexistentPath
Check for an non-existing path.
Definition CLI11.hpp:3063
AppFormatMode
Definition CLI11.hpp:3776
@ Normal
The normal, detailed help.
@ All
A fully expanded help.
@ Sub
Used when printed as part of expanded subcommand.
MultiOptionPolicy
Enumeration of the multiOption Policy selection.
Definition CLI11.hpp:3942
@ TakeAll
just get all the passed argument regardless
@ TakeFirst
take only the first Expected number of arguments
@ Throw
Throw an error if any extra arguments were given.
@ TakeLast
take only the last Expected number of arguments
@ Join
merge all the arguments together into a single string via the delimiter character default(' ')
const detail::IPV4Validator ValidIPV4
Check for an IP4 address.
Definition CLI11.hpp:3066
const detail::ExistingPathValidator ExistingPath
Check for an existing path.
Definition CLI11.hpp:3060
std::vector< std::pair< std::string, T > > TransformPairs
definition of the default transformation object
Definition CLI11.hpp:3363
const detail::ExistingFileValidator ExistingFile
Check for existing file (returns error message if check fails)
Definition CLI11.hpp:3054
typename make_void< Ts... >::type void_t
A copy of std::void_t from C++17 - same reasoning as enable_if_t, it does not hurt to redefine.
Definition CLI11.hpp:902
const Range NonNegativeNumber((std::numeric_limits< double >::max)(), "NONNEGATIVE")
Check for a non negative number.
std::function< bool(const results_t &)> callback_t
callback function definition
Definition CLI11.hpp:3935
std::string ignore_space(std::string item)
Helper function to allow checks to ignore spaces to be passed to IsMember or Transform.
Definition CLI11.hpp:3506
const Range PositiveNumber((std::numeric_limits< double >::min)(),(std::numeric_limits< double >::max)(), "POSITIVE")
Check for a positive valued number (val>0.0), min() her is the smallest positive number.
const TypeValidator< double > Number("NUMBER")
Check for a number.
std::shared_ptr< App > App_p
Definition CLI11.hpp:5279
void TriggerOff(App *trigger_app, App *app_to_enable)
Helper function to disable one option group/subcommand when another is used.
Definition CLI11.hpp:8254
@ I
Definition AngularMomentum.hpp:15
directory_iterator end(const directory_iterator &) noexcept
Definition filesystem.hpp:5858
Holds values to load into Options.
Definition CLI11.hpp:2531
std::vector< std::string > inputs
Listing of inputs.
Definition CLI11.hpp:2539
std::string name
This is the name.
Definition CLI11.hpp:2536
std::vector< std::string > parents
This is the list of parents.
Definition CLI11.hpp:2533
std::string fullname() const
The list of parents and name joined by ".".
Definition CLI11.hpp:2542
std::string type
Definition CLI11.hpp:931
This can be specialized to override the type deduction for IsMember.
Definition CLI11.hpp:928
T type
Definition CLI11.hpp:928
This class is simply to allow tests access to App's protected functions.
Definition CLI11.hpp:8385
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:8407
static App * get_fallthrough_parent(App *app)
Wrap the fallthrough parent function to make sure that is working correctly.
Definition CLI11.hpp:8413
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:8400
typename std::pointer_traits< T >::element_type type
Definition CLI11.hpp:944
not a pointer
Definition CLI11.hpp:941
T type
Definition CLI11.hpp:941
Definition CLI11.hpp:949
typename element_type< T >::type::value_type type
Definition CLI11.hpp:949
Definition CLI11.hpp:3202
std::integral_constant< bool, value > type
Definition CLI11.hpp:3208
static auto test(int) -> decltype(std::declval< CC >().find(std::declval< VV >()), std::true_type())
static auto test(...) -> decltype(std::false_type())
Definition CLI11.hpp:1074
Definition CLI11.hpp:1092
Definition CLI11.hpp:1104
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:979
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:983
typename std::remove_const< typename value_type::second_type >::type second_type
Definition CLI11.hpp:976
Adaptor for set-like structure: This just wraps a normal container in a few utilities that do almost ...
Definition CLI11.hpp:952
typename T::value_type value_type
Definition CLI11.hpp:953
typename std::remove_const< value_type >::type second_type
Definition CLI11.hpp:955
static auto second(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the second value (really just the underlying value)
Definition CLI11.hpp:962
typename std::remove_const< value_type >::type first_type
Definition CLI11.hpp:954
static auto first(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the first value (really just the underlying value)
Definition CLI11.hpp:958
forward declare the subtype_count_min structure
Definition CLI11.hpp:1242
Set of overloads to get the type size of an object.
Definition CLI11.hpp:1239
This will only trigger for actual void type.
Definition CLI11.hpp:1215
This will only trigger for actual void type.
Definition CLI11.hpp:1245
template to get the underlying value type if it exists or use a default
Definition CLI11.hpp:1207
def type
Definition CLI11.hpp:1207
Check to see if something is bool (fail check by default)
Definition CLI11.hpp:908
Check to see if something is copyable pointer.
Definition CLI11.hpp:923
Check to see if something is a shared pointer.
Definition CLI11.hpp:914
A copy of std::void_t from C++17 (helper for C++11 and C++14)
Definition CLI11.hpp:899
void type
Definition CLI11.hpp:899