HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
CLI11.h
Go to the documentation of this file.
1 // CLI11: Version 2.3.1
2 // Originally designed by Henry Schreiner
3 // https://github.com/CLIUtils/CLI11
4 //
5 // This is a standalone header file generated by MakeSingleHeader.py in CLI11/scripts
6 // from: v2.3.1
7 //
8 // CLI11 2.3.1 Copyright (c) 2017-2022 University of Cincinnati, developed by Henry
9 // Schreiner under NSF AWARD 1414736. All rights reserved.
10 //
11 // Redistribution and use in source and binary forms of CLI11, with or without
12 // modification, are permitted provided that the following conditions are met:
13 //
14 // 1. Redistributions of source code must retain the above copyright notice, this
15 // list of conditions and the following disclaimer.
16 // 2. Redistributions in binary form must reproduce the above copyright notice,
17 // this list of conditions and the following disclaimer in the documentation
18 // and/or other materials provided with the distribution.
19 // 3. Neither the name of the copyright holder nor the names of its contributors
20 // may be used to endorse or promote products derived from this software without
21 // specific prior written permission.
22 //
23 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24 // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
27 // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
30 // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 
34 // This header is not meant to be included in a .h file, to guard against
35 // conflicts if a program includes their own CLI11 header and then transitively
36 // includes this header.
37 #ifdef PXR_CLI11_H
38 #error This file should only be included once in any given source (.cpp) file.
39 #endif
40 #define PXR_CLI11_H
41 
42 #pragma once
43 
44 // Standard combined includes:
45 #include <functional>
46 #include <locale>
47 #include <cstdint>
48 #include <iomanip>
49 #include <memory>
50 #include <exception>
51 #include <stdexcept>
52 #include <string>
53 #include <vector>
54 #include <iterator>
55 #include <algorithm>
56 #include <sstream>
57 #include <cmath>
58 #include <type_traits>
59 #include <limits>
60 #include <set>
61 #include <utility>
62 #include <map>
63 #include <iostream>
64 #include <numeric>
65 #include <fstream>
66 #include <tuple>
67 
68 #include "pxr/pxr.h"
69 
70 // Guard against possible conflicts if this header is included in the
71 // same file as another CLI11 header.
72 #ifdef CLI11_VERSION
73 #error This file cannot be included alongside a different CLI11 header.
74 #endif
75 
76 #define CLI11_VERSION_MAJOR 2
77 #define CLI11_VERSION_MINOR 3
78 #define CLI11_VERSION_PATCH 1
79 #define CLI11_VERSION "2.3.1"
80 
81 
82 
83 
84 // The following version macro is very similar to the one in pybind11
85 #if !(defined(_MSC_VER) && __cplusplus == 199711L) && !defined(__INTEL_COMPILER)
86 #if __cplusplus >= 201402L
87 #define CLI11_CPP14
88 #if __cplusplus >= 201703L
89 #define CLI11_CPP17
90 #if __cplusplus > 201703L
91 #define CLI11_CPP20
92 #endif
93 #endif
94 #endif
95 #elif defined(_MSC_VER) && __cplusplus == 199711L
96 // MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully implemented)
97 // Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3 or newer
98 #if _MSVC_LANG >= 201402L
99 #define CLI11_CPP14
100 #if _MSVC_LANG > 201402L && _MSC_VER >= 1910
101 #define CLI11_CPP17
102 #if _MSVC_LANG > 201703L && _MSC_VER >= 1910
103 #define CLI11_CPP20
104 #endif
105 #endif
106 #endif
107 #endif
108 
109 #if defined(CLI11_CPP14)
110 #define CLI11_DEPRECATED(reason) [[deprecated(reason)]]
111 #elif defined(_MSC_VER)
112 #define CLI11_DEPRECATED(reason) __declspec(deprecated(reason))
113 #else
114 #define CLI11_DEPRECATED(reason) __attribute__((deprecated(reason)))
115 #endif
116 
117 // GCC < 10 doesn't ignore this in unevaluated contexts
118 #if !defined(CLI11_CPP17) || \
119  (defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER) && __GNUC__ < 10 && __GNUC__ > 4)
120 #define CLI11_NODISCARD
121 #else
122 #define CLI11_NODISCARD [[nodiscard]]
123 #endif
124 
125 /** detection of rtti */
126 #ifndef CLI11_USE_STATIC_RTTI
127 #if(defined(_HAS_STATIC_RTTI) && _HAS_STATIC_RTTI)
128 #define CLI11_USE_STATIC_RTTI 1
129 #elif defined(__cpp_rtti)
130 #if(defined(_CPPRTTI) && _CPPRTTI == 0)
131 #define CLI11_USE_STATIC_RTTI 1
132 #else
133 #define CLI11_USE_STATIC_RTTI 0
134 #endif
135 #elif(defined(__GCC_RTTI) && __GXX_RTTI)
136 #define CLI11_USE_STATIC_RTTI 0
137 #else
138 #define CLI11_USE_STATIC_RTTI 1
139 #endif
140 #endif
141 
142 /** Inline macro **/
143 #ifdef CLI11_COMPILE
144 #define CLI11_INLINE
145 #else
146 #define CLI11_INLINE inline
147 #endif
148 
149 
150 
151 // C standard library
152 // Only needed for existence checking
153 #if defined CLI11_CPP17 && defined __has_include && !defined CLI11_HAS_FILESYSTEM
154 #if __has_include(<filesystem>)
155 // Filesystem cannot be used if targeting macOS < 10.15
156 #if defined __MAC_OS_X_VERSION_MIN_REQUIRED && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500
157 #define CLI11_HAS_FILESYSTEM 0
158 #elif defined(__wasi__)
159 // As of wasi-sdk-14, filesystem is not implemented
160 #define CLI11_HAS_FILESYSTEM 0
161 #else
162 #include <filesystem>
163 #if defined __cpp_lib_filesystem && __cpp_lib_filesystem >= 201703
164 #if defined _GLIBCXX_RELEASE && _GLIBCXX_RELEASE >= 9
165 #define CLI11_HAS_FILESYSTEM 1
166 #elif defined(__GLIBCXX__)
167 // if we are using gcc and Version <9 default to no filesystem
168 #define CLI11_HAS_FILESYSTEM 0
169 #else
170 #define CLI11_HAS_FILESYSTEM 1
171 #endif
172 #else
173 #define CLI11_HAS_FILESYSTEM 0
174 #endif
175 #endif
176 #endif
177 #endif
178 
179 #if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
180 #include <filesystem> // NOLINT(build/include)
181 #else
182 #include <sys/stat.h>
183 #include <sys/types.h>
184 #endif
185 
186 // Isolate symbols from other translation units that may have included their
187 // own copy of CLI11 by wrapping in the pxr namespace as well as a secondary
188 // hard-coded namespace. The latter is needed in case the outer pxr namespace
189 // has been disabled.
191 
192 namespace pxr_CLI {
193 
194 namespace CLI {
195 
196 
197 /// Include the items in this namespace to get free conversion of enums to/from streams.
198 /// (This is available inside CLI as well, so CLI11 will use this without a using statement).
199 namespace enums {
200 
201 /// output streaming for enumerations
203 std::ostream &operator<<(std::ostream &in, const T &item) {
204  // make sure this is out of the detail namespace otherwise it won't be found when needed
206 }
207 
208 } // namespace enums
209 
210 /// Export to CLI namespace
211 using enums::operator<<;
212 
213 namespace detail {
214 /// a constant defining an expected max vector size defined to be a big number that could be multiplied by 4 and not
215 /// produce overflow for some expected uses
216 constexpr int expected_max_vector_size{1 << 29};
217 // Based on http://stackoverflow.com/questions/236129/split-a-string-in-c
218 /// Split a string by a delim
219 CLI11_INLINE std::vector<std::string> split(const std::string &s, char delim);
220 
221 /// Simple function to join a string
222 template <typename T> std::string join(const T &v, std::string delim = ",") {
223  std::ostringstream s;
224  auto beg = std::begin(v);
225  auto end = std::end(v);
226  if(beg != end)
227  s << *beg++;
228  while(beg != end) {
229  s << delim << *beg++;
230  }
231  return s.str();
232 }
233 
234 /// Simple function to join a string from processed elements
235 template <typename T,
236  typename Callable,
238 std::string join(const T &v, Callable func, std::string delim = ",") {
239  std::ostringstream s;
240  auto beg = std::begin(v);
241  auto end = std::end(v);
242  auto loc = s.tellp();
243  while(beg != end) {
244  auto nloc = s.tellp();
245  if(nloc > loc) {
246  s << delim;
247  loc = nloc;
248  }
249  s << func(*beg++);
250  }
251  return s.str();
252 }
253 
254 /// Join a string in reverse order
255 template <typename T> std::string rjoin(const T &v, std::string delim = ",") {
256  std::ostringstream s;
257  for(std::size_t start = 0; start < v.size(); start++) {
258  if(start > 0)
259  s << delim;
260  s << v[v.size() - start - 1];
261  }
262  return s.str();
263 }
264 
265 // Based roughly on http://stackoverflow.com/questions/25829143/c-trim-whitespace-from-a-string
266 
267 /// Trim whitespace from left of string
269 
270 /// Trim anything from left of string
272 
273 /// Trim whitespace from right of string
275 
276 /// Trim anything from right of string
278 
279 /// Trim whitespace from string
280 inline std::string &trim(std::string &str) { return ltrim(rtrim(str)); }
281 
282 /// Trim anything from string
283 inline std::string &trim(std::string &str, const std::string filter) { return ltrim(rtrim(str, filter), filter); }
284 
285 /// Make a copy of the string and then trim it
286 inline std::string trim_copy(const std::string &str) {
287  std::string s = str;
288  return trim(s);
289 }
290 
291 /// remove quotes at the front and back of a string either '"' or '\''
293 
294 /// Add a leader to the beginning of all new lines (nothing is added
295 /// at the start of the first line). `"; "` would be for ini files
296 ///
297 /// Can't use Regex, or this would be a subs.
299 
300 /// Make a copy of the string and then trim it, any filter string can be used (any char in string is filtered)
301 inline std::string trim_copy(const std::string &str, const std::string &filter) {
302  std::string s = str;
303  return trim(s, filter);
304 }
305 /// Print a two part "help" string
306 CLI11_INLINE std::ostream &
307 format_help(std::ostream &out, std::string name, const std::string &description, std::size_t wid);
308 
309 /// Print subcommand aliases
310 CLI11_INLINE std::ostream &format_aliases(std::ostream &out, const std::vector<std::string> &aliases, std::size_t wid);
311 
312 /// Verify the first character of an option
313 /// - is a trigger character, ! has special meaning and new lines would just be annoying to deal with
314 template <typename T> bool valid_first_char(T c) { return ((c != '-') && (c != '!') && (c != ' ') && c != '\n'); }
315 
316 /// Verify following characters of an option
317 template <typename T> bool valid_later_char(T c) {
318  // = and : are value separators, { has special meaning for option defaults,
319  // and \n would just be annoying to deal with in many places allowing space here has too much potential for
320  // inadvertent entry errors and bugs
321  return ((c != '=') && (c != ':') && (c != '{') && (c != ' ') && c != '\n');
322 }
323 
324 /// Verify an option/subcommand name
326 
327 /// Verify an app name
328 inline bool valid_alias_name_string(const std::string &str) {
329  static const std::string badChars(std::string("\n") + '\0');
330  return (str.find_first_of(badChars) == std::string::npos);
331 }
332 
333 /// check if a string is a container segment separator (empty or "%%")
334 inline bool is_separator(const std::string &str) {
335  static const std::string sep("%%");
336  return (str.empty() || str == sep);
337 }
338 
339 /// Verify that str consists of letters only
340 inline bool isalpha(const std::string &str) {
341  return std::all_of(str.begin(), str.end(), [](char c) { return std::isalpha(c, std::locale()); });
342 }
343 
344 /// Return a lower case version of a string
347  return std::tolower(x, std::locale());
348  });
349  return str;
350 }
351 
352 /// remove underscores from a string
354  str.erase(std::remove(std::begin(str), std::end(str), '_'), std::end(str));
355  return str;
356 }
357 
358 /// Find and replace a substring with another substring
360 
361 /// check if the flag definitions has possible false flags
363  return (flags.find_first_of("{!") != std::string::npos);
364 }
365 
367 
368 /// Check if a string is a member of a list of strings and optionally ignore case or ignore underscores
370  const std::vector<std::string> names,
371  bool ignore_case = false,
372  bool ignore_underscore = false);
373 
374 /// Find a trigger string and call a modify callable function that takes the current string and starting position of the
375 /// trigger and returns the position in the string to search for the next trigger string
376 template <typename Callable> inline std::string find_and_modify(std::string str, std::string trigger, Callable modify) {
377  std::size_t start_pos = 0;
378  while((start_pos = str.find(trigger, start_pos)) != std::string::npos) {
379  start_pos = modify(str, start_pos);
380  }
381  return str;
382 }
383 
384 /// Split a string '"one two" "three"' into 'one two', 'three'
385 /// Quote characters can be ` ' or "
386 CLI11_INLINE std::vector<std::string> split_up(std::string str, char delimiter = '\0');
387 
388 /// This function detects an equal or colon followed by an escaped quote after an argument
389 /// then modifies the string to replace the equality with a space. This is needed
390 /// to allow the split up function to work properly and is intended to be used with the find_and_modify function
391 /// the return value is the offset+1 which is required by the find_and_modify function.
392 CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset);
393 
394 /// Add quotes if the string contains spaces
396 
397 } // namespace detail
398 
399 
400 
401 
402 namespace detail {
403 CLI11_INLINE std::vector<std::string> split(const std::string &s, char delim) {
404  std::vector<std::string> elems;
405  // Check to see if empty string, give consistent result
406  if(s.empty()) {
407  elems.emplace_back();
408  } else {
409  std::stringstream ss;
410  ss.str(s);
411  std::string item;
412  while(std::getline(ss, item, delim)) {
413  elems.push_back(item);
414  }
415  }
416  return elems;
417 }
418 
420  auto it = std::find_if(str.begin(), str.end(), [](char ch) { return !std::isspace<char>(ch, std::locale()); });
421  str.erase(str.begin(), it);
422  return str;
423 }
424 
426  auto it = std::find_if(str.begin(), str.end(), [&filter](char ch) { return filter.find(ch) == std::string::npos; });
427  str.erase(str.begin(), it);
428  return str;
429 }
430 
432  auto it = std::find_if(str.rbegin(), str.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale()); });
433  str.erase(it.base(), str.end());
434  return str;
435 }
436 
438  auto it =
439  std::find_if(str.rbegin(), str.rend(), [&filter](char ch) { return filter.find(ch) == std::string::npos; });
440  str.erase(it.base(), str.end());
441  return str;
442 }
443 
445  if(str.length() > 1 && (str.front() == '"' || str.front() == '\'')) {
446  if(str.front() == str.back()) {
447  str.pop_back();
448  str.erase(str.begin(), str.begin() + 1);
449  }
450  }
451  return str;
452 }
453 
455  std::string::size_type n = 0;
456  while(n != std::string::npos && n < input.size()) {
457  n = input.find('\n', n);
458  if(n != std::string::npos) {
459  input = input.substr(0, n + 1) + leader + input.substr(n + 1);
460  n += leader.size();
461  }
462  }
463  return input;
464 }
465 
466 CLI11_INLINE std::ostream &
467 format_help(std::ostream &out, std::string name, const std::string &description, std::size_t wid) {
468  name = " " + name;
469  out << std::setw(static_cast<int>(wid)) << std::left << name;
470  if(!description.empty()) {
471  if(name.length() >= wid)
472  out << "\n" << std::setw(static_cast<int>(wid)) << "";
473  for(const char c : description) {
474  out.put(c);
475  if(c == '\n') {
476  out << std::setw(static_cast<int>(wid)) << "";
477  }
478  }
479  }
480  out << "\n";
481  return out;
482 }
483 
484 CLI11_INLINE std::ostream &format_aliases(std::ostream &out, const std::vector<std::string> &aliases, std::size_t wid) {
485  if(!aliases.empty()) {
486  out << std::setw(static_cast<int>(wid)) << " aliases: ";
487  bool front = true;
488  for(const auto &alias : aliases) {
489  if(!front) {
490  out << ", ";
491  } else {
492  front = false;
493  }
494  out << detail::fix_newlines(" ", alias);
495  }
496  out << "\n";
497  }
498  return out;
499 }
500 
502  if(str.empty() || !valid_first_char(str[0])) {
503  return false;
504  }
505  auto e = str.end();
506  for(auto c = str.begin() + 1; c != e; ++c)
507  if(!valid_later_char(*c))
508  return false;
509  return true;
510 }
511 
513 
514  std::size_t start_pos = 0;
515 
516  while((start_pos = str.find(from, start_pos)) != std::string::npos) {
517  str.replace(start_pos, from.length(), to);
518  start_pos += to.length();
519  }
520 
521  return str;
522 }
523 
525  auto loc = flags.find_first_of('{', 2);
526  while(loc != std::string::npos) {
527  auto finish = flags.find_first_of("},", loc + 1);
528  if((finish != std::string::npos) && (flags[finish] == '}')) {
529  flags.erase(flags.begin() + static_cast<std::ptrdiff_t>(loc),
530  flags.begin() + static_cast<std::ptrdiff_t>(finish) + 1);
531  }
532  loc = flags.find_first_of('{', loc + 1);
533  }
534  flags.erase(std::remove(flags.begin(), flags.end(), '!'), flags.end());
535 }
536 
537 CLI11_INLINE std::ptrdiff_t
538 find_member(std::string name, const std::vector<std::string> names, bool ignore_case, bool ignore_underscore) {
539  auto it = std::end(names);
540  if(ignore_case) {
541  if(ignore_underscore) {
543  it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
544  return detail::to_lower(detail::remove_underscore(local_name)) == name;
545  });
546  } else {
547  name = detail::to_lower(name);
548  it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
549  return detail::to_lower(local_name) == name;
550  });
551  }
552 
553  } else if(ignore_underscore) {
554  name = detail::remove_underscore(name);
555  it = std::find_if(std::begin(names), std::end(names), [&name](std::string local_name) {
556  return detail::remove_underscore(local_name) == name;
557  });
558  } else {
559  it = std::find(std::begin(names), std::end(names), name);
560  }
561 
562  return (it != std::end(names)) ? (it - std::begin(names)) : (-1);
563 }
564 
565 CLI11_INLINE std::vector<std::string> split_up(std::string str, char delimiter) {
566 
567  const std::string delims("\'\"`");
568  auto find_ws = [delimiter](char ch) {
569  return (delimiter == '\0') ? std::isspace<char>(ch, std::locale()) : (ch == delimiter);
570  };
571  trim(str);
572 
573  std::vector<std::string> output;
574  bool embeddedQuote = false;
575  char keyChar = ' ';
576  while(!str.empty()) {
577  if(delims.find_first_of(str[0]) != std::string::npos) {
578  keyChar = str[0];
579  auto end = str.find_first_of(keyChar, 1);
580  while((end != std::string::npos) && (str[end - 1] == '\\')) { // deal with escaped quotes
581  end = str.find_first_of(keyChar, end + 1);
582  embeddedQuote = true;
583  }
584  if(end != std::string::npos) {
585  output.push_back(str.substr(1, end - 1));
586  if(end + 2 < str.size()) {
587  str = str.substr(end + 2);
588  } else {
589  str.clear();
590  }
591 
592  } else {
593  output.push_back(str.substr(1));
594  str = "";
595  }
596  } else {
597  auto it = std::find_if(std::begin(str), std::end(str), find_ws);
598  if(it != std::end(str)) {
599  std::string value = std::string(str.begin(), it);
600  output.push_back(value);
601  str = std::string(it + 1, str.end());
602  } else {
603  output.push_back(str);
604  str = "";
605  }
606  }
607  // transform any embedded quotes into the regular character
608  if(embeddedQuote) {
609  output.back() = find_and_replace(output.back(), std::string("\\") + keyChar, std::string(1, keyChar));
610  embeddedQuote = false;
611  }
612  trim(str);
613  }
614  return output;
615 }
616 
617 CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset) {
618  auto next = str[offset + 1];
619  if((next == '\"') || (next == '\'') || (next == '`')) {
620  auto astart = str.find_last_of("-/ \"\'`", offset - 1);
621  if(astart != std::string::npos) {
622  if(str[astart] == ((str[offset] == '=') ? '-' : '/'))
623  str[offset] = ' '; // interpret this as a space so the split_up works properly
624  }
625  }
626  return offset + 1;
627 }
628 
630  if((str.front() != '"' && str.front() != '\'') || str.front() != str.back()) {
631  char quote = str.find('"') < str.find('\'') ? '\'' : '"';
632  if(str.find(' ') != std::string::npos) {
633  str.insert(0, 1, quote);
634  str.append(1, quote);
635  }
636  }
637  return str;
638 }
639 
640 } // namespace detail
641 
642 
643 
644 // Use one of these on all error classes.
645 // These are temporary and are undef'd at the end of this file.
646 #define CLI11_ERROR_DEF(parent, name) \
647  protected: \
648  name(std::string ename, std::string msg, int exit_code) : parent(std::move(ename), std::move(msg), exit_code) {} \
649  name(std::string ename, std::string msg, ExitCodes exit_code) \
650  : parent(std::move(ename), std::move(msg), exit_code) {} \
651  \
652  public: \
653  name(std::string msg, ExitCodes exit_code) : parent(#name, std::move(msg), exit_code) {} \
654  name(std::string msg, int exit_code) : parent(#name, std::move(msg), exit_code) {}
655 
656 // This is added after the one above if a class is used directly and builds its own message
657 #define CLI11_ERROR_SIMPLE(name) \
658  explicit name(std::string msg) : name(#name, msg, ExitCodes::name) {}
659 
660 /// These codes are part of every error in CLI. They can be obtained from e using e.exit_code or as a quick shortcut,
661 /// int values from e.get_error_code().
662 enum class ExitCodes {
663  Success = 0,
664  IncorrectConstruction = 100,
667  FileError,
673  ExtrasError,
674  ConfigError,
675  InvalidError,
679  BaseClass = 127
680 };
681 
682 // Error definitions
683 
684 /// @defgroup error_group Errors
685 /// @brief Errors thrown by CLI11
686 ///
687 /// These are the errors that can be thrown. Some of them, like CLI::Success, are not really errors.
688 /// @{
689 
690 /// All errors derive from this one
691 class Error : public std::runtime_error {
692  int actual_exit_code;
693  std::string error_name{"Error"};
694 
695  public:
696  CLI11_NODISCARD int get_exit_code() const { return actual_exit_code; }
697 
698  CLI11_NODISCARD std::string get_name() const { return error_name; }
699 
700  Error(std::string name, std::string msg, int exit_code = static_cast<int>(ExitCodes::BaseClass))
701  : runtime_error(msg), actual_exit_code(exit_code), error_name(std::move(name)) {}
702 
703  Error(std::string name, std::string msg, ExitCodes exit_code) : Error(name, msg, static_cast<int>(exit_code)) {}
704 };
705 
706 // Note: Using Error::Error constructors does not work on GCC 4.7
707 
708 /// Construction errors (not in parsing)
709 class ConstructionError : public Error {
711 };
712 
713 /// Thrown when an option is set to conflicting values (non-vector and multi args, for example)
717  static IncorrectConstruction PositionalFlag(std::string name) {
718  return IncorrectConstruction(name + ": Flags cannot be positional");
719  }
720  static IncorrectConstruction Set0Opt(std::string name) {
721  return IncorrectConstruction(name + ": Cannot set 0 expected, use a flag instead");
722  }
723  static IncorrectConstruction SetFlag(std::string name) {
724  return IncorrectConstruction(name + ": Cannot set an expected number for flags");
725  }
726  static IncorrectConstruction ChangeNotVector(std::string name) {
727  return IncorrectConstruction(name + ": You can only change the expected arguments for vectors");
728  }
729  static IncorrectConstruction AfterMultiOpt(std::string name) {
730  return IncorrectConstruction(
731  name + ": You can't change expected arguments after you've changed the multi option policy!");
732  }
733  static IncorrectConstruction MissingOption(std::string name) {
734  return IncorrectConstruction("Option " + name + " is not defined");
735  }
737  return IncorrectConstruction(name + ": multi_option_policy only works for flags and exact value options");
738  }
739 };
740 
741 /// Thrown on construction of a bad name
745  static BadNameString OneCharName(std::string name) { return BadNameString("Invalid one char name: " + name); }
746  static BadNameString BadLongName(std::string name) { return BadNameString("Bad long name: " + name); }
747  static BadNameString DashesOnly(std::string name) {
748  return BadNameString("Must have a name, not just dashes: " + name);
749  }
750  static BadNameString MultiPositionalNames(std::string name) {
751  return BadNameString("Only one positional name allowed, remove: " + name);
752  }
753 };
754 
755 /// Thrown when an option already exists
759  : OptionAlreadyAdded(name + " is already added", ExitCodes::OptionAlreadyAdded) {}
760  static OptionAlreadyAdded Requires(std::string name, std::string other) {
761  return {name + " requires " + other, ExitCodes::OptionAlreadyAdded};
762  }
763  static OptionAlreadyAdded Excludes(std::string name, std::string other) {
764  return {name + " excludes " + other, ExitCodes::OptionAlreadyAdded};
765  }
766 };
767 
768 // Parsing errors
769 
770 /// Anything that can error in Parse
771 class ParseError : public Error {
773 };
774 
775 // Not really "errors"
776 
777 /// This is a successful completion on parsing, supposed to exit
778 class Success : public ParseError {
780  Success() : Success("Successfully completed, should be caught and quit", ExitCodes::Success) {}
781 };
782 
783 /// -h or --help on command line
784 class CallForHelp : public Success {
786  CallForHelp() : CallForHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
787 };
788 
789 /// Usually something like --help-all on command line
790 class CallForAllHelp : public Success {
793  : CallForAllHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
794 };
795 
796 /// -v or --version on command line
797 class CallForVersion : public Success {
800  : CallForVersion("This should be caught in your main function, see examples", ExitCodes::Success) {}
801 };
802 
803 /// Does not output a diagnostic in CLI11_PARSE, but allows main() to return with a specific error code.
804 class RuntimeError : public ParseError {
806  explicit RuntimeError(int exit_code = 1) : RuntimeError("Runtime error", exit_code) {}
807 };
808 
809 /// Thrown when parsing an INI file and it is missing
810 class FileError : public ParseError {
813  static FileError Missing(std::string name) { return FileError(name + " was not readable (missing?)"); }
814 };
815 
816 /// Thrown when conversion call back fails, such as when an int fails to coerce to a string
817 class ConversionError : public ParseError {
821  : ConversionError("The value " + member + " is not an allowed value for " + name) {}
822  ConversionError(std::string name, std::vector<std::string> results)
823  : ConversionError("Could not convert: " + name + " = " + detail::join(results)) {}
824  static ConversionError TooManyInputsFlag(std::string name) {
825  return ConversionError(name + ": too many inputs for a flag");
826  }
827  static ConversionError TrueFalse(std::string name) {
828  return ConversionError(name + ": Should be true/false or a number");
829  }
830 };
831 
832 /// Thrown when validation of results fails
833 class ValidationError : public ParseError {
836  explicit ValidationError(std::string name, std::string msg) : ValidationError(name + ": " + msg) {}
837 };
838 
839 /// Thrown when a required option is missing
840 class RequiredError : public ParseError {
842  explicit RequiredError(std::string name) : RequiredError(name + " is required", ExitCodes::RequiredError) {}
843  static RequiredError Subcommand(std::size_t min_subcom) {
844  if(min_subcom == 1) {
845  return RequiredError("A subcommand");
846  }
847  return {"Requires at least " + std::to_string(min_subcom) + " subcommands", ExitCodes::RequiredError};
848  }
849  static RequiredError
850  Option(std::size_t min_option, std::size_t max_option, std::size_t used, const std::string &option_list) {
851  if((min_option == 1) && (max_option == 1) && (used == 0))
852  return RequiredError("Exactly 1 option from [" + option_list + "]");
853  if((min_option == 1) && (max_option == 1) && (used > 1)) {
854  return {"Exactly 1 option from [" + option_list + "] is required and " + std::to_string(used) +
855  " were given",
857  }
858  if((min_option == 1) && (used == 0))
859  return RequiredError("At least 1 option from [" + option_list + "]");
860  if(used < min_option) {
861  return {"Requires at least " + std::to_string(min_option) + " options used and only " +
862  std::to_string(used) + "were given from [" + option_list + "]",
864  }
865  if(max_option == 1)
866  return {"Requires at most 1 options be given from [" + option_list + "]", ExitCodes::RequiredError};
867 
868  return {"Requires at most " + std::to_string(max_option) + " options be used and " + std::to_string(used) +
869  "were given from [" + option_list + "]",
871  }
872 };
873 
874 /// Thrown when the wrong number of arguments has been received
875 class ArgumentMismatch : public ParseError {
878  ArgumentMismatch(std::string name, int expected, std::size_t received)
879  : ArgumentMismatch(expected > 0 ? ("Expected exactly " + std::to_string(expected) + " arguments to " + name +
880  ", got " + std::to_string(received))
881  : ("Expected at least " + std::to_string(-expected) + " arguments to " + name +
882  ", got " + std::to_string(received)),
884 
885  static ArgumentMismatch AtLeast(std::string name, int num, std::size_t received) {
886  return ArgumentMismatch(name + ": At least " + std::to_string(num) + " required but received " +
887  std::to_string(received));
888  }
889  static ArgumentMismatch AtMost(std::string name, int num, std::size_t received) {
890  return ArgumentMismatch(name + ": At Most " + std::to_string(num) + " required but received " +
891  std::to_string(received));
892  }
893  static ArgumentMismatch TypedAtLeast(std::string name, int num, std::string type) {
894  return ArgumentMismatch(name + ": " + std::to_string(num) + " required " + type + " missing");
895  }
896  static ArgumentMismatch FlagOverride(std::string name) {
897  return ArgumentMismatch(name + " was given a disallowed flag override");
898  }
899  static ArgumentMismatch PartialType(std::string name, int num, std::string type) {
900  return ArgumentMismatch(name + ": " + type + " only partially specified: " + std::to_string(num) +
901  " required for each element");
902  }
903 };
904 
905 /// Thrown when a requires option is missing
906 class RequiresError : public ParseError {
908  RequiresError(std::string curname, std::string subname)
909  : RequiresError(curname + " requires " + subname, ExitCodes::RequiresError) {}
910 };
911 
912 /// Thrown when an excludes option is present
913 class ExcludesError : public ParseError {
915  ExcludesError(std::string curname, std::string subname)
916  : ExcludesError(curname + " excludes " + subname, ExitCodes::ExcludesError) {}
917 };
918 
919 /// Thrown when too many positionals or options are found
920 class ExtrasError : public ParseError {
922  explicit ExtrasError(std::vector<std::string> args)
923  : ExtrasError((args.size() > 1 ? "The following arguments were not expected: "
924  : "The following argument was not expected: ") +
925  detail::rjoin(args, " "),
927  ExtrasError(const std::string &name, std::vector<std::string> args)
928  : ExtrasError(name,
929  (args.size() > 1 ? "The following arguments were not expected: "
930  : "The following argument was not expected: ") +
931  detail::rjoin(args, " "),
933 };
934 
935 /// Thrown when extra values are found in an INI file
936 class ConfigError : public ParseError {
939  static ConfigError Extras(std::string item) { return ConfigError("INI was not able to parse " + item); }
940  static ConfigError NotConfigurable(std::string item) {
941  return ConfigError(item + ": This option is not allowed in a configuration file");
942  }
943 };
944 
945 /// Thrown when validation fails before parsing
946 class InvalidError : public ParseError {
948  explicit InvalidError(std::string name)
949  : InvalidError(name + ": Too many positional arguments with unlimited expected args", ExitCodes::InvalidError) {
950  }
951 };
952 
953 /// This is just a safety check to verify selection and parsing match - you should not ever see it
954 /// Strings are directly added to this error, but again, it should never be seen.
955 class HorribleError : public ParseError {
958 };
959 
960 // After parsing
961 
962 /// Thrown when counting a non-existent option
963 class OptionNotFound : public Error {
965  explicit OptionNotFound(std::string name) : OptionNotFound(name + " not found", ExitCodes::OptionNotFound) {}
966 };
967 
968 #undef CLI11_ERROR_DEF
969 #undef CLI11_ERROR_SIMPLE
970 
971 /// @}
972 
973 
974 
975 
976 // Type tools
977 
978 // Utilities for type enabling
979 namespace detail {
980 // Based generally on https://rmf.io/cxx11/almost-static-if
981 /// Simple empty scoped class
982 enum class enabler {};
983 
984 /// An instance to use in EnableIf
985 constexpr enabler dummy = {};
986 } // namespace detail
987 
988 /// A copy of enable_if_t from C++14, compatible with C++11.
989 ///
990 /// We could check to see if C++14 is being used, but it does not hurt to redefine this
991 /// (even Google does this: https://github.com/google/skia/blob/main/include/private/SkTLogic.h)
992 /// It is not in the std namespace anyway, so no harm done.
993 template <bool B, class T = void> using enable_if_t = typename std::enable_if<B, T>::type;
994 
995 /// A copy of std::void_t from C++17 (helper for C++11 and C++14)
996 template <typename... Ts> struct make_void { using type = void; };
997 
998 /// A copy of std::void_t from C++17 - same reasoning as enable_if_t, it does not hurt to redefine
999 template <typename... Ts> using void_t = typename make_void<Ts...>::type;
1000 
1001 /// A copy of std::conditional_t from C++14 - same reasoning as enable_if_t, it does not hurt to redefine
1002 template <bool B, class T, class F> using conditional_t = typename std::conditional<B, T, F>::type;
1003 
1004 /// Check to see if something is bool (fail check by default)
1005 template <typename T> struct is_bool : std::false_type {};
1006 
1007 /// Check to see if something is bool (true if actually a bool)
1008 template <> struct is_bool<bool> : std::true_type {};
1009 
1010 /// Check to see if something is a shared pointer
1011 template <typename T> struct is_shared_ptr : std::false_type {};
1012 
1013 /// Check to see if something is a shared pointer (True if really a shared pointer)
1014 template <typename T> struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
1015 
1016 /// Check to see if something is a shared pointer (True if really a shared pointer)
1017 template <typename T> struct is_shared_ptr<const std::shared_ptr<T>> : std::true_type {};
1018 
1019 /// Check to see if something is copyable pointer
1020 template <typename T> struct is_copyable_ptr {
1022 };
1023 
1024 /// This can be specialized to override the type deduction for IsMember.
1025 template <typename T> struct IsMemberType { using type = T; };
1026 
1027 /// The main custom type needed here is const char * should be a string.
1028 template <> struct IsMemberType<const char *> { using type = std::string; };
1029 
1030 namespace detail {
1031 
1032 // These are utilities for IsMember and other transforming objects
1033 
1034 /// Handy helper to access the element_type generically. This is not part of is_copyable_ptr because it requires that
1035 /// pointer_traits<T> be valid.
1036 
1037 /// not a pointer
1038 template <typename T, typename Enable = void> struct element_type { using type = T; };
1039 
1040 template <typename T> struct element_type<T, typename std::enable_if<is_copyable_ptr<T>::value>::type> {
1041  using type = typename std::pointer_traits<T>::element_type;
1042 };
1043 
1044 /// Combination of the element type and value type - remove pointer (including smart pointers) and get the value_type of
1045 /// the container
1046 template <typename T> struct element_value_type { using type = typename element_type<T>::type::value_type; };
1047 
1048 /// Adaptor for set-like structure: This just wraps a normal container in a few utilities that do almost nothing.
1049 template <typename T, typename _ = void> struct pair_adaptor : std::false_type {
1050  using value_type = typename T::value_type;
1053 
1054  /// Get the first value (really just the underlying value)
1055  template <typename Q> static auto first(Q &&pair_value) -> decltype(std::forward<Q>(pair_value)) {
1056  return std::forward<Q>(pair_value);
1057  }
1058  /// Get the second value (really just the underlying value)
1059  template <typename Q> static auto second(Q &&pair_value) -> decltype(std::forward<Q>(pair_value)) {
1060  return std::forward<Q>(pair_value);
1061  }
1062 };
1063 
1064 /// Adaptor for map-like structure (true version, must have key_type and mapped_type).
1065 /// This wraps a mapped container in a few utilities access it in a general way.
1066 template <typename T>
1068  T,
1069  conditional_t<false, void_t<typename T::value_type::first_type, typename T::value_type::second_type>, void>>
1070  : std::true_type {
1071  using value_type = typename T::value_type;
1074 
1075  /// Get the first value (really just the underlying value)
1076  template <typename Q> static auto first(Q &&pair_value) -> decltype(std::get<0>(std::forward<Q>(pair_value))) {
1077  return std::get<0>(std::forward<Q>(pair_value));
1078  }
1079  /// Get the second value (really just the underlying value)
1080  template <typename Q> static auto second(Q &&pair_value) -> decltype(std::get<1>(std::forward<Q>(pair_value))) {
1081  return std::get<1>(std::forward<Q>(pair_value));
1082  }
1083 };
1084 
1085 // Warning is suppressed due to "bug" in gcc<5.0 and gcc 7.0 with c++17 enabled that generates a Wnarrowing warning
1086 // in the unevaluated context even if the function that was using this wasn't used. The standard says narrowing in
1087 // brace initialization shouldn't be allowed but for backwards compatibility gcc allows it in some contexts. It is a
1088 // little fuzzy what happens in template constructs and I think that was something GCC took a little while to work out.
1089 // But regardless some versions of gcc generate a warning when they shouldn't from the following code so that should be
1090 // suppressed
1091 #ifdef __GNUC__
1092 #pragma GCC diagnostic push
1093 #pragma GCC diagnostic ignored "-Wnarrowing"
1094 #endif
1095 // check for constructibility from a specific type and copy assignable used in the parse detection
1096 template <typename T, typename C> class is_direct_constructible {
1097  template <typename TT, typename CC>
1098  static auto test(int, std::true_type) -> decltype(
1099 // NVCC warns about narrowing conversions here
1100 #ifdef __CUDACC__
1101 #pragma diag_suppress 2361
1102 #endif
1103  TT{std::declval<CC>()}
1104 #ifdef __CUDACC__
1105 #pragma diag_default 2361
1106 #endif
1107  ,
1108  std::is_move_assignable<TT>());
1109 
1110  template <typename TT, typename CC> static auto test(int, std::false_type) -> std::false_type;
1111 
1112  template <typename, typename> static auto test(...) -> std::false_type;
1113 
1114  public:
1115  static constexpr bool value = decltype(test<T, C>(0, typename std::is_constructible<T, C>::type()))::value;
1116 };
1117 #ifdef __GNUC__
1118 #pragma GCC diagnostic pop
1119 #endif
1120 
1121 // Check for output streamability
1122 // Based on https://stackoverflow.com/questions/22758291/how-can-i-detect-if-a-type-can-be-streamed-to-an-stdostream
1123 
1124 template <typename T, typename S = std::ostringstream> class is_ostreamable {
1125  template <typename TT, typename SS>
1126  static auto test(int) -> decltype(std::declval<SS &>() << std::declval<TT>(), std::true_type());
1127 
1128  template <typename, typename> static auto test(...) -> std::false_type;
1129 
1130  public:
1131  static constexpr bool value = decltype(test<T, S>(0))::value;
1132 };
1133 
1134 /// Check for input streamability
1135 template <typename T, typename S = std::istringstream> class is_istreamable {
1136  template <typename TT, typename SS>
1137  static auto test(int) -> decltype(std::declval<SS &>() >> std::declval<TT &>(), std::true_type());
1138 
1139  template <typename, typename> static auto test(...) -> std::false_type;
1140 
1141  public:
1142  static constexpr bool value = decltype(test<T, S>(0))::value;
1143 };
1144 
1145 /// Check for complex
1146 template <typename T> class is_complex {
1147  template <typename TT>
1148  static auto test(int) -> decltype(std::declval<TT>().real(), std::declval<TT>().imag(), std::true_type());
1149 
1150  template <typename> static auto test(...) -> std::false_type;
1151 
1152  public:
1153  static constexpr bool value = decltype(test<T>(0))::value;
1154 };
1155 
1156 /// Templated operation to get a value from a stream
1158 bool from_stream(const std::string &istring, T &obj) {
1159  std::istringstream is;
1160  is.str(istring);
1161  is >> obj;
1162  return !is.fail() && !is.rdbuf()->in_avail();
1163 }
1164 
1166 bool from_stream(const std::string & /*istring*/, T & /*obj*/) {
1167  return false;
1168 }
1169 
1170 // check to see if an object is a mutable container (fail by default)
1171 template <typename T, typename _ = void> struct is_mutable_container : std::false_type {};
1172 
1173 /// type trait to test if a type is a mutable container meaning it has a value_type, it has an iterator, a clear, and
1174 /// end methods and an insert function. And for our purposes we exclude std::string and types that can be constructed
1175 /// from a std::string
1176 template <typename T>
1178  T,
1179  conditional_t<false,
1180  void_t<typename T::value_type,
1181  decltype(std::declval<T>().end()),
1182  decltype(std::declval<T>().clear()),
1183  decltype(std::declval<T>().insert(std::declval<decltype(std::declval<T>().end())>(),
1184  std::declval<const typename T::value_type &>()))>,
1185  void>>
1186  : public conditional_t<std::is_constructible<T, std::string>::value, std::false_type, std::true_type> {};
1187 
1188 // check to see if an object is a mutable container (fail by default)
1189 template <typename T, typename _ = void> struct is_readable_container : std::false_type {};
1190 
1191 /// type trait to test if a type is a container meaning it has a value_type, it has an iterator, a clear, and an end
1192 /// methods and an insert function. And for our purposes we exclude std::string and types that can be constructed from
1193 /// a std::string
1194 template <typename T>
1196  T,
1197  conditional_t<false, void_t<decltype(std::declval<T>().end()), decltype(std::declval<T>().begin())>, void>>
1198  : public std::true_type {};
1199 
1200 // check to see if an object is a wrapper (fail by default)
1201 template <typename T, typename _ = void> struct is_wrapper : std::false_type {};
1202 
1203 // check if an object is a wrapper (it has a value_type defined)
1204 template <typename T>
1205 struct is_wrapper<T, conditional_t<false, void_t<typename T::value_type>, void>> : public std::true_type {};
1206 
1207 // Check for tuple like types, as in classes with a tuple_size type trait
1208 template <typename S> class is_tuple_like {
1209  template <typename SS>
1210  // static auto test(int)
1211  // -> decltype(std::conditional<(std::tuple_size<SS>::value > 0), std::true_type, std::false_type>::type());
1212  static auto test(int) -> decltype(std::tuple_size<typename std::decay<SS>::type>::value, std::true_type{});
1213  template <typename> static auto test(...) -> std::false_type;
1214 
1215  public:
1216  static constexpr bool value = decltype(test<S>(0))::value;
1217 };
1218 
1219 /// Convert an object to a string (directly forward if this can become a string)
1221 auto to_string(T &&value) -> decltype(std::forward<T>(value)) {
1222  return std::forward<T>(value);
1223 }
1224 
1225 /// Construct a string from the object
1226 template <typename T,
1229 std::string to_string(const T &value) {
1230  return std::string(value); // NOLINT(google-readability-casting)
1231 }
1232 
1233 /// Convert an object to a string (streaming must be supported for that type)
1234 template <typename T,
1239  std::stringstream stream;
1240  stream << value;
1241  return stream.str();
1242 }
1243 
1244 /// If conversion is not supported, return an empty string (streaming is not supported for that type)
1245 template <typename T,
1249 std::string to_string(T &&) {
1250  return {};
1251 }
1252 
1253 /// convert a readable container to a string
1254 template <typename T,
1258 std::string to_string(T &&variable) {
1259  auto cval = variable.begin();
1260  auto end = variable.end();
1261  if(cval == end) {
1262  return {"{}"};
1263  }
1264  std::vector<std::string> defaults;
1265  while(cval != end) {
1266  defaults.emplace_back(CLI::detail::to_string(*cval));
1267  ++cval;
1268  }
1269  return {"[" + detail::join(defaults) + "]"};
1270 }
1271 
1272 /// special template overload
1273 template <typename T1,
1274  typename T2,
1275  typename T,
1277 auto checked_to_string(T &&value) -> decltype(to_string(std::forward<T>(value))) {
1278  return to_string(std::forward<T>(value));
1279 }
1280 
1281 /// special template overload
1282 template <typename T1,
1283  typename T2,
1284  typename T,
1287  return std::string{};
1288 }
1289 /// get a string as a convertible value for arithmetic types
1291 std::string value_string(const T &value) {
1292  return std::to_string(value);
1293 }
1294 /// get a string as a convertible value for enumerations
1296 std::string value_string(const T &value) {
1297  return std::to_string(static_cast<typename std::underlying_type<T>::type>(value));
1298 }
1299 /// for other types just use the regular to_string function
1300 template <typename T,
1302 auto value_string(const T &value) -> decltype(to_string(value)) {
1303  return to_string(value);
1304 }
1305 
1306 /// template to get the underlying value type if it exists or use a default
1307 template <typename T, typename def, typename Enable = void> struct wrapped_type { using type = def; };
1308 
1309 /// Type size for regular object types that do not look like a tuple
1310 template <typename T, typename def> struct wrapped_type<T, def, typename std::enable_if<is_wrapper<T>::value>::type> {
1311  using type = typename T::value_type;
1312 };
1313 
1314 /// This will only trigger for actual void type
1315 template <typename T, typename Enable = void> struct type_count_base { static const int value{0}; };
1316 
1317 /// Type size for regular object types that do not look like a tuple
1318 template <typename T>
1320  typename std::enable_if<!is_tuple_like<T>::value && !is_mutable_container<T>::value &&
1321  !std::is_void<T>::value>::type> {
1322  static constexpr int value{1};
1323 };
1324 
1325 /// the base tuple size
1326 template <typename T>
1327 struct type_count_base<T, typename std::enable_if<is_tuple_like<T>::value && !is_mutable_container<T>::value>::type> {
1328  static constexpr int value{std::tuple_size<T>::value};
1329 };
1330 
1331 /// Type count base for containers is the type_count_base of the individual element
1332 template <typename T> struct type_count_base<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1334 };
1335 
1336 /// Set of overloads to get the type size of an object
1337 
1338 /// forward declare the subtype_count structure
1339 template <typename T> struct subtype_count;
1340 
1341 /// forward declare the subtype_count_min structure
1342 template <typename T> struct subtype_count_min;
1343 
1344 /// This will only trigger for actual void type
1345 template <typename T, typename Enable = void> struct type_count { static const int value{0}; };
1346 
1347 /// Type size for regular object types that do not look like a tuple
1348 template <typename T>
1349 struct type_count<T,
1350  typename std::enable_if<!is_wrapper<T>::value && !is_tuple_like<T>::value && !is_complex<T>::value &&
1351  !std::is_void<T>::value>::type> {
1352  static constexpr int value{1};
1353 };
1354 
1355 /// Type size for complex since it sometimes looks like a wrapper
1356 template <typename T> struct type_count<T, typename std::enable_if<is_complex<T>::value>::type> {
1357  static constexpr int value{2};
1358 };
1359 
1360 /// Type size of types that are wrappers,except complex and tuples(which can also be wrappers sometimes)
1361 template <typename T> struct type_count<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1363 };
1364 
1365 /// Type size of types that are wrappers,except containers complex and tuples(which can also be wrappers sometimes)
1366 template <typename T>
1367 struct type_count<T,
1368  typename std::enable_if<is_wrapper<T>::value && !is_complex<T>::value && !is_tuple_like<T>::value &&
1369  !is_mutable_container<T>::value>::type> {
1370  static constexpr int value{type_count<typename T::value_type>::value};
1371 };
1372 
1373 /// 0 if the index > tuple size
1374 template <typename T, std::size_t I>
1376  return 0;
1377 }
1378 
1379 /// Recursively generate the tuple type name
1380 template <typename T, std::size_t I>
1382  return subtype_count<typename std::tuple_element<I, T>::type>::value + tuple_type_size<T, I + 1>();
1383 }
1384 
1385 /// Get the type size of the sum of type sizes for all the individual tuple types
1386 template <typename T> struct type_count<T, typename std::enable_if<is_tuple_like<T>::value>::type> {
1387  static constexpr int value{tuple_type_size<T, 0>()};
1388 };
1389 
1390 /// definition of subtype count
1391 template <typename T> struct subtype_count {
1393 };
1394 
1395 /// This will only trigger for actual void type
1396 template <typename T, typename Enable = void> struct type_count_min { static const int value{0}; };
1397 
1398 /// Type size for regular object types that do not look like a tuple
1399 template <typename T>
1400 struct type_count_min<
1401  T,
1402  typename std::enable_if<!is_mutable_container<T>::value && !is_tuple_like<T>::value && !is_wrapper<T>::value &&
1403  !is_complex<T>::value && !std::is_void<T>::value>::type> {
1404  static constexpr int value{type_count<T>::value};
1405 };
1406 
1407 /// Type size for complex since it sometimes looks like a wrapper
1408 template <typename T> struct type_count_min<T, typename std::enable_if<is_complex<T>::value>::type> {
1409  static constexpr int value{1};
1410 };
1411 
1412 /// Type size min of types that are wrappers,except complex and tuples(which can also be wrappers sometimes)
1413 template <typename T>
1414 struct type_count_min<
1415  T,
1416  typename std::enable_if<is_wrapper<T>::value && !is_complex<T>::value && !is_tuple_like<T>::value>::type> {
1417  static constexpr int value{subtype_count_min<typename T::value_type>::value};
1418 };
1419 
1420 /// 0 if the index > tuple size
1421 template <typename T, std::size_t I>
1422 constexpr typename std::enable_if<I == type_count_base<T>::value, int>::type tuple_type_size_min() {
1423  return 0;
1424 }
1425 
1426 /// Recursively generate the tuple type name
1427 template <typename T, std::size_t I>
1428  constexpr typename std::enable_if < I<type_count_base<T>::value, int>::type tuple_type_size_min() {
1429  return subtype_count_min<typename std::tuple_element<I, T>::type>::value + tuple_type_size_min<T, I + 1>();
1430 }
1431 
1432 /// Get the type size of the sum of type sizes for all the individual tuple types
1433 template <typename T> struct type_count_min<T, typename std::enable_if<is_tuple_like<T>::value>::type> {
1434  static constexpr int value{tuple_type_size_min<T, 0>()};
1435 };
1436 
1437 /// definition of subtype count
1438 template <typename T> struct subtype_count_min {
1439  static constexpr int value{is_mutable_container<T>::value
1441  : type_count_min<T>::value};
1442 };
1443 
1444 /// This will only trigger for actual void type
1445 template <typename T, typename Enable = void> struct expected_count { static const int value{0}; };
1446 
1447 /// For most types the number of expected items is 1
1448 template <typename T>
1449 struct expected_count<T,
1450  typename std::enable_if<!is_mutable_container<T>::value && !is_wrapper<T>::value &&
1451  !std::is_void<T>::value>::type> {
1452  static constexpr int value{1};
1453 };
1454 /// number of expected items in a vector
1455 template <typename T> struct expected_count<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1456  static constexpr int value{expected_max_vector_size};
1457 };
1458 
1459 /// number of expected items in a vector
1460 template <typename T>
1461 struct expected_count<T, typename std::enable_if<!is_mutable_container<T>::value && is_wrapper<T>::value>::type> {
1462  static constexpr int value{expected_count<typename T::value_type>::value};
1463 };
1464 
1465 // Enumeration of the different supported categorizations of objects
1466 enum class object_category : int {
1467  char_value = 1,
1468  integral_value = 2,
1469  unsigned_integral = 4,
1470  enumeration = 6,
1471  boolean_value = 8,
1472  floating_point = 10,
1473  number_constructible = 12,
1474  double_constructible = 14,
1475  integer_constructible = 16,
1476  // string like types
1477  string_assignable = 23,
1478  string_constructible = 24,
1479  other = 45,
1480  // special wrapper or container types
1481  wrapper_value = 50,
1482  complex_number = 60,
1483  tuple_value = 70,
1484  container_value = 80,
1485 
1486 };
1487 
1488 /// Set of overloads to classify an object according to type
1489 
1490 /// some type that is not otherwise recognized
1491 template <typename T, typename Enable = void> struct classify_object {
1492  static constexpr object_category value{object_category::other};
1493 };
1494 
1495 /// Signed integers
1496 template <typename T>
1497 struct classify_object<
1498  T,
1499  typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, char>::value && std::is_signed<T>::value &&
1500  !is_bool<T>::value && !std::is_enum<T>::value>::type> {
1501  static constexpr object_category value{object_category::integral_value};
1502 };
1503 
1504 /// Unsigned integers
1505 template <typename T>
1506 struct classify_object<T,
1507  typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value &&
1508  !std::is_same<T, char>::value && !is_bool<T>::value>::type> {
1509  static constexpr object_category value{object_category::unsigned_integral};
1510 };
1511 
1512 /// single character values
1513 template <typename T>
1514 struct classify_object<T, typename std::enable_if<std::is_same<T, char>::value && !std::is_enum<T>::value>::type> {
1515  static constexpr object_category value{object_category::char_value};
1516 };
1517 
1518 /// Boolean values
1519 template <typename T> struct classify_object<T, typename std::enable_if<is_bool<T>::value>::type> {
1520  static constexpr object_category value{object_category::boolean_value};
1521 };
1522 
1523 /// Floats
1524 template <typename T> struct classify_object<T, typename std::enable_if<std::is_floating_point<T>::value>::type> {
1525  static constexpr object_category value{object_category::floating_point};
1526 };
1527 
1528 /// String and similar direct assignment
1529 template <typename T>
1530 struct classify_object<T,
1531  typename std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1532  std::is_assignable<T &, std::string>::value>::type> {
1533  static constexpr object_category value{object_category::string_assignable};
1534 };
1535 
1536 /// String and similar constructible and copy assignment
1537 template <typename T>
1538 struct classify_object<
1539  T,
1540  typename std::enable_if<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1541  !std::is_assignable<T &, std::string>::value && (type_count<T>::value == 1) &&
1542  std::is_constructible<T, std::string>::value>::type> {
1543  static constexpr object_category value{object_category::string_constructible};
1544 };
1545 
1546 /// Enumerations
1547 template <typename T> struct classify_object<T, typename std::enable_if<std::is_enum<T>::value>::type> {
1548  static constexpr object_category value{object_category::enumeration};
1549 };
1550 
1551 template <typename T> struct classify_object<T, typename std::enable_if<is_complex<T>::value>::type> {
1552  static constexpr object_category value{object_category::complex_number};
1553 };
1554 
1555 /// Handy helper to contain a bunch of checks that rule out many common types (integers, string like, floating point,
1556 /// vectors, and enumerations
1557 template <typename T> struct uncommon_type {
1562  std::true_type,
1563  std::false_type>::type;
1564  static constexpr bool value = type::value;
1565 };
1566 
1567 /// wrapper type
1568 template <typename T>
1569 struct classify_object<T,
1570  typename std::enable_if<(!is_mutable_container<T>::value && is_wrapper<T>::value &&
1571  !is_tuple_like<T>::value && uncommon_type<T>::value)>::type> {
1572  static constexpr object_category value{object_category::wrapper_value};
1573 };
1574 
1575 /// Assignable from double or int
1576 template <typename T>
1577 struct classify_object<T,
1578  typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1579  !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
1580  is_direct_constructible<T, int>::value>::type> {
1581  static constexpr object_category value{object_category::number_constructible};
1582 };
1583 
1584 /// Assignable from int
1585 template <typename T>
1586 struct classify_object<T,
1587  typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1588  !is_wrapper<T>::value && !is_direct_constructible<T, double>::value &&
1589  is_direct_constructible<T, int>::value>::type> {
1590  static constexpr object_category value{object_category::integer_constructible};
1591 };
1592 
1593 /// Assignable from double
1594 template <typename T>
1595 struct classify_object<T,
1596  typename std::enable_if<uncommon_type<T>::value && type_count<T>::value == 1 &&
1597  !is_wrapper<T>::value && is_direct_constructible<T, double>::value &&
1598  !is_direct_constructible<T, int>::value>::type> {
1599  static constexpr object_category value{object_category::double_constructible};
1600 };
1601 
1602 /// Tuple type
1603 template <typename T>
1604 struct classify_object<
1605  T,
1606  typename std::enable_if<is_tuple_like<T>::value &&
1607  ((type_count<T>::value >= 2 && !is_wrapper<T>::value) ||
1608  (uncommon_type<T>::value && !is_direct_constructible<T, double>::value &&
1609  !is_direct_constructible<T, int>::value) ||
1610  (uncommon_type<T>::value && type_count<T>::value >= 2))>::type> {
1611  static constexpr object_category value{object_category::tuple_value};
1612  // the condition on this class requires it be like a tuple, but on some compilers (like Xcode) tuples can be
1613  // constructed from just the first element so tuples of <string, int,int> can be constructed from a string, which
1614  // could lead to issues so there are two variants of the condition, the first isolates things with a type size >=2
1615  // mainly to get tuples on Xcode with the exception of wrappers, the second is the main one and just separating out
1616  // those cases that are caught by other object classifications
1617 };
1618 
1619 /// container type
1620 template <typename T> struct classify_object<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1621  static constexpr object_category value{object_category::container_value};
1622 };
1623 
1624 // Type name print
1625 
1626 /// Was going to be based on
1627 /// http://stackoverflow.com/questions/1055452/c-get-name-of-type-in-template
1628 /// But this is cleaner and works better in this case
1629 
1630 template <typename T,
1631  enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> = detail::dummy>
1632 constexpr const char *type_name() {
1633  return "CHAR";
1634 }
1635 
1636 template <typename T,
1637  enable_if_t<classify_object<T>::value == object_category::integral_value ||
1638  classify_object<T>::value == object_category::integer_constructible,
1640 constexpr const char *type_name() {
1641  return "INT";
1642 }
1643 
1644 template <typename T,
1645  enable_if_t<classify_object<T>::value == object_category::unsigned_integral, detail::enabler> = detail::dummy>
1646 constexpr const char *type_name() {
1647  return "UINT";
1648 }
1649 
1650 template <typename T,
1651  enable_if_t<classify_object<T>::value == object_category::floating_point ||
1652  classify_object<T>::value == object_category::number_constructible ||
1653  classify_object<T>::value == object_category::double_constructible,
1655 constexpr const char *type_name() {
1656  return "FLOAT";
1657 }
1658 
1659 /// Print name for enumeration types
1660 template <typename T,
1661  enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> = detail::dummy>
1662 constexpr const char *type_name() {
1663  return "ENUM";
1664 }
1665 
1666 /// Print name for enumeration types
1667 template <typename T,
1668  enable_if_t<classify_object<T>::value == object_category::boolean_value, detail::enabler> = detail::dummy>
1669 constexpr const char *type_name() {
1670  return "BOOLEAN";
1671 }
1672 
1673 /// Print name for enumeration types
1674 template <typename T,
1675  enable_if_t<classify_object<T>::value == object_category::complex_number, detail::enabler> = detail::dummy>
1676 constexpr const char *type_name() {
1677  return "COMPLEX";
1678 }
1679 
1680 /// Print for all other types
1681 template <typename T,
1682  enable_if_t<classify_object<T>::value >= object_category::string_assignable &&
1683  classify_object<T>::value <= object_category::other,
1685 constexpr const char *type_name() {
1686  return "TEXT";
1687 }
1688 /// typename for tuple value
1689 template <typename T,
1690  enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value >= 2,
1692 std::string type_name(); // forward declaration
1693 
1694 /// Generate type name for a wrapper or container value
1695 template <typename T,
1696  enable_if_t<classify_object<T>::value == object_category::container_value ||
1697  classify_object<T>::value == object_category::wrapper_value,
1699 std::string type_name(); // forward declaration
1700 
1701 /// Print name for single element tuple types
1702 template <typename T,
1703  enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value == 1,
1705 inline std::string type_name() {
1707 }
1708 
1709 /// Empty string if the index > tuple size
1710 template <typename T, std::size_t I>
1712  return std::string{};
1713 }
1714 
1715 /// Recursively generate the tuple type name
1716 template <typename T, std::size_t I>
1717 inline typename std::enable_if<(I < type_count_base<T>::value), std::string>::type tuple_name() {
1719  tuple_name<T, I + 1>();
1720  if(str.back() == ',')
1721  str.pop_back();
1722  return str;
1723 }
1724 
1725 /// Print type name for tuples with 2 or more elements
1726 template <typename T,
1727  enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value >= 2,
1728  detail::enabler>>
1730  auto tname = std::string(1, '[') + tuple_name<T, 0>();
1731  tname.push_back(']');
1732  return tname;
1733 }
1734 
1735 /// get the type name for a type that has a value_type member
1736 template <typename T,
1737  enable_if_t<classify_object<T>::value == object_category::container_value ||
1738  classify_object<T>::value == object_category::wrapper_value,
1739  detail::enabler>>
1741  return type_name<typename T::value_type>();
1742 }
1743 
1744 // Lexical cast
1745 
1746 /// Convert to an unsigned integral
1748 bool integral_conversion(const std::string &input, T &output) noexcept {
1749  if(input.empty()) {
1750  return false;
1751  }
1752  char *val = nullptr;
1753  std::uint64_t output_ll = std::strtoull(input.c_str(), &val, 0);
1754  output = static_cast<T>(output_ll);
1755  if(val == (input.c_str() + input.size()) && static_cast<std::uint64_t>(output) == output_ll) {
1756  return true;
1757  }
1758  val = nullptr;
1759  std::int64_t output_sll = std::strtoll(input.c_str(), &val, 0);
1760  if(val == (input.c_str() + input.size())) {
1761  output = (output_sll < 0) ? static_cast<T>(0) : static_cast<T>(output_sll);
1762  return (static_cast<std::int64_t>(output) == output_sll);
1763  }
1764  return false;
1765 }
1766 
1767 /// Convert to a signed integral
1769 bool integral_conversion(const std::string &input, T &output) noexcept {
1770  if(input.empty()) {
1771  return false;
1772  }
1773  char *val = nullptr;
1774  std::int64_t output_ll = std::strtoll(input.c_str(), &val, 0);
1775  output = static_cast<T>(output_ll);
1776  if(val == (input.c_str() + input.size()) && static_cast<std::int64_t>(output) == output_ll) {
1777  return true;
1778  }
1779  if(input == "true") {
1780  // this is to deal with a few oddities with flags and wrapper int types
1781  output = static_cast<T>(1);
1782  return true;
1783  }
1784  return false;
1785 }
1786 
1787 /// Convert a flag into an integer value typically binary flags
1788 inline std::int64_t to_flag_value(std::string val) {
1789  static const std::string trueString("true");
1790  static const std::string falseString("false");
1791  if(val == trueString) {
1792  return 1;
1793  }
1794  if(val == falseString) {
1795  return -1;
1796  }
1797  val = detail::to_lower(val);
1798  std::int64_t ret = 0;
1799  if(val.size() == 1) {
1800  if(val[0] >= '1' && val[0] <= '9') {
1801  return (static_cast<std::int64_t>(val[0]) - '0');
1802  }
1803  switch(val[0]) {
1804  case '0':
1805  case 'f':
1806  case 'n':
1807  case '-':
1808  ret = -1;
1809  break;
1810  case 't':
1811  case 'y':
1812  case '+':
1813  ret = 1;
1814  break;
1815  default:
1816  throw std::invalid_argument("unrecognized character");
1817  }
1818  return ret;
1819  }
1820  if(val == trueString || val == "on" || val == "yes" || val == "enable") {
1821  ret = 1;
1822  } else if(val == falseString || val == "off" || val == "no" || val == "disable") {
1823  ret = -1;
1824  } else {
1825  ret = std::stoll(val);
1826  }
1827  return ret;
1828 }
1829 
1830 /// Integer conversion
1831 template <typename T,
1832  enable_if_t<classify_object<T>::value == object_category::integral_value ||
1833  classify_object<T>::value == object_category::unsigned_integral,
1834  detail::enabler> = detail::dummy>
1835 bool lexical_cast(const std::string &input, T &output) {
1836  return integral_conversion(input, output);
1837 }
1838 
1839 /// char values
1840 template <typename T,
1841  enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> = detail::dummy>
1842 bool lexical_cast(const std::string &input, T &output) {
1843  if(input.size() == 1) {
1844  output = static_cast<T>(input[0]);
1845  return true;
1846  }
1847  return integral_conversion(input, output);
1848 }
1849 
1850 /// Boolean values
1851 template <typename T,
1852  enable_if_t<classify_object<T>::value == object_category::boolean_value, detail::enabler> = detail::dummy>
1853 bool lexical_cast(const std::string &input, T &output) {
1854  try {
1855  auto out = to_flag_value(input);
1856  output = (out > 0);
1857  return true;
1858  } catch(const std::invalid_argument &) {
1859  return false;
1860  } catch(const std::out_of_range &) {
1861  // 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
1862  // valid all we care about the sign
1863  output = (input[0] != '-');
1864  return true;
1865  }
1866 }
1867 
1868 /// Floats
1869 template <typename T,
1870  enable_if_t<classify_object<T>::value == object_category::floating_point, detail::enabler> = detail::dummy>
1871 bool lexical_cast(const std::string &input, T &output) {
1872  if(input.empty()) {
1873  return false;
1874  }
1875  char *val = nullptr;
1876  auto output_ld = std::strtold(input.c_str(), &val);
1877  output = static_cast<T>(output_ld);
1878  return val == (input.c_str() + input.size());
1879 }
1880 
1881 /// complex
1882 template <typename T,
1883  enable_if_t<classify_object<T>::value == object_category::complex_number, detail::enabler> = detail::dummy>
1884 bool lexical_cast(const std::string &input, T &output) {
1885  using XC = typename wrapped_type<T, double>::type;
1886  XC x{0.0}, y{0.0};
1887  auto str1 = input;
1888  bool worked = false;
1889  auto nloc = str1.find_last_of("+-");
1890  if(nloc != std::string::npos && nloc > 0) {
1891  worked = detail::lexical_cast(str1.substr(0, nloc), x);
1892  str1 = str1.substr(nloc);
1893  if(str1.back() == 'i' || str1.back() == 'j')
1894  str1.pop_back();
1895  worked = worked && detail::lexical_cast(str1, y);
1896  } else {
1897  if(str1.back() == 'i' || str1.back() == 'j') {
1898  str1.pop_back();
1899  worked = detail::lexical_cast(str1, y);
1900  x = XC{0};
1901  } else {
1902  worked = detail::lexical_cast(str1, x);
1903  y = XC{0};
1904  }
1905  }
1906  if(worked) {
1907  output = T{x, y};
1908  return worked;
1909  }
1910  return from_stream(input, output);
1911 }
1912 
1913 /// String and similar direct assignment
1914 template <typename T,
1915  enable_if_t<classify_object<T>::value == object_category::string_assignable, detail::enabler> = detail::dummy>
1916 bool lexical_cast(const std::string &input, T &output) {
1917  output = input;
1918  return true;
1919 }
1920 
1921 /// String and similar constructible and copy assignment
1922 template <
1923  typename T,
1924  enable_if_t<classify_object<T>::value == object_category::string_constructible, detail::enabler> = detail::dummy>
1925 bool lexical_cast(const std::string &input, T &output) {
1926  output = T(input);
1927  return true;
1928 }
1929 
1930 /// Enumerations
1931 template <typename T,
1932  enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> = detail::dummy>
1933 bool lexical_cast(const std::string &input, T &output) {
1935  if(!integral_conversion(input, val)) {
1936  return false;
1937  }
1938  output = static_cast<T>(val);
1939  return true;
1940 }
1941 
1942 /// wrapper types
1943 template <typename T,
1944  enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
1946  detail::enabler> = detail::dummy>
1947 bool lexical_cast(const std::string &input, T &output) {
1948  typename T::value_type val;
1949  if(lexical_cast(input, val)) {
1950  output = val;
1951  return true;
1952  }
1953  return from_stream(input, output);
1954 }
1955 
1956 template <typename T,
1957  enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
1958  !std::is_assignable<T &, typename T::value_type>::value && std::is_assignable<T &, T>::value,
1959  detail::enabler> = detail::dummy>
1960 bool lexical_cast(const std::string &input, T &output) {
1961  typename T::value_type val;
1962  if(lexical_cast(input, val)) {
1963  output = T{val};
1964  return true;
1965  }
1966  return from_stream(input, output);
1967 }
1968 
1969 /// Assignable from double or int
1970 template <
1971  typename T,
1972  enable_if_t<classify_object<T>::value == object_category::number_constructible, detail::enabler> = detail::dummy>
1973 bool lexical_cast(const std::string &input, T &output) {
1974  int val = 0;
1975  if(integral_conversion(input, val)) {
1976  output = T(val);
1977  return true;
1978  }
1979 
1980  double dval = 0.0;
1981  if(lexical_cast(input, dval)) {
1982  output = T{dval};
1983  return true;
1984  }
1985 
1986  return from_stream(input, output);
1987 }
1988 
1989 /// Assignable from int
1990 template <
1991  typename T,
1992  enable_if_t<classify_object<T>::value == object_category::integer_constructible, detail::enabler> = detail::dummy>
1993 bool lexical_cast(const std::string &input, T &output) {
1994  int val = 0;
1995  if(integral_conversion(input, val)) {
1996  output = T(val);
1997  return true;
1998  }
1999  return from_stream(input, output);
2000 }
2001 
2002 /// Assignable from double
2003 template <
2004  typename T,
2005  enable_if_t<classify_object<T>::value == object_category::double_constructible, detail::enabler> = detail::dummy>
2006 bool lexical_cast(const std::string &input, T &output) {
2007  double val = 0.0;
2008  if(lexical_cast(input, val)) {
2009  output = T{val};
2010  return true;
2011  }
2012  return from_stream(input, output);
2013 }
2014 
2015 /// Non-string convertible from an int
2016 template <typename T,
2017  enable_if_t<classify_object<T>::value == object_category::other && std::is_assignable<T &, int>::value,
2018  detail::enabler> = detail::dummy>
2019 bool lexical_cast(const std::string &input, T &output) {
2020  int val = 0;
2021  if(integral_conversion(input, val)) {
2022 #ifdef _MSC_VER
2023 #pragma warning(push)
2024 #pragma warning(disable : 4800)
2025 #endif
2026  // with Atomic<XX> this could produce a warning due to the conversion but if atomic gets here it is an old style
2027  // so will most likely still work
2028  output = val;
2029 #ifdef _MSC_VER
2030 #pragma warning(pop)
2031 #endif
2032  return true;
2033  }
2034  // LCOV_EXCL_START
2035  // This version of cast is only used for odd cases in an older compilers the fail over
2036  // from_stream is tested elsewhere an not relevant for coverage here
2037  return from_stream(input, output);
2038  // LCOV_EXCL_STOP
2039 }
2040 
2041 /// Non-string parsable by a stream
2042 template <typename T,
2043  enable_if_t<classify_object<T>::value == object_category::other && !std::is_assignable<T &, int>::value,
2044  detail::enabler> = detail::dummy>
2045 bool lexical_cast(const std::string &input, T &output) {
2046  static_assert(is_istreamable<T>::value,
2047  "option object type must have a lexical cast overload or streaming input operator(>>) defined, if it "
2048  "is convertible from another type use the add_option<T, XC>(...) with XC being the known type");
2049  return from_stream(input, output);
2050 }
2051 
2052 /// Assign a value through lexical cast operations
2053 /// Strings can be empty so we need to do a little different
2054 template <typename AssignTo,
2055  typename ConvertTo,
2057  (classify_object<AssignTo>::value == object_category::string_assignable ||
2058  classify_object<AssignTo>::value == object_category::string_constructible),
2059  detail::enabler> = detail::dummy>
2060 bool lexical_assign(const std::string &input, AssignTo &output) {
2061  return lexical_cast(input, output);
2062 }
2063 
2064 /// Assign a value through lexical cast operations
2065 template <typename AssignTo,
2066  typename ConvertTo,
2068  classify_object<AssignTo>::value != object_category::string_assignable &&
2069  classify_object<AssignTo>::value != object_category::string_constructible,
2070  detail::enabler> = detail::dummy>
2071 bool lexical_assign(const std::string &input, AssignTo &output) {
2072  if(input.empty()) {
2073  output = AssignTo{};
2074  return true;
2075  }
2076 
2077  return lexical_cast(input, output);
2078 }
2079 
2080 /// Assign a value through lexical cast operations
2081 template <typename AssignTo,
2082  typename ConvertTo,
2084  classify_object<AssignTo>::value == object_category::wrapper_value,
2085  detail::enabler> = detail::dummy>
2086 bool lexical_assign(const std::string &input, AssignTo &output) {
2087  if(input.empty()) {
2088  typename AssignTo::value_type emptyVal{};
2089  output = emptyVal;
2090  return true;
2091  }
2092  return lexical_cast(input, output);
2093 }
2094 
2095 /// Assign a value through lexical cast operations for int compatible values
2096 /// mainly for atomic operations on some compilers
2097 template <typename AssignTo,
2098  typename ConvertTo,
2100  classify_object<AssignTo>::value != object_category::wrapper_value &&
2102  detail::enabler> = detail::dummy>
2103 bool lexical_assign(const std::string &input, AssignTo &output) {
2104  if(input.empty()) {
2105  output = 0;
2106  return true;
2107  }
2108  int val = 0;
2109  if(lexical_cast(input, val)) {
2110  output = val;
2111  return true;
2112  }
2113  return false;
2114 }
2115 
2116 /// Assign a value converted from a string in lexical cast to the output value directly
2117 template <typename AssignTo,
2118  typename ConvertTo,
2120  detail::enabler> = detail::dummy>
2121 bool lexical_assign(const std::string &input, AssignTo &output) {
2122  ConvertTo val{};
2123  bool parse_result = (!input.empty()) ? lexical_cast<ConvertTo>(input, val) : true;
2124  if(parse_result) {
2125  output = val;
2126  }
2127  return parse_result;
2128 }
2129 
2130 /// Assign a value from a lexical cast through constructing a value and move assigning it
2131 template <
2132  typename AssignTo,
2133  typename ConvertTo,
2134  enable_if_t<!std::is_same<AssignTo, ConvertTo>::value && !std::is_assignable<AssignTo &, ConvertTo &>::value &&
2136  detail::enabler> = detail::dummy>
2137 bool lexical_assign(const std::string &input, AssignTo &output) {
2138  ConvertTo val{};
2139  bool parse_result = input.empty() ? true : lexical_cast<ConvertTo>(input, val);
2140  if(parse_result) {
2141  output = AssignTo(val); // use () form of constructor to allow some implicit conversions
2142  }
2143  return parse_result;
2144 }
2145 
2146 /// primary lexical conversion operation, 1 string to 1 type of some kind
2147 template <typename AssignTo,
2148  typename ConvertTo,
2149  enable_if_t<classify_object<ConvertTo>::value <= object_category::other &&
2150  classify_object<AssignTo>::value <= object_category::wrapper_value,
2151  detail::enabler> = detail::dummy>
2152 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2153  return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2154 }
2155 
2156 /// Lexical conversion if there is only one element but the conversion type is for two, then call a two element
2157 /// constructor
2158 template <typename AssignTo,
2159  typename ConvertTo,
2162  detail::enabler> = detail::dummy>
2163 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2164  // the remove const is to handle pair types coming from a container
2167  bool retval = lexical_assign<decltype(v1), decltype(v1)>(strings[0], v1);
2168  if(strings.size() > 1) {
2169  retval = retval && lexical_assign<decltype(v2), decltype(v2)>(strings[1], v2);
2170  }
2171  if(retval) {
2172  output = AssignTo{v1, v2};
2173  }
2174  return retval;
2175 }
2176 
2177 /// Lexical conversion of a container types of single elements
2178 template <class AssignTo,
2179  class ConvertTo,
2182  detail::enabler> = detail::dummy>
2183 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2184  output.erase(output.begin(), output.end());
2185  if(strings.size() == 1 && strings[0] == "{}") {
2186  return true;
2187  }
2188  bool skip_remaining = false;
2189  if(strings.size() == 2 && strings[0] == "{}" && is_separator(strings[1])) {
2190  skip_remaining = true;
2191  }
2192  for(const auto &elem : strings) {
2193  typename AssignTo::value_type out;
2194  bool retval = lexical_assign<typename AssignTo::value_type, typename ConvertTo::value_type>(elem, out);
2195  if(!retval) {
2196  return false;
2197  }
2198  output.insert(output.end(), std::move(out));
2199  if(skip_remaining) {
2200  break;
2201  }
2202  }
2203  return (!output.empty());
2204 }
2205 
2206 /// Lexical conversion for complex types
2208 bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2209 
2210  if(strings.size() >= 2 && !strings[1].empty()) {
2211  using XC2 = typename wrapped_type<ConvertTo, double>::type;
2212  XC2 x{0.0}, y{0.0};
2213  auto str1 = strings[1];
2214  if(str1.back() == 'i' || str1.back() == 'j') {
2215  str1.pop_back();
2216  }
2217  auto worked = detail::lexical_cast(strings[0], x) && detail::lexical_cast(str1, y);
2218  if(worked) {
2219  output = ConvertTo{x, y};
2220  }
2221  return worked;
2222  }
2223  return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2224 }
2225 
2226 /// Conversion to a vector type using a particular single type as the conversion type
2227 template <class AssignTo,
2228  class ConvertTo,
2230  (type_count<ConvertTo>::value == 1),
2231  detail::enabler> = detail::dummy>
2232 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2233  bool retval = true;
2234  output.clear();
2235  output.reserve(strings.size());
2236  for(const auto &elem : strings) {
2237 
2238  output.emplace_back();
2239  retval = retval && lexical_assign<typename AssignTo::value_type, ConvertTo>(elem, output.back());
2240  }
2241  return (!output.empty()) && retval;
2242 }
2243 
2244 // forward declaration
2245 
2246 /// Lexical conversion of a container types with conversion type of two elements
2247 template <class AssignTo,
2248  class ConvertTo,
2251  detail::enabler> = detail::dummy>
2252 bool lexical_conversion(std::vector<std::string> strings, AssignTo &output);
2253 
2254 /// Lexical conversion of a vector types with type_size >2 forward declaration
2255 template <class AssignTo,
2256  class ConvertTo,
2258  type_count_base<ConvertTo>::value != 2 &&
2259  ((type_count<ConvertTo>::value > 2) ||
2260  (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
2261  detail::enabler> = detail::dummy>
2262 bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output);
2263 
2264 /// Conversion for tuples
2265 template <class AssignTo,
2266  class ConvertTo,
2268  (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2269  type_count<ConvertTo>::value > 2),
2270  detail::enabler> = detail::dummy>
2271 bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output); // forward declaration
2272 
2273 /// Conversion for operations where the assigned type is some class but the conversion is a mutable container or large
2274 /// tuple
2275 template <typename AssignTo,
2276  typename ConvertTo,
2278  classify_object<ConvertTo>::value != object_category::wrapper_value &&
2279  (is_mutable_container<ConvertTo>::value || type_count<ConvertTo>::value > 2),
2280  detail::enabler> = detail::dummy>
2281 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2282 
2283  if(strings.size() > 1 || (!strings.empty() && !(strings.front().empty()))) {
2284  ConvertTo val;
2285  auto retval = lexical_conversion<ConvertTo, ConvertTo>(strings, val);
2286  output = AssignTo{val};
2287  return retval;
2288  }
2289  output = AssignTo{};
2290  return true;
2291 }
2292 
2293 /// function template for converting tuples if the static Index is greater than the tuple size
2294 template <class AssignTo, class ConvertTo, std::size_t I>
2295 inline typename std::enable_if<(I >= type_count_base<AssignTo>::value), bool>::type
2296 tuple_conversion(const std::vector<std::string> &, AssignTo &) {
2297  return true;
2298 }
2299 
2300 /// Conversion of a tuple element where the type size ==1 and not a mutable container
2301 template <class AssignTo, class ConvertTo>
2302 inline typename std::enable_if<!is_mutable_container<ConvertTo>::value && type_count<ConvertTo>::value == 1, bool>::type
2303 tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2304  auto retval = lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2305  strings.erase(strings.begin());
2306  return retval;
2307 }
2308 
2309 /// Conversion of a tuple element where the type size !=1 but the size is fixed and not a mutable container
2310 template <class AssignTo, class ConvertTo>
2311 inline typename std::enable_if<!is_mutable_container<ConvertTo>::value && (type_count<ConvertTo>::value > 1) &&
2312  type_count<ConvertTo>::value == type_count_min<ConvertTo>::value,
2313  bool>::type
2314 tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2315  auto retval = lexical_conversion<AssignTo, ConvertTo>(strings, output);
2316  strings.erase(strings.begin(), strings.begin() + type_count<ConvertTo>::value);
2317  return retval;
2318 }
2319 
2320 /// Conversion of a tuple element where the type is a mutable container or a type with different min and max type sizes
2321 template <class AssignTo, class ConvertTo>
2323  type_count<ConvertTo>::value != type_count_min<ConvertTo>::value,
2324  bool>::type
2325 tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2326 
2328  const std::size_t mx_count{subtype_count<ConvertTo>::value};
2329  const std::size_t mx{(std::max)(mx_count, strings.size())};
2330 
2331  while(index < mx) {
2332  if(is_separator(strings[index])) {
2333  break;
2334  }
2335  ++index;
2336  }
2337  bool retval = lexical_conversion<AssignTo, ConvertTo>(
2338  std::vector<std::string>(strings.begin(), strings.begin() + static_cast<std::ptrdiff_t>(index)), output);
2339  strings.erase(strings.begin(), strings.begin() + static_cast<std::ptrdiff_t>(index) + 1);
2340  return retval;
2341 }
2342 
2343 /// Tuple conversion operation
2344 template <class AssignTo, class ConvertTo, std::size_t I>
2346 tuple_conversion(std::vector<std::string> strings, AssignTo &output) {
2347  bool retval = true;
2348  using ConvertToElement = typename std::
2350  if(!strings.empty()) {
2351  retval = retval && tuple_type_conversion<typename std::tuple_element<I, AssignTo>::type, ConvertToElement>(
2352  strings, std::get<I>(output));
2353  }
2354  retval = retval && tuple_conversion<AssignTo, ConvertTo, I + 1>(std::move(strings), output);
2355  return retval;
2356 }
2357 
2358 /// Lexical conversion of a container types with tuple elements of size 2
2359 template <class AssignTo,
2360  class ConvertTo,
2362  type_count_base<ConvertTo>::value == 2,
2363  detail::enabler>>
2364 bool lexical_conversion(std::vector<std::string> strings, AssignTo &output) {
2365  output.clear();
2366  while(!strings.empty()) {
2367 
2370  bool retval = tuple_type_conversion<decltype(v1), decltype(v1)>(strings, v1);
2371  if(!strings.empty()) {
2372  retval = retval && tuple_type_conversion<decltype(v2), decltype(v2)>(strings, v2);
2373  }
2374  if(retval) {
2375  output.insert(output.end(), typename AssignTo::value_type{v1, v2});
2376  } else {
2377  return false;
2378  }
2379  }
2380  return (!output.empty());
2381 }
2382 
2383 /// lexical conversion of tuples with type count>2 or tuples of types of some element with a type size>=2
2384 template <class AssignTo,
2385  class ConvertTo,
2387  (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2388  type_count<ConvertTo>::value > 2),
2389  detail::enabler>>
2390 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2391  static_assert(
2392  !is_tuple_like<ConvertTo>::value || type_count_base<AssignTo>::value == type_count_base<ConvertTo>::value,
2393  "if the conversion type is defined as a tuple it must be the same size as the type you are converting to");
2394  return tuple_conversion<AssignTo, ConvertTo, 0>(strings, output);
2395 }
2396 
2397 /// Lexical conversion of a vector types for everything but tuples of two elements and types of size 1
2398 template <class AssignTo,
2399  class ConvertTo,
2401  type_count_base<ConvertTo>::value != 2 &&
2402  ((type_count<ConvertTo>::value > 2) ||
2403  (type_count<ConvertTo>::value > type_count_base<ConvertTo>::value)),
2404  detail::enabler>>
2405 bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2406  bool retval = true;
2407  output.clear();
2408  std::vector<std::string> temp;
2409  std::size_t ii{0};
2410  std::size_t icount{0};
2411  std::size_t xcm{type_count<ConvertTo>::value};
2412  auto ii_max = strings.size();
2413  while(ii < ii_max) {
2414  temp.push_back(strings[ii]);
2415  ++ii;
2416  ++icount;
2417  if(icount == xcm || is_separator(temp.back()) || ii == ii_max) {
2418  if(static_cast<int>(xcm) > type_count_min<ConvertTo>::value && is_separator(temp.back())) {
2419  temp.pop_back();
2420  }
2421  typename AssignTo::value_type temp_out;
2422  retval = retval &&
2423  lexical_conversion<typename AssignTo::value_type, typename ConvertTo::value_type>(temp, temp_out);
2424  temp.clear();
2425  if(!retval) {
2426  return false;
2427  }
2428  output.insert(output.end(), std::move(temp_out));
2429  icount = 0;
2430  }
2431  }
2432  return retval;
2433 }
2434 
2435 /// conversion for wrapper types
2436 template <typename AssignTo,
2437  class ConvertTo,
2438  enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2440  detail::enabler> = detail::dummy>
2441 bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2442  if(strings.empty() || strings.front().empty()) {
2443  output = ConvertTo{};
2444  return true;
2445  }
2446  typename ConvertTo::value_type val;
2447  if(lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings, val)) {
2448  output = ConvertTo{val};
2449  return true;
2450  }
2451  return false;
2452 }
2453 
2454 /// conversion for wrapper types
2455 template <typename AssignTo,
2456  class ConvertTo,
2457  enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2459  detail::enabler> = detail::dummy>
2460 bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output) {
2461  using ConvertType = typename ConvertTo::value_type;
2462  if(strings.empty() || strings.front().empty()) {
2463  output = ConvertType{};
2464  return true;
2465  }
2466  ConvertType val;
2467  if(lexical_conversion<typename ConvertTo::value_type, typename ConvertTo::value_type>(strings, val)) {
2468  output = val;
2469  return true;
2470  }
2471  return false;
2472 }
2473 
2474 /// Sum a vector of strings
2475 inline std::string sum_string_vector(const std::vector<std::string> &values) {
2476  double val{0.0};
2477  bool fail{false};
2478  std::string output;
2479  for(const auto &arg : values) {
2480  double tv{0.0};
2481  auto comp = detail::lexical_cast<double>(arg, tv);
2482  if(!comp) {
2483  try {
2484  tv = static_cast<double>(detail::to_flag_value(arg));
2485  } catch(const std::exception &) {
2486  fail = true;
2487  break;
2488  }
2489  }
2490  val += tv;
2491  }
2492  if(fail) {
2493  for(const auto &arg : values) {
2494  output.append(arg);
2495  }
2496  } else {
2497  if(val <= static_cast<double>((std::numeric_limits<std::int64_t>::min)()) ||
2498  val >= static_cast<double>((std::numeric_limits<std::int64_t>::max)()) ||
2499  // NOLINTNEXTLINE(clang-diagnostic-float-equal,bugprone-narrowing-conversions)
2500  val == static_cast<std::int64_t>(val)) {
2501  output = detail::value_string(static_cast<int64_t>(val));
2502  } else {
2503  output = detail::value_string(val);
2504  }
2505  }
2506  return output;
2507 }
2508 
2509 } // namespace detail
2510 
2511 
2512 
2513 namespace detail {
2514 
2515 // Returns false if not a short option. Otherwise, sets opt name and rest and returns true
2517 
2518 // Returns false if not a long option. Otherwise, sets opt name and other side of = and returns true
2519 CLI11_INLINE bool split_long(const std::string &current, std::string &name, std::string &value);
2520 
2521 // Returns false if not a windows style option. Otherwise, sets opt name and value and returns true
2523 
2524 // Splits a string into multiple long and short names
2525 CLI11_INLINE std::vector<std::string> split_names(std::string current);
2526 
2527 /// extract default flag values either {def} or starting with a !
2528 CLI11_INLINE std::vector<std::pair<std::string, std::string>> get_default_flag_values(const std::string &str);
2529 
2530 /// Get a vector of short names, one of long names, and a single name
2531 CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>
2532 get_names(const std::vector<std::string> &input);
2533 
2534 } // namespace detail
2535 
2536 
2537 
2538 namespace detail {
2539 
2541  if(current.size() > 1 && current[0] == '-' && valid_first_char(current[1])) {
2542  name = current.substr(1, 1);
2543  rest = current.substr(2);
2544  return true;
2545  }
2546  return false;
2547 }
2548 
2550  if(current.size() > 2 && current.substr(0, 2) == "--" && valid_first_char(current[2])) {
2551  auto loc = current.find_first_of('=');
2552  if(loc != std::string::npos) {
2553  name = current.substr(2, loc - 2);
2554  value = current.substr(loc + 1);
2555  } else {
2556  name = current.substr(2);
2557  value = "";
2558  }
2559  return true;
2560  }
2561  return false;
2562 }
2563 
2565  if(current.size() > 1 && current[0] == '/' && valid_first_char(current[1])) {
2566  auto loc = current.find_first_of(':');
2567  if(loc != std::string::npos) {
2568  name = current.substr(1, loc - 1);
2569  value = current.substr(loc + 1);
2570  } else {
2571  name = current.substr(1);
2572  value = "";
2573  }
2574  return true;
2575  }
2576  return false;
2577 }
2578 
2579 CLI11_INLINE std::vector<std::string> split_names(std::string current) {
2580  std::vector<std::string> output;
2581  std::size_t val = 0;
2582  while((val = current.find(',')) != std::string::npos) {
2583  output.push_back(trim_copy(current.substr(0, val)));
2584  current = current.substr(val + 1);
2585  }
2586  output.push_back(trim_copy(current));
2587  return output;
2588 }
2589 
2590 CLI11_INLINE std::vector<std::pair<std::string, std::string>> get_default_flag_values(const std::string &str) {
2591  std::vector<std::string> flags = split_names(str);
2592  flags.erase(std::remove_if(flags.begin(),
2593  flags.end(),
2594  [](const std::string &name) {
2595  return ((name.empty()) || (!(((name.find_first_of('{') != std::string::npos) &&
2596  (name.back() == '}')) ||
2597  (name[0] == '!'))));
2598  }),
2599  flags.end());
2600  std::vector<std::pair<std::string, std::string>> output;
2601  output.reserve(flags.size());
2602  for(auto &flag : flags) {
2603  auto def_start = flag.find_first_of('{');
2604  std::string defval = "false";
2605  if((def_start != std::string::npos) && (flag.back() == '}')) {
2606  defval = flag.substr(def_start + 1);
2607  defval.pop_back();
2608  flag.erase(def_start, std::string::npos); // NOLINT(readability-suspicious-call-argument)
2609  }
2610  flag.erase(0, flag.find_first_not_of("-!"));
2611  output.emplace_back(flag, defval);
2612  }
2613  return output;
2614 }
2615 
2616 CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>
2617 get_names(const std::vector<std::string> &input) {
2618 
2619  std::vector<std::string> short_names;
2620  std::vector<std::string> long_names;
2621  std::string pos_name;
2622 
2623  for(std::string name : input) {
2624  if(name.length() == 0) {
2625  continue;
2626  }
2627  if(name.length() > 1 && name[0] == '-' && name[1] != '-') {
2628  if(name.length() == 2 && valid_first_char(name[1]))
2629  short_names.emplace_back(1, name[1]);
2630  else
2631  throw BadNameString::OneCharName(name);
2632  } else if(name.length() > 2 && name.substr(0, 2) == "--") {
2633  name = name.substr(2);
2634  if(valid_name_string(name))
2635  long_names.push_back(name);
2636  else
2637  throw BadNameString::BadLongName(name);
2638  } else if(name == "-" || name == "--") {
2639  throw BadNameString::DashesOnly(name);
2640  } else {
2641  if(pos_name.length() > 0)
2642  throw BadNameString::MultiPositionalNames(name);
2643  pos_name = name;
2644  }
2645  }
2646 
2647  return std::make_tuple(short_names, long_names, pos_name);
2648 }
2649 
2650 } // namespace detail
2651 
2652 
2653 
2654 class App;
2655 
2656 /// Holds values to load into Options
2657 struct ConfigItem {
2658  /// This is the list of parents
2659  std::vector<std::string> parents{};
2660 
2661  /// This is the name
2663 
2664  /// Listing of inputs
2665  std::vector<std::string> inputs{};
2666 
2667  /// The list of parents and name joined by "."
2669  std::vector<std::string> tmp = parents;
2670  tmp.emplace_back(name);
2671  return detail::join(tmp, ".");
2672  }
2673 };
2674 
2675 /// This class provides a converter for configuration files.
2676 class Config {
2677  protected:
2678  std::vector<ConfigItem> items{};
2679 
2680  public:
2681  /// Convert an app into a configuration
2682  virtual std::string to_config(const App *, bool, bool, std::string) const = 0;
2683 
2684  /// Convert a configuration into an app
2685  virtual std::vector<ConfigItem> from_config(std::istream &) const = 0;
2686 
2687  /// Get a flag value
2688  CLI11_NODISCARD virtual std::string to_flag(const ConfigItem &item) const {
2689  if(item.inputs.size() == 1) {
2690  return item.inputs.at(0);
2691  }
2692  if(item.inputs.empty()) {
2693  return "{}";
2694  }
2695  throw ConversionError::TooManyInputsFlag(item.fullname()); // LCOV_EXCL_LINE
2696  }
2697 
2698  /// Parse a config file, throw an error (ParseError:ConfigParseError or FileError) on failure
2699  CLI11_NODISCARD std::vector<ConfigItem> from_file(const std::string &name) const {
2700  std::ifstream input{name};
2701  if(!input.good())
2702  throw FileError::Missing(name);
2703 
2704  return from_config(input);
2705  }
2706 
2707  /// Virtual destructor
2708  virtual ~Config() = default;
2709 };
2710 
2711 /// This converter works with INI/TOML files; to write INI files use ConfigINI
2712 class ConfigBase : public Config {
2713  protected:
2714  /// the character used for comments
2715  char commentChar = '#';
2716  /// the character used to start an array '\0' is a default to not use
2717  char arrayStart = '[';
2718  /// the character used to end an array '\0' is a default to not use
2719  char arrayEnd = ']';
2720  /// the character used to separate elements in an array
2721  char arraySeparator = ',';
2722  /// the character used separate the name from the value
2723  char valueDelimiter = '=';
2724  /// the character to use around strings
2725  char stringQuote = '"';
2726  /// the character to use around single characters
2727  char characterQuote = '\'';
2728  /// the maximum number of layers to allow
2729  uint8_t maximumLayers{255};
2730  /// the separator used to separator parent layers
2731  char parentSeparatorChar{'.'};
2732  /// Specify the configuration index to use for arrayed sections
2733  int16_t configIndex{-1};
2734  /// Specify the configuration section that should be used
2735  std::string configSection{};
2736 
2737  public:
2738  std::string
2739  to_config(const App * /*app*/, bool default_also, bool write_description, std::string prefix) const override;
2740 
2741  std::vector<ConfigItem> from_config(std::istream &input) const override;
2742  /// Specify the configuration for comment characters
2743  ConfigBase *comment(char cchar) {
2744  commentChar = cchar;
2745  return this;
2746  }
2747  /// Specify the start and end characters for an array
2748  ConfigBase *arrayBounds(char aStart, char aEnd) {
2749  arrayStart = aStart;
2750  arrayEnd = aEnd;
2751  return this;
2752  }
2753  /// Specify the delimiter character for an array
2755  arraySeparator = aSep;
2756  return this;
2757  }
2758  /// Specify the delimiter between a name and value
2760  valueDelimiter = vSep;
2761  return this;
2762  }
2763  /// Specify the quote characters used around strings and characters
2764  ConfigBase *quoteCharacter(char qString, char qChar) {
2765  stringQuote = qString;
2766  characterQuote = qChar;
2767  return this;
2768  }
2769  /// Specify the maximum number of parents
2770  ConfigBase *maxLayers(uint8_t layers) {
2771  maximumLayers = layers;
2772  return this;
2773  }
2774  /// Specify the separator to use for parent layers
2776  parentSeparatorChar = sep;
2777  return this;
2778  }
2779  /// get a reference to the configuration section
2780  std::string &sectionRef() { return configSection; }
2781  /// get the section
2782  CLI11_NODISCARD const std::string &section() const { return configSection; }
2783  /// specify a particular section of the configuration file to use
2784  ConfigBase *section(const std::string &sectionName) {
2785  configSection = sectionName;
2786  return this;
2787  }
2788 
2789  /// get a reference to the configuration index
2790  int16_t &indexRef() { return configIndex; }
2791  /// get the section index
2792  CLI11_NODISCARD int16_t index() const { return configIndex; }
2793  /// specify a particular index in the section to use (-1) for all sections to use
2794  ConfigBase *index(int16_t sectionIndex) {
2795  configIndex = sectionIndex;
2796  return this;
2797  }
2798 };
2799 
2800 /// the default Config is the TOML file format
2802 
2803 /// ConfigINI generates a "standard" INI compliant output
2804 class ConfigINI : public ConfigTOML {
2805 
2806  public:
2808  commentChar = ';';
2809  arrayStart = '\0';
2810  arrayEnd = '\0';
2811  arraySeparator = ' ';
2812  valueDelimiter = '=';
2813  }
2814 };
2815 
2816 
2817 
2818 class Option;
2819 
2820 /// @defgroup validator_group Validators
2821 
2822 /// @brief Some validators that are provided
2823 ///
2824 /// These are simple `std::string(const std::string&)` validators that are useful. They return
2825 /// a string if the validation fails. A custom struct is provided, as well, with the same user
2826 /// semantics, but with the ability to provide a new type name.
2827 /// @{
2828 
2829 ///
2830 class Validator {
2831  protected:
2832  /// This is the description function, if empty the description_ will be used
2833  std::function<std::string()> desc_function_{[]() { return std::string{}; }};
2834 
2835  /// This is the base function that is to be called.
2836  /// Returns a string error message if validation fails.
2837  std::function<std::string(std::string &)> func_{[](std::string &) { return std::string{}; }};
2838  /// The name for search purposes of the Validator
2839  std::string name_{};
2840  /// A Validator will only apply to an indexed value (-1 is all elements)
2841  int application_index_ = -1;
2842  /// Enable for Validator to allow it to be disabled if need be
2843  bool active_{true};
2844  /// specify that a validator should not modify the input
2845  bool non_modifying_{false};
2846 
2847  Validator(std::string validator_desc, std::function<std::string(std::string &)> func)
2848  : desc_function_([validator_desc]() { return validator_desc; }), func_(std::move(func)) {}
2849 
2850  public:
2851  Validator() = default;
2852  /// Construct a Validator with just the description string
2853  explicit Validator(std::string validator_desc) : desc_function_([validator_desc]() { return validator_desc; }) {}
2854  /// Construct Validator from basic information
2855  Validator(std::function<std::string(std::string &)> op, std::string validator_desc, std::string validator_name = "")
2856  : desc_function_([validator_desc]() { return validator_desc; }), func_(std::move(op)),
2857  name_(std::move(validator_name)) {}
2858  /// Set the Validator operation function
2859  Validator &operation(std::function<std::string(std::string &)> op) {
2860  func_ = std::move(op);
2861  return *this;
2862  }
2863  /// This is the required operator for a Validator - provided to help
2864  /// users (CLI11 uses the member `func` directly)
2865  std::string operator()(std::string &str) const;
2866 
2867  /// This is the required operator for a Validator - provided to help
2868  /// users (CLI11 uses the member `func` directly)
2869  std::string operator()(const std::string &str) const {
2870  std::string value = str;
2871  return (active_) ? func_(value) : std::string{};
2872  }
2873 
2874  /// Specify the type string
2875  Validator &description(std::string validator_desc) {
2876  desc_function_ = [validator_desc]() { return validator_desc; };
2877  return *this;
2878  }
2879  /// Specify the type string
2880  CLI11_NODISCARD Validator description(std::string validator_desc) const;
2881 
2882  /// Generate type description information for the Validator
2884  if(active_) {
2885  return desc_function_();
2886  }
2887  return std::string{};
2888  }
2889  /// Specify the type string
2890  Validator &name(std::string validator_name) {
2891  name_ = std::move(validator_name);
2892  return *this;
2893  }
2894  /// Specify the type string
2895  CLI11_NODISCARD Validator name(std::string validator_name) const {
2896  Validator newval(*this);
2897  newval.name_ = std::move(validator_name);
2898  return newval;
2899  }
2900  /// Get the name of the Validator
2901  CLI11_NODISCARD const std::string &get_name() const { return name_; }
2902  /// Specify whether the Validator is active or not
2903  Validator &active(bool active_val = true) {
2904  active_ = active_val;
2905  return *this;
2906  }
2907  /// Specify whether the Validator is active or not
2908  CLI11_NODISCARD Validator active(bool active_val = true) const {
2909  Validator newval(*this);
2910  newval.active_ = active_val;
2911  return newval;
2912  }
2913 
2914  /// Specify whether the Validator can be modifying or not
2915  Validator &non_modifying(bool no_modify = true) {
2916  non_modifying_ = no_modify;
2917  return *this;
2918  }
2919  /// Specify the application index of a validator
2920  Validator &application_index(int app_index) {
2921  application_index_ = app_index;
2922  return *this;
2923  }
2924  /// Specify the application index of a validator
2926  Validator newval(*this);
2927  newval.application_index_ = app_index;
2928  return newval;
2929  }
2930  /// Get the current value of the application index
2931  CLI11_NODISCARD int get_application_index() const { return application_index_; }
2932  /// Get a boolean if the validator is active
2933  CLI11_NODISCARD bool get_active() const { return active_; }
2934 
2935  /// Get a boolean if the validator is allowed to modify the input returns true if it can modify the input
2936  CLI11_NODISCARD bool get_modifying() const { return !non_modifying_; }
2937 
2938  /// Combining validators is a new validator. Type comes from left validator if function, otherwise only set if the
2939  /// same.
2940  Validator operator&(const Validator &other) const;
2941 
2942  /// Combining validators is a new validator. Type comes from left validator if function, otherwise only set if the
2943  /// same.
2944  Validator operator|(const Validator &other) const;
2945 
2946  /// Create a validator that fails when a given validator succeeds
2947  Validator operator!() const;
2948 
2949  private:
2950  void _merge_description(const Validator &val1, const Validator &val2, const std::string &merger);
2951 };
2952 
2953 /// Class wrapping some of the accessors of Validator
2954 class CustomValidator : public Validator {
2955  public:
2956 };
2957 // The implementation of the built in validators is using the Validator class;
2958 // the user is only expected to use the const (static) versions (since there's no setup).
2959 // Therefore, this is in detail.
2960 namespace detail {
2961 
2962 /// CLI enumeration of different file types
2964 
2965 /// get the type of the path from a file name
2966 CLI11_INLINE path_type check_path(const char *file) noexcept;
2967 
2968 /// Check for an existing file (returns error message if check fails)
2970  public:
2972 };
2973 
2974 /// Check for an existing directory (returns error message if check fails)
2976  public:
2978 };
2979 
2980 /// Check for an existing path
2982  public:
2984 };
2985 
2986 /// Check for an non-existing path
2988  public:
2990 };
2991 
2992 /// Validate the given string is a legal ipv4 address
2993 class IPV4Validator : public Validator {
2994  public:
2995  IPV4Validator();
2996 };
2997 
2998 } // namespace detail
2999 
3000 // Static is not needed here, because global const implies static.
3001 
3002 /// Check for existing file (returns error message if check fails)
3004 
3005 /// Check for an existing directory (returns error message if check fails)
3007 
3008 /// Check for an existing path
3010 
3011 /// Check for an non-existing path
3013 
3014 /// Check for an IP4 address
3016 
3017 /// Validate the input as a particular type
3018 template <typename DesiredType> class TypeValidator : public Validator {
3019  public:
3020  explicit TypeValidator(const std::string &validator_name)
3021  : Validator(validator_name, [](std::string &input_string) {
3022  auto val = DesiredType();
3023  if(!detail::lexical_cast(input_string, val)) {
3024  return std::string("Failed parsing ") + input_string + " as a " + detail::type_name<DesiredType>();
3025  }
3026  return std::string();
3027  }) {}
3028  TypeValidator() : TypeValidator(detail::type_name<DesiredType>()) {}
3029 };
3030 
3031 /// Check for a number
3032 const TypeValidator<double> Number("NUMBER");
3033 
3034 /// Modify a path if the file is a particular default location, can be used as Check or transform
3035 /// with the error return optionally disabled
3037  public:
3038  explicit FileOnDefaultPath(std::string default_path, bool enableErrorReturn = true);
3039 };
3040 
3041 /// Produce a range (factory). Min and max are inclusive.
3042 class Range : public Validator {
3043  public:
3044  /// This produces a range with min and max inclusive.
3045  ///
3046  /// Note that the constructor is templated, but the struct is not, so C++17 is not
3047  /// needed to provide nice syntax for Range(a,b).
3048  template <typename T>
3049  Range(T min_val, T max_val, const std::string &validator_name = std::string{}) : Validator(validator_name) {
3050  if(validator_name.empty()) {
3051  std::stringstream out;
3052  out << detail::type_name<T>() << " in [" << min_val << " - " << max_val << "]";
3053  description(out.str());
3054  }
3055 
3056  func_ = [min_val, max_val](std::string &input) {
3057  T val;
3058  bool converted = detail::lexical_cast(input, val);
3059  if((!converted) || (val < min_val || val > max_val)) {
3060  std::stringstream out;
3061  out << "Value " << input << " not in range [";
3062  out << min_val << " - " << max_val << "]";
3063  return out.str();
3064  }
3065  return std::string{};
3066  };
3067  }
3068 
3069  /// Range of one value is 0 to value
3070  template <typename T>
3071  explicit Range(T max_val, const std::string &validator_name = std::string{})
3072  : Range(static_cast<T>(0), max_val, validator_name) {}
3073 };
3074 
3075 /// Check for a non negative number
3076 const Range NonNegativeNumber((std::numeric_limits<double>::max)(), "NONNEGATIVE");
3077 
3078 /// Check for a positive valued number (val>0.0), <double>::min here is the smallest positive number
3080 
3081 /// Produce a bounded range (factory). Min and max are inclusive.
3082 class Bound : public Validator {
3083  public:
3084  /// This bounds a value with min and max inclusive.
3085  ///
3086  /// Note that the constructor is templated, but the struct is not, so C++17 is not
3087  /// needed to provide nice syntax for Range(a,b).
3088  template <typename T> Bound(T min_val, T max_val) {
3089  std::stringstream out;
3090  out << detail::type_name<T>() << " bounded to [" << min_val << " - " << max_val << "]";
3091  description(out.str());
3092 
3093  func_ = [min_val, max_val](std::string &input) {
3094  T val;
3095  bool converted = detail::lexical_cast(input, val);
3096  if(!converted) {
3097  return std::string("Value ") + input + " could not be converted";
3098  }
3099  if(val < min_val)
3100  input = detail::to_string(min_val);
3101  else if(val > max_val)
3102  input = detail::to_string(max_val);
3103 
3104  return std::string{};
3105  };
3106  }
3107 
3108  /// Range of one value is 0 to value
3109  template <typename T> explicit Bound(T max_val) : Bound(static_cast<T>(0), max_val) {}
3110 };
3111 
3112 namespace detail {
3113 template <typename T,
3115 auto smart_deref(T value) -> decltype(*value) {
3116  return *value;
3117 }
3118 
3119 template <
3120  typename T,
3123  return value;
3124 }
3125 /// Generate a string representation of a set
3126 template <typename T> std::string generate_set(const T &set) {
3127  using element_t = typename detail::element_type<T>::type;
3128  using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3129  std::string out(1, '{');
3130  out.append(detail::join(
3131  detail::smart_deref(set),
3132  [](const iteration_type_t &v) { return detail::pair_adaptor<element_t>::first(v); },
3133  ","));
3134  out.push_back('}');
3135  return out;
3136 }
3137 
3138 /// Generate a string representation of a map
3139 template <typename T> std::string generate_map(const T &map, bool key_only = false) {
3140  using element_t = typename detail::element_type<T>::type;
3141  using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3142  std::string out(1, '{');
3143  out.append(detail::join(
3144  detail::smart_deref(map),
3145  [key_only](const iteration_type_t &v) {
3147 
3148  if(!key_only) {
3149  res.append("->");
3151  }
3152  return res;
3153  },
3154  ","));
3155  out.push_back('}');
3156  return out;
3157 }
3158 
3159 template <typename C, typename V> struct has_find {
3160  template <typename CC, typename VV>
3161  static auto test(int) -> decltype(std::declval<CC>().find(std::declval<VV>()), std::true_type());
3162  template <typename, typename> static auto test(...) -> decltype(std::false_type());
3163 
3164  static const auto value = decltype(test<C, V>(0))::value;
3165  using type = std::integral_constant<bool, value>;
3166 };
3167 
3168 /// A search function
3170 auto search(const T &set, const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3171  using element_t = typename detail::element_type<T>::type;
3172  auto &setref = detail::smart_deref(set);
3173  auto it = std::find_if(std::begin(setref), std::end(setref), [&val](decltype(*std::begin(setref)) v) {
3174  return (detail::pair_adaptor<element_t>::first(v) == val);
3175  });
3176  return {(it != std::end(setref)), it};
3177 }
3178 
3179 /// A search function that uses the built in find function
3181 auto search(const T &set, const V &val) -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3182  auto &setref = detail::smart_deref(set);
3183  auto it = setref.find(val);
3184  return {(it != std::end(setref)), it};
3185 }
3186 
3187 /// A search function with a filter function
3188 template <typename T, typename V>
3189 auto search(const T &set, const V &val, const std::function<V(V)> &filter_function)
3190  -> std::pair<bool, decltype(std::begin(detail::smart_deref(set)))> {
3191  using element_t = typename detail::element_type<T>::type;
3192  // do the potentially faster first search
3193  auto res = search(set, val);
3194  if((res.first) || (!(filter_function))) {
3195  return res;
3196  }
3197  // if we haven't found it do the longer linear search with all the element translations
3198  auto &setref = detail::smart_deref(set);
3199  auto it = std::find_if(std::begin(setref), std::end(setref), [&](decltype(*std::begin(setref)) v) {
3201  a = filter_function(a);
3202  return (a == val);
3203  });
3204  return {(it != std::end(setref)), it};
3205 }
3206 
3207 // the following suggestion was made by Nikita Ofitserov(@himikof)
3208 // done in templates to prevent compiler warnings on negation of unsigned numbers
3209 
3210 /// Do a check for overflow on signed numbers
3211 template <typename T>
3212 inline typename std::enable_if<std::is_signed<T>::value, T>::type overflowCheck(const T &a, const T &b) {
3213  if((a > 0) == (b > 0)) {
3214  return ((std::numeric_limits<T>::max)() / (std::abs)(a) < (std::abs)(b));
3215  }
3216  return ((std::numeric_limits<T>::min)() / (std::abs)(a) > -(std::abs)(b));
3217 }
3218 /// Do a check for overflow on unsigned numbers
3219 template <typename T>
3220 inline typename std::enable_if<!std::is_signed<T>::value, T>::type overflowCheck(const T &a, const T &b) {
3221  return ((std::numeric_limits<T>::max)() / a < b);
3222 }
3223 
3224 /// Performs a *= b; if it doesn't cause integer overflow. Returns false otherwise.
3225 template <typename T> typename std::enable_if<std::is_integral<T>::value, bool>::type checked_multiply(T &a, T b) {
3226  if(a == 0 || b == 0 || a == 1 || b == 1) {
3227  a *= b;
3228  return true;
3229  }
3230  if(a == (std::numeric_limits<T>::min)() || b == (std::numeric_limits<T>::min)()) {
3231  return false;
3232  }
3233  if(overflowCheck(a, b)) {
3234  return false;
3235  }
3236  a *= b;
3237  return true;
3238 }
3239 
3240 /// Performs a *= b; if it doesn't equal infinity. Returns false otherwise.
3241 template <typename T>
3243  T c = a * b;
3244  if(std::isinf(c) && !std::isinf(a) && !std::isinf(b)) {
3245  return false;
3246  }
3247  a = c;
3248  return true;
3249 }
3250 
3251 } // namespace detail
3252 /// Verify items are in a set
3253 class IsMember : public Validator {
3254  public:
3255  using filter_fn_t = std::function<std::string(std::string)>;
3256 
3257  /// This allows in-place construction using an initializer list
3258  template <typename T, typename... Args>
3259  IsMember(std::initializer_list<T> values, Args &&...args)
3260  : IsMember(std::vector<T>(values), std::forward<Args>(args)...) {}
3261 
3262  /// This checks to see if an item is in a set (empty function)
3263  template <typename T> explicit IsMember(T &&set) : IsMember(std::forward<T>(set), nullptr) {}
3264 
3265  /// This checks to see if an item is in a set: pointer or copy version. You can pass in a function that will filter
3266  /// both sides of the comparison before computing the comparison.
3267  template <typename T, typename F> explicit IsMember(T set, F filter_function) {
3268 
3269  // Get the type of the contained item - requires a container have ::value_type
3270  // if the type does not have first_type and second_type, these are both value_type
3271  using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3272  using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3273 
3274  using local_item_t = typename IsMemberType<item_t>::type; // This will convert bad types to good ones
3275  // (const char * to std::string)
3276 
3277  // Make a local copy of the filter function, using a std::function if not one already
3278  std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3279 
3280  // This is the type name for help, it will take the current version of the set contents
3281  desc_function_ = [set]() { return detail::generate_set(detail::smart_deref(set)); };
3282 
3283  // This is the function that validates
3284  // It stores a copy of the set pointer-like, so shared_ptr will stay alive
3285  func_ = [set, filter_fn](std::string &input) {
3286  local_item_t b;
3287  if(!detail::lexical_cast(input, b)) {
3288  throw ValidationError(input); // name is added later
3289  }
3290  if(filter_fn) {
3291  b = filter_fn(b);
3292  }
3293  auto res = detail::search(set, b, filter_fn);
3294  if(res.first) {
3295  // Make sure the version in the input string is identical to the one in the set
3296  if(filter_fn) {
3298  }
3299 
3300  // Return empty error string (success)
3301  return std::string{};
3302  }
3303 
3304  // If you reach this point, the result was not found
3305  return input + " not in " + detail::generate_set(detail::smart_deref(set));
3306  };
3307  }
3308 
3309  /// You can pass in as many filter functions as you like, they nest (string only currently)
3310  template <typename T, typename... Args>
3311  IsMember(T &&set, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3312  : IsMember(
3313  std::forward<T>(set),
3314  [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3315  other...) {}
3316 };
3317 
3318 /// definition of the default transformation object
3319 template <typename T> using TransformPairs = std::vector<std::pair<std::string, T>>;
3320 
3321 /// Translate named items to other or a value set
3322 class Transformer : public Validator {
3323  public:
3324  using filter_fn_t = std::function<std::string(std::string)>;
3325 
3326  /// This allows in-place construction
3327  template <typename... Args>
3328  Transformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
3329  : Transformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
3330 
3331  /// direct map of std::string to std::string
3332  template <typename T> explicit Transformer(T &&mapping) : Transformer(std::forward<T>(mapping), nullptr) {}
3333 
3334  /// This checks to see if an item is in a set: pointer or copy version. You can pass in a function that will filter
3335  /// both sides of the comparison before computing the comparison.
3336  template <typename T, typename F> explicit Transformer(T mapping, F filter_function) {
3337 
3338  static_assert(detail::pair_adaptor<typename detail::element_type<T>::type>::value,
3339  "mapping must produce value pairs");
3340  // Get the type of the contained item - requires a container have ::value_type
3341  // if the type does not have first_type and second_type, these are both value_type
3342  using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3343  using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3344  using local_item_t = typename IsMemberType<item_t>::type; // Will convert bad types to good ones
3345  // (const char * to std::string)
3346 
3347  // Make a local copy of the filter function, using a std::function if not one already
3348  std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3349 
3350  // This is the type name for help, it will take the current version of the set contents
3351  desc_function_ = [mapping]() { return detail::generate_map(detail::smart_deref(mapping)); };
3352 
3353  func_ = [mapping, filter_fn](std::string &input) {
3354  local_item_t b;
3355  if(!detail::lexical_cast(input, b)) {
3356  return std::string();
3357  // there is no possible way we can match anything in the mapping if we can't convert so just return
3358  }
3359  if(filter_fn) {
3360  b = filter_fn(b);
3361  }
3362  auto res = detail::search(mapping, b, filter_fn);
3363  if(res.first) {
3365  }
3366  return std::string{};
3367  };
3368  }
3369 
3370  /// You can pass in as many filter functions as you like, they nest
3371  template <typename T, typename... Args>
3372  Transformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3373  : Transformer(
3374  std::forward<T>(mapping),
3375  [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3376  other...) {}
3377 };
3378 
3379 /// translate named items to other or a value set
3381  public:
3382  using filter_fn_t = std::function<std::string(std::string)>;
3383 
3384  /// This allows in-place construction
3385  template <typename... Args>
3386  CheckedTransformer(std::initializer_list<std::pair<std::string, std::string>> values, Args &&...args)
3387  : CheckedTransformer(TransformPairs<std::string>(values), std::forward<Args>(args)...) {}
3388 
3389  /// direct map of std::string to std::string
3390  template <typename T> explicit CheckedTransformer(T mapping) : CheckedTransformer(std::move(mapping), nullptr) {}
3391 
3392  /// This checks to see if an item is in a set: pointer or copy version. You can pass in a function that will filter
3393  /// both sides of the comparison before computing the comparison.
3394  template <typename T, typename F> explicit CheckedTransformer(T mapping, F filter_function) {
3395 
3396  static_assert(detail::pair_adaptor<typename detail::element_type<T>::type>::value,
3397  "mapping must produce value pairs");
3398  // Get the type of the contained item - requires a container have ::value_type
3399  // if the type does not have first_type and second_type, these are both value_type
3400  using element_t = typename detail::element_type<T>::type; // Removes (smart) pointers if needed
3401  using item_t = typename detail::pair_adaptor<element_t>::first_type; // Is value_type if not a map
3402  using local_item_t = typename IsMemberType<item_t>::type; // Will convert bad types to good ones
3403  // (const char * to std::string)
3404  using iteration_type_t = typename detail::pair_adaptor<element_t>::value_type; // the type of the object pair
3405 
3406  // Make a local copy of the filter function, using a std::function if not one already
3407  std::function<local_item_t(local_item_t)> filter_fn = filter_function;
3408 
3409  auto tfunc = [mapping]() {
3410  std::string out("value in ");
3411  out += detail::generate_map(detail::smart_deref(mapping)) + " OR {";
3412  out += detail::join(
3413  detail::smart_deref(mapping),
3414  [](const iteration_type_t &v) { return detail::to_string(detail::pair_adaptor<element_t>::second(v)); },
3415  ",");
3416  out.push_back('}');
3417  return out;
3418  };
3419 
3420  desc_function_ = tfunc;
3421 
3422  func_ = [mapping, tfunc, filter_fn](std::string &input) {
3423  local_item_t b;
3424  bool converted = detail::lexical_cast(input, b);
3425  if(converted) {
3426  if(filter_fn) {
3427  b = filter_fn(b);
3428  }
3429  auto res = detail::search(mapping, b, filter_fn);
3430  if(res.first) {
3432  return std::string{};
3433  }
3434  }
3435  for(const auto &v : detail::smart_deref(mapping)) {
3437  if(output_string == input) {
3438  return std::string();
3439  }
3440  }
3441 
3442  return "Check " + input + " " + tfunc() + " FAILED";
3443  };
3444  }
3445 
3446  /// You can pass in as many filter functions as you like, they nest
3447  template <typename T, typename... Args>
3448  CheckedTransformer(T &&mapping, filter_fn_t filter_fn_1, filter_fn_t filter_fn_2, Args &&...other)
3450  std::forward<T>(mapping),
3451  [filter_fn_1, filter_fn_2](std::string a) { return filter_fn_2(filter_fn_1(a)); },
3452  other...) {}
3453 };
3454 
3455 /// Helper function to allow ignore_case to be passed to IsMember or Transform
3456 inline std::string ignore_case(std::string item) { return detail::to_lower(item); }
3457 
3458 /// Helper function to allow ignore_underscore to be passed to IsMember or Transform
3460 
3461 /// Helper function to allow checks to ignore spaces to be passed to IsMember or Transform
3463  item.erase(std::remove(std::begin(item), std::end(item), ' '), std::end(item));
3464  item.erase(std::remove(std::begin(item), std::end(item), '\t'), std::end(item));
3465  return item;
3466 }
3467 
3468 /// Multiply a number by a factor using given mapping.
3469 /// Can be used to write transforms for SIZE or DURATION inputs.
3470 ///
3471 /// Example:
3472 /// With mapping = `{"b"->1, "kb"->1024, "mb"->1024*1024}`
3473 /// one can recognize inputs like "100", "12kb", "100 MB",
3474 /// that will be automatically transformed to 100, 14448, 104857600.
3475 ///
3476 /// Output number type matches the type in the provided mapping.
3477 /// Therefore, if it is required to interpret real inputs like "0.42 s",
3478 /// the mapping should be of a type <string, float> or <string, double>.
3479 class AsNumberWithUnit : public Validator {
3480  public:
3481  /// Adjust AsNumberWithUnit behavior.
3482  /// CASE_SENSITIVE/CASE_INSENSITIVE controls how units are matched.
3483  /// UNIT_OPTIONAL/UNIT_REQUIRED throws ValidationError
3484  /// if UNIT_REQUIRED is set and unit literal is not found.
3485  enum Options {
3486  CASE_SENSITIVE = 0,
3487  CASE_INSENSITIVE = 1,
3488  UNIT_OPTIONAL = 0,
3489  UNIT_REQUIRED = 2,
3490  DEFAULT = CASE_INSENSITIVE | UNIT_OPTIONAL
3491  };
3492 
3493  template <typename Number>
3494  explicit AsNumberWithUnit(std::map<std::string, Number> mapping,
3495  Options opts = DEFAULT,
3496  const std::string &unit_name = "UNIT") {
3497  description(generate_description<Number>(unit_name, opts));
3498  validate_mapping(mapping, opts);
3499 
3500  // transform function
3501  func_ = [mapping, opts](std::string &input) -> std::string {
3502  Number num{};
3503 
3504  detail::rtrim(input);
3505  if(input.empty()) {
3506  throw ValidationError("Input is empty");
3507  }
3508 
3509  // Find split position between number and prefix
3510  auto unit_begin = input.end();
3511  while(unit_begin > input.begin() && std::isalpha(*(unit_begin - 1), std::locale())) {
3512  --unit_begin;
3513  }
3514 
3515  std::string unit{unit_begin, input.end()};
3516  input.resize(static_cast<std::size_t>(std::distance(input.begin(), unit_begin)));
3517  detail::trim(input);
3518 
3519  if(opts & UNIT_REQUIRED && unit.empty()) {
3520  throw ValidationError("Missing mandatory unit");
3521  }
3522  if(opts & CASE_INSENSITIVE) {
3524  }
3525  if(unit.empty()) {
3526  if(!detail::lexical_cast(input, num)) {
3527  throw ValidationError(std::string("Value ") + input + " could not be converted to " +
3528  detail::type_name<Number>());
3529  }
3530  // No need to modify input if no unit passed
3531  return {};
3532  }
3533 
3534  // find corresponding factor
3535  auto it = mapping.find(unit);
3536  if(it == mapping.end()) {
3537  throw ValidationError(unit +
3538  " unit not recognized. "
3539  "Allowed values: " +
3540  detail::generate_map(mapping, true));
3541  }
3542 
3543  if(!input.empty()) {
3544  bool converted = detail::lexical_cast(input, num);
3545  if(!converted) {
3546  throw ValidationError(std::string("Value ") + input + " could not be converted to " +
3547  detail::type_name<Number>());
3548  }
3549  // perform safe multiplication
3550  bool ok = detail::checked_multiply(num, it->second);
3551  if(!ok) {
3552  throw ValidationError(detail::to_string(num) + " multiplied by " + unit +
3553  " factor would cause number overflow. Use smaller value.");
3554  }
3555  } else {
3556  num = static_cast<Number>(it->second);
3557  }
3558 
3559  input = detail::to_string(num);
3560 
3561  return {};
3562  };
3563  }
3564 
3565  private:
3566  /// Check that mapping contains valid units.
3567  /// Update mapping for CASE_INSENSITIVE mode.
3568  template <typename Number> static void validate_mapping(std::map<std::string, Number> &mapping, Options opts) {
3569  for(auto &kv : mapping) {
3570  if(kv.first.empty()) {
3571  throw ValidationError("Unit must not be empty.");
3572  }
3573  if(!detail::isalpha(kv.first)) {
3574  throw ValidationError("Unit must contain only letters.");
3575  }
3576  }
3577 
3578  // make all units lowercase if CASE_INSENSITIVE
3579  if(opts & CASE_INSENSITIVE) {
3580  std::map<std::string, Number> lower_mapping;
3581  for(auto &kv : mapping) {
3582  auto s = detail::to_lower(kv.first);
3583  if(lower_mapping.count(s)) {
3584  throw ValidationError(std::string("Several matching lowercase unit representations are found: ") +
3585  s);
3586  }
3587  lower_mapping[detail::to_lower(kv.first)] = kv.second;
3588  }
3589  mapping = std::move(lower_mapping);
3590  }
3591  }
3592 
3593  /// Generate description like this: NUMBER [UNIT]
3594  template <typename Number> static std::string generate_description(const std::string &name, Options opts) {
3595  std::stringstream out;
3596  out << detail::type_name<Number>() << ' ';
3597  if(opts & UNIT_REQUIRED) {
3598  out << name;
3599  } else {
3600  out << '[' << name << ']';
3601  }
3602  return out.str();
3603  }
3604 };
3605 
3607  return static_cast<AsNumberWithUnit::Options>(static_cast<int>(a) | static_cast<int>(b));
3608 }
3609 
3610 /// Converts a human-readable size string (with unit literal) to uin64_t size.
3611 /// Example:
3612 /// "100" => 100
3613 /// "1 b" => 100
3614 /// "10Kb" => 10240 // you can configure this to be interpreted as kilobyte (*1000) or kibibyte (*1024)
3615 /// "10 KB" => 10240
3616 /// "10 kb" => 10240
3617 /// "10 kib" => 10240 // *i, *ib are always interpreted as *bibyte (*1024)
3618 /// "10kb" => 10240
3619 /// "2 MB" => 2097152
3620 /// "2 EiB" => 2^61 // Units up to exibyte are supported
3622  public:
3623  using result_t = std::uint64_t;
3624 
3625  /// If kb_is_1000 is true,
3626  /// interpret 'kb', 'k' as 1000 and 'kib', 'ki' as 1024
3627  /// (same applies to higher order units as well).
3628  /// Otherwise, interpret all literals as factors of 1024.
3629  /// The first option is formally correct, but
3630  /// the second interpretation is more wide-spread
3631  /// (see https://en.wikipedia.org/wiki/Binary_prefix).
3632  explicit AsSizeValue(bool kb_is_1000);
3633 
3634  private:
3635  /// Get <size unit, factor> mapping
3636  static std::map<std::string, result_t> init_mapping(bool kb_is_1000);
3637 
3638  /// Cache calculated mapping
3639  static std::map<std::string, result_t> get_mapping(bool kb_is_1000);
3640 };
3641 
3642 namespace detail {
3643 /// Split a string into a program name and command line arguments
3644 /// the string is assumed to contain a file name followed by other arguments
3645 /// the return value contains is a pair with the first argument containing the program name and the second
3646 /// everything else.
3647 CLI11_INLINE std::pair<std::string, std::string> split_program_name(std::string commandline);
3648 
3649 } // namespace detail
3650 /// @}
3651 
3652 
3653 
3654 
3656  std::string retstring;
3657  if(active_) {
3658  if(non_modifying_) {
3659  std::string value = str;
3660  retstring = func_(value);
3661  } else {
3662  retstring = func_(str);
3663  }
3664  }
3665  return retstring;
3666 }
3667 
3669  Validator newval(*this);
3670  newval.desc_function_ = [validator_desc]() { return validator_desc; };
3671  return newval;
3672 }
3673 
3675  Validator newval;
3676 
3677  newval._merge_description(*this, other, " AND ");
3678 
3679  // Give references (will make a copy in lambda function)
3680  const std::function<std::string(std::string & filename)> &f1 = func_;
3681  const std::function<std::string(std::string & filename)> &f2 = other.func_;
3682 
3683  newval.func_ = [f1, f2](std::string &input) {
3684  std::string s1 = f1(input);
3685  std::string s2 = f2(input);
3686  if(!s1.empty() && !s2.empty())
3687  return std::string("(") + s1 + ") AND (" + s2 + ")";
3688  return s1 + s2;
3689  };
3690 
3691  newval.active_ = active_ && other.active_;
3692  newval.application_index_ = application_index_;
3693  return newval;
3694 }
3695 
3697  Validator newval;
3698 
3699  newval._merge_description(*this, other, " OR ");
3700 
3701  // Give references (will make a copy in lambda function)
3702  const std::function<std::string(std::string &)> &f1 = func_;
3703  const std::function<std::string(std::string &)> &f2 = other.func_;
3704 
3705  newval.func_ = [f1, f2](std::string &input) {
3706  std::string s1 = f1(input);
3707  std::string s2 = f2(input);
3708  if(s1.empty() || s2.empty())
3709  return std::string();
3710 
3711  return std::string("(") + s1 + ") OR (" + s2 + ")";
3712  };
3713  newval.active_ = active_ && other.active_;
3714  newval.application_index_ = application_index_;
3715  return newval;
3716 }
3717 
3719  Validator newval;
3720  const std::function<std::string()> &dfunc1 = desc_function_;
3721  newval.desc_function_ = [dfunc1]() {
3722  auto str = dfunc1();
3723  return (!str.empty()) ? std::string("NOT ") + str : std::string{};
3724  };
3725  // Give references (will make a copy in lambda function)
3726  const std::function<std::string(std::string & res)> &f1 = func_;
3727 
3728  newval.func_ = [f1, dfunc1](std::string &test) -> std::string {
3729  std::string s1 = f1(test);
3730  if(s1.empty()) {
3731  return std::string("check ") + dfunc1() + " succeeded improperly";
3732  }
3733  return std::string{};
3734  };
3735  newval.active_ = active_;
3736  newval.application_index_ = application_index_;
3737  return newval;
3738 }
3739 
3740 CLI11_INLINE void
3741 Validator::_merge_description(const Validator &val1, const Validator &val2, const std::string &merger) {
3742 
3743  const std::function<std::string()> &dfunc1 = val1.desc_function_;
3744  const std::function<std::string()> &dfunc2 = val2.desc_function_;
3745 
3746  desc_function_ = [=]() {
3747  std::string f1 = dfunc1();
3748  std::string f2 = dfunc2();
3749  if((f1.empty()) || (f2.empty())) {
3750  return f1 + f2;
3751  }
3752  return std::string(1, '(') + f1 + ')' + merger + '(' + f2 + ')';
3753  };
3754 }
3755 
3756 namespace detail {
3757 
3758 #if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
3759 CLI11_INLINE path_type check_path(const char *file) noexcept {
3760  std::error_code ec;
3761  auto stat = std::filesystem::status(file, ec);
3762  if(ec) {
3763  return path_type::nonexistent;
3764  }
3765  switch(stat.type()) {
3766  case std::filesystem::file_type::none: // LCOV_EXCL_LINE
3767  case std::filesystem::file_type::not_found:
3768  return path_type::nonexistent;
3769  case std::filesystem::file_type::directory:
3770  return path_type::directory;
3771  case std::filesystem::file_type::symlink:
3772  case std::filesystem::file_type::block:
3773  case std::filesystem::file_type::character:
3774  case std::filesystem::file_type::fifo:
3775  case std::filesystem::file_type::socket:
3776  case std::filesystem::file_type::regular:
3777  case std::filesystem::file_type::unknown:
3778  default:
3779  return path_type::file;
3780  }
3781 }
3782 #else
3783 CLI11_INLINE path_type check_path(const char *file) noexcept {
3784 #if defined(_MSC_VER)
3785  struct __stat64 buffer;
3786  if(_stat64(file, &buffer) == 0) {
3787  return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
3788  }
3789 #else
3790  struct stat buffer;
3791  if(stat(file, &buffer) == 0) {
3792  return ((buffer.st_mode & S_IFDIR) != 0) ? path_type::directory : path_type::file;
3793  }
3794 #endif
3795  return path_type::nonexistent;
3796 }
3797 #endif
3798 
3800  func_ = [](std::string &filename) {
3801  auto path_result = check_path(filename.c_str());
3802  if(path_result == path_type::nonexistent) {
3803  return "File does not exist: " + filename;
3804  }
3805  if(path_result == path_type::directory) {
3806  return "File is actually a directory: " + filename;
3807  }
3808  return std::string();
3809  };
3810 }
3811 
3813  func_ = [](std::string &filename) {
3814  auto path_result = check_path(filename.c_str());
3815  if(path_result == path_type::nonexistent) {
3816  return "Directory does not exist: " + filename;
3817  }
3818  if(path_result == path_type::file) {
3819  return "Directory is actually a file: " + filename;
3820  }
3821  return std::string();
3822  };
3823 }
3824 
3826  func_ = [](std::string &filename) {
3827  auto path_result = check_path(filename.c_str());
3828  if(path_result == path_type::nonexistent) {
3829  return "Path does not exist: " + filename;
3830  }
3831  return std::string();
3832  };
3833 }
3834 
3836  func_ = [](std::string &filename) {
3837  auto path_result = check_path(filename.c_str());
3838  if(path_result != path_type::nonexistent) {
3839  return "Path already exists: " + filename;
3840  }
3841  return std::string();
3842  };
3843 }
3844 
3846  func_ = [](std::string &ip_addr) {
3847  auto result = CLI::detail::split(ip_addr, '.');
3848  if(result.size() != 4) {
3849  return std::string("Invalid IPV4 address must have four parts (") + ip_addr + ')';
3850  }
3851  int num = 0;
3852  for(const auto &var : result) {
3853  bool retval = detail::lexical_cast(var, num);
3854  if(!retval) {
3855  return std::string("Failed parsing number (") + var + ')';
3856  }
3857  if(num < 0 || num > 255) {
3858  return std::string("Each IP number must be between 0 and 255 ") + var;
3859  }
3860  }
3861  return std::string();
3862  };
3863 }
3864 
3865 } // namespace detail
3866 
3868  : Validator("FILE") {
3869  func_ = [default_path, enableErrorReturn](std::string &filename) {
3870  auto path_result = detail::check_path(filename.c_str());
3871  if(path_result == detail::path_type::nonexistent) {
3872  std::string test_file_path = default_path;
3873  if(default_path.back() != '/' && default_path.back() != '\\') {
3874  // Add folder separator
3875  test_file_path += '/';
3876  }
3877  test_file_path.append(filename);
3878  path_result = detail::check_path(test_file_path.c_str());
3879  if(path_result == detail::path_type::file) {
3880  filename = test_file_path;
3881  } else {
3882  if(enableErrorReturn) {
3883  return "File does not exist: " + filename;
3884  }
3885  }
3886  }
3887  return std::string{};
3888  };
3889 }
3890 
3891 CLI11_INLINE AsSizeValue::AsSizeValue(bool kb_is_1000) : AsNumberWithUnit(get_mapping(kb_is_1000)) {
3892  if(kb_is_1000) {
3893  description("SIZE [b, kb(=1000b), kib(=1024b), ...]");
3894  } else {
3895  description("SIZE [b, kb(=1024b), ...]");
3896  }
3897 }
3898 
3899 CLI11_INLINE std::map<std::string, AsSizeValue::result_t> AsSizeValue::init_mapping(bool kb_is_1000) {
3900  std::map<std::string, result_t> m;
3901  result_t k_factor = kb_is_1000 ? 1000 : 1024;
3902  result_t ki_factor = 1024;
3903  result_t k = 1;
3904  result_t ki = 1;
3905  m["b"] = 1;
3906  for(std::string p : {"k", "m", "g", "t", "p", "e"}) {
3907  k *= k_factor;
3908  ki *= ki_factor;
3909  m[p] = k;
3910  m[p + "b"] = k;
3911  m[p + "i"] = ki;
3912  m[p + "ib"] = ki;
3913  }
3914  return m;
3915 }
3916 
3917 CLI11_INLINE std::map<std::string, AsSizeValue::result_t> AsSizeValue::get_mapping(bool kb_is_1000) {
3918  if(kb_is_1000) {
3919  static auto m = init_mapping(true);
3920  return m;
3921  }
3922  static auto m = init_mapping(false);
3923  return m;
3924 }
3925 
3926 namespace detail {
3927 
3928 CLI11_INLINE std::pair<std::string, std::string> split_program_name(std::string commandline) {
3929  // try to determine the programName
3930  std::pair<std::string, std::string> vals;
3931  trim(commandline);
3932  auto esp = commandline.find_first_of(' ', 1);
3933  while(detail::check_path(commandline.substr(0, esp).c_str()) != path_type::file) {
3934  esp = commandline.find_first_of(' ', esp + 1);
3935  if(esp == std::string::npos) {
3936  // if we have reached the end and haven't found a valid file just assume the first argument is the
3937  // program name
3938  if(commandline[0] == '"' || commandline[0] == '\'' || commandline[0] == '`') {
3939  bool embeddedQuote = false;
3940  auto keyChar = commandline[0];
3941  auto end = commandline.find_first_of(keyChar, 1);
3942  while((end != std::string::npos) && (commandline[end - 1] == '\\')) { // deal with escaped quotes
3943  end = commandline.find_first_of(keyChar, end + 1);
3944  embeddedQuote = true;
3945  }
3946  if(end != std::string::npos) {
3947  vals.first = commandline.substr(1, end - 1);
3948  esp = end + 1;
3949  if(embeddedQuote) {
3950  vals.first = find_and_replace(vals.first, std::string("\\") + keyChar, std::string(1, keyChar));
3951  }
3952  } else {
3953  esp = commandline.find_first_of(' ', 1);
3954  }
3955  } else {
3956  esp = commandline.find_first_of(' ', 1);
3957  }
3958 
3959  break;
3960  }
3961  }
3962  if(vals.first.empty()) {
3963  vals.first = commandline.substr(0, esp);
3964  rtrim(vals.first);
3965  }
3966 
3967  // strip the program name
3968  vals.second = (esp < commandline.length() - 1) ? commandline.substr(esp + 1) : std::string{};
3969  ltrim(vals.second);
3970  return vals;
3971 }
3972 
3973 } // namespace detail
3974 /// @}
3975 
3976 
3977 
3978 
3979 class Option;
3980 class App;
3981 
3982 /// This enum signifies the type of help requested
3983 ///
3984 /// This is passed in by App; all user classes must accept this as
3985 /// the second argument.
3986 
3987 enum class AppFormatMode {
3988  Normal, ///< The normal, detailed help
3989  All, ///< A fully expanded help
3990  Sub, ///< Used when printed as part of expanded subcommand
3991 };
3992 
3993 /// This is the minimum requirements to run a formatter.
3994 ///
3995 /// A user can subclass this is if they do not care at all
3996 /// about the structure in CLI::Formatter.
3998  protected:
3999  /// @name Options
4000  ///@{
4001 
4002  /// The width of the first column
4003  std::size_t column_width_{30};
4004 
4005  /// @brief The required help printout labels (user changeable)
4006  /// Values are Needs, Excludes, etc.
4007  std::map<std::string, std::string> labels_{};
4008 
4009  ///@}
4010  /// @name Basic
4011  ///@{
4012 
4013  public:
4014  FormatterBase() = default;
4015  FormatterBase(const FormatterBase &) = default;
4016  FormatterBase(FormatterBase &&) = default;
4017  FormatterBase &operator=(const FormatterBase &) = default;
4018  FormatterBase &operator=(FormatterBase &&) = default;
4019 
4020  /// Adding a destructor in this form to work around bug in GCC 4.7
4021  virtual ~FormatterBase() noexcept {} // NOLINT(modernize-use-equals-default)
4022 
4023  /// This is the key method that puts together help
4024  virtual std::string make_help(const App *, std::string, AppFormatMode) const = 0;
4025 
4026  ///@}
4027  /// @name Setters
4028  ///@{
4029 
4030  /// Set the "REQUIRED" label
4031  void label(std::string key, std::string val) { labels_[key] = val; }
4032 
4033  /// Set the column width
4034  void column_width(std::size_t val) { column_width_ = val; }
4035 
4036  ///@}
4037  /// @name Getters
4038  ///@{
4039 
4040  /// Get the current value of a name (REQUIRED, etc.)
4042  if(labels_.find(key) == labels_.end())
4043  return key;
4044  return labels_.at(key);
4045  }
4046 
4047  /// Get the current column width
4048  CLI11_NODISCARD std::size_t get_column_width() const { return column_width_; }
4049 
4050  ///@}
4051 };
4052 
4053 /// This is a specialty override for lambda functions
4054 class FormatterLambda final : public FormatterBase {
4055  using funct_t = std::function<std::string(const App *, std::string, AppFormatMode)>;
4056 
4057  /// The lambda to hold and run
4058  funct_t lambda_;
4059 
4060  public:
4061  /// Create a FormatterLambda with a lambda function
4062  explicit FormatterLambda(funct_t funct) : lambda_(std::move(funct)) {}
4063 
4064  /// Adding a destructor (mostly to make GCC 4.7 happy)
4065  ~FormatterLambda() noexcept override {} // NOLINT(modernize-use-equals-default)
4066 
4067  /// This will simply call the lambda function
4068  std::string make_help(const App *app, std::string name, AppFormatMode mode) const override {
4069  return lambda_(app, name, mode);
4070  }
4071 };
4072 
4073 /// This is the default Formatter for CLI11. It pretty prints help output, and is broken into quite a few
4074 /// overridable methods, to be highly customizable with minimal effort.
4075 class Formatter : public FormatterBase {
4076  public:
4077  Formatter() = default;
4078  Formatter(const Formatter &) = default;
4079  Formatter(Formatter &&) = default;
4080  Formatter &operator=(const Formatter &) = default;
4081  Formatter &operator=(Formatter &&) = default;
4082 
4083  /// @name Overridables
4084  ///@{
4085 
4086  /// This prints out a group of options with title
4087  ///
4089  make_group(std::string group, bool is_positional, std::vector<const Option *> opts) const;
4090 
4091  /// This prints out just the positionals "group"
4092  virtual std::string make_positionals(const App *app) const;
4093 
4094  /// This prints out all the groups of options
4095  std::string make_groups(const App *app, AppFormatMode mode) const;
4096 
4097  /// This prints out all the subcommands
4098  virtual std::string make_subcommands(const App *app, AppFormatMode mode) const;
4099 
4100  /// This prints out a subcommand
4101  virtual std::string make_subcommand(const App *sub) const;
4102 
4103  /// This prints out a subcommand in help-all
4104  virtual std::string make_expanded(const App *sub) const;
4105 
4106  /// This prints out all the groups of options
4107  virtual std::string make_footer(const App *app) const;
4108 
4109  /// This displays the description line
4110  virtual std::string make_description(const App *app) const;
4111 
4112  /// This displays the usage line
4113  virtual std::string make_usage(const App *app, std::string name) const;
4114 
4115  /// This puts everything together
4116  std::string make_help(const App * /*app*/, std::string, AppFormatMode) const override;
4117 
4118  ///@}
4119  /// @name Options
4120  ///@{
4121 
4122  /// This prints out an option help line, either positional or optional form
4123  virtual std::string make_option(const Option *opt, bool is_positional) const {
4124  std::stringstream out;
4126  out, make_option_name(opt, is_positional) + make_option_opts(opt), make_option_desc(opt), column_width_);
4127  return out.str();
4128  }
4129 
4130  /// @brief This is the name part of an option, Default: left column
4131  virtual std::string make_option_name(const Option *, bool) const;
4132 
4133  /// @brief This is the options part of the name, Default: combined into left column
4134  virtual std::string make_option_opts(const Option *) const;
4135 
4136  /// @brief This is the description. Default: Right column, on new line if left column too large
4137  virtual std::string make_option_desc(const Option *) const;
4138 
4139  /// @brief This is used to print the name on the USAGE line
4140  virtual std::string make_option_usage(const Option *opt) const;
4141 
4142  ///@}
4143 };
4144 
4145 
4146 
4147 
4148 using results_t = std::vector<std::string>;
4149 /// callback function definition
4150 using callback_t = std::function<bool(const results_t &)>;
4151 
4152 class Option;
4153 class App;
4154 
4155 using Option_p = std::unique_ptr<Option>;
4156 /// Enumeration of the multiOption Policy selection
4157 enum class MultiOptionPolicy : char {
4158  Throw, //!< Throw an error if any extra arguments were given
4159  TakeLast, //!< take only the last Expected number of arguments
4160  TakeFirst, //!< take only the first Expected number of arguments
4161  Join, //!< merge all the arguments together into a single string via the delimiter character default('\n')
4162  TakeAll, //!< just get all the passed argument regardless
4163  Sum //!< sum all the arguments together if numerical or concatenate directly without delimiter
4164 };
4165 
4166 /// This is the CRTP base class for Option and OptionDefaults. It was designed this way
4167 /// to share parts of the class; an OptionDefaults can copy to an Option.
4168 template <typename CRTP> class OptionBase {
4169  friend App;
4170 
4171  protected:
4172  /// The group membership
4174 
4175  /// True if this is a required option
4176  bool required_{false};
4177 
4178  /// Ignore the case when matching (option, not value)
4179  bool ignore_case_{false};
4180 
4181  /// Ignore underscores when matching (option, not value)
4182  bool ignore_underscore_{false};
4183 
4184  /// Allow this option to be given in a configuration file
4185  bool configurable_{true};
4186 
4187  /// Disable overriding flag values with '=value'
4189 
4190  /// Specify a delimiter character for vector arguments
4191  char delimiter_{'\0'};
4192 
4193  /// Automatically capture default value
4195 
4196  /// Policy for handling multiple arguments beyond the expected Max
4198 
4199  /// Copy the contents to another similar class (one based on OptionBase)
4200  template <typename T> void copy_to(T *other) const;
4201 
4202  public:
4203  // setters
4204 
4205  /// Changes the group membership
4206  CRTP *group(const std::string &name) {
4207  if(!detail::valid_alias_name_string(name)) {
4208  throw IncorrectConstruction("Group names may not contain newlines or null characters");
4209  }
4210  group_ = name;
4211  return static_cast<CRTP *>(this);
4212  }
4213 
4214  /// Set the option as required
4215  CRTP *required(bool value = true) {
4216  required_ = value;
4217  return static_cast<CRTP *>(this);
4218  }
4219 
4220  /// Support Plumbum term
4221  CRTP *mandatory(bool value = true) { return required(value); }
4222 
4223  CRTP *always_capture_default(bool value = true) {
4225  return static_cast<CRTP *>(this);
4226  }
4227 
4228  // Getters
4229 
4230  /// Get the group of this option
4231  CLI11_NODISCARD const std::string &get_group() const { return group_; }
4232 
4233  /// True if this is a required option
4234  CLI11_NODISCARD bool get_required() const { return required_; }
4235 
4236  /// The status of ignore case
4238 
4239  /// The status of ignore_underscore
4241 
4242  /// The status of configurable
4244 
4245  /// The status of configurable
4247 
4248  /// Get the current delimiter char
4249  CLI11_NODISCARD char get_delimiter() const { return delimiter_; }
4250 
4251  /// Return true if this will automatically capture the default value for help printing
4253 
4254  /// The status of the multi option policy
4256 
4257  // Shortcuts for multi option policy
4258 
4259  /// Set the multi option policy to take last
4260  CRTP *take_last() {
4261  auto *self = static_cast<CRTP *>(this);
4263  return self;
4264  }
4265 
4266  /// Set the multi option policy to take last
4267  CRTP *take_first() {
4268  auto *self = static_cast<CRTP *>(this);
4270  return self;
4271  }
4272 
4273  /// Set the multi option policy to take all arguments
4274  CRTP *take_all() {
4275  auto self = static_cast<CRTP *>(this);
4277  return self;
4278  }
4279 
4280  /// Set the multi option policy to join
4281  CRTP *join() {
4282  auto *self = static_cast<CRTP *>(this);
4284  return self;
4285  }
4286 
4287  /// Set the multi option policy to join with a specific delimiter
4288  CRTP *join(char delim) {
4289  auto self = static_cast<CRTP *>(this);
4290  self->delimiter_ = delim;
4291  self->multi_option_policy(MultiOptionPolicy::Join);
4292  return self;
4293  }
4294 
4295  /// Allow in a configuration file
4296  CRTP *configurable(bool value = true) {
4297  configurable_ = value;
4298  return static_cast<CRTP *>(this);
4299  }
4300 
4301  /// Allow in a configuration file
4302  CRTP *delimiter(char value = '\0') {
4303  delimiter_ = value;
4304  return static_cast<CRTP *>(this);
4305  }
4306 };
4307 
4308 /// This is a version of OptionBase that only supports setting values,
4309 /// for defaults. It is stored as the default option in an App.
4310 class OptionDefaults : public OptionBase<OptionDefaults> {
4311  public:
4312  OptionDefaults() = default;
4313 
4314  // Methods here need a different implementation if they are Option vs. OptionDefault
4315 
4316  /// Take the last argument if given multiple times
4319  return this;
4320  }
4321 
4322  /// Ignore the case of the option name
4323  OptionDefaults *ignore_case(bool value = true) {
4324  ignore_case_ = value;
4325  return this;
4326  }
4327 
4328  /// Ignore underscores in the option name
4329  OptionDefaults *ignore_underscore(bool value = true) {
4331  return this;
4332  }
4333 
4334  /// Disable overriding flag values with an '=<value>' segment
4337  return this;
4338  }
4339 
4340  /// set a delimiter character to split up single arguments to treat as multiple inputs
4341  OptionDefaults *delimiter(char value = '\0') {
4342  delimiter_ = value;
4343  return this;
4344  }
4345 };
4346 
4347 class Option : public OptionBase<Option> {
4348  friend App;
4349 
4350  protected:
4351  /// @name Names
4352  ///@{
4353 
4354  /// A list of the short names (`-a`) without the leading dashes
4355  std::vector<std::string> snames_{};
4356 
4357  /// A list of the long names (`--long`) without the leading dashes
4358  std::vector<std::string> lnames_{};
4359 
4360  /// A list of the flag names with the appropriate default value, the first part of the pair should be duplicates of
4361  /// what is in snames or lnames but will trigger a particular response on a flag
4362  std::vector<std::pair<std::string, std::string>> default_flag_values_{};
4363 
4364  /// a list of flag names with specified default values;
4365  std::vector<std::string> fnames_{};
4366 
4367  /// A positional name
4369 
4370  /// If given, check the environment for this option
4372 
4373  ///@}
4374  /// @name Help
4375  ///@{
4376 
4377  /// The description for help strings
4379 
4380  /// A human readable default value, either manually set, captured, or captured by default
4382 
4383  /// If given, replace the text that describes the option type and usage in the help text
4385 
4386  /// A human readable type value, set when App creates this
4387  ///
4388  /// This is a lambda function so "types" can be dynamic, such as when a set prints its contents.
4389  std::function<std::string()> type_name_{[]() { return std::string(); }};
4390 
4391  /// Run this function to capture a default (ignore if empty)
4392  std::function<std::string()> default_function_{};
4393 
4394  ///@}
4395  /// @name Configuration
4396  ///@{
4397 
4398  /// The number of arguments that make up one option. max is the nominal type size, min is the minimum number of
4399  /// strings
4401  /// The minimum number of arguments an option should be expecting
4403 
4404  /// The minimum number of expected values
4406  /// The maximum number of expected values
4408 
4409  /// A list of Validators to run on each value parsed
4410  std::vector<Validator> validators_{};
4411 
4412  /// A list of options that are required with this option
4413  std::set<Option *> needs_{};
4414 
4415  /// A list of options that are excluded with this option
4416  std::set<Option *> excludes_{};
4417 
4418  ///@}
4419  /// @name Other
4420  ///@{
4421 
4422  /// link back up to the parent App for fallthrough
4423  App *parent_{nullptr};
4424 
4425  /// Options store a callback to do all the work
4427 
4428  ///@}
4429  /// @name Parsing results
4430  ///@{
4431 
4432  /// complete Results of parsing
4434  /// results after reduction
4436  /// enumeration for the option state machine
4437  enum class option_state : char {
4438  parsing = 0, //!< The option is currently collecting parsed results
4439  validated = 2, //!< the results have been validated
4440  reduced = 4, //!< a subset of results has been generated
4441  callback_run = 6, //!< the callback has been executed
4442  };
4443  /// Whether the callback has run (needed for INI parsing)
4445  /// Specify that extra args beyond type_size_max should be allowed
4446  bool allow_extra_args_{false};
4447  /// Specify that the option should act like a flag vs regular option
4448  bool flag_like_{false};
4449  /// Control option to run the callback to set the default
4451  /// flag indicating a separator needs to be injected after each argument call
4452  bool inject_separator_{false};
4453  /// flag indicating that the option should trigger the validation and callback chain on each result when loaded
4454  bool trigger_on_result_{false};
4455  /// flag indicating that the option should force the callback regardless if any results present
4456  bool force_callback_{false};
4457  ///@}
4458 
4459  /// Making an option by hand is not defined, it must be made by the App class
4460  Option(std::string option_name, std::string option_description, callback_t callback, App *parent)
4461  : description_(std::move(option_description)), parent_(parent), callback_(std::move(callback)) {
4462  std::tie(snames_, lnames_, pname_) = detail::get_names(detail::split_names(option_name));
4463  }
4464 
4465  public:
4466  /// @name Basic
4467  ///@{
4468 
4469  Option(const Option &) = delete;
4470  Option &operator=(const Option &) = delete;
4471 
4472  /// Count the total number of times an option was passed
4473  CLI11_NODISCARD std::size_t count() const { return results_.size(); }
4474 
4475  /// True if the option was not passed
4476  CLI11_NODISCARD bool empty() const { return results_.empty(); }
4477 
4478  /// This bool operator returns true if any arguments were passed or the option callback is forced
4479  explicit operator bool() const { return !empty() || force_callback_; }
4480 
4481  /// Clear the parsed results (mostly for testing)
4482  void clear() {
4483  results_.clear();
4485  }
4486 
4487  ///@}
4488  /// @name Setting options
4489  ///@{
4490 
4491  /// Set the number of expected arguments
4492  Option *expected(int value);
4493 
4494  /// Set the range of expected arguments
4495  Option *expected(int value_min, int value_max);
4496 
4497  /// Set the value of allow_extra_args which allows extra value arguments on the flag or option to be included
4498  /// with each instance
4499  Option *allow_extra_args(bool value = true) {
4501  return this;
4502  }
4503  /// Get the current value of allow extra args
4505  /// Set the value of trigger_on_parse which specifies that the option callback should be triggered on every parse
4506  Option *trigger_on_parse(bool value = true) {
4508  return this;
4509  }
4510  /// The status of trigger on parse
4512 
4513  /// Set the value of force_callback
4514  Option *force_callback(bool value = true) {
4516  return this;
4517  }
4518  /// The status of force_callback
4520 
4521  /// Set the value of run_callback_for_default which controls whether the callback function should be called to set
4522  /// the default This is controlled automatically but could be manipulated by the user.
4523  Option *run_callback_for_default(bool value = true) {
4525  return this;
4526  }
4527  /// Get the current value of run_callback_for_default
4529 
4530  /// Adds a Validator with a built in type name
4531  Option *check(Validator validator, const std::string &validator_name = "");
4532 
4533  /// Adds a Validator. Takes a const string& and returns an error message (empty if conversion/check is okay).
4534  Option *check(std::function<std::string(const std::string &)> Validator,
4535  std::string Validator_description = "",
4536  std::string Validator_name = "");
4537 
4538  /// Adds a transforming Validator with a built in type name
4539  Option *transform(Validator Validator, const std::string &Validator_name = "");
4540 
4541  /// Adds a Validator-like function that can change result
4542  Option *transform(const std::function<std::string(std::string)> &func,
4543  std::string transform_description = "",
4544  std::string transform_name = "");
4545 
4546  /// Adds a user supplied function to run on each item passed in (communicate though lambda capture)
4547  Option *each(const std::function<void(std::string)> &func);
4548 
4549  /// Get a named Validator
4550  Validator *get_validator(const std::string &Validator_name = "");
4551 
4552  /// Get a Validator by index NOTE: this may not be the order of definition
4554 
4555  /// Sets required options
4557  if(opt != this) {
4558  needs_.insert(opt);
4559  }
4560  return this;
4561  }
4562 
4563  /// Can find a string if needed
4564  template <typename T = App> Option *needs(std::string opt_name) {
4565  auto opt = static_cast<T *>(parent_)->get_option_no_throw(opt_name);
4566  if(opt == nullptr) {
4567  throw IncorrectConstruction::MissingOption(opt_name);
4568  }
4569  return needs(opt);
4570  }
4571 
4572  /// Any number supported, any mix of string and Opt
4573  template <typename A, typename B, typename... ARG> Option *needs(A opt, B opt1, ARG... args) {
4574  needs(opt);
4575  return needs(opt1, args...); // NOLINT(readability-suspicious-call-argument)
4576  }
4577 
4578  /// Remove needs link from an option. Returns true if the option really was in the needs list.
4579  bool remove_needs(Option *opt);
4580 
4581  /// Sets excluded options
4582  Option *excludes(Option *opt);
4583 
4584  /// Can find a string if needed
4585  template <typename T = App> Option *excludes(std::string opt_name) {
4586  auto opt = static_cast<T *>(parent_)->get_option_no_throw(opt_name);
4587  if(opt == nullptr) {
4588  throw IncorrectConstruction::MissingOption(opt_name);
4589  }
4590  return excludes(opt);
4591  }
4592 
4593  /// Any number supported, any mix of string and Opt
4594  template <typename A, typename B, typename... ARG> Option *excludes(A opt, B opt1, ARG... args) {
4595  excludes(opt);
4596  return excludes(opt1, args...);
4597  }
4598 
4599  /// Remove needs link from an option. Returns true if the option really was in the needs list.
4600  bool remove_excludes(Option *opt);
4601 
4602  /// Sets environment variable to read if no option given
4604  envname_ = std::move(name);
4605  return this;
4606  }
4607 
4608  /// Ignore case
4609  ///
4610  /// The template hides the fact that we don't have the definition of App yet.
4611  /// You are never expected to add an argument to the template here.
4612  template <typename T = App> Option *ignore_case(bool value = true);
4613 
4614  /// Ignore underscores in the option names
4615  ///
4616  /// The template hides the fact that we don't have the definition of App yet.
4617  /// You are never expected to add an argument to the template here.
4618  template <typename T = App> Option *ignore_underscore(bool value = true);
4619 
4620  /// Take the last argument if given multiple times (or another policy)
4622 
4623  /// Disable flag overrides values, e.g. --flag=<value> is not allowed
4624  Option *disable_flag_override(bool value = true) {
4626  return this;
4627  }
4628  ///@}
4629  /// @name Accessors
4630  ///@{
4631 
4632  /// The number of arguments the option expects
4634 
4635  /// The minimum number of arguments the option expects
4637  /// The maximum number of arguments the option expects
4639 
4640  /// Return the inject_separator flag
4642 
4643  /// The environment variable associated to this value
4645 
4646  /// The set of options needed
4647  CLI11_NODISCARD std::set<Option *> get_needs() const { return needs_; }
4648 
4649  /// The set of options excluded
4650  CLI11_NODISCARD std::set<Option *> get_excludes() const { return excludes_; }
4651 
4652  /// The default value (for help printing)
4654 
4655  /// Get the callback function
4657 
4658  /// Get the long names
4659  CLI11_NODISCARD const std::vector<std::string> &get_lnames() const { return lnames_; }
4660 
4661  /// Get the short names
4662  CLI11_NODISCARD const std::vector<std::string> &get_snames() const { return snames_; }
4663 
4664  /// Get the flag names with specified default values
4665  CLI11_NODISCARD const std::vector<std::string> &get_fnames() const { return fnames_; }
4666  /// Get a single name for the option, first of lname, pname, sname, envname
4668  if(!lnames_.empty()) {
4669  return lnames_[0];
4670  }
4671  if(!pname_.empty()) {
4672  return pname_;
4673  }
4674  if(!snames_.empty()) {
4675  return snames_[0];
4676  }
4677  return envname_;
4678  }
4679  /// The number of times the option expects to be included
4681 
4682  /// The number of times the option expects to be included
4684  /// The max number of times the option expects to be included
4686 
4687  /// The total min number of expected string values to be used
4689 
4690  /// Get the maximum number of items expected to be returned and used for the callback
4692  int t = type_size_max_;
4694  }
4695  /// The total min number of expected string values to be used
4697 
4698  /// True if the argument can be given directly
4699  CLI11_NODISCARD bool get_positional() const { return pname_.length() > 0; }
4700 
4701  /// True if option has at least one non-positional name
4702  CLI11_NODISCARD bool nonpositional() const { return (snames_.size() + lnames_.size()) > 0; }
4703 
4704  /// True if option has description
4705  CLI11_NODISCARD bool has_description() const { return description_.length() > 0; }
4706 
4707  /// Get the description
4709 
4710  /// Set the description
4711  Option *description(std::string option_description) {
4712  description_ = std::move(option_description);
4713  return this;
4714  }
4715 
4717  option_text_ = std::move(text);
4718  return this;
4719  }
4720 
4722 
4723  ///@}
4724  /// @name Help tools
4725  ///@{
4726 
4727  /// \brief Gets a comma separated list of names.
4728  /// Will include / prefer the positional name if positional is true.
4729  /// If all_options is false, pick just the most descriptive name to show.
4730  /// Use `get_name(true)` to get the positional name (replaces `get_pname`)
4731  CLI11_NODISCARD std::string get_name(bool positional = false, ///< Show the positional name
4732  bool all_options = false ///< Show every option
4733  ) const;
4734 
4735  ///@}
4736  /// @name Parser tools
4737  ///@{
4738 
4739  /// Process the callback
4740  void run_callback();
4741 
4742  /// If options share any of the same names, find it
4743  CLI11_NODISCARD const std::string &matching_name(const Option &other) const;
4744 
4745  /// If options share any of the same names, they are equal (not counting positional)
4746  bool operator==(const Option &other) const { return !matching_name(other).empty(); }
4747 
4748  /// Check a name. Requires "-" or "--" for short / long, supports positional name
4749  CLI11_NODISCARD bool check_name(const std::string &name) const;
4750 
4751  /// Requires "-" to be removed from string
4753  return (detail::find_member(std::move(name), snames_, ignore_case_) >= 0);
4754  }
4755 
4756  /// Requires "--" to be removed from string
4758  return (detail::find_member(std::move(name), lnames_, ignore_case_, ignore_underscore_) >= 0);
4759  }
4760 
4761  /// Requires "--" to be removed from string
4763  if(fnames_.empty()) {
4764  return false;
4765  }
4766  return (detail::find_member(std::move(name), fnames_, ignore_case_, ignore_underscore_) >= 0);
4767  }
4768 
4769  /// Get the value that goes for a flag, nominally gets the default value but allows for overrides if not
4770  /// disabled
4771  CLI11_NODISCARD std::string get_flag_value(const std::string &name, std::string input_value) const;
4772 
4773  /// Puts a result at the end
4775 
4776  /// Puts a result at the end and get a count of the number of arguments actually added
4777  Option *add_result(std::string s, int &results_added);
4778 
4779  /// Puts a result at the end
4780  Option *add_result(std::vector<std::string> s);
4781 
4782  /// Get the current complete results set
4783  CLI11_NODISCARD const results_t &results() const { return results_; }
4784 
4785  /// Get a copy of the results
4787 
4788  /// Get the results as a specified type
4789  template <typename T> void results(T &output) const {
4790  bool retval = false;
4791  if(current_option_state_ >= option_state::reduced || (results_.size() == 1 && validators_.empty())) {
4792  const results_t &res = (proc_results_.empty()) ? results_ : proc_results_;
4793  retval = detail::lexical_conversion<T, T>(res, output);
4794  } else {
4795  results_t res;
4796  if(results_.empty()) {
4797  if(!default_str_.empty()) {
4798  // _add_results takes an rvalue only
4799  _add_result(std::string(default_str_), res);
4800  _validate_results(res);
4801  results_t extra;
4802  _reduce_results(extra, res);
4803  if(!extra.empty()) {
4804  res = std::move(extra);
4805  }
4806  } else {
4807  res.emplace_back();
4808  }
4809  } else {
4810  res = reduced_results();
4811  }
4812  retval = detail::lexical_conversion<T, T>(res, output);
4813  }
4814  if(!retval) {
4815  throw ConversionError(get_name(), results_);
4816  }
4817  }
4818 
4819  /// Return the results as the specified type
4820  template <typename T> CLI11_NODISCARD T as() const {
4821  T output;
4822  results(output);
4823  return output;
4824  }
4825 
4826  /// See if the callback has been run already
4828 
4829  ///@}
4830  /// @name Custom options
4831  ///@{
4832 
4833  /// Set the type function to run when displayed on this option
4834  Option *type_name_fn(std::function<std::string()> typefun) {
4835  type_name_ = std::move(typefun);
4836  return this;
4837  }
4838 
4839  /// Set a custom option typestring
4841  type_name_fn([typeval]() { return typeval; });
4842  return this;
4843  }
4844 
4845  /// Set a custom option size
4846  Option *type_size(int option_type_size);
4847 
4848  /// Set a custom option type size range
4849  Option *type_size(int option_type_size_min, int option_type_size_max);
4850 
4851  /// Set the value of the separator injection flag
4852  void inject_separator(bool value = true) { inject_separator_ = value; }
4853 
4854  /// Set a capture function for the default. Mostly used by App.
4855  Option *default_function(const std::function<std::string()> &func) {
4857  return this;
4858  }
4859 
4860  /// Capture the default value from the original value (if it can be captured)
4862  if(default_function_) {
4864  }
4865  return this;
4866  }
4867 
4868  /// Set the default value string representation (does not change the contained value)
4870  default_str_ = std::move(val);
4871  return this;
4872  }
4873 
4874  /// Set the default value and validate the results and run the callback if appropriate to set the value into the
4875  /// bound value only available for types that can be converted to a string
4876  template <typename X> Option *default_val(const X &val) {
4877  std::string val_str = detail::to_string(val);
4878  auto old_option_state = current_option_state_;
4879  results_t old_results{std::move(results_)};
4880  results_.clear();
4881  try {
4882  add_result(val_str);
4883  // if trigger_on_result_ is set the callback already ran
4885  run_callback(); // run callback sets the state, we need to reset it again
4887  } else {
4888  _validate_results(results_);
4889  current_option_state_ = old_option_state;
4890  }
4891  } catch(const CLI::Error &) {
4892  // this should be done
4893  results_ = std::move(old_results);
4894  current_option_state_ = old_option_state;
4895  throw;
4896  }
4897  results_ = std::move(old_results);
4898  default_str_ = std::move(val_str);
4899  return this;
4900  }
4901 
4902  /// Get the full typename for this option
4904 
4905  private:
4906  /// Run the results through the Validators
4907  void _validate_results(results_t &res) const;
4908 
4909  /** reduce the results in accordance with the MultiOptionPolicy
4910  @param[out] out results are assigned to res if there if they are different
4911  */
4912  void _reduce_results(results_t &out, const results_t &original) const;
4913 
4914  // Run a result through the Validators
4915  std::string _validate(std::string &result, int index) const;
4916 
4917  /// Add a single result to the result set, taking into account delimiters
4918  int _add_result(std::string &&result, std::vector<std::string> &res) const;
4919 };
4920 
4921 
4922 
4923 
4924 template <typename CRTP> template <typename T> void OptionBase<CRTP>::copy_to(T *other) const {
4925  other->group(group_);
4926  other->required(required_);
4927  other->ignore_case(ignore_case_);
4928  other->ignore_underscore(ignore_underscore_);
4929  other->configurable(configurable_);
4930  other->disable_flag_override(disable_flag_override_);
4931  other->delimiter(delimiter_);
4932  other->always_capture_default(always_capture_default_);
4933  other->multi_option_policy(multi_option_policy_);
4934 }
4935 
4937  if(value < 0) {
4938  expected_min_ = -value;
4941  }
4942  allow_extra_args_ = true;
4943  flag_like_ = false;
4944  } else if(value == detail::expected_max_vector_size) {
4945  expected_min_ = 1;
4947  allow_extra_args_ = true;
4948  flag_like_ = false;
4949  } else {
4950  expected_min_ = value;
4951  expected_max_ = value;
4952  flag_like_ = (expected_min_ == 0);
4953  }
4954  return this;
4955 }
4956 
4957 CLI11_INLINE Option *Option::expected(int value_min, int value_max) {
4958  if(value_min < 0) {
4959  value_min = -value_min;
4960  }
4961 
4962  if(value_max < 0) {
4964  }
4965  if(value_max < value_min) {
4966  expected_min_ = value_max;
4967  expected_max_ = value_min;
4968  } else {
4969  expected_max_ = value_max;
4970  expected_min_ = value_min;
4971  }
4972 
4973  return this;
4974 }
4975 
4976 CLI11_INLINE Option *Option::check(Validator validator, const std::string &validator_name) {
4977  validator.non_modifying();
4978  validators_.push_back(std::move(validator));
4979  if(!validator_name.empty())
4980  validators_.back().name(validator_name);
4981  return this;
4982 }
4983 
4985  std::string Validator_description,
4986  std::string Validator_name) {
4987  validators_.emplace_back(Validator, std::move(Validator_description), std::move(Validator_name));
4988  validators_.back().non_modifying();
4989  return this;
4990 }
4991 
4993  validators_.insert(validators_.begin(), std::move(Validator));
4994  if(!Validator_name.empty())
4995  validators_.front().name(Validator_name);
4996  return this;
4997 }
4998 
5000  std::string transform_description,
5001  std::string transform_name) {
5002  validators_.insert(validators_.begin(),
5003  Validator(
5004  [func](std::string &val) {
5005  val = func(val);
5006  return std::string{};
5007  },
5008  std::move(transform_description),
5009  std::move(transform_name)));
5010 
5011  return this;
5012 }
5013 
5014 CLI11_INLINE Option *Option::each(const std::function<void(std::string)> &func) {
5015  validators_.emplace_back(
5016  [func](std::string &inout) {
5017  func(inout);
5018  return std::string{};
5019  },
5020  std::string{});
5021  return this;
5022 }
5023 
5025  for(auto &Validator : validators_) {
5026  if(Validator_name == Validator.get_name()) {
5027  return &Validator;
5028  }
5029  }
5030  if((Validator_name.empty()) && (!validators_.empty())) {
5031  return &(validators_.front());
5032  }
5033  throw OptionNotFound(std::string{"Validator "} + Validator_name + " Not Found");
5034 }
5035 
5037  // This is an signed int so that it is not equivalent to a pointer.
5038  if(index >= 0 && index < static_cast<int>(validators_.size())) {
5039  return &(validators_[static_cast<decltype(validators_)::size_type>(index)]);
5040  }
5041  throw OptionNotFound("Validator index is not valid");
5042 }
5043 
5045  auto iterator = std::find(std::begin(needs_), std::end(needs_), opt);
5046 
5047  if(iterator == std::end(needs_)) {
5048  return false;
5049  }
5050  needs_.erase(iterator);
5051  return true;
5052 }
5053 
5055  if(opt == this) {
5056  throw(IncorrectConstruction("and option cannot exclude itself"));
5057  }
5058  excludes_.insert(opt);
5059 
5060  // Help text should be symmetric - excluding a should exclude b
5061  opt->excludes_.insert(this);
5062 
5063  // Ignoring the insert return value, excluding twice is now allowed.
5064  // (Mostly to allow both directions to be excluded by user, even though the library does it for you.)
5065 
5066  return this;
5067 }
5068 
5070  auto iterator = std::find(std::begin(excludes_), std::end(excludes_), opt);
5071 
5072  if(iterator == std::end(excludes_)) {
5073  return false;
5074  }
5075  excludes_.erase(iterator);
5076  return true;
5077 }
5078 
5079 template <typename T> Option *Option::ignore_case(bool value) {
5080  if(!ignore_case_ && value) {
5081  ignore_case_ = value;
5082  auto *parent = static_cast<T *>(parent_);
5083  for(const Option_p &opt : parent->options_) {
5084  if(opt.get() == this) {
5085  continue;
5086  }
5087  const auto &omatch = opt->matching_name(*this);
5088  if(!omatch.empty()) {
5089  ignore_case_ = false;
5090  throw OptionAlreadyAdded("adding ignore case caused a name conflict with " + omatch);
5091  }
5092  }
5093  } else {
5094  ignore_case_ = value;
5095  }
5096  return this;
5097 }
5098 
5099 template <typename T> Option *Option::ignore_underscore(bool value) {
5100 
5101  if(!ignore_underscore_ && value) {
5103  auto *parent = static_cast<T *>(parent_);
5104  for(const Option_p &opt : parent->options_) {
5105  if(opt.get() == this) {
5106  continue;
5107  }
5108  const auto &omatch = opt->matching_name(*this);
5109  if(!omatch.empty()) {
5110  ignore_underscore_ = false;
5111  throw OptionAlreadyAdded("adding ignore underscore caused a name conflict with " + omatch);
5112  }
5113  }
5114  } else {
5116  }
5117  return this;
5118 }
5119 
5121  if(value != multi_option_policy_) {
5123  expected_min_ > 1) { // this bizarre condition is to maintain backwards compatibility
5124  // with the previous behavior of expected_ with vectors
5126  }
5129  }
5130  return this;
5131 }
5132 
5133 CLI11_NODISCARD CLI11_INLINE std::string Option::get_name(bool positional, bool all_options) const {
5134  if(get_group().empty())
5135  return {}; // Hidden
5136 
5137  if(all_options) {
5138 
5139  std::vector<std::string> name_list;
5140 
5141  /// The all list will never include a positional unless asked or that's the only name.
5142  if((positional && (!pname_.empty())) || (snames_.empty() && lnames_.empty())) {
5143  name_list.push_back(pname_);
5144  }
5145  if((get_items_expected() == 0) && (!fnames_.empty())) {
5146  for(const std::string &sname : snames_) {
5147  name_list.push_back("-" + sname);
5148  if(check_fname(sname)) {
5149  name_list.back() += "{" + get_flag_value(sname, "") + "}";
5150  }
5151  }
5152 
5153  for(const std::string &lname : lnames_) {
5154  name_list.push_back("--" + lname);
5155  if(check_fname(lname)) {
5156  name_list.back() += "{" + get_flag_value(lname, "") + "}";
5157  }
5158  }
5159  } else {
5160  for(const std::string &sname : snames_)
5161  name_list.push_back("-" + sname);
5162 
5163  for(const std::string &lname : lnames_)
5164  name_list.push_back("--" + lname);
5165  }
5166 
5167  return detail::join(name_list);
5168  }
5169 
5170  // This returns the positional name no matter what
5171  if(positional)
5172  return pname_;
5173 
5174  // Prefer long name
5175  if(!lnames_.empty())
5176  return std::string(2, '-') + lnames_[0];
5177 
5178  // Or short name if no long name
5179  if(!snames_.empty())
5180  return std::string(1, '-') + snames_[0];
5181 
5182  // If positional is the only name, it's okay to use that
5183  return pname_;
5184 }
5185 
5187  if(force_callback_ && results_.empty()) {
5189  }
5191  _validate_results(results_);
5193  }
5194 
5196  _reduce_results(proc_results_, results_);
5198  }
5201  if(!(callback_)) {
5202  return;
5203  }
5204  const results_t &send_results = proc_results_.empty() ? results_ : proc_results_;
5205  bool local_result = callback_(send_results);
5206 
5207  if(!local_result)
5208  throw ConversionError(get_name(), results_);
5209  }
5210 }
5211 
5213  static const std::string estring;
5214  for(const std::string &sname : snames_)
5215  if(other.check_sname(sname))
5216  return sname;
5217  for(const std::string &lname : lnames_)
5218  if(other.check_lname(lname))
5219  return lname;
5220 
5221  if(ignore_case_ ||
5222  ignore_underscore_) { // We need to do the inverse, in case we are ignore_case or ignore underscore
5223  for(const std::string &sname : other.snames_)
5224  if(check_sname(sname))
5225  return sname;
5226  for(const std::string &lname : other.lnames_)
5227  if(check_lname(lname))
5228  return lname;
5229  }
5230  return estring;
5231 }
5232 
5234 
5235  if(name.length() > 2 && name[0] == '-' && name[1] == '-')
5236  return check_lname(name.substr(2));
5237  if(name.length() > 1 && name.front() == '-')
5238  return check_sname(name.substr(1));
5239  if(!pname_.empty()) {
5240  std::string local_pname = pname_;
5241  std::string local_name = name;
5242  if(ignore_underscore_) {
5243  local_pname = detail::remove_underscore(local_pname);
5244  local_name = detail::remove_underscore(local_name);
5245  }
5246  if(ignore_case_) {
5247  local_pname = detail::to_lower(local_pname);
5248  local_name = detail::to_lower(local_name);
5249  }
5250  if(local_name == local_pname) {
5251  return true;
5252  }
5253  }
5254 
5255  if(!envname_.empty()) {
5256  // this needs to be the original since envname_ shouldn't match on case insensitivity
5257  return (name == envname_);
5258  }
5259  return false;
5260 }
5261 
5263  std::string input_value) const {
5264  static const std::string trueString{"true"};
5265  static const std::string falseString{"false"};
5266  static const std::string emptyString{"{}"};
5267  // check for disable flag override_
5269  if(!((input_value.empty()) || (input_value == emptyString))) {
5270  auto default_ind = detail::find_member(name, fnames_, ignore_case_, ignore_underscore_);
5271  if(default_ind >= 0) {
5272  // We can static cast this to std::size_t because it is more than 0 in this block
5273  if(default_flag_values_[static_cast<std::size_t>(default_ind)].second != input_value) {
5274  throw(ArgumentMismatch::FlagOverride(name));
5275  }
5276  } else {
5277  if(input_value != trueString) {
5278  throw(ArgumentMismatch::FlagOverride(name));
5279  }
5280  }
5281  }
5282  }
5284  if((input_value.empty()) || (input_value == emptyString)) {
5285  if(flag_like_) {
5286  return (ind < 0) ? trueString : default_flag_values_[static_cast<std::size_t>(ind)].second;
5287  }
5288  return (ind < 0) ? default_str_ : default_flag_values_[static_cast<std::size_t>(ind)].second;
5289  }
5290  if(ind < 0) {
5291  return input_value;
5292  }
5293  if(default_flag_values_[static_cast<std::size_t>(ind)].second == falseString) {
5294  try {
5295  auto val = detail::to_flag_value(input_value);
5296  return (val == 1) ? falseString : (val == (-1) ? trueString : std::to_string(-val));
5297  } catch(const std::invalid_argument &) {
5298  return input_value;
5299  }
5300  } else {
5301  return input_value;
5302  }
5303 }
5304 
5306  _add_result(std::move(s), results_);
5308  return this;
5309 }
5310 
5312  results_added = _add_result(std::move(s), results_);
5314  return this;
5315 }
5316 
5317 CLI11_INLINE Option *Option::add_result(std::vector<std::string> s) {
5319  for(auto &str : s) {
5320  _add_result(std::move(str), results_);
5321  }
5322  return this;
5323 }
5324 
5326  results_t res = proc_results_.empty() ? results_ : proc_results_;
5329  res = results_;
5330  _validate_results(res);
5331  }
5332  if(!res.empty()) {
5333  results_t extra;
5334  _reduce_results(extra, res);
5335  if(!extra.empty()) {
5336  res = std::move(extra);
5337  }
5338  }
5339  }
5340  return res;
5341 }
5342 
5343 CLI11_INLINE Option *Option::type_size(int option_type_size) {
5344  if(option_type_size < 0) {
5345  // this section is included for backwards compatibility
5346  type_size_max_ = -option_type_size;
5347  type_size_min_ = -option_type_size;
5349  } else {
5350  type_size_max_ = option_type_size;
5352  type_size_min_ = option_type_size;
5353  } else {
5354  inject_separator_ = true;
5355  }
5356  if(type_size_max_ == 0)
5357  required_ = false;
5358  }
5359  return this;
5360 }
5361 
5362 CLI11_INLINE Option *Option::type_size(int option_type_size_min, int option_type_size_max) {
5363  if(option_type_size_min < 0 || option_type_size_max < 0) {
5364  // this section is included for backwards compatibility
5366  option_type_size_min = (std::abs)(option_type_size_min);
5367  option_type_size_max = (std::abs)(option_type_size_max);
5368  }
5369 
5370  if(option_type_size_min > option_type_size_max) {
5371  type_size_max_ = option_type_size_min;
5372  type_size_min_ = option_type_size_max;
5373  } else {
5374  type_size_min_ = option_type_size_min;
5375  type_size_max_ = option_type_size_max;
5376  }
5377  if(type_size_max_ == 0) {
5378  required_ = false;
5379  }
5381  inject_separator_ = true;
5382  }
5383  return this;
5384 }
5385 
5387  std::string full_type_name = type_name_();
5388  if(!validators_.empty()) {
5389  for(const auto &Validator : validators_) {
5391  if(!vtype.empty()) {
5392  full_type_name += ":" + vtype;
5393  }
5394  }
5395  }
5396  return full_type_name;
5397 }
5398 
5399 CLI11_INLINE void Option::_validate_results(results_t &res) const {
5400  // Run the Validators (can change the string)
5401  if(!validators_.empty()) {
5402  if(type_size_max_ > 1) { // in this context index refers to the index in the type
5403  int index = 0;
5404  if(get_items_expected_max() < static_cast<int>(res.size()) &&
5406  // create a negative index for the earliest ones
5407  index = get_items_expected_max() - static_cast<int>(res.size());
5408  }
5409 
5410  for(std::string &result : res) {
5411  if(detail::is_separator(result) && type_size_max_ != type_size_min_ && index >= 0) {
5412  index = 0; // reset index for variable size chunks
5413  continue;
5414  }
5415  auto err_msg = _validate(result, (index >= 0) ? (index % type_size_max_) : index);
5416  if(!err_msg.empty())
5417  throw ValidationError(get_name(), err_msg);
5418  ++index;
5419  }
5420  } else {
5421  int index = 0;
5422  if(expected_max_ < static_cast<int>(res.size()) &&
5424  // create a negative index for the earliest ones
5425  index = expected_max_ - static_cast<int>(res.size());
5426  }
5427  for(std::string &result : res) {
5428  auto err_msg = _validate(result, index);
5429  ++index;
5430  if(!err_msg.empty())
5431  throw ValidationError(get_name(), err_msg);
5432  }
5433  }
5434  }
5435 }
5436 
5437 CLI11_INLINE void Option::_reduce_results(results_t &out, const results_t &original) const {
5438 
5439  // max num items expected or length of vector, always at least 1
5440  // Only valid for a trimming policy
5441 
5442  out.clear();
5443  // Operation depends on the policy setting
5444  switch(multi_option_policy_) {
5446  break;
5448  // Allow multi-option sizes (including 0)
5449  std::size_t trim_size = std::min<std::size_t>(
5450  static_cast<std::size_t>(std::max<int>(get_items_expected_max(), 1)), original.size());
5451  if(original.size() != trim_size) {
5452  out.assign(original.end() - static_cast<results_t::difference_type>(trim_size), original.end());
5453  }
5454  } break;
5456  std::size_t trim_size = std::min<std::size_t>(
5457  static_cast<std::size_t>(std::max<int>(get_items_expected_max(), 1)), original.size());
5458  if(original.size() != trim_size) {
5459  out.assign(original.begin(), original.begin() + static_cast<results_t::difference_type>(trim_size));
5460  }
5461  } break;
5463  if(results_.size() > 1) {
5464  out.push_back(detail::join(original, std::string(1, (delimiter_ == '\0') ? '\n' : delimiter_)));
5465  }
5466  break;
5468  out.push_back(detail::sum_string_vector(original));
5469  break;
5471  default: {
5472  auto num_min = static_cast<std::size_t>(get_items_expected_min());
5473  auto num_max = static_cast<std::size_t>(get_items_expected_max());
5474  if(num_min == 0) {
5475  num_min = 1;
5476  }
5477  if(num_max == 0) {
5478  num_max = 1;
5479  }
5480  if(original.size() < num_min) {
5481  throw ArgumentMismatch::AtLeast(get_name(), static_cast<int>(num_min), original.size());
5482  }
5483  if(original.size() > num_max) {
5484  throw ArgumentMismatch::AtMost(get_name(), static_cast<int>(num_max), original.size());
5485  }
5486  break;
5487  }
5488  }
5489  // this check is to allow an empty vector in certain circumstances but not if expected is not zero.
5490  // {} is the indicator for an empty container
5491  if(out.empty()) {
5492  if(original.size() == 1 && original[0] == "{}" && get_items_expected_min() > 0) {
5493  out.push_back("{}");
5494  out.push_back("%%");
5495  }
5496  } else if(out.size() == 1 && out[0] == "{}" && get_items_expected_min() > 0) {
5497  out.push_back("%%");
5498  }
5499 }
5500 
5501 CLI11_INLINE std::string Option::_validate(std::string &result, int index) const {
5502  std::string err_msg;
5503  if(result.empty() && expected_min_ == 0) {
5504  // an empty with nothing expected is allowed
5505  return err_msg;
5506  }
5507  for(const auto &vali : validators_) {
5508  auto v = vali.get_application_index();
5509  if(v == -1 || v == index) {
5510  try {
5511  err_msg = vali(result);
5512  } catch(const ValidationError &err) {
5513  err_msg = err.what();
5514  }
5515  if(!err_msg.empty())
5516  break;
5517  }
5518  }
5519 
5520  return err_msg;
5521 }
5522 
5523 CLI11_INLINE int Option::_add_result(std::string &&result, std::vector<std::string> &res) const {
5524  int result_count = 0;
5525  if(allow_extra_args_ && !result.empty() && result.front() == '[' &&
5526  result.back() == ']') { // this is now a vector string likely from the default or user entry
5527  result.pop_back();
5528 
5529  for(auto &var : CLI::detail::split(result.substr(1), ',')) {
5530  if(!var.empty()) {
5531  result_count += _add_result(std::move(var), res);
5532  }
5533  }
5534  return result_count;
5535  }
5536  if(delimiter_ == '\0') {
5537  res.push_back(std::move(result));
5538  ++result_count;
5539  } else {
5540  if((result.find_first_of(delimiter_) != std::string::npos)) {
5541  for(const auto &var : CLI::detail::split(result, delimiter_)) {
5542  if(!var.empty()) {
5543  res.push_back(var);
5544  ++result_count;
5545  }
5546  }
5547  } else {
5548  res.push_back(std::move(result));
5549  ++result_count;
5550  }
5551  }
5552  return result_count;
5553 }
5554 
5555 
5556 
5557 #ifndef CLI11_PARSE
5558 #define CLI11_PARSE(app, argc, argv) \
5559  try { \
5560  (app).parse((argc), (argv)); \
5561  } catch(const CLI::ParseError &e) { \
5562  return (app).exit(e); \
5563  }
5564 #endif
5565 
5566 namespace detail {
5568 struct AppFriend;
5569 } // namespace detail
5570 
5571 namespace FailureMessage {
5572 std::string simple(const App *app, const Error &e);
5573 std::string help(const App *app, const Error &e);
5574 } // namespace FailureMessage
5575 
5576 /// enumeration of modes of how to deal with extras in config files
5577 
5578 enum class config_extras_mode : char { error = 0, ignore, ignore_all, capture };
5579 
5580 class App;
5581 
5582 using App_p = std::shared_ptr<App>;
5583 
5584 namespace detail {
5585 /// helper functions for adding in appropriate flag modifiers for add_flag
5586 
5589  return opt->always_capture_default();
5590 }
5591 
5592 /// summing modifiers
5596 }
5597 
5598 } // namespace detail
5599 
5600 class Option_group;
5601 /// Creates a command line program, with very few defaults.
5602 /** To use, create a new `Program()` instance with `argc`, `argv`, and a help description. The templated
5603  * add_option methods make it easy to prepare options. Remember to call `.start` before starting your
5604  * program, so that the options can be evaluated and the help option doesn't accidentally run your program. */
5605 class App {
5606  friend Option;
5607  friend detail::AppFriend;
5608 
5609  protected:
5610  // This library follows the Google style guide for member names ending in underscores
5611 
5612  /// @name Basics
5613  ///@{
5614 
5615  /// Subcommand name or program name (from parser if name is empty)
5617 
5618  /// Description of the current program/subcommand
5620 
5621  /// If true, allow extra arguments (ie, don't throw an error). INHERITABLE
5622  bool allow_extras_{false};
5623 
5624  /// If ignore, allow extra arguments in the ini file (ie, don't throw an error). INHERITABLE
5625  /// if error error on an extra argument, and if capture feed it to the app
5627 
5628  /// If true, return immediately on an unrecognized option (implies allow_extras) INHERITABLE
5629  bool prefix_command_{false};
5630 
5631  /// If set to true the name was automatically generated from the command line vs a user set name
5632  bool has_automatic_name_{false};
5633 
5634  /// If set to true the subcommand is required to be processed and used, ignored for main app
5635  bool required_{false};
5636 
5637  /// If set to true the subcommand is disabled and cannot be used, ignored for main app
5638  bool disabled_{false};
5639 
5640  /// Flag indicating that the pre_parse_callback has been triggered
5641  bool pre_parse_called_{false};
5642 
5643  /// Flag indicating that the callback for the subcommand should be executed immediately on parse completion which is
5644  /// before help or ini files are processed. INHERITABLE
5645  bool immediate_callback_{false};
5646 
5647  /// This is a function that runs prior to the start of parsing
5648  std::function<void(std::size_t)> pre_parse_callback_{};
5649 
5650  /// This is a function that runs when parsing has finished.
5651  std::function<void()> parse_complete_callback_{};
5652 
5653  /// This is a function that runs when all processing has completed
5654  std::function<void()> final_callback_{};
5655 
5656  ///@}
5657  /// @name Options
5658  ///@{
5659 
5660  /// The default values for options, customizable and changeable INHERITABLE
5662 
5663  /// The list of options, stored locally
5664  std::vector<Option_p> options_{};
5665 
5666  ///@}
5667  /// @name Help
5668  ///@{
5669 
5670  /// Footer to put after all options in the help output INHERITABLE
5672 
5673  /// This is a function that generates a footer to put after all other options in help output
5674  std::function<std::string()> footer_callback_{};
5675 
5676  /// A pointer to the help flag if there is one INHERITABLE
5677  Option *help_ptr_{nullptr};
5678 
5679  /// A pointer to the help all flag if there is one INHERITABLE
5681 
5682  /// A pointer to a version flag if there is one
5684 
5685  /// This is the formatter for help printing. Default provided. INHERITABLE (same pointer)
5686  std::shared_ptr<FormatterBase> formatter_{new Formatter()};
5687 
5688  /// The error message printing function INHERITABLE
5689  std::function<std::string(const App *, const Error &e)> failure_message_{FailureMessage::simple};
5690 
5691  ///@}
5692  /// @name Parsing
5693  ///@{
5694 
5695  using missing_t = std::vector<std::pair<detail::Classifier, std::string>>;
5696 
5697  /// Pair of classifier, string for missing options. (extra detail is removed on returning from parse)
5698  ///
5699  /// This is faster and cleaner than storing just a list of strings and reparsing. This may contain the -- separator.
5701 
5702  /// This is a list of pointers to options with the original parse order
5703  std::vector<Option *> parse_order_{};
5704 
5705  /// This is a list of the subcommands collected, in order
5706  std::vector<App *> parsed_subcommands_{};
5707 
5708  /// this is a list of subcommands that are exclusionary to this one
5709  std::set<App *> exclude_subcommands_{};
5710 
5711  /// This is a list of options which are exclusionary to this App, if the options were used this subcommand should
5712  /// not be
5713  std::set<Option *> exclude_options_{};
5714 
5715  /// this is a list of subcommands or option groups that are required by this one, the list is not mutual, the
5716  /// listed subcommands do not require this one
5717  std::set<App *> need_subcommands_{};
5718 
5719  /// This is a list of options which are required by this app, the list is not mutual, listed options do not need the
5720  /// subcommand not be
5721  std::set<Option *> need_options_{};
5722 
5723  ///@}
5724  /// @name Subcommands
5725  ///@{
5726 
5727  /// Storage for subcommand list
5728  std::vector<App_p> subcommands_{};
5729 
5730  /// If true, the program name is not case sensitive INHERITABLE
5731  bool ignore_case_{false};
5732 
5733  /// If true, the program should ignore underscores INHERITABLE
5734  bool ignore_underscore_{false};
5735 
5736  /// Allow subcommand fallthrough, so that parent commands can collect commands after subcommand. INHERITABLE
5737  bool fallthrough_{false};
5738 
5739  /// Allow '/' for options for Windows like options. Defaults to true on Windows, false otherwise. INHERITABLE
5741 #ifdef _WIN32
5742  true
5743 #else
5744  false
5745 #endif
5746  };
5747  /// specify that positional arguments come at the end of the argument sequence not inheritable
5748  bool positionals_at_end_{false};
5749 
5750  enum class startup_mode : char { stable, enabled, disabled };
5751  /// specify the startup mode for the app
5752  /// stable=no change, enabled= startup enabled, disabled=startup disabled
5754 
5755  /// if set to true the subcommand can be triggered via configuration files INHERITABLE
5756  bool configurable_{false};
5757 
5758  /// If set to true positional options are validated before assigning INHERITABLE
5760 
5761  /// If set to true optional vector arguments are validated before assigning INHERITABLE
5763 
5764  /// indicator that the subcommand is silent and won't show up in subcommands list
5765  /// This is potentially useful as a modifier subcommand
5766  bool silent_{false};
5767 
5768  /// Counts the number of times this command/subcommand was parsed
5769  std::uint32_t parsed_{0U};
5770 
5771  /// Minimum required subcommands (not inheritable!)
5772  std::size_t require_subcommand_min_{0};
5773 
5774  /// Max number of subcommands allowed (parsing stops after this number). 0 is unlimited INHERITABLE
5775  std::size_t require_subcommand_max_{0};
5776 
5777  /// Minimum required options (not inheritable!)
5778  std::size_t require_option_min_{0};
5779 
5780  /// Max number of options allowed. 0 is unlimited (not inheritable)
5781  std::size_t require_option_max_{0};
5782 
5783  /// A pointer to the parent if this is a subcommand
5784  App *parent_{nullptr};
5785 
5786  /// The group membership INHERITABLE
5787  std::string group_{"Subcommands"};
5788 
5789  /// Alias names for the subcommand
5790  std::vector<std::string> aliases_{};
5791 
5792  ///@}
5793  /// @name Config
5794  ///@{
5795 
5796  /// Pointer to the config option
5797  Option *config_ptr_{nullptr};
5798 
5799  /// This is the formatter for help printing. Default provided. INHERITABLE (same pointer)
5800  std::shared_ptr<Config> config_formatter_{new ConfigTOML()};
5801 
5802  ///@}
5803 
5804  /// Special private constructor for subcommand
5805  App(std::string app_description, std::string app_name, App *parent);
5806 
5807  public:
5808  /// @name Basic
5809  ///@{
5810 
5811  /// Create a new program. Pass in the same arguments as main(), along with a help string.
5812  explicit App(std::string app_description = "", std::string app_name = "")
5813  : App(app_description, app_name, nullptr) {
5814  set_help_flag("-h,--help", "Print this help message and exit");
5815  }
5816 
5817  App(const App &) = delete;
5818  App &operator=(const App &) = delete;
5819 
5820  /// virtual destructor
5821  virtual ~App() = default;
5822 
5823  /// Set a callback for execution when all parsing and processing has completed
5824  ///
5825  /// Due to a bug in c++11,
5826  /// it is not possible to overload on std::function (fixed in c++14
5827  /// and backported to c++11 on newer compilers). Use capture by reference
5828  /// to get a pointer to App if needed.
5829  App *callback(std::function<void()> app_callback) {
5830  if(immediate_callback_) {
5831  parse_complete_callback_ = std::move(app_callback);
5832  } else {
5833  final_callback_ = std::move(app_callback);
5834  }
5835  return this;
5836  }
5837 
5838  /// Set a callback for execution when all parsing and processing has completed
5839  /// aliased as callback
5840  App *final_callback(std::function<void()> app_callback) {
5841  final_callback_ = std::move(app_callback);
5842  return this;
5843  }
5844 
5845  /// Set a callback to execute when parsing has completed for the app
5846  ///
5847  App *parse_complete_callback(std::function<void()> pc_callback) {
5848  parse_complete_callback_ = std::move(pc_callback);
5849  return this;
5850  }
5851 
5852  /// Set a callback to execute prior to parsing.
5853  ///
5854  App *preparse_callback(std::function<void(std::size_t)> pp_callback) {
5855  pre_parse_callback_ = std::move(pp_callback);
5856  return this;
5857  }
5858 
5859  /// Set a name for the app (empty will use parser to set the name)
5860  App *name(std::string app_name = "");
5861 
5862  /// Set an alias for the app
5863  App *alias(std::string app_name);
5864 
5865  /// Remove the error when extras are left over on the command line.
5866  App *allow_extras(bool allow = true) {
5867  allow_extras_ = allow;
5868  return this;
5869  }
5870 
5871  /// Remove the error when extras are left over on the command line.
5872  App *required(bool require = true) {
5873  required_ = require;
5874  return this;
5875  }
5876 
5877  /// Disable the subcommand or option group
5878  App *disabled(bool disable = true) {
5879  disabled_ = disable;
5880  return this;
5881  }
5882 
5883  /// silence the subcommand from showing up in the processed list
5884  App *silent(bool silence = true) {
5885  silent_ = silence;
5886  return this;
5887  }
5888 
5889  /// Set the subcommand to be disabled by default, so on clear(), at the start of each parse it is disabled
5890  App *disabled_by_default(bool disable = true) {
5891  if(disable) {
5893  } else {
5895  }
5896  return this;
5897  }
5898 
5899  /// Set the subcommand to be enabled by default, so on clear(), at the start of each parse it is enabled (not
5900  /// disabled)
5901  App *enabled_by_default(bool enable = true) {
5902  if(enable) {
5904  } else {
5905  default_startup =
5907  }
5908  return this;
5909  }
5910 
5911  /// Set the subcommand callback to be executed immediately on subcommand completion
5912  App *immediate_callback(bool immediate = true);
5913 
5914  /// Set the subcommand to validate positional arguments before assigning
5915  App *validate_positionals(bool validate = true) {
5916  validate_positionals_ = validate;
5917  return this;
5918  }
5919 
5920  /// Set the subcommand to validate optional vector arguments before assigning
5921  App *validate_optional_arguments(bool validate = true) {
5922  validate_optional_arguments_ = validate;
5923  return this;
5924  }
5925 
5926  /// ignore extras in config files
5927  App *allow_config_extras(bool allow = true) {
5928  if(allow) {
5930  allow_extras_ = true;
5931  } else {
5933  }
5934  return this;
5935  }
5936 
5937  /// ignore extras in config files
5940  return this;
5941  }
5942 
5943  /// Do not parse anything after the first unrecognized option and return
5944  App *prefix_command(bool allow = true) {
5945  prefix_command_ = allow;
5946  return this;
5947  }
5948 
5949  /// Ignore case. Subcommands inherit value.
5950  App *ignore_case(bool value = true);
5951 
5952  /// Allow windows style options, such as `/opt`. First matching short or long name used. Subcommands inherit
5953  /// value.
5954  App *allow_windows_style_options(bool value = true) {
5956  return this;
5957  }
5958 
5959  /// Specify that the positional arguments are only at the end of the sequence
5960  App *positionals_at_end(bool value = true) {
5962  return this;
5963  }
5964 
5965  /// Specify that the subcommand can be triggered by a config file
5966  App *configurable(bool value = true) {
5967  configurable_ = value;
5968  return this;
5969  }
5970 
5971  /// Ignore underscore. Subcommands inherit value.
5972  App *ignore_underscore(bool value = true);
5973 
5974  /// Set the help formatter
5975  App *formatter(std::shared_ptr<FormatterBase> fmt) {
5976  formatter_ = fmt;
5977  return this;
5978  }
5979 
5980  /// Set the help formatter
5981  App *formatter_fn(std::function<std::string(const App *, std::string, AppFormatMode)> fmt) {
5982  formatter_ = std::make_shared<FormatterLambda>(fmt);
5983  return this;
5984  }
5985 
5986  /// Set the config formatter
5987  App *config_formatter(std::shared_ptr<Config> fmt) {
5988  config_formatter_ = fmt;
5989  return this;
5990  }
5991 
5992  /// Check to see if this subcommand was parsed, true only if received on command line.
5993  CLI11_NODISCARD bool parsed() const { return parsed_ > 0; }
5994 
5995  /// Get the OptionDefault object, to set option defaults
5997 
5998  ///@}
5999  /// @name Adding options
6000  ///@{
6001 
6002  /// Add an option, will automatically understand the type for common types.
6003  ///
6004  /// To use, create a variable with the expected type, and pass it in after the name.
6005  /// After start is called, you can use count to see if the value was passed, and
6006  /// the value will be initialized properly. Numbers, vectors, and strings are supported.
6007  ///
6008  /// ->required(), ->default, and the validators are options,
6009  /// The positional options take an optional number of arguments.
6010  ///
6011  /// For example,
6012  ///
6013  /// std::string filename;
6014  /// program.add_option("filename", filename, "description of filename");
6015  ///
6016  Option *add_option(std::string option_name,
6017  callback_t option_callback,
6018  std::string option_description = "",
6019  bool defaulted = false,
6020  std::function<std::string()> func = {});
6021 
6022  /// Add option for assigning to a variable
6023  template <typename AssignTo,
6024  typename ConvertTo = AssignTo,
6027  AssignTo &variable, ///< The variable to set
6028  std::string option_description = "") {
6029 
6030  auto fun = [&variable](const CLI::results_t &res) { // comment for spacing
6031  return detail::lexical_conversion<AssignTo, ConvertTo>(res, variable);
6032  };
6033 
6034  Option *opt = add_option(option_name, fun, option_description, false, [&variable]() {
6035  return CLI::detail::checked_to_string<AssignTo, ConvertTo>(variable);
6036  });
6037  opt->type_name(detail::type_name<ConvertTo>());
6038  // these must be actual lvalues since (std::max) sometimes is defined in terms of references and references
6039  // to structs used in the evaluation can be temporary so that would cause issues.
6041  auto XCcount = detail::type_count<ConvertTo>::value;
6044  opt->run_callback_for_default();
6045  return opt;
6046  }
6047 
6048  /// Add option for assigning to a variable
6051  AssignTo &variable, ///< The variable to set
6052  std::string option_description = "") {
6053 
6054  auto fun = [&variable](const CLI::results_t &res) { // comment for spacing
6055  return detail::lexical_conversion<AssignTo, AssignTo>(res, variable);
6056  };
6057 
6058  Option *opt = add_option(option_name, fun, option_description, false, []() { return std::string{}; });
6059  opt->type_name(detail::type_name<AssignTo>());
6062  opt->run_callback_for_default();
6063  return opt;
6064  }
6065 
6066  /// Add option for a callback of a specific type
6067  template <typename ArgType>
6069  const std::function<void(const ArgType &)> &func, ///< the callback to execute
6070  std::string option_description = "") {
6071 
6072  auto fun = [func](const CLI::results_t &res) {
6073  ArgType variable;
6074  bool result = detail::lexical_conversion<ArgType, ArgType>(res, variable);
6075  if(result) {
6076  func(variable);
6077  }
6078  return result;
6079  };
6080 
6081  Option *opt = add_option(option_name, std::move(fun), option_description, false);
6082  opt->type_name(detail::type_name<ArgType>());
6085  return opt;
6086  }
6087 
6088  /// Add option with no description or variable assignment
6090  return add_option(option_name, CLI::callback_t{}, std::string{}, false);
6091  }
6092 
6093  /// Add option with description but with no variable assignment or callback
6094  template <typename T,
6096  detail::dummy>
6097  Option *add_option(std::string option_name, T &option_description) {
6098  return add_option(option_name, CLI::callback_t(), option_description, false);
6099  }
6100 
6101  /// Set a help flag, replace the existing one if present
6102  Option *set_help_flag(std::string flag_name = "", const std::string &help_description = "");
6103 
6104  /// Set a help all flag, replaced the existing one if present
6105  Option *set_help_all_flag(std::string help_name = "", const std::string &help_description = "");
6106 
6107  /// Set a version flag and version display string, replace the existing one if present
6108  Option *set_version_flag(std::string flag_name = "",
6109  const std::string &versionString = "",
6110  const std::string &version_help = "Display program version information and exit");
6111 
6112  /// Generate the version string through a callback function
6113  Option *set_version_flag(std::string flag_name,
6114  std::function<std::string()> vfunc,
6115  const std::string &version_help = "Display program version information and exit");
6116 
6117  private:
6118  /// Internal function for adding a flag
6119  Option *_add_flag_internal(std::string flag_name, CLI::callback_t fun, std::string flag_description);
6120 
6121  public:
6122  /// Add a flag with no description or variable assignment
6123  Option *add_flag(std::string flag_name) { return _add_flag_internal(flag_name, CLI::callback_t(), std::string{}); }
6124 
6125  /// Add flag with description but with no variable assignment or callback
6126  /// takes a constant string, if a variable string is passed that variable will be assigned the results from the
6127  /// flag
6128  template <typename T,
6130  detail::dummy>
6131  Option *add_flag(std::string flag_name, T &flag_description) {
6132  return _add_flag_internal(flag_name, CLI::callback_t(), flag_description);
6133  }
6134 
6135  /// Other type version accepts all other types that are not vectors such as bool, enum, string or other classes
6136  /// that can be converted from a string
6137  template <typename T,
6139  !std::is_constructible<std::function<void(int)>, T>::value,
6140  detail::enabler> = detail::dummy>
6142  T &flag_result, ///< A variable holding the flag result
6143  std::string flag_description = "") {
6144 
6145  CLI::callback_t fun = [&flag_result](const CLI::results_t &res) {
6146  return CLI::detail::lexical_cast(res[0], flag_result);
6147  };
6148  auto *opt = _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
6149  return detail::default_flag_modifiers<T>(opt);
6150  }
6151 
6152  /// Vector version to capture multiple flags.
6153  template <typename T,
6155  detail::dummy>
6157  std::vector<T> &flag_results, ///< A vector of values with the flag results
6158  std::string flag_description = "") {
6159  CLI::callback_t fun = [&flag_results](const CLI::results_t &res) {
6160  bool retval = true;
6161  for(const auto &elem : res) {
6162  flag_results.emplace_back();
6163  retval &= detail::lexical_cast(elem, flag_results.back());
6164  }
6165  return retval;
6166  };
6167  return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
6170  }
6171 
6172  /// Add option for callback that is triggered with a true flag and takes no arguments
6174  std::function<void(void)> function, ///< A function to call, void(void)
6175  std::string flag_description = "");
6176 
6177  /// Add option for callback with an integer value
6179  std::function<void(std::int64_t)> function, ///< A function to call, void(int)
6180  std::string flag_description = "");
6181 
6182 #ifdef CLI11_CPP14
6183  /// Add option for callback (C++14 or better only)
6184  Option *add_flag(std::string flag_name,
6185  std::function<void(std::int64_t)> function, ///< A function to call, void(std::int64_t)
6186  std::string flag_description = "") {
6187  return add_flag_function(std::move(flag_name), std::move(function), std::move(flag_description));
6188  }
6189 #endif
6190 
6191  /// Set a configuration ini file option, or clear it if no name passed
6192  Option *set_config(std::string option_name = "",
6193  std::string default_filename = "",
6194  const std::string &help_message = "Read an ini file",
6195  bool config_required = false);
6196 
6197  /// Removes an option from the App. Takes an option pointer. Returns true if found and removed.
6198  bool remove_option(Option *opt);
6199 
6200  /// creates an option group as part of the given app
6201  template <typename T = Option_group>
6202  T *add_option_group(std::string group_name, std::string group_description = "") {
6203  if(!detail::valid_alias_name_string(group_name)) {
6204  throw IncorrectConstruction("option group names may not contain newlines or null characters");
6205  }
6206  auto option_group = std::make_shared<T>(std::move(group_description), group_name, this);
6207  auto *ptr = option_group.get();
6208  // move to App_p for overload resolution on older gcc versions
6209  App_p app_ptr = std::dynamic_pointer_cast<App>(option_group);
6210  add_subcommand(std::move(app_ptr));
6211  return ptr;
6212  }
6213 
6214  ///@}
6215  /// @name Subcommands
6216  ///@{
6217 
6218  /// Add a subcommand. Inherits INHERITABLE and OptionDefaults, and help flag
6219  App *add_subcommand(std::string subcommand_name = "", std::string subcommand_description = "");
6220 
6221  /// Add a previously created app as a subcommand
6222  App *add_subcommand(CLI::App_p subcom);
6223 
6224  /// Removes a subcommand from the App. Takes a subcommand pointer. Returns true if found and removed.
6225  bool remove_subcommand(App *subcom);
6226 
6227  /// Check to see if a subcommand is part of this command (doesn't have to be in command line)
6228  /// returns the first subcommand if passed a nullptr
6229  App *get_subcommand(const App *subcom) const;
6230 
6231  /// Check to see if a subcommand is part of this command (text version)
6233 
6234  /// Get a pointer to subcommand by index
6235  CLI11_NODISCARD App *get_subcommand(int index = 0) const;
6236 
6237  /// Check to see if a subcommand is part of this command and get a shared_ptr to it
6238  CLI::App_p get_subcommand_ptr(App *subcom) const;
6239 
6240  /// Check to see if a subcommand is part of this command (text version)
6242 
6243  /// Get an owning pointer to subcommand by index
6244  CLI11_NODISCARD CLI::App_p get_subcommand_ptr(int index = 0) const;
6245 
6246  /// Check to see if an option group is part of this App
6247  CLI11_NODISCARD App *get_option_group(std::string group_name) const;
6248 
6249  /// No argument version of count counts the number of times this subcommand was
6250  /// passed in. The main app will return 1. Unnamed subcommands will also return 1 unless
6251  /// otherwise modified in a callback
6252  CLI11_NODISCARD std::size_t count() const { return parsed_; }
6253 
6254  /// Get a count of all the arguments processed in options and subcommands, this excludes arguments which were
6255  /// treated as extras.
6256  CLI11_NODISCARD std::size_t count_all() const;
6257 
6258  /// Changes the group membership
6259  App *group(std::string group_name) {
6260  group_ = group_name;
6261  return this;
6262  }
6263 
6264  /// The argumentless form of require subcommand requires 1 or more subcommands
6268  return this;
6269  }
6270 
6271  /// Require a subcommand to be given (does not affect help call)
6272  /// The number required can be given. Negative values indicate maximum
6273  /// number allowed (0 for any number). Max number inheritable.
6274  App *require_subcommand(int value) {
6275  if(value < 0) {
6277  require_subcommand_max_ = static_cast<std::size_t>(-value);
6278  } else {
6279  require_subcommand_min_ = static_cast<std::size_t>(value);
6280  require_subcommand_max_ = static_cast<std::size_t>(value);
6281  }
6282  return this;
6283  }
6284 
6285  /// Explicitly control the number of subcommands required. Setting 0
6286  /// for the max means unlimited number allowed. Max number inheritable.
6287  App *require_subcommand(std::size_t min, std::size_t max) {
6290  return this;
6291  }
6292 
6293  /// The argumentless form of require option requires 1 or more options be used
6295  require_option_min_ = 1;
6296  require_option_max_ = 0;
6297  return this;
6298  }
6299 
6300  /// Require an option to be given (does not affect help call)
6301  /// The number required can be given. Negative values indicate maximum
6302  /// number allowed (0 for any number).
6303  App *require_option(int value) {
6304  if(value < 0) {
6305  require_option_min_ = 0;
6306  require_option_max_ = static_cast<std::size_t>(-value);
6307  } else {
6308  require_option_min_ = static_cast<std::size_t>(value);
6309  require_option_max_ = static_cast<std::size_t>(value);
6310  }
6311  return this;
6312  }
6313 
6314  /// Explicitly control the number of options required. Setting 0
6315  /// for the max means unlimited number allowed. Max number inheritable.
6316  App *require_option(std::size_t min, std::size_t max) {
6319  return this;
6320  }
6321 
6322  /// Stop subcommand fallthrough, so that parent commands cannot collect commands after subcommand.
6323  /// Default from parent, usually set on parent.
6324  App *fallthrough(bool value = true) {
6325  fallthrough_ = value;
6326  return this;
6327  }
6328 
6329  /// Check to see if this subcommand was parsed, true only if received on command line.
6330  /// This allows the subcommand to be directly checked.
6331  explicit operator bool() const { return parsed_ > 0; }
6332 
6333  ///@}
6334  /// @name Extras for subclassing
6335  ///@{
6336 
6337  /// This allows subclasses to inject code before callbacks but after parse.
6338  ///
6339  /// This does not run if any errors or help is thrown.
6340  virtual void pre_callback() {}
6341 
6342  ///@}
6343  /// @name Parsing
6344  ///@{
6345  //
6346  /// Reset the parsed data
6347  void clear();
6348 
6349  /// Parses the command line - throws errors.
6350  /// This must be called after the options are in but before the rest of the program.
6351  void parse(int argc, const char *const *argv);
6352 
6353  /// Parse a single string as if it contained command line arguments.
6354  /// This function splits the string into arguments then calls parse(std::vector<std::string> &)
6355  /// the function takes an optional boolean argument specifying if the programName is included in the string to
6356  /// process
6357  void parse(std::string commandline, bool program_name_included = false);
6358 
6359  /// The real work is done here. Expects a reversed vector.
6360  /// Changes the vector to the remaining options.
6361  void parse(std::vector<std::string> &args);
6362 
6363  /// The real work is done here. Expects a reversed vector.
6364  void parse(std::vector<std::string> &&args);
6365 
6366  void parse_from_stream(std::istream &input);
6367 
6368  /// Provide a function to print a help message. The function gets access to the App pointer and error.
6369  void failure_message(std::function<std::string(const App *, const Error &e)> function) {
6370  failure_message_ = function;
6371  }
6372 
6373  /// Print a nice error message and return the exit code
6374  int exit(const Error &e, std::ostream &out = std::cout, std::ostream &err = std::cerr) const;
6375 
6376  ///@}
6377  /// @name Post parsing
6378  ///@{
6379 
6380  /// Counts the number of times the given option was passed.
6381  CLI11_NODISCARD std::size_t count(std::string option_name) const { return get_option(option_name)->count(); }
6382 
6383  /// Get a subcommand pointer list to the currently selected subcommands (after parsing by default, in command
6384  /// line order; use parsed = false to get the original definition list.)
6385  CLI11_NODISCARD std::vector<App *> get_subcommands() const { return parsed_subcommands_; }
6386 
6387  /// Get a filtered subcommand pointer list from the original definition list. An empty function will provide all
6388  /// subcommands (const)
6389  std::vector<const App *> get_subcommands(const std::function<bool(const App *)> &filter) const;
6390 
6391  /// Get a filtered subcommand pointer list from the original definition list. An empty function will provide all
6392  /// subcommands
6393  std::vector<App *> get_subcommands(const std::function<bool(App *)> &filter);
6394 
6395  /// Check to see if given subcommand was selected
6396  bool got_subcommand(const App *subcom) const {
6397  // get subcom needed to verify that this was a real subcommand
6398  return get_subcommand(subcom)->parsed_ > 0;
6399  }
6400 
6401  /// Check with name instead of pointer to see if subcommand was selected
6402  CLI11_NODISCARD bool got_subcommand(std::string subcommand_name) const {
6403  return get_subcommand(subcommand_name)->parsed_ > 0;
6404  }
6405 
6406  /// Sets excluded options for the subcommand
6408  if(opt == nullptr) {
6409  throw OptionNotFound("nullptr passed");
6410  }
6411  exclude_options_.insert(opt);
6412  return this;
6413  }
6414 
6415  /// Sets excluded subcommands for the subcommand
6416  App *excludes(App *app) {
6417  if(app == nullptr) {
6418  throw OptionNotFound("nullptr passed");
6419  }
6420  if(app == this) {
6421  throw OptionNotFound("cannot self reference in needs");
6422  }
6423  auto res = exclude_subcommands_.insert(app);
6424  // subcommand exclusion should be symmetric
6425  if(res.second) {
6426  app->exclude_subcommands_.insert(this);
6427  }
6428  return this;
6429  }
6430 
6431  App *needs(Option *opt) {
6432  if(opt == nullptr) {
6433  throw OptionNotFound("nullptr passed");
6434  }
6435  need_options_.insert(opt);
6436  return this;
6437  }
6438 
6439  App *needs(App *app) {
6440  if(app == nullptr) {
6441  throw OptionNotFound("nullptr passed");
6442  }
6443  if(app == this) {
6444  throw OptionNotFound("cannot self reference in needs");
6445  }
6446  need_subcommands_.insert(app);
6447  return this;
6448  }
6449 
6450  /// Removes an option from the excludes list of this subcommand
6451  bool remove_excludes(Option *opt);
6452 
6453  /// Removes a subcommand from the excludes list of this subcommand
6454  bool remove_excludes(App *app);
6455 
6456  /// Removes an option from the needs list of this subcommand
6457  bool remove_needs(Option *opt);
6458 
6459  /// Removes a subcommand from the needs list of this subcommand
6460  bool remove_needs(App *app);
6461  ///@}
6462  /// @name Help
6463  ///@{
6464 
6465  /// Set footer.
6466  App *footer(std::string footer_string) {
6467  footer_ = std::move(footer_string);
6468  return this;
6469  }
6470  /// Set footer.
6471  App *footer(std::function<std::string()> footer_function) {
6472  footer_callback_ = std::move(footer_function);
6473  return this;
6474  }
6475  /// Produce a string that could be read in as a config of the current values of the App. Set default_also to
6476  /// include default arguments. write_descriptions will print a description for the App and for each option.
6477  CLI11_NODISCARD std::string config_to_str(bool default_also = false, bool write_description = false) const {
6478  return config_formatter_->to_config(this, default_also, write_description, "");
6479  }
6480 
6481  /// Makes a help message, using the currently configured formatter
6482  /// Will only do one subcommand at a time
6484 
6485  /// Displays a version string
6487  ///@}
6488  /// @name Getters
6489  ///@{
6490 
6491  /// Access the formatter
6492  CLI11_NODISCARD std::shared_ptr<FormatterBase> get_formatter() const { return formatter_; }
6493 
6494  /// Access the config formatter
6495  CLI11_NODISCARD std::shared_ptr<Config> get_config_formatter() const { return config_formatter_; }
6496 
6497  /// Access the config formatter as a configBase pointer
6498  CLI11_NODISCARD std::shared_ptr<ConfigBase> get_config_formatter_base() const {
6499  // This is safer as a dynamic_cast if we have RTTI, as Config -> ConfigBase
6500 #if CLI11_USE_STATIC_RTTI == 0
6501  return std::dynamic_pointer_cast<ConfigBase>(config_formatter_);
6502 #else
6503  return std::static_pointer_cast<ConfigBase>(config_formatter_);
6504 #endif
6505  }
6506 
6507  /// Get the app or subcommand description
6509 
6510  /// Set the description of the app
6511  App *description(std::string app_description) {
6512  description_ = std::move(app_description);
6513  return this;
6514  }
6515 
6516  /// Get the list of options (user facing function, so returns raw pointers), has optional filter function
6517  std::vector<const Option *> get_options(const std::function<bool(const Option *)> filter = {}) const;
6518 
6519  /// Non-const version of the above
6520  std::vector<Option *> get_options(const std::function<bool(Option *)> filter = {});
6521 
6522  /// Get an option by name (noexcept non-const version)
6523  Option *get_option_no_throw(std::string option_name) noexcept;
6524 
6525  /// Get an option by name (noexcept const version)
6526  CLI11_NODISCARD const Option *get_option_no_throw(std::string option_name) const noexcept;
6527 
6528  /// Get an option by name
6529  CLI11_NODISCARD const Option *get_option(std::string option_name) const {
6530  const auto *opt = get_option_no_throw(option_name);
6531  if(opt == nullptr) {
6532  throw OptionNotFound(option_name);
6533  }
6534  return opt;
6535  }
6536 
6537  /// Get an option by name (non-const version)
6539  auto *opt = get_option_no_throw(option_name);
6540  if(opt == nullptr) {
6541  throw OptionNotFound(option_name);
6542  }
6543  return opt;
6544  }
6545 
6546  /// Shortcut bracket operator for getting a pointer to an option
6547  const Option *operator[](const std::string &option_name) const { return get_option(option_name); }
6548 
6549  /// Shortcut bracket operator for getting a pointer to an option
6550  const Option *operator[](const char *option_name) const { return get_option(option_name); }
6551 
6552  /// Check the status of ignore_case
6554 
6555  /// Check the status of ignore_underscore
6557 
6558  /// Check the status of fallthrough
6560 
6561  /// Check the status of the allow windows style options
6563 
6564  /// Check the status of the allow windows style options
6566 
6567  /// Check the status of the allow windows style options
6569 
6570  /// Get the group of this subcommand
6571  CLI11_NODISCARD const std::string &get_group() const { return group_; }
6572 
6573  /// Generate and return the footer.
6575  return (footer_callback_) ? footer_callback_() + '\n' + footer_ : footer_;
6576  }
6577 
6578  /// Get the required min subcommand value
6580 
6581  /// Get the required max subcommand value
6583 
6584  /// Get the required min option value
6586 
6587  /// Get the required max option value
6589 
6590  /// Get the prefix command status
6592 
6593  /// Get the status of allow extras
6595 
6596  /// Get the status of required
6597  CLI11_NODISCARD bool get_required() const { return required_; }
6598 
6599  /// Get the status of disabled
6600  CLI11_NODISCARD bool get_disabled() const { return disabled_; }
6601 
6602  /// Get the status of silence
6603  CLI11_NODISCARD bool get_silent() const { return silent_; }
6604 
6605  /// Get the status of disabled
6607 
6608  /// Get the status of disabled by default
6610 
6611  /// Get the status of disabled by default
6613  /// Get the status of validating positionals
6615  /// Get the status of validating optional vector arguments
6617 
6618  /// Get the status of allow extras
6620 
6621  /// Get a pointer to the help flag.
6623 
6624  /// Get a pointer to the help flag. (const)
6625  CLI11_NODISCARD const Option *get_help_ptr() const { return help_ptr_; }
6626 
6627  /// Get a pointer to the help all flag. (const)
6629 
6630  /// Get a pointer to the config option.
6632 
6633  /// Get a pointer to the config option. (const)
6635 
6636  /// Get a pointer to the version option.
6638 
6639  /// Get a pointer to the version option. (const)
6641 
6642  /// Get the parent of this subcommand (or nullptr if main app)
6643  App *get_parent() { return parent_; }
6644 
6645  /// Get the parent of this subcommand (or nullptr if main app) (const version)
6646  CLI11_NODISCARD const App *get_parent() const { return parent_; }
6647 
6648  /// Get the name of the current app
6649  CLI11_NODISCARD const std::string &get_name() const { return name_; }
6650 
6651  /// Get the aliases of the current app
6652  CLI11_NODISCARD const std::vector<std::string> &get_aliases() const { return aliases_; }
6653 
6654  /// clear all the aliases of the current App
6656  aliases_.clear();
6657  return this;
6658  }
6659 
6660  /// Get a display name for an app
6661  CLI11_NODISCARD std::string get_display_name(bool with_aliases = false) const;
6662 
6663  /// Check the name, case insensitive and underscore insensitive if set
6664  CLI11_NODISCARD bool check_name(std::string name_to_check) const;
6665 
6666  /// Get the groups available directly from this option (in order)
6667  CLI11_NODISCARD std::vector<std::string> get_groups() const;
6668 
6669  /// This gets a vector of pointers with the original parse order
6670  CLI11_NODISCARD const std::vector<Option *> &parse_order() const { return parse_order_; }
6671 
6672  /// This returns the missing options from the current subcommand
6673  CLI11_NODISCARD std::vector<std::string> remaining(bool recurse = false) const;
6674 
6675  /// This returns the missing options in a form ready for processing by another command line program
6676  CLI11_NODISCARD std::vector<std::string> remaining_for_passthrough(bool recurse = false) const;
6677 
6678  /// This returns the number of remaining options, minus the -- separator
6679  CLI11_NODISCARD std::size_t remaining_size(bool recurse = false) const;
6680 
6681  ///@}
6682 
6683  protected:
6684  /// Check the options to make sure there are no conflicts.
6685  ///
6686  /// Currently checks to see if multiple positionals exist with unlimited args and checks if the min and max options
6687  /// are feasible
6688  void _validate() const;
6689 
6690  /// configure subcommands to enable parsing through the current object
6691  /// set the correct fallthrough and prefix for nameless subcommands and manage the automatic enable or disable
6692  /// makes sure parent is set correctly
6693  void _configure();
6694 
6695  /// Internal function to run (App) callback, bottom up
6696  void run_callback(bool final_mode = false, bool suppress_final_callback = false);
6697 
6698  /// Check to see if a subcommand is valid. Give up immediately if subcommand max has been reached.
6699  CLI11_NODISCARD bool _valid_subcommand(const std::string &current, bool ignore_used = true) const;
6700 
6701  /// Selects a Classifier enum based on the type of the current argument
6703  bool ignore_used_subcommands = true) const;
6704 
6705  // The parse function is now broken into several parts, and part of process
6706 
6707  /// Read and process a configuration file (main app only)
6708  void _process_config_file();
6709 
6710  /// Get envname options if not yet passed. Runs on *all* subcommands.
6711  void _process_env();
6712 
6713  /// Process callbacks. Runs on *all* subcommands.
6714  void _process_callbacks();
6715 
6716  /// Run help flag processing if any are found.
6717  ///
6718  /// The flags allow recursive calls to remember if there was a help flag on a parent.
6719  void _process_help_flags(bool trigger_help = false, bool trigger_all_help = false) const;
6720 
6721  /// Verify required options and cross requirements. Subcommands too (only if selected).
6722  void _process_requirements();
6723 
6724  /// Process callbacks and such.
6725  void _process();
6726 
6727  /// Throw an error if anything is left over and should not be.
6728  void _process_extras();
6729 
6730  /// Throw an error if anything is left over and should not be.
6731  /// Modifies the args to fill in the missing items before throwing.
6732  void _process_extras(std::vector<std::string> &args);
6733 
6734  /// Internal function to recursively increment the parsed counter on the current app as well unnamed subcommands
6735  void increment_parsed();
6736 
6737  /// Internal parse function
6738  void _parse(std::vector<std::string> &args);
6739 
6740  /// Internal parse function
6741  void _parse(std::vector<std::string> &&args);
6742 
6743  /// Internal function to parse a stream
6744  void _parse_stream(std::istream &input);
6745 
6746  /// Parse one config param, return false if not found in any subcommand, remove if it is
6747  ///
6748  /// If this has more than one dot.separated.name, go into the subcommand matching it
6749  /// Returns true if it managed to find the option, if false you'll need to remove the arg manually.
6750  void _parse_config(const std::vector<ConfigItem> &args);
6751 
6752  /// Fill in a single config option
6753  bool _parse_single_config(const ConfigItem &item, std::size_t level = 0);
6754 
6755  /// Parse "one" argument (some may eat more than one), delegate to parent if fails, add to missing if missing
6756  /// from main return false if the parse has failed and needs to return to parent
6757  bool _parse_single(std::vector<std::string> &args, bool &positional_only);
6758 
6759  /// Count the required remaining positional arguments
6760  CLI11_NODISCARD std::size_t _count_remaining_positionals(bool required_only = false) const;
6761 
6762  /// Count the required remaining positional arguments
6764 
6765  /// Parse a positional, go up the tree to check
6766  /// @param haltOnSubcommand if set to true the operation will not process subcommands merely return false
6767  /// Return true if the positional was used false otherwise
6768  bool _parse_positional(std::vector<std::string> &args, bool haltOnSubcommand);
6769 
6770  /// Locate a subcommand by name with two conditions, should disabled subcommands be ignored, and should used
6771  /// subcommands be ignored
6773  _find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept;
6774 
6775  /// Parse a subcommand, modify args and continue
6776  ///
6777  /// Unlike the others, this one will always allow fallthrough
6778  /// return true if the subcommand was processed false otherwise
6779  bool _parse_subcommand(std::vector<std::string> &args);
6780 
6781  /// Parse a short (false) or long (true) argument, must be at the top of the list
6782  /// return true if the argument was processed or false if nothing was done
6783  bool _parse_arg(std::vector<std::string> &args, detail::Classifier current_type);
6784 
6785  /// Trigger the pre_parse callback if needed
6786  void _trigger_pre_parse(std::size_t remaining_args);
6787 
6788  /// Get the appropriate parent to fallthrough to which is the first one that has a name or the main app
6790 
6791  /// Helper function to run through all possible comparisons of subcommand names to check there is no overlap
6792  CLI11_NODISCARD const std::string &_compare_subcommand_names(const App &subcom, const App &base) const;
6793 
6794  /// Helper function to place extra values in the most appropriate position
6795  void _move_to_missing(detail::Classifier val_type, const std::string &val);
6796 
6797  public:
6798  /// function that could be used by subclasses of App to shift options around into subcommands
6799  void _move_option(Option *opt, App *app);
6800 }; // namespace CLI
6801 
6802 /// Extension of App to better manage groups of options
6803 class Option_group : public App {
6804  public:
6805  Option_group(std::string group_description, std::string group_name, App *parent)
6806  : App(std::move(group_description), "", parent) {
6807  group(group_name);
6808  // option groups should have automatic fallthrough
6809  }
6810  using App::add_option;
6811  /// Add an existing option to the Option_group
6813  if(get_parent() == nullptr) {
6814  throw OptionNotFound("Unable to locate the specified option");
6815  }
6816  get_parent()->_move_option(opt, this);
6817  return opt;
6818  }
6819  /// Add an existing option to the Option_group
6820  void add_options(Option *opt) { add_option(opt); }
6821  /// Add a bunch of options to the group
6822  template <typename... Args> void add_options(Option *opt, Args... args) {
6823  add_option(opt);
6824  add_options(args...);
6825  }
6826  using App::add_subcommand;
6827  /// Add an existing subcommand to be a member of an option_group
6828  App *add_subcommand(App *subcom) {
6829  App_p subc = subcom->get_parent()->get_subcommand_ptr(subcom);
6830  subc->get_parent()->remove_subcommand(subcom);
6831  add_subcommand(std::move(subc));
6832  return subcom;
6833  }
6834 };
6835 
6836 /// Helper function to enable one option group/subcommand when another is used
6837 CLI11_INLINE void TriggerOn(App *trigger_app, App *app_to_enable);
6838 
6839 /// Helper function to enable one option group/subcommand when another is used
6840 CLI11_INLINE void TriggerOn(App *trigger_app, std::vector<App *> apps_to_enable);
6841 
6842 /// Helper function to disable one option group/subcommand when another is used
6843 CLI11_INLINE void TriggerOff(App *trigger_app, App *app_to_enable);
6844 
6845 /// Helper function to disable one option group/subcommand when another is used
6846 CLI11_INLINE void TriggerOff(App *trigger_app, std::vector<App *> apps_to_enable);
6847 
6848 /// Helper function to mark an option as deprecated
6849 CLI11_INLINE void deprecate_option(Option *opt, const std::string &replacement = "");
6850 
6851 /// Helper function to mark an option as deprecated
6852 inline void deprecate_option(App *app, const std::string &option_name, const std::string &replacement = "") {
6853  auto *opt = app->get_option(option_name);
6854  deprecate_option(opt, replacement);
6855 }
6856 
6857 /// Helper function to mark an option as deprecated
6858 inline void deprecate_option(App &app, const std::string &option_name, const std::string &replacement = "") {
6859  auto *opt = app.get_option(option_name);
6860  deprecate_option(opt, replacement);
6861 }
6862 
6863 /// Helper function to mark an option as retired
6864 CLI11_INLINE void retire_option(App *app, Option *opt);
6865 
6866 /// Helper function to mark an option as retired
6867 CLI11_INLINE void retire_option(App &app, Option *opt);
6868 
6869 /// Helper function to mark an option as retired
6870 CLI11_INLINE void retire_option(App *app, const std::string &option_name);
6871 
6872 /// Helper function to mark an option as retired
6873 CLI11_INLINE void retire_option(App &app, const std::string &option_name);
6874 
6875 namespace FailureMessage {
6876 
6877 /// Printout a clean, simple message on error (the default in CLI11 1.5+)
6878 CLI11_INLINE std::string simple(const App *app, const Error &e);
6879 
6880 /// Printout the full help string on error (if this fn is set, the old default for CLI11)
6881 CLI11_INLINE std::string help(const App *app, const Error &e);
6882 
6883 } // namespace FailureMessage
6884 
6885 namespace detail {
6886 /// This class is simply to allow tests access to App's protected functions
6887 struct AppFriend {
6888 #ifdef CLI11_CPP14
6889 
6890  /// Wrap _parse_short, perfectly forward arguments and return
6891  template <typename... Args> static decltype(auto) parse_arg(App *app, Args &&...args) {
6892  return app->_parse_arg(std::forward<Args>(args)...);
6893  }
6894 
6895  /// Wrap _parse_subcommand, perfectly forward arguments and return
6896  template <typename... Args> static decltype(auto) parse_subcommand(App *app, Args &&...args) {
6897  return app->_parse_subcommand(std::forward<Args>(args)...);
6898  }
6899 #else
6900  /// Wrap _parse_short, perfectly forward arguments and return
6901  template <typename... Args>
6902  static auto parse_arg(App *app, Args &&...args) ->
6903  typename std::result_of<decltype (&App::_parse_arg)(App, Args...)>::type {
6904  return app->_parse_arg(std::forward<Args>(args)...);
6905  }
6906 
6907  /// Wrap _parse_subcommand, perfectly forward arguments and return
6908  template <typename... Args>
6909  static auto parse_subcommand(App *app, Args &&...args) ->
6910  typename std::result_of<decltype (&App::_parse_subcommand)(App, Args...)>::type {
6911  return app->_parse_subcommand(std::forward<Args>(args)...);
6912  }
6913 #endif
6914  /// Wrap the fallthrough parent function to make sure that is working correctly
6915  static App *get_fallthrough_parent(App *app) { return app->_get_fallthrough_parent(); }
6916 };
6917 } // namespace detail
6918 
6919 
6920 
6921 
6922 CLI11_INLINE App::App(std::string app_description, std::string app_name, App *parent)
6923  : name_(std::move(app_name)), description_(std::move(app_description)), parent_(parent) {
6924  // Inherit if not from a nullptr
6925  if(parent_ != nullptr) {
6926  if(parent_->help_ptr_ != nullptr)
6928  if(parent_->help_all_ptr_ != nullptr)
6930 
6931  /// OptionDefaults
6933 
6934  // INHERITABLE
6947  group_ = parent_->group_;
6948  footer_ = parent_->footer_;
6952  }
6953 }
6954 
6956 
6957  if(parent_ != nullptr) {
6958  auto oname = name_;
6959  name_ = app_name;
6960  const auto &res = _compare_subcommand_names(*this, *_get_fallthrough_parent());
6961  if(!res.empty()) {
6962  name_ = oname;
6963  throw(OptionAlreadyAdded(app_name + " conflicts with existing subcommand names"));
6964  }
6965  } else {
6966  name_ = app_name;
6967  }
6968  has_automatic_name_ = false;
6969  return this;
6970 }
6971 
6973  if(app_name.empty() || !detail::valid_alias_name_string(app_name)) {
6974  throw IncorrectConstruction("Aliases may not be empty or contain newlines or null characters");
6975  }
6976  if(parent_ != nullptr) {
6977  aliases_.push_back(app_name);
6978  const auto &res = _compare_subcommand_names(*this, *_get_fallthrough_parent());
6979  if(!res.empty()) {
6980  aliases_.pop_back();
6981  throw(OptionAlreadyAdded("alias already matches an existing subcommand: " + app_name));
6982  }
6983  } else {
6984  aliases_.push_back(app_name);
6985  }
6986 
6987  return this;
6988 }
6989 
6991  immediate_callback_ = immediate;
6992  if(immediate_callback_) {
6995  }
6996  } else if(!(final_callback_) && parse_complete_callback_) {
6998  }
6999  return this;
7000 }
7001 
7003  if(value && !ignore_case_) {
7004  ignore_case_ = true;
7005  auto *p = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
7006  const auto &match = _compare_subcommand_names(*this, *p);
7007  if(!match.empty()) {
7008  ignore_case_ = false; // we are throwing so need to be exception invariant
7009  throw OptionAlreadyAdded("ignore case would cause subcommand name conflicts: " + match);
7010  }
7011  }
7012  ignore_case_ = value;
7013  return this;
7014 }
7015 
7017  if(value && !ignore_underscore_) {
7018  ignore_underscore_ = true;
7019  auto *p = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
7020  const auto &match = _compare_subcommand_names(*this, *p);
7021  if(!match.empty()) {
7022  ignore_underscore_ = false;
7023  throw OptionAlreadyAdded("ignore underscore would cause subcommand name conflicts: " + match);
7024  }
7025  }
7027  return this;
7028 }
7029 
7031  callback_t option_callback,
7032  std::string option_description,
7033  bool defaulted,
7034  std::function<std::string()> func) {
7035  Option myopt{option_name, option_description, option_callback, this};
7036 
7037  if(std::find_if(std::begin(options_), std::end(options_), [&myopt](const Option_p &v) { return *v == myopt; }) ==
7038  std::end(options_)) {
7039  options_.emplace_back();
7040  Option_p &option = options_.back();
7041  option.reset(new Option(option_name, option_description, option_callback, this));
7042 
7043  // Set the default string capture function
7044  option->default_function(func);
7045 
7046  // For compatibility with CLI11 1.7 and before, capture the default string here
7047  if(defaulted)
7048  option->capture_default_str();
7049 
7050  // Transfer defaults to the new option
7051  option_defaults_.copy_to(option.get());
7052 
7053  // Don't bother to capture if we already did
7054  if(!defaulted && option->get_always_capture_default())
7055  option->capture_default_str();
7056 
7057  return option.get();
7058  }
7059  // we know something matches now find what it is so we can produce more error information
7060  for(auto &opt : options_) {
7061  const auto &matchname = opt->matching_name(myopt);
7062  if(!matchname.empty()) {
7063  throw(OptionAlreadyAdded("added option matched existing option name: " + matchname));
7064  }
7065  }
7066  // this line should not be reached the above loop should trigger the throw
7067  throw(OptionAlreadyAdded("added option matched existing option name")); // LCOV_EXCL_LINE
7068 }
7069 
7070 CLI11_INLINE Option *App::set_help_flag(std::string flag_name, const std::string &help_description) {
7071  // take flag_description by const reference otherwise add_flag tries to assign to help_description
7072  if(help_ptr_ != nullptr) {
7074  help_ptr_ = nullptr;
7075  }
7076 
7077  // Empty name will simply remove the help flag
7078  if(!flag_name.empty()) {
7079  help_ptr_ = add_flag(flag_name, help_description);
7080  help_ptr_->configurable(false);
7081  }
7082 
7083  return help_ptr_;
7084 }
7085 
7086 CLI11_INLINE Option *App::set_help_all_flag(std::string help_name, const std::string &help_description) {
7087  // take flag_description by const reference otherwise add_flag tries to assign to flag_description
7088  if(help_all_ptr_ != nullptr) {
7090  help_all_ptr_ = nullptr;
7091  }
7092 
7093  // Empty name will simply remove the help all flag
7094  if(!help_name.empty()) {
7095  help_all_ptr_ = add_flag(help_name, help_description);
7096  help_all_ptr_->configurable(false);
7097  }
7098 
7099  return help_all_ptr_;
7100 }
7101 
7103 App::set_version_flag(std::string flag_name, const std::string &versionString, const std::string &version_help) {
7104  // take flag_description by const reference otherwise add_flag tries to assign to version_description
7105  if(version_ptr_ != nullptr) {
7107  version_ptr_ = nullptr;
7108  }
7109 
7110  // Empty name will simply remove the version flag
7111  if(!flag_name.empty()) {
7113  flag_name, [versionString]() { throw(CLI::CallForVersion(versionString, 0)); }, version_help);
7114  version_ptr_->configurable(false);
7115  }
7116 
7117  return version_ptr_;
7118 }
7119 
7121 App::set_version_flag(std::string flag_name, std::function<std::string()> vfunc, const std::string &version_help) {
7122  if(version_ptr_ != nullptr) {
7124  version_ptr_ = nullptr;
7125  }
7126 
7127  // Empty name will simply remove the version flag
7128  if(!flag_name.empty()) {
7130  flag_name, [vfunc]() { throw(CLI::CallForVersion(vfunc(), 0)); }, version_help);
7131  version_ptr_->configurable(false);
7132  }
7133 
7134  return version_ptr_;
7135 }
7136 
7137 CLI11_INLINE Option *App::_add_flag_internal(std::string flag_name, CLI::callback_t fun, std::string flag_description) {
7138  Option *opt = nullptr;
7139  if(detail::has_default_flag_values(flag_name)) {
7140  // check for default values and if it has them
7141  auto flag_defaults = detail::get_default_flag_values(flag_name);
7143  opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description), false);
7144  for(const auto &fname : flag_defaults)
7145  opt->fnames_.push_back(fname.first);
7146  opt->default_flag_values_ = std::move(flag_defaults);
7147  } else {
7148  opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description), false);
7149  }
7150  // flags cannot have positional values
7151  if(opt->get_positional()) {
7152  auto pos_name = opt->get_name(true);
7153  remove_option(opt);
7154  throw IncorrectConstruction::PositionalFlag(pos_name);
7155  }
7157  opt->expected(0);
7158  opt->required(false);
7159  return opt;
7160 }
7161 
7163  std::function<void(void)> function, ///< A function to call, void(void)
7164  std::string flag_description) {
7165 
7166  CLI::callback_t fun = [function](const CLI::results_t &res) {
7167  bool trigger{false};
7168  auto result = CLI::detail::lexical_cast(res[0], trigger);
7169  if(result && trigger) {
7170  function();
7171  }
7172  return result;
7173  };
7174  return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
7175 }
7176 
7179  std::function<void(std::int64_t)> function, ///< A function to call, void(int)
7180  std::string flag_description) {
7181 
7182  CLI::callback_t fun = [function](const CLI::results_t &res) {
7183  std::int64_t flag_count{0};
7184  CLI::detail::lexical_cast(res[0], flag_count);
7185  function(flag_count);
7186  return true;
7187  };
7188  return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
7190 }
7191 
7193  std::string default_filename,
7194  const std::string &help_message,
7195  bool config_required) {
7196 
7197  // Remove existing config if present
7198  if(config_ptr_ != nullptr) {
7200  config_ptr_ = nullptr; // need to remove the config_ptr completely
7201  }
7202 
7203  // Only add config if option passed
7204  if(!option_name.empty()) {
7205  config_ptr_ = add_option(option_name, help_message);
7206  if(config_required) {
7207  config_ptr_->required();
7208  }
7209  if(!default_filename.empty()) {
7210  config_ptr_->default_str(std::move(default_filename));
7211  }
7212  config_ptr_->configurable(false);
7213  }
7214 
7215  return config_ptr_;
7216 }
7217 
7219  // Make sure no links exist
7220  for(Option_p &op : options_) {
7221  op->remove_needs(opt);
7222  op->remove_excludes(opt);
7223  }
7224 
7225  if(help_ptr_ == opt)
7226  help_ptr_ = nullptr;
7227  if(help_all_ptr_ == opt)
7228  help_all_ptr_ = nullptr;
7229 
7230  auto iterator =
7231  std::find_if(std::begin(options_), std::end(options_), [opt](const Option_p &v) { return v.get() == opt; });
7232  if(iterator != std::end(options_)) {
7233  options_.erase(iterator);
7234  return true;
7235  }
7236  return false;
7237 }
7238 
7239 CLI11_INLINE App *App::add_subcommand(std::string subcommand_name, std::string subcommand_description) {
7240  if(!subcommand_name.empty() && !detail::valid_name_string(subcommand_name)) {
7241  if(!detail::valid_first_char(subcommand_name[0])) {
7242  throw IncorrectConstruction("Subcommand name starts with invalid character, '!' and '-' are not allowed");
7243  }
7244  for(auto c : subcommand_name) {
7245  if(!detail::valid_later_char(c)) {
7246  throw IncorrectConstruction(std::string("Subcommand name contains invalid character ('") + c +
7247  "'), all characters are allowed except"
7248  "'=',':','{','}', and ' '");
7249  }
7250  }
7251  }
7252  CLI::App_p subcom = std::shared_ptr<App>(new App(std::move(subcommand_description), subcommand_name, this));
7253  return add_subcommand(std::move(subcom));
7254 }
7255 
7257  if(!subcom)
7258  throw IncorrectConstruction("passed App is not valid");
7259  auto *ckapp = (name_.empty() && parent_ != nullptr) ? _get_fallthrough_parent() : this;
7260  const auto &mstrg = _compare_subcommand_names(*subcom, *ckapp);
7261  if(!mstrg.empty()) {
7262  throw(OptionAlreadyAdded("subcommand name or alias matches existing subcommand: " + mstrg));
7263  }
7264  subcom->parent_ = this;
7265  subcommands_.push_back(std::move(subcom));
7266  return subcommands_.back().get();
7267 }
7268 
7270  // Make sure no links exist
7271  for(App_p &sub : subcommands_) {
7272  sub->remove_excludes(subcom);
7273  sub->remove_needs(subcom);
7274  }
7275 
7276  auto iterator = std::find_if(
7277  std::begin(subcommands_), std::end(subcommands_), [subcom](const App_p &v) { return v.get() == subcom; });
7278  if(iterator != std::end(subcommands_)) {
7279  subcommands_.erase(iterator);
7280  return true;
7281  }
7282  return false;
7283 }
7284 
7285 CLI11_INLINE App *App::get_subcommand(const App *subcom) const {
7286  if(subcom == nullptr)
7287  throw OptionNotFound("nullptr passed");
7288  for(const App_p &subcomptr : subcommands_)
7289  if(subcomptr.get() == subcom)
7290  return subcomptr.get();
7291  throw OptionNotFound(subcom->get_name());
7292 }
7293 
7295  auto *subc = _find_subcommand(subcom, false, false);
7296  if(subc == nullptr)
7297  throw OptionNotFound(subcom);
7298  return subc;
7299 }
7300 
7302  if(index >= 0) {
7303  auto uindex = static_cast<unsigned>(index);
7304  if(uindex < subcommands_.size())
7305  return subcommands_[uindex].get();
7306  }
7307  throw OptionNotFound(std::to_string(index));
7308 }
7309 
7311  if(subcom == nullptr)
7312  throw OptionNotFound("nullptr passed");
7313  for(const App_p &subcomptr : subcommands_)
7314  if(subcomptr.get() == subcom)
7315  return subcomptr;
7316  throw OptionNotFound(subcom->get_name());
7317 }
7318 
7320  for(const App_p &subcomptr : subcommands_)
7321  if(subcomptr->check_name(subcom))
7322  return subcomptr;
7323  throw OptionNotFound(subcom);
7324 }
7325 
7327  if(index >= 0) {
7328  auto uindex = static_cast<unsigned>(index);
7329  if(uindex < subcommands_.size())
7330  return subcommands_[uindex];
7331  }
7332  throw OptionNotFound(std::to_string(index));
7333 }
7334 
7336  for(const App_p &app : subcommands_) {
7337  if(app->name_.empty() && app->group_ == group_name) {
7338  return app.get();
7339  }
7340  }
7341  throw OptionNotFound(group_name);
7342 }
7343 
7345  std::size_t cnt{0};
7346  for(const auto &opt : options_) {
7347  cnt += opt->count();
7348  }
7349  for(const auto &sub : subcommands_) {
7350  cnt += sub->count_all();
7351  }
7352  if(!get_name().empty()) { // for named subcommands add the number of times the subcommand was called
7353  cnt += parsed_;
7354  }
7355  return cnt;
7356 }
7357 
7359 
7360  parsed_ = 0;
7361  pre_parse_called_ = false;
7362 
7363  missing_.clear();
7364  parsed_subcommands_.clear();
7365  for(const Option_p &opt : options_) {
7366  opt->clear();
7367  }
7368  for(const App_p &subc : subcommands_) {
7369  subc->clear();
7370  }
7371 }
7372 
7373 CLI11_INLINE void App::parse(int argc, const char *const *argv) {
7374  // If the name is not set, read from command line
7375  if(name_.empty() || has_automatic_name_) {
7376  has_automatic_name_ = true;
7377  name_ = argv[0];
7378  }
7379 
7380  std::vector<std::string> args;
7381  args.reserve(static_cast<std::size_t>(argc) - 1U);
7382  for(auto i = static_cast<std::size_t>(argc) - 1U; i > 0U; --i)
7383  args.emplace_back(argv[i]);
7384  parse(std::move(args));
7385 }
7386 
7387 CLI11_INLINE void App::parse(std::string commandline, bool program_name_included) {
7388 
7389  if(program_name_included) {
7390  auto nstr = detail::split_program_name(commandline);
7391  if((name_.empty()) || (has_automatic_name_)) {
7392  has_automatic_name_ = true;
7393  name_ = nstr.first;
7394  }
7395  commandline = std::move(nstr.second);
7396  } else {
7397  detail::trim(commandline);
7398  }
7399  // the next section of code is to deal with quoted arguments after an '=' or ':' for windows like operations
7400  if(!commandline.empty()) {
7401  commandline = detail::find_and_modify(commandline, "=", detail::escape_detect);
7403  commandline = detail::find_and_modify(commandline, ":", detail::escape_detect);
7404  }
7405 
7406  auto args = detail::split_up(std::move(commandline));
7407  // remove all empty strings
7408  args.erase(std::remove(args.begin(), args.end(), std::string{}), args.end());
7409  std::reverse(args.begin(), args.end());
7410 
7411  parse(std::move(args));
7412 }
7413 
7414 CLI11_INLINE void App::parse(std::vector<std::string> &args) {
7415  // Clear if parsed
7416  if(parsed_ > 0)
7417  clear();
7418 
7419  // parsed_ is incremented in commands/subcommands,
7420  // but placed here to make sure this is cleared when
7421  // running parse after an error is thrown, even by _validate or _configure.
7422  parsed_ = 1;
7423  _validate();
7424  _configure();
7425  // set the parent as nullptr as this object should be the top now
7426  parent_ = nullptr;
7427  parsed_ = 0;
7428 
7429  _parse(args);
7430  run_callback();
7431 }
7432 
7433 CLI11_INLINE void App::parse(std::vector<std::string> &&args) {
7434  // Clear if parsed
7435  if(parsed_ > 0)
7436  clear();
7437 
7438  // parsed_ is incremented in commands/subcommands,
7439  // but placed here to make sure this is cleared when
7440  // running parse after an error is thrown, even by _validate or _configure.
7441  parsed_ = 1;
7442  _validate();
7443  _configure();
7444  // set the parent as nullptr as this object should be the top now
7445  parent_ = nullptr;
7446  parsed_ = 0;
7447 
7448  _parse(std::move(args));
7449  run_callback();
7450 }
7451 
7452 CLI11_INLINE void App::parse_from_stream(std::istream &input) {
7453  if(parsed_ == 0) {
7454  _validate();
7455  _configure();
7456  // set the parent as nullptr as this object should be the top now
7457  }
7458 
7459  _parse_stream(input);
7460  run_callback();
7461 }
7462 
7463 CLI11_INLINE int App::exit(const Error &e, std::ostream &out, std::ostream &err) const {
7464 
7465  /// Avoid printing anything if this is a CLI::RuntimeError
7466  if(e.get_name() == "RuntimeError")
7467  return e.get_exit_code();
7468 
7469  if(e.get_name() == "CallForHelp") {
7470  out << help();
7471  return e.get_exit_code();
7472  }
7473 
7474  if(e.get_name() == "CallForAllHelp") {
7475  out << help("", AppFormatMode::All);
7476  return e.get_exit_code();
7477  }
7478 
7479  if(e.get_name() == "CallForVersion") {
7480  out << e.what() << std::endl;
7481  return e.get_exit_code();
7482  }
7483 
7484  if(e.get_exit_code() != static_cast<int>(ExitCodes::Success)) {
7485  if(failure_message_)
7486  err << failure_message_(this, e) << std::flush;
7487  }
7488 
7489  return e.get_exit_code();
7490 }
7491 
7492 CLI11_INLINE std::vector<const App *> App::get_subcommands(const std::function<bool(const App *)> &filter) const {
7493  std::vector<const App *> subcomms(subcommands_.size());
7495  std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](const App_p &v) { return v.get(); });
7496 
7497  if(filter) {
7498  subcomms.erase(std::remove_if(std::begin(subcomms),
7499  std::end(subcomms),
7500  [&filter](const App *app) { return !filter(app); }),
7501  std::end(subcomms));
7502  }
7503 
7504  return subcomms;
7505 }
7506 
7507 CLI11_INLINE std::vector<App *> App::get_subcommands(const std::function<bool(App *)> &filter) {
7508  std::vector<App *> subcomms(subcommands_.size());
7510  std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](const App_p &v) { return v.get(); });
7511 
7512  if(filter) {
7513  subcomms.erase(
7514  std::remove_if(std::begin(subcomms), std::end(subcomms), [&filter](App *app) { return !filter(app); }),
7515  std::end(subcomms));
7516  }
7517 
7518  return subcomms;
7519 }
7520 
7523  if(iterator == std::end(exclude_options_)) {
7524  return false;
7525  }
7526  exclude_options_.erase(iterator);
7527  return true;
7528 }
7529 
7532  if(iterator == std::end(exclude_subcommands_)) {
7533  return false;
7534  }
7535  auto *other_app = *iterator;
7536  exclude_subcommands_.erase(iterator);
7537  other_app->remove_excludes(this);
7538  return true;
7539 }
7540 
7542  auto iterator = std::find(std::begin(need_options_), std::end(need_options_), opt);
7543  if(iterator == std::end(need_options_)) {
7544  return false;
7545  }
7546  need_options_.erase(iterator);
7547  return true;
7548 }
7549 
7552  if(iterator == std::end(need_subcommands_)) {
7553  return false;
7554  }
7555  need_subcommands_.erase(iterator);
7556  return true;
7557 }
7558 
7560  if(prev.empty())
7561  prev = get_name();
7562  else
7563  prev += " " + get_name();
7564 
7565  // Delegate to subcommand if needed
7566  auto selected_subcommands = get_subcommands();
7567  if(!selected_subcommands.empty()) {
7568  return selected_subcommands.at(0)->help(prev, mode);
7569  }
7570  return formatter_->make_help(this, prev, mode);
7571 }
7572 
7574  std::string val;
7575  if(version_ptr_ != nullptr) {
7576  auto rv = version_ptr_->results();
7577  version_ptr_->clear();
7578  version_ptr_->add_result("true");
7579  try {
7581  } catch(const CLI::CallForVersion &cfv) {
7582  val = cfv.what();
7583  }
7584  version_ptr_->clear();
7585  version_ptr_->add_result(rv);
7586  }
7587  return val;
7588 }
7589 
7590 CLI11_INLINE std::vector<const Option *> App::get_options(const std::function<bool(const Option *)> filter) const {
7591  std::vector<const Option *> options(options_.size());
7593  std::begin(options_), std::end(options_), std::begin(options), [](const Option_p &val) { return val.get(); });
7594 
7595  if(filter) {
7596  options.erase(std::remove_if(std::begin(options),
7597  std::end(options),
7598  [&filter](const Option *opt) { return !filter(opt); }),
7599  std::end(options));
7600  }
7601 
7602  return options;
7603 }
7604 
7605 CLI11_INLINE std::vector<Option *> App::get_options(const std::function<bool(Option *)> filter) {
7606  std::vector<Option *> options(options_.size());
7608  std::begin(options_), std::end(options_), std::begin(options), [](const Option_p &val) { return val.get(); });
7609 
7610  if(filter) {
7611  options.erase(
7612  std::remove_if(std::begin(options), std::end(options), [&filter](Option *opt) { return !filter(opt); }),
7613  std::end(options));
7614  }
7615 
7616  return options;
7617 }
7618 
7620  for(Option_p &opt : options_) {
7621  if(opt->check_name(option_name)) {
7622  return opt.get();
7623  }
7624  }
7625  for(auto &subc : subcommands_) {
7626  // also check down into nameless subcommands
7627  if(subc->get_name().empty()) {
7628  auto *opt = subc->get_option_no_throw(option_name);
7629  if(opt != nullptr) {
7630  return opt;
7631  }
7632  }
7633  }
7634  return nullptr;
7635 }
7636 
7638  for(const Option_p &opt : options_) {
7639  if(opt->check_name(option_name)) {
7640  return opt.get();
7641  }
7642  }
7643  for(const auto &subc : subcommands_) {
7644  // also check down into nameless subcommands
7645  if(subc->get_name().empty()) {
7646  auto *opt = subc->get_option_no_throw(option_name);
7647  if(opt != nullptr) {
7648  return opt;
7649  }
7650  }
7651  }
7652  return nullptr;
7653 }
7654 
7656  if(name_.empty()) {
7657  return std::string("[Option Group: ") + get_group() + "]";
7658  }
7659  if(aliases_.empty() || !with_aliases) {
7660  return name_;
7661  }
7662  std::string dispname = name_;
7663  for(const auto &lalias : aliases_) {
7664  dispname.push_back(',');
7665  dispname.push_back(' ');
7666  dispname.append(lalias);
7667  }
7668  return dispname;
7669 }
7670 
7673  if(ignore_underscore_) {
7674  local_name = detail::remove_underscore(name_);
7675  name_to_check = detail::remove_underscore(name_to_check);
7676  }
7677  if(ignore_case_) {
7678  local_name = detail::to_lower(name_);
7679  name_to_check = detail::to_lower(name_to_check);
7680  }
7681 
7682  if(local_name == name_to_check) {
7683  return true;
7684  }
7685  for(auto les : aliases_) { // NOLINT(performance-for-range-copy)
7686  if(ignore_underscore_) {
7687  les = detail::remove_underscore(les);
7688  }
7689  if(ignore_case_) {
7690  les = detail::to_lower(les);
7691  }
7692  if(les == name_to_check) {
7693  return true;
7694  }
7695  }
7696  return false;
7697 }
7698 
7699 CLI11_NODISCARD CLI11_INLINE std::vector<std::string> App::get_groups() const {
7700  std::vector<std::string> groups;
7701 
7702  for(const Option_p &opt : options_) {
7703  // Add group if it is not already in there
7704  if(std::find(groups.begin(), groups.end(), opt->get_group()) == groups.end()) {
7705  groups.push_back(opt->get_group());
7706  }
7707  }
7708 
7709  return groups;
7710 }
7711 
7712 CLI11_NODISCARD CLI11_INLINE std::vector<std::string> App::remaining(bool recurse) const {
7713  std::vector<std::string> miss_list;
7714  for(const std::pair<detail::Classifier, std::string> &miss : missing_) {
7715  miss_list.push_back(std::get<1>(miss));
7716  }
7717  // Get from a subcommand that may allow extras
7718  if(recurse) {
7719  if(!allow_extras_) {
7720  for(const auto &sub : subcommands_) {
7721  if(sub->name_.empty() && !sub->missing_.empty()) {
7722  for(const std::pair<detail::Classifier, std::string> &miss : sub->missing_) {
7723  miss_list.push_back(std::get<1>(miss));
7724  }
7725  }
7726  }
7727  }
7728  // Recurse into subcommands
7729 
7730  for(const App *sub : parsed_subcommands_) {
7731  std::vector<std::string> output = sub->remaining(recurse);
7732  std::copy(std::begin(output), std::end(output), std::back_inserter(miss_list));
7733  }
7734  }
7735  return miss_list;
7736 }
7737 
7738 CLI11_NODISCARD CLI11_INLINE std::vector<std::string> App::remaining_for_passthrough(bool recurse) const {
7739  std::vector<std::string> miss_list = remaining(recurse);
7740  std::reverse(std::begin(miss_list), std::end(miss_list));
7741  return miss_list;
7742 }
7743 
7744 CLI11_NODISCARD CLI11_INLINE std::size_t App::remaining_size(bool recurse) const {
7745  auto remaining_options = static_cast<std::size_t>(std::count_if(
7746  std::begin(missing_), std::end(missing_), [](const std::pair<detail::Classifier, std::string> &val) {
7747  return val.first != detail::Classifier::POSITIONAL_MARK;
7748  }));
7749 
7750  if(recurse) {
7751  for(const App_p &sub : subcommands_) {
7752  remaining_options += sub->remaining_size(recurse);
7753  }
7754  }
7755  return remaining_options;
7756 }
7757 
7759  // count the number of positional only args
7760  auto pcount = std::count_if(std::begin(options_), std::end(options_), [](const Option_p &opt) {
7761  return opt->get_items_expected_max() >= detail::expected_max_vector_size && !opt->nonpositional();
7762  });
7763  if(pcount > 1) {
7764  auto pcount_req = std::count_if(std::begin(options_), std::end(options_), [](const Option_p &opt) {
7765  return opt->get_items_expected_max() >= detail::expected_max_vector_size && !opt->nonpositional() &&
7766  opt->get_required();
7767  });
7768  if(pcount - pcount_req > 1) {
7769  throw InvalidError(name_);
7770  }
7771  }
7772 
7773  std::size_t nameless_subs{0};
7774  for(const App_p &app : subcommands_) {
7775  app->_validate();
7776  if(app->get_name().empty())
7777  ++nameless_subs;
7778  }
7779 
7780  if(require_option_min_ > 0) {
7781  if(require_option_max_ > 0) {
7783  throw(InvalidError("Required min options greater than required max options", ExitCodes::InvalidError));
7784  }
7785  }
7786  if(require_option_min_ > (options_.size() + nameless_subs)) {
7787  throw(
7788  InvalidError("Required min options greater than number of available options", ExitCodes::InvalidError));
7789  }
7790  }
7791 }
7792 
7795  disabled_ = false;
7796  } else if(default_startup == startup_mode::disabled) {
7797  disabled_ = true;
7798  }
7799  for(const App_p &app : subcommands_) {
7800  if(app->has_automatic_name_) {
7801  app->name_.clear();
7802  }
7803  if(app->name_.empty()) {
7804  app->fallthrough_ = false; // make sure fallthrough_ is false to prevent infinite loop
7805  app->prefix_command_ = false;
7806  }
7807  // make sure the parent is set to be this object in preparation for parse
7808  app->parent_ = this;
7809  app->_configure();
7810  }
7811 }
7812 
7813 CLI11_INLINE void App::run_callback(bool final_mode, bool suppress_final_callback) {
7814  pre_callback();
7815  // in the main app if immediate_callback_ is set it runs the main callback before the used subcommands
7816  if(!final_mode && parse_complete_callback_) {
7818  }
7819  // run the callbacks for the received subcommands
7820  for(App *subc : get_subcommands()) {
7821  if(subc->parent_ == this) {
7822  subc->run_callback(true, suppress_final_callback);
7823  }
7824  }
7825  // now run callbacks for option_groups
7826  for(auto &subc : subcommands_) {
7827  if(subc->name_.empty() && subc->count_all() > 0) {
7828  subc->run_callback(true, suppress_final_callback);
7829  }
7830  }
7831 
7832  // finally run the main callback
7833  if(final_callback_ && (parsed_ > 0) && (!suppress_final_callback)) {
7834  if(!name_.empty() || count_all() > 0 || parent_ == nullptr) {
7835  final_callback_();
7836  }
7837  }
7838 }
7839 
7840 CLI11_NODISCARD CLI11_INLINE bool App::_valid_subcommand(const std::string &current, bool ignore_used) const {
7841  // Don't match if max has been reached - but still check parents
7843  return parent_ != nullptr && parent_->_valid_subcommand(current, ignore_used);
7844  }
7845  auto *com = _find_subcommand(current, true, ignore_used);
7846  if(com != nullptr) {
7847  return true;
7848  }
7849  // Check parent if exists, else return false
7850  return parent_ != nullptr && parent_->_valid_subcommand(current, ignore_used);
7851 }
7852 
7854  bool ignore_used_subcommands) const {
7855  std::string dummy1, dummy2;
7856 
7857  if(current == "--")
7859  if(_valid_subcommand(current, ignore_used_subcommands))
7861  if(detail::split_long(current, dummy1, dummy2))
7862  return detail::Classifier::LONG;
7863  if(detail::split_short(current, dummy1, dummy2)) {
7864  if(dummy1[0] >= '0' && dummy1[0] <= '9') {
7865  if(get_option_no_throw(std::string{'-', dummy1[0]}) == nullptr) {
7866  return detail::Classifier::NONE;
7867  }
7868  }
7870  }
7871  if((allow_windows_style_options_) && (detail::split_windows_style(current, dummy1, dummy2)))
7873  if((current == "++") && !name_.empty() && parent_ != nullptr)
7875  return detail::Classifier::NONE;
7876 }
7877 
7879  if(config_ptr_ != nullptr) {
7880  bool config_required = config_ptr_->get_required();
7881  auto file_given = config_ptr_->count() > 0;
7882  auto config_files = config_ptr_->as<std::vector<std::string>>();
7883  if(config_files.empty() || config_files.front().empty()) {
7884  if(config_required) {
7885  throw FileError::Missing("no specified config file");
7886  }
7887  return;
7888  }
7889  for(auto rit = config_files.rbegin(); rit != config_files.rend(); ++rit) {
7890  const auto &config_file = *rit;
7891  auto path_result = detail::check_path(config_file.c_str());
7892  if(path_result == detail::path_type::file) {
7893  try {
7894  std::vector<ConfigItem> values = config_formatter_->from_file(config_file);
7895  _parse_config(values);
7896  if(!file_given) {
7897  config_ptr_->add_result(config_file);
7898  }
7899  } catch(const FileError &) {
7900  if(config_required || file_given)
7901  throw;
7902  }
7903  } else if(config_required || file_given) {
7904  throw FileError::Missing(config_file);
7905  }
7906  }
7907  }
7908 }
7909 
7911  for(const Option_p &opt : options_) {
7912  if(opt->count() == 0 && !opt->envname_.empty()) {
7913  char *buffer = nullptr;
7914  std::string ename_string;
7915 
7916 #ifdef _MSC_VER
7917  // Windows version
7918  std::size_t sz = 0;
7919  if(_dupenv_s(&buffer, &sz, opt->envname_.c_str()) == 0 && buffer != nullptr) {
7920  ename_string = std::string(buffer);
7921  free(buffer);
7922  }
7923 #else
7924  // This also works on Windows, but gives a warning
7925  buffer = std::getenv(opt->envname_.c_str());
7926  if(buffer != nullptr)
7927  ename_string = std::string(buffer);
7928 #endif
7929 
7930  if(!ename_string.empty()) {
7931  opt->add_result(ename_string);
7932  }
7933  }
7934  }
7935 
7936  for(App_p &sub : subcommands_) {
7937  if(sub->get_name().empty() || !sub->parse_complete_callback_)
7938  sub->_process_env();
7939  }
7940 }
7941 
7943 
7944  for(App_p &sub : subcommands_) {
7945  // process the priority option_groups first
7946  if(sub->get_name().empty() && sub->parse_complete_callback_) {
7947  if(sub->count_all() > 0) {
7948  sub->_process_callbacks();
7949  sub->run_callback();
7950  }
7951  }
7952  }
7953 
7954  for(const Option_p &opt : options_) {
7955  if((*opt) && !opt->get_callback_run()) {
7956  opt->run_callback();
7957  }
7958  }
7959  for(App_p &sub : subcommands_) {
7960  if(!sub->parse_complete_callback_) {
7961  sub->_process_callbacks();
7962  }
7963  }
7964 }
7965 
7966 CLI11_INLINE void App::_process_help_flags(bool trigger_help, bool trigger_all_help) const {
7967  const Option *help_ptr = get_help_ptr();
7968  const Option *help_all_ptr = get_help_all_ptr();
7969 
7970  if(help_ptr != nullptr && help_ptr->count() > 0)
7971  trigger_help = true;
7972  if(help_all_ptr != nullptr && help_all_ptr->count() > 0)
7973  trigger_all_help = true;
7974 
7975  // If there were parsed subcommands, call those. First subcommand wins if there are multiple ones.
7976  if(!parsed_subcommands_.empty()) {
7977  for(const App *sub : parsed_subcommands_)
7978  sub->_process_help_flags(trigger_help, trigger_all_help);
7979 
7980  // Only the final subcommand should call for help. All help wins over help.
7981  } else if(trigger_all_help) {
7982  throw CallForAllHelp();
7983  } else if(trigger_help) {
7984  throw CallForHelp();
7985  }
7986 }
7987 
7989  // check excludes
7990  bool excluded{false};
7991  std::string excluder;
7992  for(const auto &opt : exclude_options_) {
7993  if(opt->count() > 0) {
7994  excluded = true;
7995  excluder = opt->get_name();
7996  }
7997  }
7998  for(const auto &subc : exclude_subcommands_) {
7999  if(subc->count_all() > 0) {
8000  excluded = true;
8001  excluder = subc->get_display_name();
8002  }
8003  }
8004  if(excluded) {
8005  if(count_all() > 0) {
8006  throw ExcludesError(get_display_name(), excluder);
8007  }
8008  // if we are excluded but didn't receive anything, just return
8009  return;
8010  }
8011 
8012  // check excludes
8013  bool missing_needed{false};
8014  std::string missing_need;
8015  for(const auto &opt : need_options_) {
8016  if(opt->count() == 0) {
8017  missing_needed = true;
8018  missing_need = opt->get_name();
8019  }
8020  }
8021  for(const auto &subc : need_subcommands_) {
8022  if(subc->count_all() == 0) {
8023  missing_needed = true;
8024  missing_need = subc->get_display_name();
8025  }
8026  }
8027  if(missing_needed) {
8028  if(count_all() > 0) {
8029  throw RequiresError(get_display_name(), missing_need);
8030  }
8031  // if we missing something but didn't have any options, just return
8032  return;
8033  }
8034 
8035  std::size_t used_options = 0;
8036  for(const Option_p &opt : options_) {
8037 
8038  if(opt->count() != 0) {
8039  ++used_options;
8040  }
8041  // Required but empty
8042  if(opt->get_required() && opt->count() == 0) {
8043  throw RequiredError(opt->get_name());
8044  }
8045  // Requires
8046  for(const Option *opt_req : opt->needs_)
8047  if(opt->count() > 0 && opt_req->count() == 0)
8048  throw RequiresError(opt->get_name(), opt_req->get_name());
8049  // Excludes
8050  for(const Option *opt_ex : opt->excludes_)
8051  if(opt->count() > 0 && opt_ex->count() != 0)
8052  throw ExcludesError(opt->get_name(), opt_ex->get_name());
8053  }
8054  // check for the required number of subcommands
8055  if(require_subcommand_min_ > 0) {
8056  auto selected_subcommands = get_subcommands();
8057  if(require_subcommand_min_ > selected_subcommands.size())
8058  throw RequiredError::Subcommand(require_subcommand_min_);
8059  }
8060 
8061  // Max error cannot occur, the extra subcommand will parse as an ExtrasError or a remaining item.
8062 
8063  // run this loop to check how many unnamed subcommands were actually used since they are considered options
8064  // from the perspective of an App
8065  for(App_p &sub : subcommands_) {
8066  if(sub->disabled_)
8067  continue;
8068  if(sub->name_.empty() && sub->count_all() > 0) {
8069  ++used_options;
8070  }
8071  }
8072 
8073  if(require_option_min_ > used_options || (require_option_max_ > 0 && require_option_max_ < used_options)) {
8074  auto option_list = detail::join(options_, [this](const Option_p &ptr) {
8075  if(ptr.get() == help_ptr_ || ptr.get() == help_all_ptr_) {
8076  return std::string{};
8077  }
8078  return ptr->get_name(false, true);
8079  });
8080 
8081  auto subc_list = get_subcommands([](App *app) { return ((app->get_name().empty()) && (!app->disabled_)); });
8082  if(!subc_list.empty()) {
8083  option_list += "," + detail::join(subc_list, [](const App *app) { return app->get_display_name(); });
8084  }
8085  throw RequiredError::Option(require_option_min_, require_option_max_, used_options, option_list);
8086  }
8087 
8088  // now process the requirements for subcommands if needed
8089  for(App_p &sub : subcommands_) {
8090  if(sub->disabled_)
8091  continue;
8092  if(sub->name_.empty() && sub->required_ == false) {
8093  if(sub->count_all() == 0) {
8094  if(require_option_min_ > 0 && require_option_min_ <= used_options) {
8095  continue;
8096  // if we have met the requirement and there is nothing in this option group skip checking
8097  // requirements
8098  }
8099  if(require_option_max_ > 0 && used_options >= require_option_min_) {
8100  continue;
8101  // if we have met the requirement and there is nothing in this option group skip checking
8102  // requirements
8103  }
8104  }
8105  }
8106  if(sub->count() > 0 || sub->name_.empty()) {
8107  sub->_process_requirements();
8108  }
8109 
8110  if(sub->required_ && sub->count_all() == 0) {
8111  throw(CLI::RequiredError(sub->get_display_name()));
8112  }
8113  }
8114 }
8115 
8117  try {
8118  // the config file might generate a FileError but that should not be processed until later in the process
8119  // to allow for help, version and other errors to generate first.
8121 
8122  // process env shouldn't throw but no reason to process it if config generated an error
8123  _process_env();
8124  } catch(const CLI::FileError &) {
8125  // callbacks and help_flags can generate exceptions which should take priority
8126  // over the config file error if one exists.
8129  throw;
8130  }
8131 
8134 
8136 }
8137 
8139  if(!(allow_extras_ || prefix_command_)) {
8140  std::size_t num_left_over = remaining_size();
8141  if(num_left_over > 0) {
8142  throw ExtrasError(name_, remaining(false));
8143  }
8144  }
8145 
8146  for(App_p &sub : subcommands_) {
8147  if(sub->count() > 0)
8148  sub->_process_extras();
8149  }
8150 }
8151 
8152 CLI11_INLINE void App::_process_extras(std::vector<std::string> &args) {
8153  if(!(allow_extras_ || prefix_command_)) {
8154  std::size_t num_left_over = remaining_size();
8155  if(num_left_over > 0) {
8156  args = remaining(false);
8157  throw ExtrasError(name_, args);
8158  }
8159  }
8160 
8161  for(App_p &sub : subcommands_) {
8162  if(sub->count() > 0)
8163  sub->_process_extras(args);
8164  }
8165 }
8166 
8168  ++parsed_;
8169  for(App_p &sub : subcommands_) {
8170  if(sub->get_name().empty())
8171  sub->increment_parsed();
8172  }
8173 }
8174 
8175 CLI11_INLINE void App::_parse(std::vector<std::string> &args) {
8176  increment_parsed();
8177  _trigger_pre_parse(args.size());
8178  bool positional_only = false;
8179 
8180  while(!args.empty()) {
8181  if(!_parse_single(args, positional_only)) {
8182  break;
8183  }
8184  }
8185 
8186  if(parent_ == nullptr) {
8187  _process();
8188 
8189  // Throw error if any items are left over (depending on settings)
8190  _process_extras(args);
8191 
8192  // Convert missing (pairs) to extras (string only) ready for processing in another app
8193  args = remaining_for_passthrough(false);
8194  } else if(parse_complete_callback_) {
8195  _process_env();
8199  run_callback(false, true);
8200  }
8201 }
8202 
8203 CLI11_INLINE void App::_parse(std::vector<std::string> &&args) {
8204  // this can only be called by the top level in which case parent == nullptr by definition
8205  // operation is simplified
8206  increment_parsed();
8207  _trigger_pre_parse(args.size());
8208  bool positional_only = false;
8209 
8210  while(!args.empty()) {
8211  _parse_single(args, positional_only);
8212  }
8213  _process();
8214 
8215  // Throw error if any items are left over (depending on settings)
8216  _process_extras();
8217 }
8218 
8219 CLI11_INLINE void App::_parse_stream(std::istream &input) {
8220  auto values = config_formatter_->from_config(input);
8221  _parse_config(values);
8222  increment_parsed();
8223  _trigger_pre_parse(values.size());
8224  _process();
8225 
8226  // Throw error if any items are left over (depending on settings)
8227  _process_extras();
8228 }
8229 
8230 CLI11_INLINE void App::_parse_config(const std::vector<ConfigItem> &args) {
8231  for(const ConfigItem &item : args) {
8233  throw ConfigError::Extras(item.fullname());
8234  }
8235 }
8236 
8237 CLI11_INLINE bool App::_parse_single_config(const ConfigItem &item, std::size_t level) {
8238  if(level < item.parents.size()) {
8239  try {
8240  auto *subcom = get_subcommand(item.parents.at(level));
8241  auto result = subcom->_parse_single_config(item, level + 1);
8242 
8243  return result;
8244  } catch(const OptionNotFound &) {
8245  return false;
8246  }
8247  }
8248  // check for section open
8249  if(item.name == "++") {
8250  if(configurable_) {
8251  increment_parsed();
8252  _trigger_pre_parse(2);
8253  if(parent_ != nullptr) {
8254  parent_->parsed_subcommands_.push_back(this);
8255  }
8256  }
8257  return true;
8258  }
8259  // check for section close
8260  if(item.name == "--") {
8264  run_callback();
8265  }
8266  return true;
8267  }
8268  Option *op = get_option_no_throw("--" + item.name);
8269  if(op == nullptr) {
8270  if(item.name.size() == 1) {
8271  op = get_option_no_throw("-" + item.name);
8272  }
8273  }
8274  if(op == nullptr) {
8275  op = get_option_no_throw(item.name);
8276  }
8277  if(op == nullptr) {
8278  // If the option was not present
8280  // Should we worry about classifying the extras properly?
8281  missing_.emplace_back(detail::Classifier::NONE, item.fullname());
8282  return false;
8283  }
8284 
8285  if(!op->get_configurable()) {
8287  return false;
8288  }
8289  throw ConfigError::NotConfigurable(item.fullname());
8290  }
8291 
8292  if(op->empty()) {
8293 
8294  if(op->get_expected_min() == 0) {
8295  if(item.inputs.size() <= 1) {
8296  // Flag parsing
8297  auto res = config_formatter_->to_flag(item);
8298  res = op->get_flag_value(item.name, res);
8299 
8300  op->add_result(res);
8301  return true;
8302  }
8303  if(static_cast<int>(item.inputs.size()) > op->get_items_expected_max()) {
8304  if(op->get_items_expected_max() > 1) {
8305  throw ArgumentMismatch::AtMost(item.fullname(), op->get_items_expected_max(), item.inputs.size());
8306  }
8307  throw ConversionError::TooManyInputsFlag(item.fullname());
8308  }
8309  }
8310  op->add_result(item.inputs);
8311  op->run_callback();
8312  }
8313 
8314  return true;
8315 }
8316 
8317 CLI11_INLINE bool App::_parse_single(std::vector<std::string> &args, bool &positional_only) {
8318  bool retval = true;
8319  detail::Classifier classifier = positional_only ? detail::Classifier::NONE : _recognize(args.back());
8320  switch(classifier) {
8322  args.pop_back();
8323  positional_only = true;
8324  if((!_has_remaining_positionals()) && (parent_ != nullptr)) {
8325  retval = false;
8326  } else {
8327  _move_to_missing(classifier, "--");
8328  }
8329  break;
8331  // treat this like a positional mark if in the parent app
8332  args.pop_back();
8333  retval = false;
8334  break;
8336  retval = _parse_subcommand(args);
8337  break;
8341  // If already parsed a subcommand, don't accept options_
8342  _parse_arg(args, classifier);
8343  break;
8345  // Probably a positional or something for a parent (sub)command
8346  retval = _parse_positional(args, false);
8347  if(retval && positionals_at_end_) {
8348  positional_only = true;
8349  }
8350  break;
8351  // LCOV_EXCL_START
8352  default:
8353  throw HorribleError("unrecognized classifier (you should not see this!)");
8354  // LCOV_EXCL_STOP
8355  }
8356  return retval;
8357 }
8358 
8359 CLI11_NODISCARD CLI11_INLINE std::size_t App::_count_remaining_positionals(bool required_only) const {
8360  std::size_t retval = 0;
8361  for(const Option_p &opt : options_) {
8362  if(opt->get_positional() && (!required_only || opt->get_required())) {
8363  if(opt->get_items_expected_min() > 0 && static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
8364  retval += static_cast<std::size_t>(opt->get_items_expected_min()) - opt->count();
8365  }
8366  }
8367  }
8368  return retval;
8369 }
8370 
8372  for(const Option_p &opt : options_) {
8373  if(opt->get_positional() && ((static_cast<int>(opt->count()) < opt->get_items_expected_min()))) {
8374  return true;
8375  }
8376  }
8377 
8378  return false;
8379 }
8380 
8381 CLI11_INLINE bool App::_parse_positional(std::vector<std::string> &args, bool haltOnSubcommand) {
8382 
8383  const std::string &positional = args.back();
8384 
8385  if(positionals_at_end_) {
8386  // deal with the case of required arguments at the end which should take precedence over other arguments
8387  auto arg_rem = args.size();
8388  auto remreq = _count_remaining_positionals(true);
8389  if(arg_rem <= remreq) {
8390  for(const Option_p &opt : options_) {
8391  if(opt->get_positional() && opt->required_) {
8392  if(static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
8393  if(validate_positionals_) {
8394  std::string pos = positional;
8395  pos = opt->_validate(pos, 0);
8396  if(!pos.empty()) {
8397  continue;
8398  }
8399  }
8400 
8401  parse_order_.push_back(opt.get());
8402  /// if we require a separator add it here
8403  if(opt->get_inject_separator()) {
8404  if(!opt->results().empty() && !opt->results().back().empty()) {
8405  opt->add_result(std::string{});
8406  }
8407  }
8408  if(opt->get_trigger_on_parse() &&
8410  opt->clear();
8411  }
8412  opt->add_result(positional);
8413  if(opt->get_trigger_on_parse()) {
8414  opt->run_callback();
8415  }
8416  args.pop_back();
8417  return true;
8418  }
8419  }
8420  }
8421  }
8422  }
8423  for(const Option_p &opt : options_) {
8424  // Eat options, one by one, until done
8425  if(opt->get_positional() &&
8426  (static_cast<int>(opt->count()) < opt->get_items_expected_min() || opt->get_allow_extra_args())) {
8427  if(validate_positionals_) {
8428  std::string pos = positional;
8429  pos = opt->_validate(pos, 0);
8430  if(!pos.empty()) {
8431  continue;
8432  }
8433  }
8434  if(opt->get_inject_separator()) {
8435  if(!opt->results().empty() && !opt->results().back().empty()) {
8436  opt->add_result(std::string{});
8437  }
8438  }
8440  opt->clear();
8441  }
8442  opt->add_result(positional);
8443  if(opt->get_trigger_on_parse()) {
8444  opt->run_callback();
8445  }
8446  parse_order_.push_back(opt.get());
8447  args.pop_back();
8448  return true;
8449  }
8450  }
8451 
8452  for(auto &subc : subcommands_) {
8453  if((subc->name_.empty()) && (!subc->disabled_)) {
8454  if(subc->_parse_positional(args, false)) {
8455  if(!subc->pre_parse_called_) {
8456  subc->_trigger_pre_parse(args.size());
8457  }
8458  return true;
8459  }
8460  }
8461  }
8462  // let the parent deal with it if possible
8463  if(parent_ != nullptr && fallthrough_)
8464  return _get_fallthrough_parent()->_parse_positional(args, static_cast<bool>(parse_complete_callback_));
8465 
8466  /// Try to find a local subcommand that is repeated
8467  auto *com = _find_subcommand(args.back(), true, false);
8468  if(com != nullptr && (require_subcommand_max_ == 0 || require_subcommand_max_ > parsed_subcommands_.size())) {
8469  if(haltOnSubcommand) {
8470  return false;
8471  }
8472  args.pop_back();
8473  com->_parse(args);
8474  return true;
8475  }
8476  /// now try one last gasp at subcommands that have been executed before, go to root app and try to find a
8477  /// subcommand in a broader way, if one exists let the parent deal with it
8478  auto *parent_app = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
8479  com = parent_app->_find_subcommand(args.back(), true, false);
8480  if(com != nullptr && (com->parent_->require_subcommand_max_ == 0 ||
8481  com->parent_->require_subcommand_max_ > com->parent_->parsed_subcommands_.size())) {
8482  return false;
8483  }
8484 
8485  if(positionals_at_end_) {
8486  throw CLI::ExtrasError(name_, args);
8487  }
8488  /// If this is an option group don't deal with it
8489  if(parent_ != nullptr && name_.empty()) {
8490  return false;
8491  }
8492  /// We are out of other options this goes to missing
8494  args.pop_back();
8495  if(prefix_command_) {
8496  while(!args.empty()) {
8498  args.pop_back();
8499  }
8500  }
8501 
8502  return true;
8503 }
8504 
8506 App::_find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept {
8507  for(const App_p &com : subcommands_) {
8508  if(com->disabled_ && ignore_disabled)
8509  continue;
8510  if(com->get_name().empty()) {
8511  auto *subc = com->_find_subcommand(subc_name, ignore_disabled, ignore_used);
8512  if(subc != nullptr) {
8513  return subc;
8514  }
8515  }
8516  if(com->check_name(subc_name)) {
8517  if((!*com) || !ignore_used)
8518  return com.get();
8519  }
8520  }
8521  return nullptr;
8522 }
8523 
8524 CLI11_INLINE bool App::_parse_subcommand(std::vector<std::string> &args) {
8525  if(_count_remaining_positionals(/* required */ true) > 0) {
8526  _parse_positional(args, false);
8527  return true;
8528  }
8529  auto *com = _find_subcommand(args.back(), true, true);
8530  if(com != nullptr) {
8531  args.pop_back();
8532  if(!com->silent_) {
8533  parsed_subcommands_.push_back(com);
8534  }
8535  com->_parse(args);
8536  auto *parent_app = com->parent_;
8537  while(parent_app != this) {
8538  parent_app->_trigger_pre_parse(args.size());
8539  if(!com->silent_) {
8540  parent_app->parsed_subcommands_.push_back(com);
8541  }
8542  parent_app = parent_app->parent_;
8543  }
8544  return true;
8545  }
8546 
8547  if(parent_ == nullptr)
8548  throw HorribleError("Subcommand " + args.back() + " missing");
8549  return false;
8550 }
8551 
8552 CLI11_INLINE bool App::_parse_arg(std::vector<std::string> &args, detail::Classifier current_type) {
8553 
8554  std::string current = args.back();
8555 
8556  std::string arg_name;
8558  std::string rest;
8559 
8560  switch(current_type) {
8562  if(!detail::split_long(current, arg_name, value))
8563  throw HorribleError("Long parsed but missing (you should not see this):" + args.back());
8564  break;
8566  if(!detail::split_short(current, arg_name, rest))
8567  throw HorribleError("Short parsed but missing! You should not see this");
8568  break;
8570  if(!detail::split_windows_style(current, arg_name, value))
8571  throw HorribleError("windows option parsed but missing! You should not see this");
8572  break;
8577  default:
8578  throw HorribleError("parsing got called with invalid option! You should not see this");
8579  }
8580 
8581  auto op_ptr = std::find_if(std::begin(options_), std::end(options_), [arg_name, current_type](const Option_p &opt) {
8582  if(current_type == detail::Classifier::LONG)
8583  return opt->check_lname(arg_name);
8584  if(current_type == detail::Classifier::SHORT)
8585  return opt->check_sname(arg_name);
8586  // this will only get called for detail::Classifier::WINDOWS_STYLE
8587  return opt->check_lname(arg_name) || opt->check_sname(arg_name);
8588  });
8589 
8590  // Option not found
8591  if(op_ptr == std::end(options_)) {
8592  for(auto &subc : subcommands_) {
8593  if(subc->name_.empty() && !subc->disabled_) {
8594  if(subc->_parse_arg(args, current_type)) {
8595  if(!subc->pre_parse_called_) {
8596  subc->_trigger_pre_parse(args.size());
8597  }
8598  return true;
8599  }
8600  }
8601  }
8602 
8603  // don't capture missing if this is a nameless subcommand and nameless subcommands can't fallthrough
8604  if(parent_ != nullptr && name_.empty()) {
8605  return false;
8606  }
8607 
8608  // If a subcommand, try the main command
8609  if(parent_ != nullptr && fallthrough_)
8610  return _get_fallthrough_parent()->_parse_arg(args, current_type);
8611 
8612  // Otherwise, add to missing
8613  args.pop_back();
8614  _move_to_missing(current_type, current);
8615  return true;
8616  }
8617 
8618  args.pop_back();
8619 
8620  // Get a reference to the pointer to make syntax bearable
8621  Option_p &op = *op_ptr;
8622  /// if we require a separator add it here
8623  if(op->get_inject_separator()) {
8624  if(!op->results().empty() && !op->results().back().empty()) {
8625  op->add_result(std::string{});
8626  }
8627  }
8628  if(op->get_trigger_on_parse() && op->current_option_state_ == Option::option_state::callback_run) {
8629  op->clear();
8630  }
8631  int min_num = (std::min)(op->get_type_size_min(), op->get_items_expected_min());
8632  int max_num = op->get_items_expected_max();
8633  // check container like options to limit the argument size to a single type if the allow_extra_flags argument is
8634  // set. 16 is somewhat arbitrary (needs to be at least 4)
8635  if(max_num >= detail::expected_max_vector_size / 16 && !op->get_allow_extra_args()) {
8636  auto tmax = op->get_type_size_max();
8637  max_num = detail::checked_multiply(tmax, op->get_expected_min()) ? tmax : detail::expected_max_vector_size;
8638  }
8639  // Make sure we always eat the minimum for unlimited vectors
8640  int collected = 0; // total number of arguments collected
8641  int result_count = 0; // local variable for number of results in a single arg string
8642  // deal with purely flag like things
8643  if(max_num == 0) {
8644  auto res = op->get_flag_value(arg_name, value);
8645  op->add_result(res);
8646  parse_order_.push_back(op.get());
8647  } else if(!value.empty()) { // --this=value
8648  op->add_result(value, result_count);
8649  parse_order_.push_back(op.get());
8650  collected += result_count;
8651  // -Trest
8652  } else if(!rest.empty()) {
8653  op->add_result(rest, result_count);
8654  parse_order_.push_back(op.get());
8655  rest = "";
8656  collected += result_count;
8657  }
8658 
8659  // gather the minimum number of arguments
8660  while(min_num > collected && !args.empty()) {
8661  std::string current_ = args.back();
8662  args.pop_back();
8663  op->add_result(current_, result_count);
8664  parse_order_.push_back(op.get());
8665  collected += result_count;
8666  }
8667 
8668  if(min_num > collected) { // if we have run out of arguments and the minimum was not met
8669  throw ArgumentMismatch::TypedAtLeast(op->get_name(), min_num, op->get_type_name());
8670  }
8671 
8672  // now check for optional arguments
8673  if(max_num > collected || op->get_allow_extra_args()) { // we allow optional arguments
8674  auto remreqpos = _count_remaining_positionals(true);
8675  // we have met the minimum now optionally check up to the maximum
8676  while((collected < max_num || op->get_allow_extra_args()) && !args.empty() &&
8677  _recognize(args.back(), false) == detail::Classifier::NONE) {
8678  // If any required positionals remain, don't keep eating
8679  if(remreqpos >= args.size()) {
8680  break;
8681  }
8683  std::string arg = args.back();
8684  arg = op->_validate(arg, 0);
8685  if(!arg.empty()) {
8686  break;
8687  }
8688  }
8689  op->add_result(args.back(), result_count);
8690  parse_order_.push_back(op.get());
8691  args.pop_back();
8692  collected += result_count;
8693  }
8694 
8695  // Allow -- to end an unlimited list and "eat" it
8696  if(!args.empty() && _recognize(args.back()) == detail::Classifier::POSITIONAL_MARK)
8697  args.pop_back();
8698  // optional flag that didn't receive anything now get the default value
8699  if(min_num == 0 && max_num > 0 && collected == 0) {
8700  auto res = op->get_flag_value(arg_name, std::string{});
8701  op->add_result(res);
8702  parse_order_.push_back(op.get());
8703  }
8704  }
8705  // if we only partially completed a type then add an empty string if allowed for later processing
8706  if(min_num > 0 && (collected % op->get_type_size_max()) != 0) {
8707  if(op->get_type_size_max() != op->get_type_size_min()) {
8708  op->add_result(std::string{});
8709  } else {
8710  throw ArgumentMismatch::PartialType(op->get_name(), op->get_type_size_min(), op->get_type_name());
8711  }
8712  }
8713  if(op->get_trigger_on_parse()) {
8714  op->run_callback();
8715  }
8716  if(!rest.empty()) {
8717  rest = "-" + rest;
8718  args.push_back(rest);
8719  }
8720  return true;
8721 }
8722 
8723 CLI11_INLINE void App::_trigger_pre_parse(std::size_t remaining_args) {
8724  if(!pre_parse_called_) {
8725  pre_parse_called_ = true;
8726  if(pre_parse_callback_) {
8727  pre_parse_callback_(remaining_args);
8728  }
8729  } else if(immediate_callback_) {
8730  if(!name_.empty()) {
8731  auto pcnt = parsed_;
8732  auto extras = std::move(missing_);
8733  clear();
8734  parsed_ = pcnt;
8735  pre_parse_called_ = true;
8736  missing_ = std::move(extras);
8737  }
8738  }
8739 }
8740 
8742  if(parent_ == nullptr) {
8743  throw(HorribleError("No Valid parent"));
8744  }
8745  auto *fallthrough_parent = parent_;
8746  while((fallthrough_parent->parent_ != nullptr) && (fallthrough_parent->get_name().empty())) {
8747  fallthrough_parent = fallthrough_parent->parent_;
8748  }
8749  return fallthrough_parent;
8750 }
8751 
8753  const App &base) const {
8754  static const std::string estring;
8755  if(subcom.disabled_) {
8756  return estring;
8757  }
8758  for(const auto &subc : base.subcommands_) {
8759  if(subc.get() != &subcom) {
8760  if(subc->disabled_) {
8761  continue;
8762  }
8763  if(!subcom.get_name().empty()) {
8764  if(subc->check_name(subcom.get_name())) {
8765  return subcom.get_name();
8766  }
8767  }
8768  if(!subc->get_name().empty()) {
8769  if(subcom.check_name(subc->get_name())) {
8770  return subc->get_name();
8771  }
8772  }
8773  for(const auto &les : subcom.aliases_) {
8774  if(subc->check_name(les)) {
8775  return les;
8776  }
8777  }
8778  // this loop is needed in case of ignore_underscore or ignore_case on one but not the other
8779  for(const auto &les : subc->aliases_) {
8780  if(subcom.check_name(les)) {
8781  return les;
8782  }
8783  }
8784  // if the subcommand is an option group we need to check deeper
8785  if(subc->get_name().empty()) {
8786  const auto &cmpres = _compare_subcommand_names(subcom, *subc);
8787  if(!cmpres.empty()) {
8788  return cmpres;
8789  }
8790  }
8791  // if the test subcommand is an option group we need to check deeper
8792  if(subcom.get_name().empty()) {
8793  const auto &cmpres = _compare_subcommand_names(*subc, subcom);
8794  if(!cmpres.empty()) {
8795  return cmpres;
8796  }
8797  }
8798  }
8799  }
8800  return estring;
8801 }
8802 
8804  if(allow_extras_ || subcommands_.empty()) {
8805  missing_.emplace_back(val_type, val);
8806  return;
8807  }
8808  // allow extra arguments to be places in an option group if it is allowed there
8809  for(auto &subc : subcommands_) {
8810  if(subc->name_.empty() && subc->allow_extras_) {
8811  subc->missing_.emplace_back(val_type, val);
8812  return;
8813  }
8814  }
8815  // if we haven't found any place to put them yet put them in missing
8816  missing_.emplace_back(val_type, val);
8817 }
8818 
8820  if(opt == nullptr) {
8821  throw OptionNotFound("the option is NULL");
8822  }
8823  // verify that the give app is actually a subcommand
8824  bool found = false;
8825  for(auto &subc : subcommands_) {
8826  if(app == subc.get()) {
8827  found = true;
8828  }
8829  }
8830  if(!found) {
8831  throw OptionNotFound("The Given app is not a subcommand");
8832  }
8833 
8834  if((help_ptr_ == opt) || (help_all_ptr_ == opt))
8835  throw OptionAlreadyAdded("cannot move help options");
8836 
8837  if(config_ptr_ == opt)
8838  throw OptionAlreadyAdded("cannot move config file options");
8839 
8840  auto iterator =
8841  std::find_if(std::begin(options_), std::end(options_), [opt](const Option_p &v) { return v.get() == opt; });
8842  if(iterator != std::end(options_)) {
8843  const auto &opt_p = *iterator;
8844  if(std::find_if(std::begin(app->options_), std::end(app->options_), [&opt_p](const Option_p &v) {
8845  return (*v == *opt_p);
8846  }) == std::end(app->options_)) {
8847  // only erase after the insertion was successful
8848  app->options_.push_back(std::move(*iterator));
8849  options_.erase(iterator);
8850  } else {
8851  throw OptionAlreadyAdded("option was not located: " + opt->get_name());
8852  }
8853  } else {
8854  throw OptionNotFound("could not locate the given Option");
8855  }
8856 }
8857 
8858 CLI11_INLINE void TriggerOn(App *trigger_app, App *app_to_enable) {
8859  app_to_enable->enabled_by_default(false);
8860  app_to_enable->disabled_by_default();
8861  trigger_app->preparse_callback([app_to_enable](std::size_t) { app_to_enable->disabled(false); });
8862 }
8863 
8864 CLI11_INLINE void TriggerOn(App *trigger_app, std::vector<App *> apps_to_enable) {
8865  for(auto &app : apps_to_enable) {
8866  app->enabled_by_default(false);
8867  app->disabled_by_default();
8868  }
8869 
8870  trigger_app->preparse_callback([apps_to_enable](std::size_t) {
8871  for(const auto &app : apps_to_enable) {
8872  app->disabled(false);
8873  }
8874  });
8875 }
8876 
8877 CLI11_INLINE void TriggerOff(App *trigger_app, App *app_to_enable) {
8878  app_to_enable->disabled_by_default(false);
8879  app_to_enable->enabled_by_default();
8880  trigger_app->preparse_callback([app_to_enable](std::size_t) { app_to_enable->disabled(); });
8881 }
8882 
8883 CLI11_INLINE void TriggerOff(App *trigger_app, std::vector<App *> apps_to_enable) {
8884  for(auto &app : apps_to_enable) {
8885  app->disabled_by_default(false);
8886  app->enabled_by_default();
8887  }
8888 
8889  trigger_app->preparse_callback([apps_to_enable](std::size_t) {
8890  for(const auto &app : apps_to_enable) {
8891  app->disabled();
8892  }
8893  });
8894 }
8895 
8896 CLI11_INLINE void deprecate_option(Option *opt, const std::string &replacement) {
8897  Validator deprecate_warning{[opt, replacement](std::string &) {
8898  std::cout << opt->get_name() << " is deprecated please use '" << replacement
8899  << "' instead\n";
8900  return std::string();
8901  },
8902  "DEPRECATED"};
8903  deprecate_warning.application_index(0);
8904  opt->check(deprecate_warning);
8905  if(!replacement.empty()) {
8906  opt->description(opt->get_description() + " DEPRECATED: please use '" + replacement + "' instead");
8907  }
8908 }
8909 
8911  App temp;
8912  auto *option_copy = temp.add_option(opt->get_name(false, true))
8913  ->type_size(opt->get_type_size_min(), opt->get_type_size_max())
8914  ->expected(opt->get_expected_min(), opt->get_expected_max())
8915  ->allow_extra_args(opt->get_allow_extra_args());
8916 
8917  app->remove_option(opt);
8918  auto *opt2 = app->add_option(option_copy->get_name(false, true), "option has been retired and has no effect")
8919  ->type_name("RETIRED")
8920  ->default_str("RETIRED")
8921  ->type_size(option_copy->get_type_size_min(), option_copy->get_type_size_max())
8922  ->expected(option_copy->get_expected_min(), option_copy->get_expected_max())
8923  ->allow_extra_args(option_copy->get_allow_extra_args());
8924 
8925  Validator retired_warning{[opt2](std::string &) {
8926  std::cout << "WARNING " << opt2->get_name() << " is retired and has no effect\n";
8927  return std::string();
8928  },
8929  ""};
8930  retired_warning.application_index(0);
8931  opt2->check(retired_warning);
8932 }
8933 
8934 CLI11_INLINE void retire_option(App &app, Option *opt) { retire_option(&app, opt); }
8935 
8936 CLI11_INLINE void retire_option(App *app, const std::string &option_name) {
8937 
8938  auto *opt = app->get_option_no_throw(option_name);
8939  if(opt != nullptr) {
8940  retire_option(app, opt);
8941  return;
8942  }
8943  auto *opt2 = app->add_option(option_name, "option has been retired and has no effect")
8944  ->type_name("RETIRED")
8945  ->expected(0, 1)
8946  ->default_str("RETIRED");
8947  Validator retired_warning{[opt2](std::string &) {
8948  std::cout << "WARNING " << opt2->get_name() << " is retired and has no effect\n";
8949  return std::string();
8950  },
8951  ""};
8952  retired_warning.application_index(0);
8953  opt2->check(retired_warning);
8954 }
8955 
8956 CLI11_INLINE void retire_option(App &app, const std::string &option_name) { retire_option(&app, option_name); }
8957 
8958 namespace FailureMessage {
8959 
8960 CLI11_INLINE std::string simple(const App *app, const Error &e) {
8961  std::string header = std::string(e.what()) + "\n";
8962  std::vector<std::string> names;
8963 
8964  // Collect names
8965  if(app->get_help_ptr() != nullptr)
8966  names.push_back(app->get_help_ptr()->get_name());
8967 
8968  if(app->get_help_all_ptr() != nullptr)
8969  names.push_back(app->get_help_all_ptr()->get_name());
8970 
8971  // If any names found, suggest those
8972  if(!names.empty())
8973  header += "Run with " + detail::join(names, " or ") + " for more information.\n";
8974 
8975  return header;
8976 }
8977 
8978 CLI11_INLINE std::string help(const App *app, const Error &e) {
8979  std::string header = std::string("ERROR: ") + e.get_name() + ": " + e.what() + "\n";
8980  header += app->help();
8981  return header;
8982 }
8983 
8984 } // namespace FailureMessage
8985 
8986 
8987 
8988 
8989 namespace detail {
8990 
8991 std::string convert_arg_for_ini(const std::string &arg, char stringQuote = '"', char characterQuote = '\'');
8992 
8993 /// Comma separated join, adds quotes if needed
8994 std::string ini_join(const std::vector<std::string> &args,
8995  char sepChar = ',',
8996  char arrayStart = '[',
8997  char arrayEnd = ']',
8998  char stringQuote = '"',
8999  char characterQuote = '\'');
9000 
9001 std::vector<std::string> generate_parents(const std::string &section, std::string &name, char parentSeparator);
9002 
9003 /// assuming non default segments do a check on the close and open of the segments in a configItem structure
9004 void checkParentSegments(std::vector<ConfigItem> &output, const std::string &currentSection, char parentSeparator);
9005 } // namespace detail
9006 
9007 
9008 
9009 
9010 namespace detail {
9011 
9012 CLI11_INLINE std::string convert_arg_for_ini(const std::string &arg, char stringQuote, char characterQuote) {
9013  if(arg.empty()) {
9014  return std::string(2, stringQuote);
9015  }
9016  // some specifically supported strings
9017  if(arg == "true" || arg == "false" || arg == "nan" || arg == "inf") {
9018  return arg;
9019  }
9020  // floating point conversion can convert some hex codes, but don't try that here
9021  if(arg.compare(0, 2, "0x") != 0 && arg.compare(0, 2, "0X") != 0) {
9022  double val = 0.0;
9023  if(detail::lexical_cast(arg, val)) {
9024  return arg;
9025  }
9026  }
9027  // just quote a single non numeric character
9028  if(arg.size() == 1) {
9029  return std::string(1, characterQuote) + arg + characterQuote;
9030  }
9031  // handle hex, binary or octal arguments
9032  if(arg.front() == '0') {
9033  if(arg[1] == 'x') {
9034  if(std::all_of(arg.begin() + 2, arg.end(), [](char x) {
9035  return (x >= '0' && x <= '9') || (x >= 'A' && x <= 'F') || (x >= 'a' && x <= 'f');
9036  })) {
9037  return arg;
9038  }
9039  } else if(arg[1] == 'o') {
9040  if(std::all_of(arg.begin() + 2, arg.end(), [](char x) { return (x >= '0' && x <= '7'); })) {
9041  return arg;
9042  }
9043  } else if(arg[1] == 'b') {
9044  if(std::all_of(arg.begin() + 2, arg.end(), [](char x) { return (x == '0' || x == '1'); })) {
9045  return arg;
9046  }
9047  }
9048  }
9049  if(arg.find_first_of(stringQuote) == std::string::npos) {
9050  return std::string(1, stringQuote) + arg + stringQuote;
9051  }
9052  return characterQuote + arg + characterQuote;
9053 }
9054 
9055 CLI11_INLINE std::string ini_join(const std::vector<std::string> &args,
9056  char sepChar,
9057  char arrayStart,
9058  char arrayEnd,
9059  char stringQuote,
9060  char characterQuote) {
9061  std::string joined;
9062  if(args.size() > 1 && arrayStart != '\0') {
9063  joined.push_back(arrayStart);
9064  }
9065  std::size_t start = 0;
9066  for(const auto &arg : args) {
9067  if(start++ > 0) {
9068  joined.push_back(sepChar);
9069  if(!std::isspace<char>(sepChar, std::locale())) {
9070  joined.push_back(' ');
9071  }
9072  }
9073  joined.append(convert_arg_for_ini(arg, stringQuote, characterQuote));
9074  }
9075  if(args.size() > 1 && arrayEnd != '\0') {
9076  joined.push_back(arrayEnd);
9077  }
9078  return joined;
9079 }
9080 
9081 CLI11_INLINE std::vector<std::string>
9082 generate_parents(const std::string &section, std::string &name, char parentSeparator) {
9083  std::vector<std::string> parents;
9084  if(detail::to_lower(section) != "default") {
9085  if(section.find(parentSeparator) != std::string::npos) {
9086  parents = detail::split(section, parentSeparator);
9087  } else {
9088  parents = {section};
9089  }
9090  }
9091  if(name.find(parentSeparator) != std::string::npos) {
9092  std::vector<std::string> plist = detail::split(name, parentSeparator);
9093  name = plist.back();
9094  detail::remove_quotes(name);
9095  plist.pop_back();
9096  parents.insert(parents.end(), plist.begin(), plist.end());
9097  }
9098 
9099  // clean up quotes on the parents
9100  for(auto &parent : parents) {
9101  detail::remove_quotes(parent);
9102  }
9103  return parents;
9104 }
9105 
9106 CLI11_INLINE void
9107 checkParentSegments(std::vector<ConfigItem> &output, const std::string &currentSection, char parentSeparator) {
9108 
9109  std::string estring;
9110  auto parents = detail::generate_parents(currentSection, estring, parentSeparator);
9111  if(!output.empty() && output.back().name == "--") {
9112  std::size_t msize = (parents.size() > 1U) ? parents.size() : 2;
9113  while(output.back().parents.size() >= msize) {
9114  output.push_back(output.back());
9115  output.back().parents.pop_back();
9116  }
9117 
9118  if(parents.size() > 1) {
9119  std::size_t common = 0;
9120  std::size_t mpair = (std::min)(output.back().parents.size(), parents.size() - 1);
9121  for(std::size_t ii = 0; ii < mpair; ++ii) {
9122  if(output.back().parents[ii] != parents[ii]) {
9123  break;
9124  }
9125  ++common;
9126  }
9127  if(common == mpair) {
9128  output.pop_back();
9129  } else {
9130  while(output.back().parents.size() > common + 1) {
9131  output.push_back(output.back());
9132  output.back().parents.pop_back();
9133  }
9134  }
9135  for(std::size_t ii = common; ii < parents.size() - 1; ++ii) {
9136  output.emplace_back();
9137  output.back().parents.assign(parents.begin(), parents.begin() + static_cast<std::ptrdiff_t>(ii) + 1);
9138  output.back().name = "++";
9139  }
9140  }
9141  } else if(parents.size() > 1) {
9142  for(std::size_t ii = 0; ii < parents.size() - 1; ++ii) {
9143  output.emplace_back();
9144  output.back().parents.assign(parents.begin(), parents.begin() + static_cast<std::ptrdiff_t>(ii) + 1);
9145  output.back().name = "++";
9146  }
9147  }
9148 
9149  // insert a section end which is just an empty items_buffer
9150  output.emplace_back();
9151  output.back().parents = std::move(parents);
9152  output.back().name = "++";
9153 }
9154 } // namespace detail
9155 
9156 inline std::vector<ConfigItem> ConfigBase::from_config(std::istream &input) const {
9157  std::string line;
9158  std::string currentSection = "default";
9159  std::string previousSection = "default";
9160  std::vector<ConfigItem> output;
9161  bool isDefaultArray = (arrayStart == '[' && arrayEnd == ']' && arraySeparator == ',');
9162  bool isINIArray = (arrayStart == '\0' || arrayStart == ' ') && arrayStart == arrayEnd;
9163  bool inSection{false};
9164  char aStart = (isINIArray) ? '[' : arrayStart;
9165  char aEnd = (isINIArray) ? ']' : arrayEnd;
9166  char aSep = (isINIArray && arraySeparator == ' ') ? ',' : arraySeparator;
9167  int currentSectionIndex{0};
9168  while(getline(input, line)) {
9169  std::vector<std::string> items_buffer;
9170  std::string name;
9171 
9172  detail::trim(line);
9173  std::size_t len = line.length();
9174  // lines have to be at least 3 characters to have any meaning to CLI just skip the rest
9175  if(len < 3) {
9176  continue;
9177  }
9178  if(line.front() == '[' && line.back() == ']') {
9179  if(currentSection != "default") {
9180  // insert a section end which is just an empty items_buffer
9181  output.emplace_back();
9182  output.back().parents = detail::generate_parents(currentSection, name, parentSeparatorChar);
9183  output.back().name = "--";
9184  }
9185  currentSection = line.substr(1, len - 2);
9186  // deal with double brackets for TOML
9187  if(currentSection.size() > 1 && currentSection.front() == '[' && currentSection.back() == ']') {
9188  currentSection = currentSection.substr(1, currentSection.size() - 2);
9189  }
9190  if(detail::to_lower(currentSection) == "default") {
9191  currentSection = "default";
9192  } else {
9193  detail::checkParentSegments(output, currentSection, parentSeparatorChar);
9194  }
9195  inSection = false;
9196  if(currentSection == previousSection) {
9197  ++currentSectionIndex;
9198  } else {
9199  currentSectionIndex = 0;
9200  previousSection = currentSection;
9201  }
9202  continue;
9203  }
9204 
9205  // comment lines
9206  if(line.front() == ';' || line.front() == '#' || line.front() == commentChar) {
9207  continue;
9208  }
9209 
9210  // Find = in string, split and recombine
9211  auto pos = line.find(valueDelimiter);
9212  if(pos != std::string::npos) {
9213  name = detail::trim_copy(line.substr(0, pos));
9214  std::string item = detail::trim_copy(line.substr(pos + 1));
9215  auto cloc = item.find(commentChar);
9216  if(cloc != std::string::npos) {
9217  item.erase(cloc, std::string::npos); // NOLINT(readability-suspicious-call-argument)
9218  detail::trim(item);
9219  }
9220  if(item.size() > 1 && item.front() == aStart) {
9221  for(std::string multiline; item.back() != aEnd && std::getline(input, multiline);) {
9222  detail::trim(multiline);
9223  item += multiline;
9224  }
9225  items_buffer = detail::split_up(item.substr(1, item.length() - 2), aSep);
9226  } else if((isDefaultArray || isINIArray) && item.find_first_of(aSep) != std::string::npos) {
9227  items_buffer = detail::split_up(item, aSep);
9228  } else if((isDefaultArray || isINIArray) && item.find_first_of(' ') != std::string::npos) {
9229  items_buffer = detail::split_up(item);
9230  } else {
9231  items_buffer = {item};
9232  }
9233  } else {
9234  name = detail::trim_copy(line);
9235  auto cloc = name.find(commentChar);
9236  if(cloc != std::string::npos) {
9237  name.erase(cloc, std::string::npos); // NOLINT(readability-suspicious-call-argument)
9238  detail::trim(name);
9239  }
9240 
9241  items_buffer = {"true"};
9242  }
9243  if(name.find(parentSeparatorChar) == std::string::npos) {
9244  detail::remove_quotes(name);
9245  }
9246  // clean up quotes on the items
9247  for(auto &it : items_buffer) {
9249  }
9250 
9251  std::vector<std::string> parents = detail::generate_parents(currentSection, name, parentSeparatorChar);
9252  if(parents.size() > maximumLayers) {
9253  continue;
9254  }
9255  if(!configSection.empty() && !inSection) {
9256  if(parents.empty() || parents.front() != configSection) {
9257  continue;
9258  }
9259  if(configIndex >= 0 && currentSectionIndex != configIndex) {
9260  continue;
9261  }
9262  parents.erase(parents.begin());
9263  inSection = true;
9264  }
9265  if(!output.empty() && name == output.back().name && parents == output.back().parents) {
9266  output.back().inputs.insert(output.back().inputs.end(), items_buffer.begin(), items_buffer.end());
9267  } else {
9268  output.emplace_back();
9269  output.back().parents = std::move(parents);
9270  output.back().name = std::move(name);
9271  output.back().inputs = std::move(items_buffer);
9272  }
9273  }
9274  if(currentSection != "default") {
9275  // insert a section end which is just an empty items_buffer
9276  std::string ename;
9277  output.emplace_back();
9278  output.back().parents = detail::generate_parents(currentSection, ename, parentSeparatorChar);
9279  output.back().name = "--";
9280  while(output.back().parents.size() > 1) {
9281  output.push_back(output.back());
9282  output.back().parents.pop_back();
9283  }
9284  }
9285  return output;
9286 }
9287 
9289 ConfigBase::to_config(const App *app, bool default_also, bool write_description, std::string prefix) const {
9290  std::stringstream out;
9291  std::string commentLead;
9292  commentLead.push_back(commentChar);
9293  commentLead.push_back(' ');
9294 
9295  std::vector<std::string> groups = app->get_groups();
9296  bool defaultUsed = false;
9297  groups.insert(groups.begin(), std::string("Options"));
9298  if(write_description && (app->get_configurable() || app->get_parent() == nullptr || app->get_name().empty())) {
9299  out << commentLead << detail::fix_newlines(commentLead, app->get_description()) << '\n';
9300  }
9301  for(auto &group : groups) {
9302  if(group == "Options" || group.empty()) {
9303  if(defaultUsed) {
9304  continue;
9305  }
9306  defaultUsed = true;
9307  }
9308  if(write_description && group != "Options" && !group.empty()) {
9309  out << '\n' << commentLead << group << " Options\n";
9310  }
9311  for(const Option *opt : app->get_options({})) {
9312 
9313  // Only process options that are configurable
9314  if(opt->get_configurable()) {
9315  if(opt->get_group() != group) {
9316  if(!(group == "Options" && opt->get_group().empty())) {
9317  continue;
9318  }
9319  }
9320  std::string name = prefix + opt->get_single_name();
9321  std::string value = detail::ini_join(
9323 
9324  if(value.empty() && default_also) {
9325  if(!opt->get_default_str().empty()) {
9327  } else if(opt->get_expected_min() == 0) {
9328  value = "false";
9329  } else if(opt->get_run_callback_for_default()) {
9330  value = "\"\""; // empty string default value
9331  }
9332  }
9333 
9334  if(!value.empty()) {
9335  if(!opt->get_fnames().empty()) {
9336  value = opt->get_flag_value(name, value);
9337  }
9338  if(write_description && opt->has_description()) {
9339  out << '\n';
9340  out << commentLead << detail::fix_newlines(commentLead, opt->get_description()) << '\n';
9341  }
9342  out << name << valueDelimiter << value << '\n';
9343  }
9344  }
9345  }
9346  }
9347  auto subcommands = app->get_subcommands({});
9348  for(const App *subcom : subcommands) {
9349  if(subcom->get_name().empty()) {
9350  if(write_description && !subcom->get_group().empty()) {
9351  out << '\n' << commentLead << subcom->get_group() << " Options\n";
9352  }
9353  out << to_config(subcom, default_also, write_description, prefix);
9354  }
9355  }
9356 
9357  for(const App *subcom : subcommands) {
9358  if(!subcom->get_name().empty()) {
9359  if(subcom->get_configurable() && app->got_subcommand(subcom)) {
9360  if(!prefix.empty() || app->get_parent() == nullptr) {
9361  out << '[' << prefix << subcom->get_name() << "]\n";
9362  } else {
9363  std::string subname = app->get_name() + parentSeparatorChar + subcom->get_name();
9364  const auto *p = app->get_parent();
9365  while(p->get_parent() != nullptr) {
9366  subname = p->get_name() + parentSeparatorChar + subname;
9367  p = p->get_parent();
9368  }
9369  out << '[' << subname << "]\n";
9370  }
9371  out << to_config(subcom, default_also, write_description, "");
9372  } else {
9373  out << to_config(
9374  subcom, default_also, write_description, prefix + subcom->get_name() + parentSeparatorChar);
9375  }
9376  }
9377  }
9378 
9379  return out.str();
9380 }
9381 
9382 
9383 
9384 
9385 
9386 
9388 Formatter::make_group(std::string group, bool is_positional, std::vector<const Option *> opts) const {
9389  std::stringstream out;
9390 
9391  out << "\n" << group << ":\n";
9392  for(const Option *opt : opts) {
9393  out << make_option(opt, is_positional);
9394  }
9395 
9396  return out.str();
9397 }
9398 
9400  std::vector<const Option *> opts =
9401  app->get_options([](const Option *opt) { return !opt->get_group().empty() && opt->get_positional(); });
9402 
9403  if(opts.empty())
9404  return {};
9405 
9406  return make_group(get_label("Positionals"), true, opts);
9407 }
9408 
9410  std::stringstream out;
9411  std::vector<std::string> groups = app->get_groups();
9412 
9413  // Options
9414  for(const std::string &group : groups) {
9415  std::vector<const Option *> opts = app->get_options([app, mode, &group](const Option *opt) {
9416  return opt->get_group() == group // Must be in the right group
9417  && opt->nonpositional() // Must not be a positional
9418  && (mode != AppFormatMode::Sub // If mode is Sub, then
9419  || (app->get_help_ptr() != opt // Ignore help pointer
9420  && app->get_help_all_ptr() != opt)); // Ignore help all pointer
9421  });
9422  if(!group.empty() && !opts.empty()) {
9423  out << make_group(group, false, opts);
9424 
9425  if(group != groups.back())
9426  out << "\n";
9427  }
9428  }
9429 
9430  return out.str();
9431 }
9432 
9434  std::string desc = app->get_description();
9435  auto min_options = app->get_require_option_min();
9436  auto max_options = app->get_require_option_max();
9437  if(app->get_required()) {
9438  desc += " REQUIRED ";
9439  }
9440  if((max_options == min_options) && (min_options > 0)) {
9441  if(min_options == 1) {
9442  desc += " \n[Exactly 1 of the following options is required]";
9443  } else {
9444  desc += " \n[Exactly " + std::to_string(min_options) + "options from the following list are required]";
9445  }
9446  } else if(max_options > 0) {
9447  if(min_options > 0) {
9448  desc += " \n[Between " + std::to_string(min_options) + " and " + std::to_string(max_options) +
9449  " of the follow options are required]";
9450  } else {
9451  desc += " \n[At most " + std::to_string(max_options) + " of the following options are allowed]";
9452  }
9453  } else if(min_options > 0) {
9454  desc += " \n[At least " + std::to_string(min_options) + " of the following options are required]";
9455  }
9456  return (!desc.empty()) ? desc + "\n" : std::string{};
9457 }
9458 
9460  std::stringstream out;
9461 
9462  out << get_label("Usage") << ":" << (name.empty() ? "" : " ") << name;
9463 
9464  std::vector<std::string> groups = app->get_groups();
9465 
9466  // Print an Options badge if any options exist
9467  std::vector<const Option *> non_pos_options =
9468  app->get_options([](const Option *opt) { return opt->nonpositional(); });
9469  if(!non_pos_options.empty())
9470  out << " [" << get_label("OPTIONS") << "]";
9471 
9472  // Positionals need to be listed here
9473  std::vector<const Option *> positionals = app->get_options([](const Option *opt) { return opt->get_positional(); });
9474 
9475  // Print out positionals if any are left
9476  if(!positionals.empty()) {
9477  // Convert to help names
9478  std::vector<std::string> positional_names(positionals.size());
9479  std::transform(positionals.begin(), positionals.end(), positional_names.begin(), [this](const Option *opt) {
9480  return make_option_usage(opt);
9481  });
9482 
9483  out << " " << detail::join(positional_names, " ");
9484  }
9485 
9486  // Add a marker if subcommands are expected or optional
9487  if(!app->get_subcommands(
9488  [](const CLI::App *subc) { return ((!subc->get_disabled()) && (!subc->get_name().empty())); })
9489  .empty()) {
9490  out << " " << (app->get_require_subcommand_min() == 0 ? "[" : "")
9491  << get_label(app->get_require_subcommand_max() < 2 || app->get_require_subcommand_min() > 1 ? "SUBCOMMAND"
9492  : "SUBCOMMANDS")
9493  << (app->get_require_subcommand_min() == 0 ? "]" : "");
9494  }
9495 
9496  out << std::endl;
9497 
9498  return out.str();
9499 }
9500 
9501 CLI11_INLINE std::string Formatter::make_footer(const App *app) const {
9502  std::string footer = app->get_footer();
9503  if(footer.empty()) {
9504  return std::string{};
9505  }
9506  return "\n" + footer + "\n";
9507 }
9508 
9509 CLI11_INLINE std::string Formatter::make_help(const App *app, std::string name, AppFormatMode mode) const {
9510 
9511  // This immediately forwards to the make_expanded method. This is done this way so that subcommands can
9512  // have overridden formatters
9513  if(mode == AppFormatMode::Sub)
9514  return make_expanded(app);
9515 
9516  std::stringstream out;
9517  if((app->get_name().empty()) && (app->get_parent() != nullptr)) {
9518  if(app->get_group() != "Subcommands") {
9519  out << app->get_group() << ':';
9520  }
9521  }
9522 
9523  out << make_description(app);
9524  out << make_usage(app, name);
9525  out << make_positionals(app);
9526  out << make_groups(app, mode);
9527  out << make_subcommands(app, mode);
9528  out << make_footer(app);
9529 
9530  return out.str();
9531 }
9532 
9533 CLI11_INLINE std::string Formatter::make_subcommands(const App *app, AppFormatMode mode) const {
9534  std::stringstream out;
9535 
9536  std::vector<const App *> subcommands = app->get_subcommands({});
9537 
9538  // Make a list in definition order of the groups seen
9539  std::vector<std::string> subcmd_groups_seen;
9540  for(const App *com : subcommands) {
9541  if(com->get_name().empty()) {
9542  if(!com->get_group().empty()) {
9543  out << make_expanded(com);
9544  }
9545  continue;
9546  }
9547  std::string group_key = com->get_group();
9548  if(!group_key.empty() &&
9549  std::find_if(subcmd_groups_seen.begin(), subcmd_groups_seen.end(), [&group_key](std::string a) {
9550  return detail::to_lower(a) == detail::to_lower(group_key);
9551  }) == subcmd_groups_seen.end())
9552  subcmd_groups_seen.push_back(group_key);
9553  }
9554 
9555  // For each group, filter out and print subcommands
9556  for(const std::string &group : subcmd_groups_seen) {
9557  out << "\n" << group << ":\n";
9558  std::vector<const App *> subcommands_group = app->get_subcommands(
9559  [&group](const App *sub_app) { return detail::to_lower(sub_app->get_group()) == detail::to_lower(group); });
9560  for(const App *new_com : subcommands_group) {
9561  if(new_com->get_name().empty())
9562  continue;
9563  if(mode != AppFormatMode::All) {
9564  out << make_subcommand(new_com);
9565  } else {
9566  out << new_com->help(new_com->get_name(), AppFormatMode::Sub);
9567  out << "\n";
9568  }
9569  }
9570  }
9571 
9572  return out.str();
9573 }
9574 
9575 CLI11_INLINE std::string Formatter::make_subcommand(const App *sub) const {
9576  std::stringstream out;
9577  detail::format_help(out, sub->get_display_name(true), sub->get_description(), column_width_);
9578  return out.str();
9579 }
9580 
9581 CLI11_INLINE std::string Formatter::make_expanded(const App *sub) const {
9582  std::stringstream out;
9583  out << sub->get_display_name(true) << "\n";
9584 
9585  out << make_description(sub);
9586  if(sub->get_name().empty() && !sub->get_aliases().empty()) {
9587  detail::format_aliases(out, sub->get_aliases(), column_width_ + 2);
9588  }
9589  out << make_positionals(sub);
9590  out << make_groups(sub, AppFormatMode::Sub);
9591  out << make_subcommands(sub, AppFormatMode::Sub);
9592 
9593  // Drop blank spaces
9594  std::string tmp = detail::find_and_replace(out.str(), "\n\n", "\n");
9595  tmp = tmp.substr(0, tmp.size() - 1); // Remove the final '\n'
9596 
9597  // Indent all but the first line (the name)
9598  return detail::find_and_replace(tmp, "\n", "\n ") + "\n";
9599 }
9600 
9601 CLI11_INLINE std::string Formatter::make_option_name(const Option *opt, bool is_positional) const {
9602  if(is_positional)
9603  return opt->get_name(true, false);
9604 
9605  return opt->get_name(false, true);
9606 }
9607 
9608 CLI11_INLINE std::string Formatter::make_option_opts(const Option *opt) const {
9609  std::stringstream out;
9610 
9611  if(!opt->get_option_text().empty()) {
9612  out << " " << opt->get_option_text();
9613  } else {
9614  if(opt->get_type_size() != 0) {
9615  if(!opt->get_type_name().empty())
9616  out << " " << get_label(opt->get_type_name());
9617  if(!opt->get_default_str().empty())
9618  out << " [" << opt->get_default_str() << "] ";
9620  out << " ...";
9621  else if(opt->get_expected_min() > 1)
9622  out << " x " << opt->get_expected();
9623 
9624  if(opt->get_required())
9625  out << " " << get_label("REQUIRED");
9626  }
9627  if(!opt->get_envname().empty())
9628  out << " (" << get_label("Env") << ":" << opt->get_envname() << ")";
9629  if(!opt->get_needs().empty()) {
9630  out << " " << get_label("Needs") << ":";
9631  for(const Option *op : opt->get_needs())
9632  out << " " << op->get_name();
9633  }
9634  if(!opt->get_excludes().empty()) {
9635  out << " " << get_label("Excludes") << ":";
9636  for(const Option *op : opt->get_excludes())
9637  out << " " << op->get_name();
9638  }
9639  }
9640  return out.str();
9641 }
9642 
9643 CLI11_INLINE std::string Formatter::make_option_desc(const Option *opt) const { return opt->get_description(); }
9644 
9645 CLI11_INLINE std::string Formatter::make_option_usage(const Option *opt) const {
9646  // Note that these are positionals usages
9647  std::stringstream out;
9648  out << make_option_name(opt, true);
9650  out << "...";
9651  else if(opt->get_expected_max() > 1)
9652  out << "(" << opt->get_expected() << "x)";
9653 
9654  return opt->get_required() ? out.str() : "[" + out.str() + "]";
9655 }
9656 
9657 
9658 } // namespace CLI
9659 
9660 } // namespace pxr_CLI
9661 
CLI11_NODISCARD int get_type_size_min() const
The minimum number of arguments the option expects.
Definition: CLI11.h:4636
Anything that can error in Parse.
Definition: CLI11.h:771
App * footer(std::function< std::string()> footer_function)
Set footer.
Definition: CLI11.h:6471
virtual std::string make_footer(const App *app) const
This prints out all the groups of options.
Definition: CLI11.h:9501
GLuint GLuint stream
Definition: glcorearb.h:1832
void copy_to(T *other) const
Copy the contents to another similar class (one based on OptionBase)
Definition: CLI11.h:4924
CLI11_NODISCARD bool get_validate_optional_arguments() const
Get the status of validating optional vector arguments.
Definition: CLI11.h:6616
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.h:4460
CLI11_INLINE std::string fix_newlines(const std::string &leader, std::string input)
Definition: CLI11.h:454
App * allow_config_extras(bool allow=true)
ignore extras in config files
Definition: CLI11.h:5927
App * validate_positionals(bool validate=true)
Set the subcommand to validate positional arguments before assigning.
Definition: CLI11.h:5915
void clear()
Clear the parsed results (mostly for testing)
Definition: CLI11.h:4482
void _process_requirements()
Verify required options and cross requirements. Subcommands too (only if selected).
Definition: CLI11.h:7988
CLI11_NODISCARD std::string help(std::string prev="", AppFormatMode mode=AppFormatMode::Normal) const
Definition: CLI11.h:7559
Option * envname(std::string name)
Sets environment variable to read if no option given.
Definition: CLI11.h:4603
Check for an existing path.
Definition: CLI11.h:2981
std::string simple(const App *app, const Error &e)
Printout a clean, simple message on error (the default in CLI11 1.5+)
Definition: CLI11.h:8960
void results(T &output) const
Get the results as a specified type.
Definition: CLI11.h:4789
App * excludes(Option *opt)
Sets excluded options for the subcommand.
Definition: CLI11.h:6407
typedef int(APIENTRYP RE_PFNGLXSWAPINTERVALSGIPROC)(int)
void column_width(std::size_t val)
Set the column width.
Definition: CLI11.h:4034
the results have been validated
std::vector< std::pair< detail::Classifier, std::string >> missing_t
Definition: CLI11.h:5695
std::string ignore_case(std::string item)
Helper function to allow ignore_case to be passed to IsMember or Transform.
Definition: CLI11.h:3456
std::string find_and_modify(std::string str, std::string trigger, Callable modify)
Definition: CLI11.h:376
typename std::enable_if< B, T >::type enable_if_t
Define Imath::enable_if_t to be std for C++14, equivalent for C++11.
CLI11_NODISCARD bool get_configurable() const
The status of configurable.
Definition: CLI11.h:4243
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.h:6902
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.h:5890
GLbitfield flags
Definition: glcorearb.h:1596
bool from_stream(const std::string &istring, T &obj)
Templated operation to get a value from a stream.
Definition: CLI11.h:1158
path_type
CLI enumeration of different file types.
Definition: CLI11.h:2963
CheckedTransformer(T mapping)
direct map of std::string to std::string
Definition: CLI11.h:3390
CLI11_NODISCARD const std::vector< std::string > & get_fnames() const
Get the flag names with specified default values.
Definition: CLI11.h:4665
Error(std::string name, std::string msg, ExitCodes exit_code)
Definition: CLI11.h:703
cvex test(vector P=0;int unbound=3;export float s=0;export vector Cf=0;)
Definition: test.vfl:11
CLI11_NODISCARD bool get_ignore_underscore() const
Check the status of ignore_underscore.
Definition: CLI11.h:6556
CRTP * take_all()
Set the multi option policy to take all arguments.
Definition: CLI11.h:4274
std::vector< std::pair< std::string, std::string > > default_flag_values_
Definition: CLI11.h:4362
CLI11_INLINE bool split_long(const std::string &current, std::string &name, std::string &value)
Definition: CLI11.h:2549
App * preparse_callback(std::function< void(std::size_t)> pp_callback)
Definition: CLI11.h:5854
GT_API const UT_StringHolder filename
Thrown when validation of results fails.
Definition: CLI11.h:833
CLI11_NODISCARD const App * get_parent() const
Get the parent of this subcommand (or nullptr if main app) (const version)
Definition: CLI11.h:6646
void run_callback()
Process the callback.
Definition: CLI11.h:5186
OptionDefaults * option_defaults()
Get the OptionDefault object, to set option defaults.
Definition: CLI11.h:5996
This class is simply to allow tests access to App's protected functions.
Definition: CLI11.h:6887
CLI11_NODISCARD bool get_validate_positionals() const
Get the status of validating positionals.
Definition: CLI11.h:6614
std::string envname_
If given, check the environment for this option.
Definition: CLI11.h:4371
Option * description(std::string option_description)
Set the description.
Definition: CLI11.h:4711
CLI11_NODISCARD results_t reduced_results() const
Get a copy of the results.
Definition: CLI11.h:5325
bool _parse_positional(std::vector< std::string > &args, bool haltOnSubcommand)
Definition: CLI11.h:8381
constexpr std::enable_if< I==type_count_base< T >::value, int >::type tuple_type_size()
0 if the index > tuple size
Definition: CLI11.h:1375
Option * add_option(std::string option_name)
Add option with no description or variable assignment.
Definition: CLI11.h:6089
CLI11_NODISCARD int get_items_expected_min() const
The total min number of expected string values to be used.
Definition: CLI11.h:4688
bool _parse_single_config(const ConfigItem &item, std::size_t level=0)
Fill in a single config option.
Definition: CLI11.h:8237
std::string group_
The group membership INHERITABLE.
Definition: CLI11.h:5787
std::vector< std::string > parents
This is the list of parents.
Definition: CLI11.h:2659
CLI11_INLINE bool valid_name_string(const std::string &str)
Verify an option/subcommand name.
Definition: CLI11.h:501
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.h:7162
CLI11_NODISCARD App * _find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept
Definition: CLI11.h:8506
CLI11_NODISCARD bool get_allow_windows_style_options() const
Check the status of the allow windows style options.
Definition: CLI11.h:6562
std::vector< std::string > snames_
A list of the short names (-a) without the leading dashes.
Definition: CLI11.h:4355
CLI11_INLINE std::string & remove_quotes(std::string &str)
remove quotes at the front and back of a string either '"' or '\''
Definition: CLI11.h:444
void add_options(Option *opt)
Add an existing option to the Option_group.
Definition: CLI11.h:6820
char commentChar
the character used for comments
Definition: CLI11.h:2715
CLI11_NODISCARD Validator application_index(int app_index) const
Specify the application index of a validator.
Definition: CLI11.h:2925
CLI11_NODISCARD int get_type_size() const
The number of arguments the option expects.
Definition: CLI11.h:4633
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.h:7178
std::set< Option * > exclude_options_
Definition: CLI11.h:5713
CLI11_NODISCARD char get_delimiter() const
Get the current delimiter char.
Definition: CLI11.h:4249
Option * add_option(Option *opt)
Add an existing option to the Option_group.
Definition: CLI11.h:6812
OIIO_NAMESPACE_BEGIN typedef std::ifstream ifstream
Definition: filesystem.h:57
CLI11_NODISCARD std::size_t get_require_option_max() const
Get the required max option value.
Definition: CLI11.h:6588
std::string remove_underscore(std::string str)
remove underscores from a string
Definition: CLI11.h:353
CLI11_NODISCARD App * get_option_group(std::string group_name) const
Check to see if an option group is part of this App.
Definition: CLI11.h:7335
Option * config_ptr_
Pointer to the config option.
Definition: CLI11.h:5797
Error(std::string name, std::string msg, int exit_code=static_cast< int >(ExitCodes::BaseClass))
Definition: CLI11.h:700
CLI11_NODISCARD std::string get_default_str() const
The default value (for help printing)
Definition: CLI11.h:4653
CLI11_INLINE std::vector< std::string > split(const std::string &s, char delim)
Split a string by a delim.
Definition: CLI11.h:403
Option * add_option(std::string option_name, AssignTo &variable, std::string option_description="")
Add option for assigning to a variable.
Definition: CLI11.h:6026
PUGI__FN const char_t * local_name(const xpath_node &node)
Definition: pugixml.cpp:8249
CLI11_NODISCARD config_extras_mode get_allow_config_extras() const
Get the status of allow extras.
Definition: CLI11.h:6619
std::set< Option * > excludes_
A list of options that are excluded with this option.
Definition: CLI11.h:4416
App * require_subcommand(int value)
Definition: CLI11.h:6274
CRTP * always_capture_default(bool value=true)
Definition: CLI11.h:4223
CLI11_NODISCARD 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.h:8752
void
Definition: png.h:1083
std::shared_ptr< App > App_p
Definition: CLI11.h:5582
std::function< std::string()> desc_function_
This is the description function, if empty the description_ will be used.
Definition: CLI11.h:2833
GLint left
Definition: glcorearb.h:2005
CLI11_NODISCARD const std::string & get_name() const
Get the name of the current app.
Definition: CLI11.h:6649
bool remove_option(Option *opt)
Removes an option from the App. Takes an option pointer. Returns true if found and removed...
Definition: CLI11.h:7218
void swap(UT::ArraySet< Key, MULTI, MAX_LOAD_FACTOR_256, Clearer, Hash, KeyEqual > &a, UT::ArraySet< Key, MULTI, MAX_LOAD_FACTOR_256, Clearer, Hash, KeyEqual > &b)
Definition: UT_ArraySet.h:1639
This will only trigger for actual void type.
Definition: CLI11.h:1315
OIIO_UTIL_API bool copy(string_view from, string_view to, std::string &err)
FormatterBase & operator=(const FormatterBase &)=default
Adding a destructor in this form to work around bug in GCC 4.7.
Option * option_text(std::string text)
The number of arguments the option expects.
Definition: CLI11.h:4716
const GLdouble * v
Definition: glcorearb.h:837
Check for an existing file (returns error message if check fails)
Definition: CLI11.h:2969
OIIO_UTIL_API bool remove(string_view path, std::string &err)
std::vector< std::pair< std::string, T >> TransformPairs
definition of the default transformation object
Definition: CLI11.h:3319
Thrown when parsing an INI file and it is missing.
Definition: CLI11.h:810
OptionDefaults option_defaults_
The default values for options, customizable and changeable INHERITABLE.
Definition: CLI11.h:5661
just get all the passed argument regardless
virtual std::string make_subcommand(const App *sub) const
This prints out a subcommand.
Definition: CLI11.h:9575
Option * default_val(const X &val)
Definition: CLI11.h:4876
GLuint start
Definition: glcorearb.h:475
option_state
enumeration for the option state machine
Definition: CLI11.h:4437
GLsizei const GLchar *const * string
Definition: glcorearb.h:814
App * required(bool require=true)
Remove the error when extras are left over on the command line.
Definition: CLI11.h:5872
CheckedTransformer(T mapping, F filter_function)
Definition: CLI11.h:3394
GLsizei const GLfloat * value
Definition: glcorearb.h:824
option_state current_option_state_
Whether the callback has run (needed for INI parsing)
Definition: CLI11.h:4444
CLI11_NODISCARD std::size_t get_require_option_min() const
Get the required min option value.
Definition: CLI11.h:6585
bool operator==(const Option &other) const
If options share any of the same names, they are equal (not counting positional)
Definition: CLI11.h:4746
bool active_
Enable for Validator to allow it to be disabled if need be.
Definition: CLI11.h:2843
void _parse_config(const std::vector< ConfigItem > &args)
Definition: CLI11.h:8230
CLI11_INLINE void deprecate_option(Option *opt, const std::string &replacement="")
Helper function to mark an option as deprecated.
Definition: CLI11.h:8896
CLI11_NODISCARD bool get_allow_extra_args() const
Get the current value of allow extra args.
Definition: CLI11.h:4504
results_t results_
complete Results of parsing
Definition: CLI11.h:4433
Thrown when conversion call back fails, such as when an int fails to coerce to a string.
Definition: CLI11.h:817
Check for complex.
Definition: CLI11.h:1146
std::vector< ConfigItem > from_config(std::istream &input) const override
Convert a configuration into an app.
Definition: CLI11.h:9156
void _process()
Process callbacks and such.
Definition: CLI11.h:8116
void parse_from_stream(std::istream &input)
Definition: CLI11.h:7452
bool positionals_at_end_
specify that positional arguments come at the end of the argument sequence not inheritable ...
Definition: CLI11.h:5748
CLI11_NODISCARD std::size_t count_all() const
Definition: CLI11.h:7344
bool allow_windows_style_options_
Allow '/' for options for Windows like options. Defaults to true on Windows, false otherwise...
Definition: CLI11.h:5740
std::function< std::string(std::string)> filter_fn_t
Definition: CLI11.h:3324
Option * add_result(std::string s)
Puts a result at the end.
Definition: CLI11.h:5305
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.h:7103
CLI11_NODISCARD std::set< Option * > get_excludes() const
The set of options excluded.
Definition: CLI11.h:4650
Validator & name(std::string validator_name)
Specify the type string.
Definition: CLI11.h:2890
Check to see if something is bool (fail check by default)
Definition: CLI11.h:1005
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.h:7590
Thrown when counting a non-existent option.
Definition: CLI11.h:963
CRTP * mandatory(bool value=true)
Support Plumbum term.
Definition: CLI11.h:4221
bool validate_positionals_
If set to true positional options are validated before assigning INHERITABLE.
Definition: CLI11.h:5759
CLI11_NODISCARD const std::string & get_option_text() const
The number of arguments the option expects.
Definition: CLI11.h:4721
virtual std::string make_description(const App *app) const
This displays the description line.
Definition: CLI11.h:9433
Thrown when an excludes option is present.
Definition: CLI11.h:913
CLI11_NODISCARD std::size_t count() const
Definition: CLI11.h:6252
CLI11_NODISCARD const std::vector< Option * > & parse_order() const
This gets a vector of pointers with the original parse order.
Definition: CLI11.h:6670
CRTP * take_last()
Set the multi option policy to take last.
Definition: CLI11.h:4260
std::shared_ptr< FormatterBase > formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer) ...
Definition: CLI11.h:5686
CLI11_NODISCARD std::size_t count() const
Count the total number of times an option was passed.
Definition: CLI11.h:4473
GLint level
Definition: glcorearb.h:108
App * require_subcommand(std::size_t min, std::size_t max)
Definition: CLI11.h:6287
void parse(int argc, const char *const *argv)
Definition: CLI11.h:7373
CRTP * join(char delim)
Set the multi option policy to join with a specific delimiter.
Definition: CLI11.h:4288
CLI11_NODISCARD std::string get_envname() const
The environment variable associated to this value.
Definition: CLI11.h:4644
bool has_default_flag_values(const std::string &flags)
check if the flag definitions has possible false flags
Definition: CLI11.h:362
CLI11_NODISCARD const std::vector< std::string > & get_lnames() const
Get the long names.
Definition: CLI11.h:4659
CLI11_NODISCARD const std::string & get_single_name() const
Get a single name for the option, first of lname, pname, sname, envname.
Definition: CLI11.h:4667
Option * add_flag(std::string flag_name, T &flag_description)
Definition: CLI11.h:6131
Validate the input as a particular type.
Definition: CLI11.h:3018
GLboolean GLboolean GLboolean GLboolean a
Definition: glcorearb.h:1222
CLI11_NODISCARD MultiOptionPolicy get_multi_option_policy() const
The status of the multi option policy.
Definition: CLI11.h:4255
void reverse(I begin, I end)
Definition: pugixml.cpp:7190
GLdouble s
Definition: glad.h:3009
CLI11_NODISCARD bool get_disabled() const
Get the status of disabled.
Definition: CLI11.h:6600
CLI11_NODISCARD 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.h:7738
std::string operator()(std::string &str) const
Definition: CLI11.h:3655
GA_API const UT_StringHolder com
std::uint32_t parsed_
Counts the number of times this command/subcommand was parsed.
Definition: CLI11.h:5769
Validator & description(std::string validator_desc)
Specify the type string.
Definition: CLI11.h:2875
CLI11_NODISCARD const std::vector< std::string > & get_aliases() const
Get the aliases of the current app.
Definition: CLI11.h:6652
bool has_automatic_name_
If set to true the name was automatically generated from the command line vs a user set name...
Definition: CLI11.h:5632
CLI11_NODISCARD const Option * get_version_ptr() const
Get a pointer to the version option. (const)
Definition: CLI11.h:6640
CLI11_NODISCARD std::set< Option * > get_needs() const
The set of options needed.
Definition: CLI11.h:4647
bool valid_later_char(T c)
Verify following characters of an option.
Definition: CLI11.h:317
Option * disable_flag_override(bool value=true)
Disable flag overrides values, e.g. –flag=is not allowed.
Definition: CLI11.h:4624
std::string name
This is the name.
Definition: CLI11.h:2662
enabler
Simple empty scoped class.
Definition: CLI11.h:982
App * clear_aliases()
clear all the aliases of the current App
Definition: CLI11.h:6655
CLI11_NODISCARD bool get_trigger_on_parse() const
The status of trigger on parse.
Definition: CLI11.h:4511
ImageBuf OIIO_API min(Image_or_Const A, Image_or_Const B, ROI roi={}, int nthreads=0)
std::function< std::string()> footer_callback_
This is a function that generates a footer to put after all other options in help output...
Definition: CLI11.h:5674
CLI11_NODISCARD bool get_ignore_case() const
The status of ignore case.
Definition: CLI11.h:4237
App * immediate_callback(bool immediate=true)
Set the subcommand callback to be executed immediately on subcommand completion.
Definition: CLI11.h:6990
FileOnDefaultPath(std::string default_path, bool enableErrorReturn=true)
Definition: CLI11.h:3867
Option * default_function(const std::function< std::string()> &func)
Set a capture function for the default. Mostly used by App.
Definition: CLI11.h:4855
typename std::enable_if< B, T >::type enable_if_t
Definition: CLI11.h:993
GLint y
Definition: glcorearb.h:103
std::string make_groups(const App *app, AppFormatMode mode) const
This prints out all the groups of options.
Definition: CLI11.h:9409
App * configurable(bool value=true)
Specify that the subcommand can be triggered by a config file.
Definition: CLI11.h:5966
App * add_subcommand(App *subcom)
Add an existing subcommand to be a member of an option_group.
Definition: CLI11.h:6828
CLI11_INLINE std::vector< std::string > split_up(std::string str, char delimiter= '\0')
Definition: CLI11.h:565
bool flag_like_
Specify that the option should act like a flag vs regular option.
Definition: CLI11.h:4448
std::string to_string(T &&value)
Convert an object to a string (streaming must be supported for that type)
Definition: CLI11.h:1238
CLI11_NODISCARD bool get_required() const
Get the status of required.
Definition: CLI11.h:6597
Thrown when an option is set to conflicting values (non-vector and multi args, for example) ...
Definition: CLI11.h:714
Set of overloads to get the type size of an object.
Definition: CLI11.h:1339
App * final_callback(std::function< void()> app_callback)
Definition: CLI11.h:5840
bool inject_separator_
flag indicating a separator needs to be injected after each argument call
Definition: CLI11.h:4452
ConfigBase * maxLayers(uint8_t layers)
Specify the maximum number of parents.
Definition: CLI11.h:2770
**But if you need a result
Definition: thread.h:613
std::vector< std::string > generate_parents(const std::string &section, std::string &name, char parentSeparator)
Definition: CLI11.h:9082
Option * allow_extra_args(bool value=true)
Definition: CLI11.h:4499
CLI11_NODISCARD std::size_t get_require_subcommand_max() const
Get the required max subcommand value.
Definition: CLI11.h:6582
Bound(T max_val)
Range of one value is 0 to value.
Definition: CLI11.h:3109
void _move_option(Option *opt, App *app)
function that could be used by subclasses of App to shift options around into subcommands ...
Definition: CLI11.h:8819
const detail::IPV4Validator ValidIPV4
Check for an IP4 address.
Definition: CLI11.h:3015
OptionDefaults * delimiter(char value= '\0')
set a delimiter character to split up single arguments to treat as multiple inputs ...
Definition: CLI11.h:4341
GLfloat GLfloat GLfloat v2
Definition: glcorearb.h:818
int expected_min_
The minimum number of expected values.
Definition: CLI11.h:4405
CRTP * take_first()
Set the multi option policy to take last.
Definition: CLI11.h:4267
T * add_option_group(std::string group_name, std::string group_description="")
creates an option group as part of the given app
Definition: CLI11.h:6202
CLI11_INLINE std::string & add_quotes_if_needed(std::string &str)
Add quotes if the string contains spaces.
Definition: CLI11.h:629
bool disabled_
If set to true the subcommand is disabled and cannot be used, ignored for main app.
Definition: CLI11.h:5638
Check for input streamability.
Definition: CLI11.h:1135
bool configurable_
Allow this option to be given in a configuration file.
Definition: CLI11.h:4185
const detail::NonexistentPathValidator NonexistentPath
Check for an non-existing path.
Definition: CLI11.h:3012
const Range PositiveNumber((std::numeric_limits< double >::min)(),(std::numeric_limits< double >::max)(),"POSITIVE")
Check for a positive valued number (val>0.0), <double>::min here is the smallest positive number...
CLI11_NODISCARD std::string get_flag_value(const std::string &name, std::string input_value) const
Definition: CLI11.h:5262
Option * get_config_ptr()
Get a pointer to the config option.
Definition: CLI11.h:6631
Option * excludes(std::string opt_name)
Can find a string if needed.
Definition: CLI11.h:4585
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.h:8978
std::vector< std::string > results_t
Definition: CLI11.h:4148
const detail::ExistingFileValidator ExistingFile
Check for existing file (returns error message if check fails)
Definition: CLI11.h:3003
auto arg(const Char *name, const T &arg) -> detail::named_arg< Char, T >
Definition: core.h:1736
void run_callback(bool final_mode=false, bool suppress_final_callback=false)
Internal function to run (App) callback, bottom up.
Definition: CLI11.h:7813
const Option * operator[](const char *option_name) const
Shortcut bracket operator for getting a pointer to an option.
Definition: CLI11.h:6550
ConfigBase * index(int16_t sectionIndex)
specify a particular index in the section to use (-1) for all sections to use
Definition: CLI11.h:2794
std::string & trim(std::string &str)
Trim whitespace from string.
Definition: CLI11.h:280
CLI11_INLINE 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.h:467
MultiOptionPolicy multi_option_policy_
Policy for handling multiple arguments beyond the expected Max.
Definition: CLI11.h:4197
App * footer(std::string footer_string)
Set footer.
Definition: CLI11.h:6466
Formatter & operator=(const Formatter &)=default
OptionDefaults * disable_flag_override(bool value=true)
Disable overriding flag values with an '=' segment.
Definition: CLI11.h:4335
CheckedTransformer(std::initializer_list< std::pair< std::string, std::string >> values, Args &&...args)
This allows in-place construction.
Definition: CLI11.h:3386
Option * ignore_underscore(bool value=true)
Definition: CLI11.h:5099
std::function< void()> final_callback_
This is a function that runs when all processing has completed.
Definition: CLI11.h:5654
uint64 value_type
Definition: GA_PrimCompat.h:29
A fully expanded help.
bool is_separator(const std::string &str)
check if a string is a container segment separator (empty or "%%")
Definition: CLI11.h:334
virtual ~App()=default
virtual destructor
bool remove_needs(Option *opt)
Remove needs link from an option. Returns true if the option really was in the needs list...
Definition: CLI11.h:5044
Option * excludes(Option *opt)
Sets excluded options.
Definition: CLI11.h:5054
typename T::value_type value_type
Definition: CLI11.h:1050
std::string trim_copy(const std::string &str)
Make a copy of the string and then trim it.
Definition: CLI11.h:286
results_t proc_results_
results after reduction
Definition: CLI11.h:4435
CLI11_INLINE std::string & ltrim(std::string &str)
Trim whitespace from left of string.
Definition: CLI11.h:419
take only the first Expected number of arguments
std::string generate_map(const T &map, bool key_only=false)
Generate a string representation of a map.
Definition: CLI11.h:3139
CLI11_NODISCARD bool get_required() const
True if this is a required option.
Definition: CLI11.h:4234
Thrown on construction of a bad name.
Definition: CLI11.h:742
CLI11_NODISCARD bool get_immediate_callback() const
Get the status of disabled.
Definition: CLI11.h:6606
CLI11_NODISCARD const std::vector< std::string > & get_snames() const
Get the short names.
Definition: CLI11.h:4662
CLI11_INLINE bool split_windows_style(const std::string &current, std::string &name, std::string &value)
Definition: CLI11.h:2564
Thrown when validation fails before parsing.
Definition: CLI11.h:946
Option * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times (or another policy)
Definition: CLI11.h:5120
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.h:9289
CLI11_NODISCARD std::string version() const
Displays a version string.
Definition: CLI11.h:7573
Validator & non_modifying(bool no_modify=true)
Specify whether the Validator can be modifying or not.
Definition: CLI11.h:2915
This is a successful completion on parsing, supposed to exit.
Definition: CLI11.h:778
std::map< std::string, std::string > labels_
The required help printout labels (user changeable) Values are Needs, Excludes, etc.
Definition: CLI11.h:4007
CLI11_NODISCARD bool get_configurable() const
Check the status of the allow windows style options.
Definition: CLI11.h:6568
CLI11_NODISCARD std::string get_name(bool positional=false, bool all_options=false) const
Gets a comma separated list of names. Will include / prefer the positional name if positional is true...
Definition: CLI11.h:5133
std::uint64_t result_t
Definition: CLI11.h:3623
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.h:4506
CLI11_NODISCARD 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.h:7840
CLI11_NODISCARD callback_t get_callback() const
Get the callback function.
Definition: CLI11.h:4656
CLI11_NODISCARD bool check_lname(std::string name) const
Requires "--" to be removed from string.
Definition: CLI11.h:4757
Transformer(std::initializer_list< std::pair< std::string, std::string >> values, Args &&...args)
This allows in-place construction.
Definition: CLI11.h:3328
bool got_subcommand(const App *subcom) const
Check to see if given subcommand was selected.
Definition: CLI11.h:6396
Option * get_option(std::string option_name)
Get an option by name (non-const version)
Definition: CLI11.h:6538
Option * add_option_no_stream(std::string option_name, AssignTo &variable, std::string option_description="")
Add option for assigning to a variable.
Definition: CLI11.h:6050
CLI11_INLINE std::vector< std::string > split_names(std::string current)
Definition: CLI11.h:2579
CLI11_NODISCARD std::shared_ptr< FormatterBase > get_formatter() const
Access the formatter.
Definition: CLI11.h:6492
Option * help_all_ptr_
A pointer to the help all flag if there is one INHERITABLE.
Definition: CLI11.h:5680
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.h:5014
virtual std::string make_subcommands(const App *app, AppFormatMode mode) const
This prints out all the subcommands.
Definition: CLI11.h:9533
bool lexical_cast(const std::string &input, T &output)
Integer conversion.
Definition: CLI11.h:1835
App * needs(App *app)
Counts the number of times the given option was passed.
Definition: CLI11.h:6439
App * ignore_underscore(bool value=true)
Ignore underscore. Subcommands inherit value.
Definition: CLI11.h:7016
App * description(std::string app_description)
Set the description of the app.
Definition: CLI11.h:6511
void inject_separator(bool value=true)
Set the value of the separator injection flag.
Definition: CLI11.h:4852
AsSizeValue(bool kb_is_1000)
Definition: CLI11.h:3891
Check for an non-existing path.
Definition: CLI11.h:2987
bool allow_extras_
If true, allow extra arguments (ie, don't throw an error). INHERITABLE.
Definition: CLI11.h:5622
bool force_callback_
flag indicating that the option should force the callback regardless if any results present ...
Definition: CLI11.h:4456
bool immediate_callback_
Definition: CLI11.h:5645
CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset)
Definition: CLI11.h:617
CLI11_NODISCARD 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.h:2936
startup_mode default_startup
Definition: CLI11.h:5753
GLdouble n
Definition: glcorearb.h:2008
auto checked_to_string(T &&value) -> decltype(to_string(std::forward< T >(value)))
special template overload
Definition: CLI11.h:1277
Option * needs(std::string opt_name)
Can find a string if needed.
Definition: CLI11.h:4564
bool ignore_underscore_
Ignore underscores when matching (option, not value)
Definition: CLI11.h:4182
virtual CLI11_NODISCARD std::string make_group(std::string group, bool is_positional, std::vector< const Option * > opts) const
Definition: CLI11.h:9388
Option * capture_default_str()
Capture the default value from the original value (if it can be captured)
Definition: CLI11.h:4861
Validator(std::string validator_desc)
Construct a Validator with just the description string.
Definition: CLI11.h:2853
ConfigBase * comment(char cchar)
Specify the configuration for comment characters.
Definition: CLI11.h:2743
bool fallthrough_
Allow subcommand fallthrough, so that parent commands can collect commands after subcommand. INHERITABLE.
Definition: CLI11.h:5737
void _process_env()
Get envname options if not yet passed. Runs on all subcommands.
Definition: CLI11.h:7910
void _process_help_flags(bool trigger_help=false, bool trigger_all_help=false) const
Definition: CLI11.h:7966
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.h:9643
const TypeValidator< double > Number("NUMBER")
Check for a number.
GLintptr offset
Definition: glcorearb.h:665
std::string & sectionRef()
get a reference to the configuration section
Definition: CLI11.h:2780
std::string rjoin(const T &v, std::string delim=",")
Join a string in reverse order.
Definition: CLI11.h:255
Option * run_callback_for_default(bool value=true)
Definition: CLI11.h:4523
std::size_t require_option_min_
Minimum required options (not inheritable!)
Definition: CLI11.h:5778
ImageBuf OIIO_API sub(Image_or_Const A, Image_or_Const B, ROI roi={}, int nthreads=0)
Definition: core.h:760
std::ostream & operator<<(std::ostream &in, const T &item)
output streaming for enumerations
Definition: CLI11.h:203
std::string ignore_underscore(std::string item)
Helper function to allow ignore_underscore to be passed to IsMember or Transform. ...
Definition: CLI11.h:3459
std::function< bool(const results_t &)> callback_t
callback function definition
Definition: CLI11.h:4150
App * disabled(bool disable=true)
Disable the subcommand or option group.
Definition: CLI11.h:5878
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.h:7463
std::size_t require_subcommand_max_
Max number of subcommands allowed (parsing stops after this number). 0 is unlimited INHERITABLE...
Definition: CLI11.h:5775
App * alias(std::string app_name)
Set an alias for the app.
Definition: CLI11.h:6972
virtual std::string make_option_name(const Option *, bool) const
This is the name part of an option, Default: left column.
Definition: CLI11.h:9601
CLI11_NODISCARD bool get_enabled_by_default() const
Get the status of disabled by default.
Definition: CLI11.h:6612
CLI11_NODISCARD bool get_positionals_at_end() const
Check the status of the allow windows style options.
Definition: CLI11.h:6565
bool integral_conversion(const std::string &input, T &output) noexcept
Convert to an unsigned integral.
Definition: CLI11.h:1748
App * require_subcommand()
The argumentless form of require subcommand requires 1 or more subcommands.
Definition: CLI11.h:6265
CLI11_NODISCARD Validator name(std::string validator_name) const
Specify the type string.
Definition: CLI11.h:2895
std::set< App * > exclude_subcommands_
this is a list of subcommands that are exclusionary to this one
Definition: CLI11.h:5709
Option * type_name_fn(std::function< std::string()> typefun)
Set the type function to run when displayed on this option.
Definition: CLI11.h:4834
AsNumberWithUnit::Options operator|(const AsNumberWithUnit::Options &a, const AsNumberWithUnit::Options &b)
definition of the default transformation object
Definition: CLI11.h:3606
Used when printed as part of expanded subcommand.
std::string option_text_
If given, replace the text that describes the option type and usage in the help text.
Definition: CLI11.h:4384
Option * default_flag_modifiers(Option *opt)
helper functions for adding in appropriate flag modifiers for add_flag
Definition: CLI11.h:5588
bool allow_extra_args_
Specify that extra args beyond type_size_max should be allowed.
Definition: CLI11.h:4446
forward declare the subtype_count_min structure
Definition: CLI11.h:1342
std::vector< std::string > lnames_
A list of the long names (--long) without the leading dashes.
Definition: CLI11.h:4358
Check to see if something is a shared pointer.
Definition: CLI11.h:1011
CLI11_INLINE void TriggerOff(App *trigger_app, App *app_to_enable)
Helper function to disable one option group/subcommand when another is used.
Definition: CLI11.h:8877
bool trigger_on_result_
flag indicating that the option should trigger the validation and callback chain on each result when ...
Definition: CLI11.h:4454
Validator & operation(std::function< std::string(std::string &)> op)
Set the Validator operation function.
Definition: CLI11.h:2859
App * get_subcommand(const App *subcom) const
Definition: CLI11.h:7285
#define CLI11_ERROR_SIMPLE(name)
Definition: CLI11.h:657
std::string make_help(const App *, std::string, AppFormatMode) const override
This puts everything together.
Definition: CLI11.h:9509
CLI11_NODISCARD const std::string & section() const
get the section
Definition: CLI11.h:2782
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.h:7192
std::integral_constant< bool, value > type
Definition: CLI11.h:3165
const Option * operator[](const std::string &option_name) const
Shortcut bracket operator for getting a pointer to an option.
Definition: CLI11.h:6547
Option * ignore_case(bool value=true)
Definition: CLI11.h:5079
std::set< App * > need_subcommands_
Definition: CLI11.h:5717
#define CLI11_NODISCARD
Definition: CLI11.h:120
Option * get_version_ptr()
Get a pointer to the version option.
Definition: CLI11.h:6637
Option * transform(Validator Validator, const std::string &Validator_name="")
Adds a transforming Validator with a built in type name.
Definition: CLI11.h:4992
std::string value_string(const T &value)
get a string as a convertible value for arithmetic types
Definition: CLI11.h:1291
bool always_capture_default_
Automatically capture default value.
Definition: CLI11.h:4194
CLI11_INLINE path_type check_path(const char *file) noexcept
get the type of the path from a file name
Definition: CLI11.h:3783
std::function< std::string(std::string)> filter_fn_t
Definition: CLI11.h:3255
bool validate_optional_arguments_
If set to true optional vector arguments are validated before assigning INHERITABLE.
Definition: CLI11.h:5762
ConfigINI generates a "standard" INI compliant output.
Definition: CLI11.h:2804
bool prefix_command_
If true, return immediately on an unrecognized option (implies allow_extras) INHERITABLE.
Definition: CLI11.h:5629
char delimiter_
Specify a delimiter character for vector arguments.
Definition: CLI11.h:4191
template to get the underlying value type if it exists or use a default
Definition: CLI11.h:1307
CLI11_NODISCARD int get_items_expected() const
The total min number of expected string values to be used.
Definition: CLI11.h:4696
-h or –help on command line
Definition: CLI11.h:784
std::size_t require_option_max_
Max number of options allowed. 0 is unlimited (not inheritable)
Definition: CLI11.h:5781
CLI11_NODISCARD std::size_t get_require_subcommand_min() const
Get the required min subcommand value.
Definition: CLI11.h:6579
Construction errors (not in parsing)
Definition: CLI11.h:709
void _process_extras()
Throw an error if anything is left over and should not be.
Definition: CLI11.h:8138
std::string join(const T &v, std::string delim=",")
Simple function to join a string.
Definition: CLI11.h:222
CLI11_NODISCARD std::shared_ptr< ConfigBase > get_config_formatter_base() const
Access the config formatter as a configBase pointer.
Definition: CLI11.h:6498
constexpr std::enable_if< I< type_count_base< T >::value, int >::type tuple_type_size(){return subtype_count< typename std::tuple_element< I, T >::type >::value+tuple_type_size< T, I+1 >);}template< typename T > struct type_count< T, typename std::enable_if< is_tuple_like< T >::value >::type >{static constexpr int value{tuple_type_size< T, 0 >)};};template< typename T > struct subtype_count{static constexpr int value{is_mutable_container< T >::value?expected_max_vector_size:type_count< T >::value};};template< typename T, typename Enable=void > struct type_count_min{static const int value{0};};template< typename T >struct type_count_min< T, typename std::enable_if<!is_mutable_container< T >::value &&!is_tuple_like< T >::value &&!is_wrapper< T >::value &&!is_complex< T >::value &&!std::is_void< T >::value >::type >{static constexpr int value{type_count< T >::value};};template< typename T > struct type_count_min< T, typename std::enable_if< is_complex< T >::value >::type >{static constexpr int value{1};};template< typename T >struct type_count_min< T, typename std::enable_if< is_wrapper< T >::value &&!is_complex< T >::value &&!is_tuple_like< T >::value >::type >{static constexpr int value{subtype_count_min< typename T::value_type >::value};};template< typename T, std::size_t I >constexpr typename std::enable_if< I==type_count_base< T >::value, int >::type tuple_type_size_min(){return 0;}template< typename T, std::size_t I > constexpr typename std::enable_if< I< type_count_base< T >::value, int >::type tuple_type_size_min(){return subtype_count_min< typename std::tuple_element< I, T >::type >::value+tuple_type_size_min< T, I+1 >);}template< typename T > struct type_count_min< T, typename std::enable_if< is_tuple_like< T >::value >::type >{static constexpr int value{tuple_type_size_min< T, 0 >)};};template< typename T > struct subtype_count_min{static constexpr int value{is_mutable_container< T >::value?((type_count< T >::value< expected_max_vector_size)?type_count< T >::value:0):type_count_min< T >::value};};template< typename T, typename Enable=void > struct expected_count{static const int value{0};};template< typename T >struct expected_count< T, typename std::enable_if<!is_mutable_container< T >::value &&!is_wrapper< T >::value &&!std::is_void< T >::value >::type >{static constexpr int value{1};};template< typename T > struct expected_count< T, typename std::enable_if< is_mutable_container< T >::value >::type >{static constexpr int value{expected_max_vector_size};};template< typename T >struct expected_count< T, typename std::enable_if<!is_mutable_container< T >::value &&is_wrapper< T >::value >::type >{static constexpr int value{expected_count< typename T::value_type >::value};};enum class object_category:int{char_value=1, integral_value=2, unsigned_integral=4, enumeration=6, boolean_value=8, floating_point=10, number_constructible=12, double_constructible=14, integer_constructible=16, string_assignable=23, string_constructible=24, other=45, wrapper_value=50, complex_number=60, tuple_value=70, container_value=80,};template< typename T, typename Enable=void > struct classify_object{static constexpr object_category value{object_category::other};};template< typename T >struct classify_object< T, typename std::enable_if< std::is_integral< T >::value &&!std::is_same< T, char >::value &&std::is_signed< T >::value &&!is_bool< T >::value &&!std::is_enum< T >::value >::type >{static constexpr object_category value{object_category::integral_value};};template< typename T >struct classify_object< T, typename std::enable_if< std::is_integral< T >::value &&std::is_unsigned< T >::value &&!std::is_same< T, char >::value &&!is_bool< T >::value >::type >{static constexpr object_category value{object_category::unsigned_integral};};template< typename T >struct classify_object< T, typename std::enable_if< std::is_same< T, char >::value &&!std::is_enum< T >::value >::type >{static constexpr object_category value{object_category::char_value};};template< typename T > struct classify_object< T, typename std::enable_if< is_bool< T >::value >::type >{static constexpr object_category value{object_category::boolean_value};};template< typename T > struct classify_object< T, typename std::enable_if< std::is_floating_point< T >::value >::type >{static constexpr object_category value{object_category::floating_point};};template< typename T >struct classify_object< T, typename std::enable_if<!std::is_floating_point< T >::value &&!std::is_integral< T >::value &&std::is_assignable< T &, std::string >::value >::type >{static constexpr object_category value{object_category::string_assignable};};template< typename T >struct classify_object< T, typename std::enable_if<!std::is_floating_point< T >::value &&!std::is_integral< T >::value &&!std::is_assignable< T &, std::string >::value &&(type_count< T >::value==1)&&std::is_constructible< T, std::string >::value >::type >{static constexpr object_category value{object_category::string_constructible};};template< typename T > struct classify_object< T, typename std::enable_if< std::is_enum< T >::value >::type >{static constexpr object_category value{object_category::enumeration};};template< typename T > struct classify_object< T, typename std::enable_if< is_complex< T >::value >::type >{static constexpr object_category value{object_category::complex_number};};template< typename T > struct uncommon_type{using type=typename std::conditional<!std::is_floating_point< T >::value &&!std::is_integral< T >::value &&!std::is_assignable< T &, std::string >::value &&!std::is_constructible< T, std::string >::value &&!is_complex< T >::value &&!is_mutable_container< T >::value &&!std::is_enum< T >::value, std::true_type, std::false_type >::type;static constexpr bool value=type::value;};template< typename T >struct classify_object< T, typename std::enable_if<(!is_mutable_container< T >::value &&is_wrapper< T >::value &&!is_tuple_like< T >::value &&uncommon_type< T >::value)>::type >{static constexpr object_category value{object_category::wrapper_value};};template< typename T >struct classify_object< T, typename std::enable_if< uncommon_type< T >::value &&type_count< T >::value==1 &&!is_wrapper< T >::value &&is_direct_constructible< T, double >::value &&is_direct_constructible< T, int >::value >::type >{static constexpr object_category value{object_category::number_constructible};};template< typename T >struct classify_object< T, typename std::enable_if< uncommon_type< T >::value &&type_count< T >::value==1 &&!is_wrapper< T >::value &&!is_direct_constructible< T, double >::value &&is_direct_constructible< T, int >::value >::type >{static constexpr object_category value{object_category::integer_constructible};};template< typename T >struct classify_object< T, typename std::enable_if< uncommon_type< T >::value &&type_count< T >::value==1 &&!is_wrapper< T >::value &&is_direct_constructible< T, double >::value &&!is_direct_constructible< T, int >::value >::type >{static constexpr object_category value{object_category::double_constructible};};template< typename T >struct classify_object< T, typename std::enable_if< is_tuple_like< T >::value &&((type_count< T >::value >=2 &&!is_wrapper< T >::value)||(uncommon_type< T >::value &&!is_direct_constructible< T, double >::value &&!is_direct_constructible< T, int >::value)||(uncommon_type< T >::value &&type_count< T >::value >=2))>::type >{static constexpr object_category value{object_category::tuple_value};};template< typename T > struct classify_object< T, typename std::enable_if< is_mutable_container< T >::value >::type >{static constexpr object_category value{object_category::container_value};};template< typename T, enable_if_t< classify_object< T >::value==object_category::char_value, detail::enabler >=detail::dummy >constexpr const char *type_name(){return"CHAR";}template< typename T, enable_if_t< classify_object< T >::value==object_category::integral_value||classify_object< T >::value==object_category::integer_constructible, detail::enabler >=detail::dummy >constexpr const char *type_name(){return"INT";}template< typename T, enable_if_t< classify_object< T >::value==object_category::unsigned_integral, detail::enabler >=detail::dummy >constexpr const char *type_name(){return"UINT";}template< typename T, enable_if_t< classify_object< T >::value==object_category::floating_point||classify_object< T >::value==object_category::number_constructible||classify_object< T >::value==object_category::double_constructible, detail::enabler >=detail::dummy >constexpr const char *type_name(){return"FLOAT";}template< typename T, enable_if_t< classify_object< T >::value==object_category::enumeration, detail::enabler >=detail::dummy >constexpr const char *type_name(){return"ENUM";}template< typename T, enable_if_t< classify_object< T >::value==object_category::boolean_value, detail::enabler >=detail::dummy >constexpr const char *type_name(){return"BOOLEAN";}template< typename T, enable_if_t< classify_object< T >::value==object_category::complex_number, detail::enabler >=detail::dummy >constexpr const char *type_name(){return"COMPLEX";}template< typename T, enable_if_t< classify_object< T >::value >=object_category::string_assignable &&classify_object< T >::value<=object_category::other, detail::enabler >=detail::dummy >constexpr const char *type_name(){return"TEXT";}template< typename T, enable_if_t< classify_object< T >::value==object_category::tuple_value &&type_count_base< T >::value >=2, detail::enabler >=detail::dummy >std::string type_name();template< typename T, enable_if_t< classify_object< T >::value==object_category::container_value||classify_object< T >::value==object_category::wrapper_value, detail::enabler >=detail::dummy >std::string type_name();template< typename T, enable_if_t< classify_object< T >::value==object_category::tuple_value &&type_count_base< T >::value==1, detail::enabler >=detail::dummy >inline std::string type_name(){return type_name< typename std::decay< typename std::tuple_element< 0, T >::type >::type >);}template< typename T, std::size_t I >inline typename std::enable_if< I==type_count_base< T >::value, std::string >::type tuple_name(){return std::string{};}template< typename T, std::size_t I >inline typename std::enable_if<(I< type_count_base< T >::value), std::string >::type tuple_name(){auto str=std::string{type_name< typename std::decay< typename std::tuple_element< I, T >::type >::type >)}+ ','+tuple_name< T, I+1 >);if(str.back()== ',') str.pop_back();return str;}template< typename T, enable_if_t< classify_object< T >::value==object_category::tuple_value &&type_count_base< T >::value >=2, detail::enabler > > std::string type_name()
Recursively generate the tuple type name.
Definition: CLI11.h:1729
Validator & active(bool active_val=true)
Specify whether the Validator is active or not.
Definition: CLI11.h:2903
GLuint GLuint end
Definition: glcorearb.h:475
std::string ignore_space(std::string item)
Helper function to allow checks to ignore spaces to be passed to IsMember or Transform.
Definition: CLI11.h:3462
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.h:1002
bool ignore_underscore_
If true, the program should ignore underscores INHERITABLE.
Definition: CLI11.h:5734
std::size_t require_subcommand_min_
Minimum required subcommands (not inheritable!)
Definition: CLI11.h:5772
std::vector< std::string > fnames_
a list of flag names with specified default values;
Definition: CLI11.h:4365
bool remove_excludes(Option *opt)
Remove needs link from an option. Returns true if the option really was in the needs list...
Definition: CLI11.h:5069
App * enabled_by_default(bool enable=true)
Definition: CLI11.h:5901
std::string name_
Subcommand name or program name (from parser if name is empty)
Definition: CLI11.h:5616
config_extras_mode allow_config_extras_
Definition: CLI11.h:5626
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.h:3225
CLI11_NODISCARD int get_expected_min() const
The number of times the option expects to be included.
Definition: CLI11.h:4683
bool pre_parse_called_
Flag indicating that the pre_parse_callback has been triggered.
Definition: CLI11.h:5641
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.h:8803
App * needs(Option *opt)
Counts the number of times the given option was passed.
Definition: CLI11.h:6431
Option * check(Validator validator, const std::string &validator_name="")
Adds a Validator with a built in type name.
Definition: CLI11.h:4976
char arrayEnd
the character used to end an array '\0' is a default to not use
Definition: CLI11.h:2719
std::string operator()(const std::string &str) const
Definition: CLI11.h:2869
Option * help_ptr_
A pointer to the help flag if there is one INHERITABLE.
Definition: CLI11.h:5677
std::function< void(std::size_t)> pre_parse_callback_
This is a function that runs prior to the start of parsing.
Definition: CLI11.h:5648
constexpr enabler dummy
An instance to use in EnableIf.
Definition: CLI11.h:985
std::size_t column_width_
The width of the first column.
Definition: CLI11.h:4003
CLI11_NODISCARD std::string get_name() const
Definition: CLI11.h:698
virtual ~FormatterBase() noexcept
Adding a destructor in this form to work around bug in GCC 4.7.
Definition: CLI11.h:4021
CLI11_NODISCARD bool get_prefix_command() const
Get the prefix command status.
Definition: CLI11.h:6591
App * require_option()
The argumentless form of require option requires 1 or more options be used.
Definition: CLI11.h:6294
typename std::remove_const< value_type >::type second_type
Definition: CLI11.h:1052
App * add_subcommand(std::string subcommand_name="", std::string subcommand_description="")
Add a subcommand. Inherits INHERITABLE and OptionDefaults, and help flag.
Definition: CLI11.h:7239
virtual std::string make_help(const App *, std::string, AppFormatMode) const =0
This is the key method that puts together help.
Thrown when an option already exists.
Definition: CLI11.h:756
App(std::string app_description, std::string app_name, App *parent)
Special private constructor for subcommand.
Definition: CLI11.h:6922
Option * add_option(std::string option_name, T &option_description)
Add option with description but with no variable assignment or callback.
Definition: CLI11.h:6097
CLI11_NODISCARD const std::string & get_group() const
Get the group of this subcommand.
Definition: CLI11.h:6571
Validate the given string is a legal ipv4 address.
Definition: CLI11.h:2993
std::int64_t to_flag_value(std::string val)
Convert a flag into an integer value typically binary flags.
Definition: CLI11.h:1788
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.h:7070
char arraySeparator
the character used to separate elements in an array
Definition: CLI11.h:2721
png_const_structrp png_const_inforp int * unit
Definition: png.h:2161
uint8_t maximumLayers
the maximum number of layers to allow
Definition: CLI11.h:2729
SYS_FORCE_INLINE const char * c_str() const
CLI11_NODISCARD bool check_name(std::string name_to_check) const
Check the name, case insensitive and underscore insensitive if set.
Definition: CLI11.h:7671
Option * add_flag(std::string flag_name, std::vector< T > &flag_results, std::string flag_description="")
Vector version to capture multiple flags.
Definition: CLI11.h:6156
Thrown when a required option is missing.
Definition: CLI11.h:840
ConfigBase ConfigTOML
the default Config is the TOML file format
Definition: CLI11.h:2801
IsMember(T &&set)
This checks to see if an item is in a set (empty function)
Definition: CLI11.h:3263
CLI11_NODISCARD int get_expected() const
The number of times the option expects to be included.
Definition: CLI11.h:4680
Does not output a diagnostic in CLI11_PARSE, but allows main() to return with a specific error code...
Definition: CLI11.h:804
std::unique_ptr< Option > Option_p
Definition: CLI11.h:4155
char valueDelimiter
the character used separate the name from the value
Definition: CLI11.h:2723
CLI11_NODISCARD int get_items_expected_max() const
Get the maximum number of items expected to be returned and used for the callback.
Definition: CLI11.h:4691
Class wrapping some of the accessors of Validator.
Definition: CLI11.h:2954
#define CLI11_INLINE
Definition: CLI11.h:146
GLuint const GLchar * name
Definition: glcorearb.h:786
All errors derive from this one.
Definition: CLI11.h:691
std::vector< App_p > subcommands_
Storage for subcommand list.
Definition: CLI11.h:5728
bool _parse_arg(std::vector< std::string > &args, detail::Classifier current_type)
Definition: CLI11.h:8552
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.h:9055
name_(std::move(validator_name))
Definition: CLI11.h:2857
CLI11_NODISCARD bool parsed() const
Check to see if this subcommand was parsed, true only if received on command line.
Definition: CLI11.h:5993
App * prefix_command(bool allow=true)
Do not parse anything after the first unrecognized option and return.
Definition: CLI11.h:5944
FormatterLambda(funct_t funct)
Create a FormatterLambda with a lambda function.
Definition: CLI11.h:4062
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.h:6909
CLI11_NODISCARD bool get_run_callback_for_default() const
Get the current value of run_callback_for_default.
Definition: CLI11.h:4528
CLI11_INLINE void TriggerOn(App *trigger_app, App *app_to_enable)
Helper function to enable one option group/subcommand when another is used.
Definition: CLI11.h:8858
std::set< Option * > needs_
A list of options that are required with this option.
Definition: CLI11.h:4413
App * fallthrough(bool value=true)
Definition: CLI11.h:6324
Option * needs(Option *opt)
Sets required options.
Definition: CLI11.h:4556
void _process_callbacks()
Process callbacks. Runs on all subcommands.
Definition: CLI11.h:7942
GLsizei const GLchar *const * strings
Definition: glcorearb.h:1933
GLboolean GLboolean GLboolean b
Definition: glcorearb.h:1222
std::function< void()> parse_complete_callback_
This is a function that runs when parsing has finished.
Definition: CLI11.h:5651
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.h:5812
GA_API const UT_StringHolder transform
Option * needs(A opt, B opt1, ARG...args)
Any number supported, any mix of string and Opt.
Definition: CLI11.h:4573
CLI11_NODISCARD std::vector< App * > get_subcommands() const
Definition: CLI11.h:6385
GLint GLenum GLint x
Definition: glcorearb.h:409
Range(T max_val, const std::string &validator_name=std::string{})
Range of one value is 0 to value.
Definition: CLI11.h:3071
bool configurable_
if set to true the subcommand can be triggered via configuration files INHERITABLE ...
Definition: CLI11.h:5756
IsMember(T set, F filter_function)
Definition: CLI11.h:3267
std::vector< Option_p > options_
The list of options, stored locally.
Definition: CLI11.h:5664
CLI11_NODISCARD bool get_disable_flag_override() const
The status of configurable.
Definition: CLI11.h:4246
CLI11_NODISCARD std::size_t _count_remaining_positionals(bool required_only=false) const
Count the required remaining positional arguments.
Definition: CLI11.h:8359
Thrown when extra values are found in an INI file.
Definition: CLI11.h:936
char arrayStart
the character used to start an array '\0' is a default to not use
Definition: CLI11.h:2717
int16_t & indexRef()
get a reference to the configuration index
Definition: CLI11.h:2790
CLI11_NODISCARD int16_t index() const
get the section index
Definition: CLI11.h:2792
Thrown when too many positionals or options are found.
Definition: CLI11.h:920
App * require_option(std::size_t min, std::size_t max)
Definition: CLI11.h:6316
CLI11_INLINE bool split_short(const std::string &current, std::string &name, std::string &rest)
Definition: CLI11.h:2540
Option * excludes(A opt, B opt1, ARG...args)
Any number supported, any mix of string and Opt.
Definition: CLI11.h:4594
GLdouble t
Definition: glad.h:2397
CLI11_NODISCARD const Option * get_config_ptr() const
Get a pointer to the config option. (const)
Definition: CLI11.h:6634
OptionDefaults * ignore_case(bool value=true)
Ignore the case of the option name.
Definition: CLI11.h:4323
-v or –version on command line
Definition: CLI11.h:797
ConfigBase * section(const std::string &sectionName)
specify a particular section of the configuration file to use
Definition: CLI11.h:2784
bool run_callback_for_default_
Control option to run the callback to set the default.
Definition: CLI11.h:4450
GLenum mode
Definition: glcorearb.h:99
auto search(const T &set, const V &val) -> std::pair< bool, decltype(std::begin(detail::smart_deref(set)))>
A search function.
Definition: CLI11.h:3170
Thrown when the wrong number of arguments has been received.
Definition: CLI11.h:875
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.h:999
static App * get_fallthrough_parent(App *app)
Wrap the fallthrough parent function to make sure that is working correctly.
Definition: CLI11.h:6915
take only the last Expected number of arguments
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.h:6068
a subset of results has been generated
bool empty() const
method name that maches std::string
CLI11_INLINE std::ostream & format_aliases(std::ostream &out, const std::vector< std::string > &aliases, std::size_t wid)
Print subcommand aliases.
Definition: CLI11.h:484
AsNumberWithUnit(std::map< std::string, Number > mapping, Options opts=DEFAULT, const std::string &unit_name="UNIT")
Definition: CLI11.h:3494
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.h:3311
CLI11_NODISCARD std::size_t count(std::string option_name) const
Counts the number of times the given option was passed.
Definition: CLI11.h:6381
CLI11_NODISCARD bool get_ignore_underscore() const
The status of ignore_underscore.
Definition: CLI11.h:4240
std::function< std::string(const App *, const Error &e)> failure_message_
The error message printing function INHERITABLE.
Definition: CLI11.h:5689
CRTP * group(const std::string &name)
Changes the group membership.
Definition: CLI11.h:4206
Option * get_option_no_throw(std::string option_name) noexcept
Get an option by name (noexcept non-const version)
Definition: CLI11.h:7619
Validator(std::string validator_desc, std::function< std::string(std::string &)> func)
Definition: CLI11.h:2847
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.h:1221
CLI11_NODISCARD bool get_disabled_by_default() const
Get the status of disabled by default.
Definition: CLI11.h:6609
std::string to_lower(std::string str)
Return a lower case version of a string.
Definition: CLI11.h:345
CLI11_NODISCARD bool nonpositional() const
True if option has at least one non-positional name.
Definition: CLI11.h:4702
std::vector< Option * > parse_order_
This is a list of pointers to options with the original parse order.
Definition: CLI11.h:5703
OIIO_API string_view getenv(string_view name, string_view defaultval)
CLI11_NODISCARD int get_application_index() const
Get the current value of the application index.
Definition: CLI11.h:2931
This is a specialty override for lambda functions.
Definition: CLI11.h:4054
CLI11_INLINE 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.h:2617
ConfigBase * valueSeparator(char vSep)
Specify the delimiter between a name and value.
Definition: CLI11.h:2759
Produce a range (factory). Min and max are inclusive.
Definition: CLI11.h:3042
~FormatterLambda() noexceptoverride
Adding a destructor (mostly to make GCC 4.7 happy)
Definition: CLI11.h:4065
CLI11_INLINE 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.h:538
GLenum func
Definition: glcorearb.h:783
CLI11_NODISCARD std::string get_display_name(bool with_aliases=false) const
Get a display name for an app.
Definition: CLI11.h:7655
CLI11_NODISCARD bool get_force_callback() const
The status of force_callback.
Definition: CLI11.h:4519
Error
Definition: oidn.hpp:577
Transformer(T mapping, F filter_function)
Definition: CLI11.h:3336
std::string convert_arg_for_ini(const std::string &arg, char stringQuote= '"', char characterQuote = '\'')
Definition: CLI11.h:9012
OptionDefaults * ignore_underscore(bool value=true)
Ignore underscores in the option name.
Definition: CLI11.h:4329
Usd_Term operator!(Usd_PrimFlags flag)
Definition: primFlags.h:131
bool lexical_assign(const std::string &input, AssignTo &output)
Assign a value through lexical cast operations.
Definition: CLI11.h:2060
Option * type_name(std::string typeval)
Set a custom option typestring.
Definition: CLI11.h:4840
std::function< std::string(std::string)> filter_fn_t
Definition: CLI11.h:3382
Option * type_size(int option_type_size)
Set a custom option size.
Definition: CLI11.h:5343
Extension of App to better manage groups of options.
Definition: CLI11.h:6803
virtual std::string make_option_opts(const Option *) const
This is the options part of the name, Default: combined into left column.
Definition: CLI11.h:9608
CLI11_NODISCARD detail::Classifier _recognize(const std::string &current, bool ignore_used_subcommands=true) const
Selects a Classifier enum based on the type of the current argument.
Definition: CLI11.h:7853
std::vector< std::string > inputs
Listing of inputs.
Definition: CLI11.h:2665
CLI11_NODISCARD bool check_sname(std::string name) const
Requires "-" to be removed from string.
Definition: CLI11.h:4752
App * allow_extras(bool allow=true)
Remove the error when extras are left over on the command line.
Definition: CLI11.h:5866
Validator operator!() const
Create a validator that fails when a given validator succeeds.
Definition: CLI11.h:3718
std::string name_
The name for search purposes of the Validator.
Definition: CLI11.h:2839
PXR_NAMESPACE_CLOSE_SCOPE PXR_NAMESPACE_OPEN_SCOPE
Definition: path.h:1432
Validator & application_index(int app_index)
Specify the application index of a validator.
Definition: CLI11.h:2920
bool disable_flag_override_
Disable overriding flag values with '=value'.
Definition: CLI11.h:4188
MultiOptionPolicy
Enumeration of the multiOption Policy selection.
Definition: CLI11.h:4157
CLI11_NODISCARD bool _has_remaining_positionals() const
Count the required remaining positional arguments.
Definition: CLI11.h:8371
GLenum GLsizei GLsizei GLint * values
Definition: glcorearb.h:1602
int expected_max_
The maximum number of expected values.
Definition: CLI11.h:4407
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.h:3372
App * name(std::string app_name="")
Set a name for the app (empty will use parser to set the name)
Definition: CLI11.h:6955
App * allow_windows_style_options(bool value=true)
Definition: CLI11.h:5954
CLI11_INLINE void retire_option(App *app, Option *opt)
Helper function to mark an option as retired.
Definition: CLI11.h:8910
std::string configSection
Specify the configuration section that should be used.
Definition: CLI11.h:2735
Option * default_str(std::string val)
Set the default value string representation (does not change the contained value) ...
Definition: CLI11.h:4869
virtual std::string make_usage(const App *app, std::string name) const
This displays the usage line.
Definition: CLI11.h:9459
translate named items to other or a value set
Definition: CLI11.h:3380
CLI11_NODISCARD int get_type_size_max() const
The maximum number of arguments the option expects.
Definition: CLI11.h:4638
std::vector< std::string > aliases_
Alias names for the subcommand.
Definition: CLI11.h:5790
virtual std::string make_positionals(const App *app) const
This prints out just the positionals "group".
Definition: CLI11.h:9399
void _configure()
Definition: CLI11.h:7793
App * parse_complete_callback(std::function< void()> pc_callback)
Definition: CLI11.h:5847
Option * version_ptr_
A pointer to a version flag if there is one.
Definition: CLI11.h:5683
Throw an error if any extra arguments were given.
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.h:8741
CRTP * required(bool value=true)
Set the option as required.
Definition: CLI11.h:4215
missing_t missing_
Definition: CLI11.h:5700
GLuint index
Definition: glcorearb.h:786
typename std::remove_const< value_type >::type first_type
Definition: CLI11.h:1051
ConfigBase * arrayDelimiter(char aSep)
Specify the delimiter character for an array.
Definition: CLI11.h:2754
std::string group_
The group membership.
Definition: CLI11.h:4173
CLI11_NODISCARD const results_t & results() const
Get the current complete results set.
Definition: CLI11.h:4783
This can be specialized to override the type deduction for IsMember.
Definition: CLI11.h:1025
App & operator=(const App &)=delete
Create a new program. Pass in the same arguments as main(), along with a help string.
void _validate() const
Definition: CLI11.h:7758
App * ignore_case(bool value=true)
Ignore case. Subcommands inherit value.
Definition: CLI11.h:7002
TypeValidator(const std::string &validator_name)
Definition: CLI11.h:3020
static auto first(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the first value (really just the underlying value)
Definition: CLI11.h:1055
Option * add_flag(std::string flag_name, T &flag_result, std::string flag_description="")
Definition: CLI11.h:6141
CLI11_NODISCARD bool get_always_capture_default() const
Return true if this will automatically capture the default value for help printing.
Definition: CLI11.h:4252
Range(T min_val, T max_val, const std::string &validator_name=std::string{})
Definition: CLI11.h:3049
void _parse_stream(std::istream &input)
Internal function to parse a stream.
Definition: CLI11.h:8219
GLfloat GLfloat v1
Definition: glcorearb.h:817
auto ptr(T p) -> const void *
Definition: format.h:2448
ImageBuf OIIO_API max(Image_or_Const A, Image_or_Const B, ROI roi={}, int nthreads=0)
GLuint GLfloat * val
Definition: glcorearb.h:1608
A copy of std::void_t from C++17 (helper for C++11 and C++14)
Definition: CLI11.h:996
App * formatter_fn(std::function< std::string(const App *, std::string, AppFormatMode)> fmt)
Set the help formatter.
Definition: CLI11.h:5981
void _trigger_pre_parse(std::size_t remaining_args)
Trigger the pre_parse callback if needed.
Definition: CLI11.h:8723
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.h:4123
#define PXR_NAMESPACE_CLOSE_SCOPE
Definition: pxr.h:91
CLI11_NODISCARD bool get_allow_extras() const
Get the status of allow extras.
Definition: CLI11.h:6594
Bound(T min_val, T max_val)
Definition: CLI11.h:3088
ConfigBase * quoteCharacter(char qString, char qChar)
Specify the quote characters used around strings and characters.
Definition: CLI11.h:2764
CLI11_NODISCARD bool check_fname(std::string name) const
Requires "--" to be removed from string.
Definition: CLI11.h:4762
bool remove_subcommand(App *subcom)
Removes a subcommand from the App. Takes a subcommand pointer. Returns true if found and removed...
Definition: CLI11.h:7269
App * formatter(std::shared_ptr< FormatterBase > fmt)
Set the help formatter.
Definition: CLI11.h:5975
std::shared_ptr< Config > config_formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer) ...
Definition: CLI11.h:5800
std::vector< Validator > validators_
A list of Validators to run on each value parsed.
Definition: CLI11.h:4410
static auto second(Q &&pair_value) -> decltype(std::forward< Q >(pair_value))
Get the second value (really just the underlying value)
Definition: CLI11.h:1059
CLI11_NODISCARD std::string get_label(std::string key) const
Get the current value of a name (REQUIRED, etc.)
Definition: CLI11.h:4041
Validator operator|(const Validator &other) const
Definition: CLI11.h:3696
CLI11_NODISCARD bool got_subcommand(std::string subcommand_name) const
Check with name instead of pointer to see if subcommand was selected.
Definition: CLI11.h:6402
Validator * get_validator(const std::string &Validator_name="")
Get a named Validator.
Definition: CLI11.h:5024
This class provides a converter for configuration files.
Definition: CLI11.h:2676
IsMember(std::initializer_list< T > values, Args &&...args)
This allows in-place construction using an initializer list.
Definition: CLI11.h:3259
**If you just want to fire and args
Definition: thread.h:609
CLI11_NODISCARD const Option * get_option(std::string option_name) const
Get an option by name.
Definition: CLI11.h:6529
CLI11_NODISCARD bool get_inject_separator() const
Return the inject_separator flag.
Definition: CLI11.h:4641
App * excludes(App *app)
Sets excluded subcommands for the subcommand.
Definition: CLI11.h:6416
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.h:7310
CLI11_INLINE std::pair< std::string, std::string > split_program_name(std::string commandline)
Definition: CLI11.h:3928
Check to see if something is copyable pointer.
Definition: CLI11.h:1020
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.h:7086
CLI11_NODISCARD const Option * get_help_ptr() const
Get a pointer to the help flag. (const)
Definition: CLI11.h:6625
std::function< std::string(std::string &)> func_
Definition: CLI11.h:2837
CLI11_INLINE std::string & rtrim(std::string &str)
Trim whitespace from right of string.
Definition: CLI11.h:431
CLI11_NODISCARD const Option * get_help_all_ptr() const
Get a pointer to the help all flag. (const)
Definition: CLI11.h:6628
auto smart_deref(T value) -> decltype(*value)
Definition: CLI11.h:3115
CLI11_NODISCARD const std::string & get_description() const
Get the description.
Definition: CLI11.h:4708
config_extras_mode
enumeration of modes of how to deal with extras in config files
Definition: CLI11.h:5578
CLI11_NODISCARD const std::string & get_name() const
Get the name of the Validator.
Definition: CLI11.h:2901
bool required_
If set to true the subcommand is required to be processed and used, ignored for main app...
Definition: CLI11.h:5635
std::string description_
Description of the current program/subcommand.
Definition: CLI11.h:5619
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.h:1080
bool _parse_single(std::vector< std::string > &args, bool &positional_only)
Definition: CLI11.h:8317
The normal, detailed help.
CLI11_NODISCARD std::string config_to_str(bool default_also=false, bool write_description=false) const
Definition: CLI11.h:6477
App * silent(bool silence=true)
silence the subcommand from showing up in the processed list
Definition: CLI11.h:5884
char stringQuote
the character to use around strings
Definition: CLI11.h:2725
Transformer(T &&mapping)
direct map of std::string to std::string
Definition: CLI11.h:3332
virtual CLI11_NODISCARD std::string to_flag(const ConfigItem &item) const
Get a flag value.
Definition: CLI11.h:2688
App * callback(std::function< void()> app_callback)
Definition: CLI11.h:5829
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.h:6369
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.h:3448
void _parse(std::vector< std::string > &args)
Internal parse function.
Definition: CLI11.h:8175
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.h:7030
Definition: core.h:1131
IMATH_INTERNAL_NAMESPACE_HEADER_ENTER IMATH_HOSTDEVICE constexpr T abs(T a) IMATH_NOEXCEPT
Definition: ImathFun.h:26
callback_t callback_
Options store a callback to do all the work.
Definition: CLI11.h:4426
CLI11_NODISCARD bool get_positional() const
True if the argument can be given directly.
Definition: CLI11.h:4699
App * require_option(int value)
Definition: CLI11.h:6303
Adaptor for set-like structure: This just wraps a normal container in a few utilities that do almost ...
Definition: CLI11.h:1049
CLI11_NODISCARD bool get_active() const
Get a boolean if the validator is active.
Definition: CLI11.h:2933
CLI11_NODISCARD std::string get_description() const
Generate type description information for the Validator.
Definition: CLI11.h:2883
The option is currently collecting parsed results.
App * get_parent()
Get the parent of this subcommand (or nullptr if main app)
Definition: CLI11.h:6643
CLI11_NODISCARD std::string get_type_name() const
Get the full typename for this option.
Definition: CLI11.h:5386
Option * add_flag(std::string flag_name)
Add a flag with no description or variable assignment.
Definition: CLI11.h:6123
merge all the arguments together into a single string via the delimiter character default(' ') ...
CLI11_NODISCARD std::string get_description() const
Get the app or subcommand description.
Definition: CLI11.h:6508
App * parent_
link back up to the parent App for fallthrough
Definition: CLI11.h:4423
CLI11_NODISCARD std::size_t get_column_width() const
Get the current column width.
Definition: CLI11.h:4048
Option * force_callback(bool value=true)
Set the value of force_callback.
Definition: CLI11.h:4514
CLI11_NODISCARD bool has_description() const
True if option has description.
Definition: CLI11.h:4705
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.h:3212
App * config_formatter(std::shared_ptr< Config > fmt)
Set the config formatter.
Definition: CLI11.h:5987
CLI11_NODISCARD std::string fullname() const
The list of parents and name joined by ".".
Definition: CLI11.h:2668
bool ignore_case_
Ignore the case when matching (option, not value)
Definition: CLI11.h:4179
App * allow_config_extras(config_extras_mode mode)
ignore extras in config files
Definition: CLI11.h:5938
CLI11_NODISCARD std::vector< std::string > remaining(bool recurse=false) const
This returns the missing options from the current subcommand.
Definition: CLI11.h:7712
SIM_API const UT_StringHolder distance
sum all the arguments together if numerical or concatenate directly without delimiter ...
const Range NonNegativeNumber((std::numeric_limits< double >::max)(),"NONNEGATIVE")
Check for a non negative number.
std::string description_
The description for help strings.
Definition: CLI11.h:4378
char parentSeparatorChar
the separator used to separator parent layers
Definition: CLI11.h:2731
CLI11_NODISCARD bool get_fallthrough() const
Check the status of fallthrough.
Definition: CLI11.h:6559
App * validate_optional_arguments(bool validate=true)
Set the subcommand to validate optional vector arguments before assigning.
Definition: CLI11.h:5921
Usually something like –help-all on command line.
Definition: CLI11.h:790
This converter works with INI/TOML files; to write INI files use ConfigINI.
Definition: CLI11.h:2712
Option_group(std::string group_description, std::string group_name, App *parent)
Definition: CLI11.h:6805
startup_mode
Storage for subcommand list.
Definition: CLI11.h:5750
Option * expected(int value)
Set the number of expected arguments.
Definition: CLI11.h:4936
Option & operator=(const Option &)=delete
Count the total number of times an option was passed.
int type_size_min_
The minimum number of arguments an option should be expecting.
Definition: CLI11.h:4402
void add_options(Option *opt, Args...args)
Add a bunch of options to the group.
Definition: CLI11.h:6822
CLI11_NODISCARD const std::string & get_group() const
Get the group of this option.
Definition: CLI11.h:4231
bool remove_excludes(Option *opt)
Removes an option from the excludes list of this subcommand.
Definition: CLI11.h:7521
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.h:1076
bool valid_alias_name_string(const std::string &str)
Verify an app name.
Definition: CLI11.h:328
std::vector< App * > parsed_subcommands_
This is a list of the subcommands collected, in order.
Definition: CLI11.h:5706
CLI11_INLINE std::string find_and_replace(std::string str, std::string from, std::string to)
Find and replace a substring with another substring.
Definition: CLI11.h:512
type
Definition: core.h:1059
void clear()
Reset the parsed data.
Definition: CLI11.h:7358
bool required_
True if this is a required option.
Definition: CLI11.h:4176
std::string type_name()
get the type name for a type that has a value_type member
Definition: CLI11.h:1740
void label(std::string key, std::string val)
Set the "REQUIRED" label.
Definition: CLI11.h:4031
GA_API const UT_StringHolder rest
std::function< std::string()> default_function_
Run this function to capture a default (ignore if empty)
Definition: CLI11.h:4392
bool isalpha(const std::string &str)
Verify that str consists of letters only.
Definition: CLI11.h:340
bool ignore_case_
If true, the program name is not case sensitive INHERITABLE.
Definition: CLI11.h:5731
CLI11_NODISCARD std::size_t remaining_size(bool recurse=false) const
This returns the number of remaining options, minus the – separator.
Definition: CLI11.h:7744
virtual std::string make_option_usage(const Option *opt) const
This is used to print the name on the USAGE line.
Definition: CLI11.h:9645
Validator operator&(const Validator &other) const
Definition: CLI11.h:3674
Translate named items to other or a value set.
Definition: CLI11.h:3322
App * parent_
A pointer to the parent if this is a subcommand.
Definition: CLI11.h:5784
App * group(std::string group_name)
Changes the group membership.
Definition: CLI11.h:6259
bool valid_first_char(T c)
Definition: CLI11.h:314
CLI11_NODISCARD std::vector< ConfigItem > from_file(const std::string &name) const
Parse a config file, throw an error (ParseError:ConfigParseError or FileError) on failure...
Definition: CLI11.h:2699
CRTP * configurable(bool value=true)
Allow in a configuration file.
Definition: CLI11.h:4296
CLI11_NODISCARD T as() const
Return the results as the specified type.
Definition: CLI11.h:4820
virtual std::string make_expanded(const App *sub) const
This prints out a subcommand in help-all.
Definition: CLI11.h:9581
Thrown when a requires option is missing.
Definition: CLI11.h:906
This will only trigger for actual void type.
Definition: CLI11.h:1345
CLI11_NODISCARD int get_exit_code() const
Definition: CLI11.h:696
CLI11_NODISCARD std::vector< std::string > get_groups() const
Get the groups available directly from this option (in order)
Definition: CLI11.h:7699
CLI11_NODISCARD bool get_silent() const
Get the status of silence.
Definition: CLI11.h:6603
int16_t configIndex
Specify the configuration index to use for arrayed sections.
Definition: CLI11.h:2733
constexpr int expected_max_vector_size
Definition: CLI11.h:216
App * positionals_at_end(bool value=true)
Specify that the positional arguments are only at the end of the sequence.
Definition: CLI11.h:5960
CLI11_INLINE 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.h:2590
CRTP * delimiter(char value= '\0')
Allow in a configuration file.
Definition: CLI11.h:4302
CLI11_NODISCARD int get_expected_max() const
The max number of times the option expects to be included.
Definition: CLI11.h:4685
Option * get_help_ptr()
Get a pointer to the help flag.
Definition: CLI11.h:6622
#define CLI11_ERROR_DEF(parent, name)
Definition: CLI11.h:646
CLI11_NODISCARD Validator active(bool active_val=true) const
Specify whether the Validator is active or not.
Definition: CLI11.h:2908
Some validators that are provided.
Definition: CLI11.h:2830
CLI11_NODISCARD bool get_ignore_case() const
Check the status of ignore_case.
Definition: CLI11.h:6553
typename element_type< T >::type::value_type type
Definition: CLI11.h:1046
std::string make_help(const App *app, std::string name, AppFormatMode mode) const override
This will simply call the lambda function.
Definition: CLI11.h:4068
CLI11_NODISCARD bool check_name(const std::string &name) const
Check a name. Requires "-" or "--" for short / long, supports positional name.
Definition: CLI11.h:5233
std::string footer_
Footer to put after all options in the help output INHERITABLE.
Definition: CLI11.h:5671
const detail::ExistingDirectoryValidator ExistingDirectory
Check for an existing directory (returns error message if check fails)
Definition: CLI11.h:3006
std::function< std::string()> type_name_
Definition: CLI11.h:4389
std::string default_str_
A human readable default value, either manually set, captured, or captured by default.
Definition: CLI11.h:4381
FormatterBase()=default
Adding a destructor in this form to work around bug in GCC 4.7.
void _process_config_file()
Read and process a configuration file (main app only)
Definition: CLI11.h:7878
bool remove_needs(Option *opt)
Removes an option from the needs list of this subcommand.
Definition: CLI11.h:7541
bool _parse_subcommand(std::vector< std::string > &args)
Definition: CLI11.h:8524
int application_index_
A Validator will only apply to an indexed value (-1 is all elements)
Definition: CLI11.h:2841
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.h:9107
virtual void pre_callback()
Definition: CLI11.h:6340
Produce a bounded range (factory). Min and max are inclusive.
Definition: CLI11.h:3082
void increment_parsed()
Internal function to recursively increment the parsed counter on the current app as well unnamed subc...
Definition: CLI11.h:8167
std::string pname_
A positional name.
Definition: CLI11.h:4368
Verify items are in a set.
Definition: CLI11.h:3253
Creates a command line program, with very few defaults.
Definition: CLI11.h:5605
std::string generate_set(const T &set)
Generate a string representation of a set.
Definition: CLI11.h:3126
Check for an existing directory (returns error message if check fails)
Definition: CLI11.h:2975
FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr &out) -> bool
Definition: core.h:2089
CLI11_NODISCARD const std::string & matching_name(const Option &other) const
If options share any of the same names, find it.
Definition: CLI11.h:5212
ConfigBase * arrayBounds(char aStart, char aEnd)
Specify the start and end characters for an array.
Definition: CLI11.h:2748
Holds values to load into Options.
Definition: CLI11.h:2657
CLI11_INLINE void remove_default_flag_values(std::string &flags)
Definition: CLI11.h:524
CLI11_NODISCARD bool get_callback_run() const
See if the callback has been run already.
Definition: CLI11.h:4827
std::set< Option * > need_options_
Definition: CLI11.h:5721
CLI11_NODISCARD std::shared_ptr< Config > get_config_formatter() const
Access the config formatter.
Definition: CLI11.h:6495
CLI11_NODISCARD bool empty() const
True if the option was not passed.
Definition: CLI11.h:4476
OptionDefaults * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times.
Definition: CLI11.h:4317
GLint GLint GLint GLint GLint GLint GLint GLbitfield GLenum filter
Definition: glcorearb.h:1297
char characterQuote
the character to use around single characters
Definition: CLI11.h:2727
ConfigBase * parentSeparator(char sep)
Specify the separator to use for parent layers.
Definition: CLI11.h:2775
CLI11_NODISCARD std::string get_footer() const
Generate and return the footer.
Definition: CLI11.h:6574
const detail::ExistingPathValidator ExistingPath
Check for an existing path.
Definition: CLI11.h:3009
CRTP * join()
Set the multi option policy to join.
Definition: CLI11.h:4281
PcpNodeRef_ChildrenIterator begin(const PcpNodeRef::child_const_range &r)
Support for range-based for loops for PcpNodeRef children ranges.
Definition: node.h:558