Loading...
Searching...
No Matches
CLI11.h
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
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
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.
190PXR_NAMESPACE_OPEN_SCOPE
191
192namespace pxr_CLI {
193
194namespace CLI {
195
196
199namespace enums {
200
202template <typename T, typename = typename std::enable_if<std::is_enum<T>::value>::type>
203std::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
205 return in << static_cast<typename std::underlying_type<T>::type>(item);
206}
207
208} // namespace enums
209
211using enums::operator<<;
212
213namespace detail {
216constexpr int expected_max_vector_size{1 << 29};
217// Based on http://stackoverflow.com/questions/236129/split-a-string-in-c
219CLI11_INLINE std::vector<std::string> split(const std::string &s, char delim);
220
222template <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
235template <typename T,
236 typename Callable,
237 typename = typename std::enable_if<!std::is_constructible<std::string, Callable>::value>::type>
238std::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
255template <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
268CLI11_INLINE std::string &ltrim(std::string &str);
269
271CLI11_INLINE std::string &ltrim(std::string &str, const std::string &filter);
272
274CLI11_INLINE std::string &rtrim(std::string &str);
275
277CLI11_INLINE std::string &rtrim(std::string &str, const std::string &filter);
278
280inline std::string &trim(std::string &str) { return ltrim(rtrim(str)); }
281
283inline std::string &trim(std::string &str, const std::string filter) { return ltrim(rtrim(str, filter), filter); }
284
286inline std::string trim_copy(const std::string &str) {
287 std::string s = str;
288 return trim(s);
289}
290
292CLI11_INLINE std::string &remove_quotes(std::string &str);
293
298CLI11_INLINE std::string fix_newlines(const std::string &leader, std::string input);
299
301inline std::string trim_copy(const std::string &str, const std::string &filter) {
302 std::string s = str;
303 return trim(s, filter);
304}
306CLI11_INLINE std::ostream &
307format_help(std::ostream &out, std::string name, const std::string &description, std::size_t wid);
308
310CLI11_INLINE std::ostream &format_aliases(std::ostream &out, const std::vector<std::string> &aliases, std::size_t wid);
311
314template <typename T> bool valid_first_char(T c) { return ((c != '-') && (c != '!') && (c != ' ') && c != '\n'); }
315
317template <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
325CLI11_INLINE bool valid_name_string(const std::string &str);
326
328inline 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
334inline bool is_separator(const std::string &str) {
335 static const std::string sep("%%");
336 return (str.empty() || str == sep);
337}
338
340inline 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
345inline std::string to_lower(std::string str) {
346 std::transform(std::begin(str), std::end(str), std::begin(str), [](const std::string::value_type &x) {
347 return std::tolower(x, std::locale());
348 });
349 return str;
350}
351
353inline std::string remove_underscore(std::string str) {
354 str.erase(std::remove(std::begin(str), std::end(str), '_'), std::end(str));
355 return str;
356}
357
359CLI11_INLINE std::string find_and_replace(std::string str, std::string from, std::string to);
360
362inline bool has_default_flag_values(const std::string &flags) {
363 return (flags.find_first_of("{!") != std::string::npos);
364}
365
366CLI11_INLINE void remove_default_flag_values(std::string &flags);
367
369CLI11_INLINE std::ptrdiff_t find_member(std::string name,
370 const std::vector<std::string> names,
371 bool ignore_case = false,
372 bool ignore_underscore = false);
373
376template <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
386CLI11_INLINE std::vector<std::string> split_up(std::string str, char delimiter = '\0');
387
392CLI11_INLINE std::size_t escape_detect(std::string &str, std::size_t offset);
393
395CLI11_INLINE std::string &add_quotes_if_needed(std::string &str);
396
397} // namespace detail
398
399
400
401
402namespace detail {
403CLI11_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
419CLI11_INLINE std::string &ltrim(std::string &str) {
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
425CLI11_INLINE std::string &ltrim(std::string &str, const std::string &filter) {
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
431CLI11_INLINE std::string &rtrim(std::string &str) {
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
437CLI11_INLINE std::string &rtrim(std::string &str, const std::string &filter) {
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
444CLI11_INLINE std::string &remove_quotes(std::string &str) {
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
454CLI11_INLINE std::string fix_newlines(const std::string &leader, std::string input) {
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
466CLI11_INLINE std::ostream &
467format_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
484CLI11_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
501CLI11_INLINE bool valid_name_string(const std::string &str) {
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
512CLI11_INLINE std::string find_and_replace(std::string str, std::string from, std::string to) {
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
524CLI11_INLINE void remove_default_flag_values(std::string &flags) {
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
537CLI11_INLINE std::ptrdiff_t
538find_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) {
542 name = detail::to_lower(detail::remove_underscore(name));
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
565CLI11_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
617CLI11_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
629CLI11_INLINE std::string &add_quotes_if_needed(std::string &str) {
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
662enum class ExitCodes {
663 Success = 0,
664 IncorrectConstruction = 100,
665 BadNameString,
666 OptionAlreadyAdded,
667 FileError,
668 ConversionError,
669 ValidationError,
670 RequiredError,
671 RequiresError,
672 ExcludesError,
673 ExtrasError,
674 ConfigError,
675 InvalidError,
676 HorribleError,
677 OptionNotFound,
678 ArgumentMismatch,
679 BaseClass = 127
680};
681
682// Error definitions
683
689
691class 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
709class ConstructionError : public Error {
710 CLI11_ERROR_DEF(Error, ConstructionError)
711};
712
716 CLI11_ERROR_SIMPLE(IncorrectConstruction)
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) {
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 }
736 static IncorrectConstruction MultiOptionPolicy(std::string name) {
737 return IncorrectConstruction(name + ": multi_option_policy only works for flags and exact value options");
738 }
739};
740
743 CLI11_ERROR_DEF(ConstructionError, BadNameString)
744 CLI11_ERROR_SIMPLE(BadNameString)
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
757 CLI11_ERROR_DEF(ConstructionError, OptionAlreadyAdded)
758 explicit OptionAlreadyAdded(std::string name)
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
771class ParseError : public Error {
772 CLI11_ERROR_DEF(Error, ParseError)
773};
774
775// Not really "errors"
776
778class Success : public ParseError {
779 CLI11_ERROR_DEF(ParseError, Success)
780 Success() : Success("Successfully completed, should be caught and quit", ExitCodes::Success) {}
781};
782
784class CallForHelp : public Success {
785 CLI11_ERROR_DEF(Success, CallForHelp)
786 CallForHelp() : CallForHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
787};
788
790class CallForAllHelp : public Success {
791 CLI11_ERROR_DEF(Success, CallForAllHelp)
793 : CallForAllHelp("This should be caught in your main function, see examples", ExitCodes::Success) {}
794};
795
797class CallForVersion : public Success {
798 CLI11_ERROR_DEF(Success, CallForVersion)
800 : CallForVersion("This should be caught in your main function, see examples", ExitCodes::Success) {}
801};
802
804class RuntimeError : public ParseError {
805 CLI11_ERROR_DEF(ParseError, RuntimeError)
806 explicit RuntimeError(int exit_code = 1) : RuntimeError("Runtime error", exit_code) {}
807};
808
810class FileError : public ParseError {
811 CLI11_ERROR_DEF(ParseError, FileError)
812 CLI11_ERROR_SIMPLE(FileError)
813 static FileError Missing(std::string name) { return FileError(name + " was not readable (missing?)"); }
814};
815
818 CLI11_ERROR_DEF(ParseError, ConversionError)
819 CLI11_ERROR_SIMPLE(ConversionError)
820 ConversionError(std::string member, std::string name)
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
834 CLI11_ERROR_DEF(ParseError, ValidationError)
835 CLI11_ERROR_SIMPLE(ValidationError)
836 explicit ValidationError(std::string name, std::string msg) : ValidationError(name + ": " + msg) {}
837};
838
840class RequiredError : public ParseError {
841 CLI11_ERROR_DEF(ParseError, RequiredError)
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",
856 ExitCodes::RequiredError};
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 + "]",
863 ExitCodes::RequiredError};
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 + "]",
870 ExitCodes::RequiredError};
871 }
872};
873
876 CLI11_ERROR_DEF(ParseError, ArgumentMismatch)
877 CLI11_ERROR_SIMPLE(ArgumentMismatch)
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)),
883 ExitCodes::ArgumentMismatch) {}
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
906class RequiresError : public ParseError {
907 CLI11_ERROR_DEF(ParseError, RequiresError)
908 RequiresError(std::string curname, std::string subname)
909 : RequiresError(curname + " requires " + subname, ExitCodes::RequiresError) {}
910};
911
913class ExcludesError : public ParseError {
914 CLI11_ERROR_DEF(ParseError, ExcludesError)
915 ExcludesError(std::string curname, std::string subname)
916 : ExcludesError(curname + " excludes " + subname, ExitCodes::ExcludesError) {}
917};
918
920class ExtrasError : public ParseError {
921 CLI11_ERROR_DEF(ParseError, ExtrasError)
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, " "),
926 ExitCodes::ExtrasError) {}
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, " "),
932 ExitCodes::ExtrasError) {}
933};
934
936class ConfigError : public ParseError {
937 CLI11_ERROR_DEF(ParseError, ConfigError)
938 CLI11_ERROR_SIMPLE(ConfigError)
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
946class InvalidError : public ParseError {
947 CLI11_ERROR_DEF(ParseError, InvalidError)
948 explicit InvalidError(std::string name)
949 : InvalidError(name + ": Too many positional arguments with unlimited expected args", ExitCodes::InvalidError) {
950 }
951};
952
955class HorribleError : public ParseError {
956 CLI11_ERROR_DEF(ParseError, HorribleError)
957 CLI11_ERROR_SIMPLE(HorribleError)
958};
959
960// After parsing
961
963class OptionNotFound : public Error {
964 CLI11_ERROR_DEF(Error, OptionNotFound)
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
972
973
974
975
976// Type tools
977
978// Utilities for type enabling
979namespace detail {
980// Based generally on https://rmf.io/cxx11/almost-static-if
982enum class enabler {};
983
985constexpr enabler dummy = {};
986} // namespace detail
987
993template <bool B, class T = void> using enable_if_t = typename std::enable_if<B, T>::type;
994
996template <typename... Ts> struct make_void { using type = void; };
997
999template <typename... Ts> using void_t = typename make_void<Ts...>::type;
1000
1002template <bool B, class T, class F> using conditional_t = typename std::conditional<B, T, F>::type;
1003
1005template <typename T> struct is_bool : std::false_type {};
1006
1008template <> struct is_bool<bool> : std::true_type {};
1009
1011template <typename T> struct is_shared_ptr : std::false_type {};
1012
1014template <typename T> struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
1015
1017template <typename T> struct is_shared_ptr<const std::shared_ptr<T>> : std::true_type {};
1018
1020template <typename T> struct is_copyable_ptr {
1021 static bool const value = is_shared_ptr<T>::value || std::is_pointer<T>::value;
1022};
1023
1025template <typename T> struct IsMemberType { using type = T; };
1026
1028template <> struct IsMemberType<const char *> { using type = std::string; };
1029
1030namespace detail {
1031
1032// These are utilities for IsMember and other transforming objects
1033
1036
1038template <typename T, typename Enable = void> struct element_type { using type = T; };
1039
1040template <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
1046template <typename T> struct element_value_type { using type = typename element_type<T>::type::value_type; };
1047
1049template <typename T, typename _ = void> struct pair_adaptor : std::false_type {
1050 using value_type = typename T::value_type;
1051 using first_type = typename std::remove_const<value_type>::type;
1052 using second_type = typename std::remove_const<value_type>::type;
1053
1055 template <typename Q> static auto first(Q &&pair_value) -> decltype(std::forward<Q>(pair_value)) {
1056 return std::forward<Q>(pair_value);
1057 }
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
1066template <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;
1072 using first_type = typename std::remove_const<typename value_type::first_type>::type;
1073 using second_type = typename std::remove_const<typename value_type::second_type>::type;
1074
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 }
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
1096template <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
1124template <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
1135template <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
1146template <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
1157template <typename T, enable_if_t<is_istreamable<T>::value, detail::enabler> = detail::dummy>
1158bool 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
1165template <typename T, enable_if_t<!is_istreamable<T>::value, detail::enabler> = detail::dummy>
1166bool 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)
1171template <typename T, typename _ = void> struct is_mutable_container : std::false_type {};
1172
1176template <typename T>
1177struct is_mutable_container<
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)
1189template <typename T, typename _ = void> struct is_readable_container : std::false_type {};
1190
1194template <typename T>
1195struct is_readable_container<
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)
1201template <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)
1204template <typename T>
1205struct 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
1208template <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
1220template <typename T, enable_if_t<std::is_convertible<T, std::string>::value, detail::enabler> = detail::dummy>
1221auto to_string(T &&value) -> decltype(std::forward<T>(value)) {
1222 return std::forward<T>(value);
1223}
1224
1226template <typename T,
1227 enable_if_t<std::is_constructible<std::string, T>::value && !std::is_convertible<T, std::string>::value,
1228 detail::enabler> = detail::dummy>
1229std::string to_string(const T &value) {
1230 return std::string(value); // NOLINT(google-readability-casting)
1231}
1232
1234template <typename T,
1235 enable_if_t<!std::is_convertible<std::string, T>::value && !std::is_constructible<std::string, T>::value &&
1236 is_ostreamable<T>::value,
1237 detail::enabler> = detail::dummy>
1238std::string to_string(T &&value) {
1239 std::stringstream stream;
1240 stream << value;
1241 return stream.str();
1242}
1243
1245template <typename T,
1246 enable_if_t<!std::is_constructible<std::string, T>::value && !is_ostreamable<T>::value &&
1247 !is_readable_container<typename std::remove_const<T>::type>::value,
1248 detail::enabler> = detail::dummy>
1249std::string to_string(T &&) {
1250 return {};
1251}
1252
1254template <typename T,
1255 enable_if_t<!std::is_constructible<std::string, T>::value && !is_ostreamable<T>::value &&
1256 is_readable_container<T>::value,
1257 detail::enabler> = detail::dummy>
1258std::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
1273template <typename T1,
1274 typename T2,
1275 typename T,
1276 enable_if_t<std::is_same<T1, T2>::value, detail::enabler> = detail::dummy>
1277auto checked_to_string(T &&value) -> decltype(to_string(std::forward<T>(value))) {
1278 return to_string(std::forward<T>(value));
1279}
1280
1282template <typename T1,
1283 typename T2,
1284 typename T,
1285 enable_if_t<!std::is_same<T1, T2>::value, detail::enabler> = detail::dummy>
1286std::string checked_to_string(T &&) {
1287 return std::string{};
1288}
1290template <typename T, enable_if_t<std::is_arithmetic<T>::value, detail::enabler> = detail::dummy>
1291std::string value_string(const T &value) {
1292 return std::to_string(value);
1293}
1295template <typename T, enable_if_t<std::is_enum<T>::value, detail::enabler> = detail::dummy>
1296std::string value_string(const T &value) {
1297 return std::to_string(static_cast<typename std::underlying_type<T>::type>(value));
1298}
1300template <typename T,
1301 enable_if_t<!std::is_enum<T>::value && !std::is_arithmetic<T>::value, detail::enabler> = detail::dummy>
1302auto value_string(const T &value) -> decltype(to_string(value)) {
1303 return to_string(value);
1304}
1305
1307template <typename T, typename def, typename Enable = void> struct wrapped_type { using type = def; };
1308
1310template <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
1315template <typename T, typename Enable = void> struct type_count_base { static const int value{0}; };
1316
1318template <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
1326template <typename T>
1327struct 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
1332template <typename T> struct type_count_base<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1333 static constexpr int value{type_count_base<typename T::value_type>::value};
1334};
1335
1337
1339template <typename T> struct subtype_count;
1340
1342template <typename T> struct subtype_count_min;
1343
1345template <typename T, typename Enable = void> struct type_count { static const int value{0}; };
1346
1348template <typename T>
1349struct 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
1356template <typename T> struct type_count<T, typename std::enable_if<is_complex<T>::value>::type> {
1357 static constexpr int value{2};
1358};
1359
1361template <typename T> struct type_count<T, typename std::enable_if<is_mutable_container<T>::value>::type> {
1362 static constexpr int value{subtype_count<typename T::value_type>::value};
1363};
1364
1366template <typename T>
1367struct 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
1374template <typename T, std::size_t I>
1375constexpr typename std::enable_if<I == type_count_base<T>::value, int>::type tuple_type_size() {
1376 return 0;
1377}
1378
1380template <typename T, std::size_t I>
1381 constexpr typename std::enable_if < I<type_count_base<T>::value, int>::type tuple_type_size() {
1382 return subtype_count<typename std::tuple_element<I, T>::type>::value + tuple_type_size<T, I + 1>();
1383}
1384
1386template <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
1391template <typename T> struct subtype_count {
1392 static constexpr int value{is_mutable_container<T>::value ? expected_max_vector_size : type_count<T>::value};
1393};
1394
1396template <typename T, typename Enable = void> struct type_count_min { static const int value{0}; };
1397
1399template <typename T>
1400struct 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
1408template <typename T> struct type_count_min<T, typename std::enable_if<is_complex<T>::value>::type> {
1409 static constexpr int value{1};
1410};
1411
1413template <typename T>
1414struct 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
1421template <typename T, std::size_t I>
1422constexpr typename std::enable_if<I == type_count_base<T>::value, int>::type tuple_type_size_min() {
1423 return 0;
1424}
1425
1427template <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
1433template <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
1438template <typename T> struct subtype_count_min {
1439 static constexpr int value{is_mutable_container<T>::value
1440 ? ((type_count<T>::value < expected_max_vector_size) ? type_count<T>::value : 0)
1441 : type_count_min<T>::value};
1442};
1443
1445template <typename T, typename Enable = void> struct expected_count { static const int value{0}; };
1446
1448template <typename T>
1449struct 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};
1455template <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
1460template <typename T>
1461struct 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
1466enum 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
1489
1491template <typename T, typename Enable = void> struct classify_object {
1492 static constexpr object_category value{object_category::other};
1493};
1494
1496template <typename T>
1497struct 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
1505template <typename T>
1506struct 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
1513template <typename T>
1514struct 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
1519template <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
1524template <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
1529template <typename T>
1530struct 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
1537template <typename T>
1538struct 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
1547template <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
1551template <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
1557template <typename T> struct uncommon_type {
1558 using type = typename std::conditional<!std::is_floating_point<T>::value && !std::is_integral<T>::value &&
1559 !std::is_assignable<T &, std::string>::value &&
1560 !std::is_constructible<T, std::string>::value && !is_complex<T>::value &&
1561 !is_mutable_container<T>::value && !std::is_enum<T>::value,
1562 std::true_type,
1563 std::false_type>::type;
1564 static constexpr bool value = type::value;
1565};
1566
1568template <typename T>
1569struct 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
1576template <typename T>
1577struct 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
1585template <typename T>
1586struct 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
1594template <typename T>
1595struct 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
1603template <typename T>
1604struct 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
1620template <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
1629
1630template <typename T,
1631 enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> = detail::dummy>
1632constexpr const char *type_name() {
1633 return "CHAR";
1634}
1635
1636template <typename T,
1637 enable_if_t<classify_object<T>::value == object_category::integral_value ||
1638 classify_object<T>::value == object_category::integer_constructible,
1639 detail::enabler> = detail::dummy>
1640constexpr const char *type_name() {
1641 return "INT";
1642}
1643
1644template <typename T,
1645 enable_if_t<classify_object<T>::value == object_category::unsigned_integral, detail::enabler> = detail::dummy>
1646constexpr const char *type_name() {
1647 return "UINT";
1648}
1649
1650template <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,
1654 detail::enabler> = detail::dummy>
1655constexpr const char *type_name() {
1656 return "FLOAT";
1657}
1658
1660template <typename T,
1661 enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> = detail::dummy>
1662constexpr const char *type_name() {
1663 return "ENUM";
1664}
1665
1667template <typename T,
1668 enable_if_t<classify_object<T>::value == object_category::boolean_value, detail::enabler> = detail::dummy>
1669constexpr const char *type_name() {
1670 return "BOOLEAN";
1671}
1672
1674template <typename T,
1675 enable_if_t<classify_object<T>::value == object_category::complex_number, detail::enabler> = detail::dummy>
1676constexpr const char *type_name() {
1677 return "COMPLEX";
1678}
1679
1681template <typename T,
1682 enable_if_t<classify_object<T>::value >= object_category::string_assignable &&
1683 classify_object<T>::value <= object_category::other,
1684 detail::enabler> = detail::dummy>
1685constexpr const char *type_name() {
1686 return "TEXT";
1687}
1689template <typename T,
1690 enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value >= 2,
1691 detail::enabler> = detail::dummy>
1692std::string type_name(); // forward declaration
1693
1695template <typename T,
1696 enable_if_t<classify_object<T>::value == object_category::container_value ||
1697 classify_object<T>::value == object_category::wrapper_value,
1698 detail::enabler> = detail::dummy>
1699std::string type_name(); // forward declaration
1700
1702template <typename T,
1703 enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value == 1,
1704 detail::enabler> = detail::dummy>
1705inline std::string type_name() {
1706 return type_name<typename std::decay<typename std::tuple_element<0, T>::type>::type>();
1707}
1708
1710template <typename T, std::size_t I>
1711inline typename std::enable_if<I == type_count_base<T>::value, std::string>::type tuple_name() {
1712 return std::string{};
1713}
1714
1716template <typename T, std::size_t I>
1717inline typename std::enable_if<(I < type_count_base<T>::value), std::string>::type tuple_name() {
1718 auto str = std::string{type_name<typename std::decay<typename std::tuple_element<I, T>::type>::type>()} + ',' +
1719 tuple_name<T, I + 1>();
1720 if(str.back() == ',')
1721 str.pop_back();
1722 return str;
1723}
1724
1726template <typename T,
1727 enable_if_t<classify_object<T>::value == object_category::tuple_value && type_count_base<T>::value >= 2,
1728 detail::enabler>>
1729inline std::string type_name() {
1730 auto tname = std::string(1, '[') + tuple_name<T, 0>();
1731 tname.push_back(']');
1732 return tname;
1733}
1734
1736template <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>>
1740inline std::string type_name() {
1741 return type_name<typename T::value_type>();
1742}
1743
1744// Lexical cast
1745
1747template <typename T, enable_if_t<std::is_unsigned<T>::value, detail::enabler> = detail::dummy>
1748bool 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
1768template <typename T, enable_if_t<std::is_signed<T>::value, detail::enabler> = detail::dummy>
1769bool 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
1788inline 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
1831template <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>
1835bool lexical_cast(const std::string &input, T &output) {
1836 return integral_conversion(input, output);
1837}
1838
1840template <typename T,
1841 enable_if_t<classify_object<T>::value == object_category::char_value, detail::enabler> = detail::dummy>
1842bool 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
1851template <typename T,
1852 enable_if_t<classify_object<T>::value == object_category::boolean_value, detail::enabler> = detail::dummy>
1853bool 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
1869template <typename T,
1870 enable_if_t<classify_object<T>::value == object_category::floating_point, detail::enabler> = detail::dummy>
1871bool 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
1882template <typename T,
1883 enable_if_t<classify_object<T>::value == object_category::complex_number, detail::enabler> = detail::dummy>
1884bool 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
1914template <typename T,
1915 enable_if_t<classify_object<T>::value == object_category::string_assignable, detail::enabler> = detail::dummy>
1916bool lexical_cast(const std::string &input, T &output) {
1917 output = input;
1918 return true;
1919}
1920
1922template <
1923 typename T,
1924 enable_if_t<classify_object<T>::value == object_category::string_constructible, detail::enabler> = detail::dummy>
1925bool lexical_cast(const std::string &input, T &output) {
1926 output = T(input);
1927 return true;
1928}
1929
1931template <typename T,
1932 enable_if_t<classify_object<T>::value == object_category::enumeration, detail::enabler> = detail::dummy>
1933bool lexical_cast(const std::string &input, T &output) {
1934 typename std::underlying_type<T>::type val;
1935 if(!integral_conversion(input, val)) {
1936 return false;
1937 }
1938 output = static_cast<T>(val);
1939 return true;
1940}
1941
1943template <typename T,
1944 enable_if_t<classify_object<T>::value == object_category::wrapper_value &&
1945 std::is_assignable<T &, typename T::value_type>::value,
1946 detail::enabler> = detail::dummy>
1947bool 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
1956template <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>
1960bool 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
1970template <
1971 typename T,
1972 enable_if_t<classify_object<T>::value == object_category::number_constructible, detail::enabler> = detail::dummy>
1973bool 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
1990template <
1991 typename T,
1992 enable_if_t<classify_object<T>::value == object_category::integer_constructible, detail::enabler> = detail::dummy>
1993bool 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
2003template <
2004 typename T,
2005 enable_if_t<classify_object<T>::value == object_category::double_constructible, detail::enabler> = detail::dummy>
2006bool 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
2016template <typename T,
2017 enable_if_t<classify_object<T>::value == object_category::other && std::is_assignable<T &, int>::value,
2018 detail::enabler> = detail::dummy>
2019bool 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
2042template <typename T,
2043 enable_if_t<classify_object<T>::value == object_category::other && !std::is_assignable<T &, int>::value,
2044 detail::enabler> = detail::dummy>
2045bool 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
2054template <typename AssignTo,
2055 typename ConvertTo,
2056 enable_if_t<std::is_same<AssignTo, ConvertTo>::value &&
2057 (classify_object<AssignTo>::value == object_category::string_assignable ||
2058 classify_object<AssignTo>::value == object_category::string_constructible),
2059 detail::enabler> = detail::dummy>
2060bool lexical_assign(const std::string &input, AssignTo &output) {
2061 return lexical_cast(input, output);
2062}
2063
2065template <typename AssignTo,
2066 typename ConvertTo,
2067 enable_if_t<std::is_same<AssignTo, ConvertTo>::value && std::is_assignable<AssignTo &, AssignTo>::value &&
2068 classify_object<AssignTo>::value != object_category::string_assignable &&
2069 classify_object<AssignTo>::value != object_category::string_constructible,
2070 detail::enabler> = detail::dummy>
2071bool 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
2081template <typename AssignTo,
2082 typename ConvertTo,
2083 enable_if_t<std::is_same<AssignTo, ConvertTo>::value && !std::is_assignable<AssignTo &, AssignTo>::value &&
2084 classify_object<AssignTo>::value == object_category::wrapper_value,
2085 detail::enabler> = detail::dummy>
2086bool 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
2097template <typename AssignTo,
2098 typename ConvertTo,
2099 enable_if_t<std::is_same<AssignTo, ConvertTo>::value && !std::is_assignable<AssignTo &, AssignTo>::value &&
2100 classify_object<AssignTo>::value != object_category::wrapper_value &&
2101 std::is_assignable<AssignTo &, int>::value,
2102 detail::enabler> = detail::dummy>
2103bool 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
2117template <typename AssignTo,
2118 typename ConvertTo,
2119 enable_if_t<!std::is_same<AssignTo, ConvertTo>::value && std::is_assignable<AssignTo &, ConvertTo &>::value,
2120 detail::enabler> = detail::dummy>
2121bool 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
2131template <
2132 typename AssignTo,
2133 typename ConvertTo,
2134 enable_if_t<!std::is_same<AssignTo, ConvertTo>::value && !std::is_assignable<AssignTo &, ConvertTo &>::value &&
2135 std::is_move_assignable<AssignTo>::value,
2136 detail::enabler> = detail::dummy>
2137bool 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
2147template <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>
2152bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2153 return lexical_assign<AssignTo, ConvertTo>(strings[0], output);
2154}
2155
2158template <typename AssignTo,
2159 typename ConvertTo,
2160 enable_if_t<(type_count<AssignTo>::value <= 2) && expected_count<AssignTo>::value == 1 &&
2161 is_tuple_like<ConvertTo>::value && type_count_base<ConvertTo>::value == 2,
2162 detail::enabler> = detail::dummy>
2163bool lexical_conversion(const std::vector<std ::string> &strings, AssignTo &output) {
2164 // the remove const is to handle pair types coming from a container
2165 typename std::remove_const<typename std::tuple_element<0, ConvertTo>::type>::type v1;
2166 typename std::tuple_element<1, ConvertTo>::type v2;
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
2178template <class AssignTo,
2179 class ConvertTo,
2180 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2181 type_count<ConvertTo>::value == 1,
2182 detail::enabler> = detail::dummy>
2183bool 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
2207template <class AssignTo, class ConvertTo, enable_if_t<is_complex<ConvertTo>::value, detail::enabler> = detail::dummy>
2208bool 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
2227template <class AssignTo,
2228 class ConvertTo,
2229 enable_if_t<is_mutable_container<AssignTo>::value && (expected_count<ConvertTo>::value == 1) &&
2230 (type_count<ConvertTo>::value == 1),
2231 detail::enabler> = detail::dummy>
2232bool 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
2247template <class AssignTo,
2248 class ConvertTo,
2249 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2250 type_count_base<ConvertTo>::value == 2,
2251 detail::enabler> = detail::dummy>
2252bool lexical_conversion(std::vector<std::string> strings, AssignTo &output);
2253
2255template <class AssignTo,
2256 class ConvertTo,
2257 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
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>
2262bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output);
2263
2265template <class AssignTo,
2266 class ConvertTo,
2267 enable_if_t<is_tuple_like<AssignTo>::value && is_tuple_like<ConvertTo>::value &&
2268 (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2269 type_count<ConvertTo>::value > 2),
2270 detail::enabler> = detail::dummy>
2271bool lexical_conversion(const std::vector<std::string> &strings, AssignTo &output); // forward declaration
2272
2275template <typename AssignTo,
2276 typename ConvertTo,
2277 enable_if_t<!is_tuple_like<AssignTo>::value && !is_mutable_container<AssignTo>::value &&
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>
2281bool 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
2294template <class AssignTo, class ConvertTo, std::size_t I>
2295inline typename std::enable_if<(I >= type_count_base<AssignTo>::value), bool>::type
2296tuple_conversion(const std::vector<std::string> &, AssignTo &) {
2297 return true;
2298}
2299
2301template <class AssignTo, class ConvertTo>
2302inline typename std::enable_if<!is_mutable_container<ConvertTo>::value && type_count<ConvertTo>::value == 1, bool>::type
2303tuple_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
2310template <class AssignTo, class ConvertTo>
2311inline 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
2314tuple_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
2321template <class AssignTo, class ConvertTo>
2322inline typename std::enable_if<is_mutable_container<ConvertTo>::value ||
2323 type_count<ConvertTo>::value != type_count_min<ConvertTo>::value,
2324 bool>::type
2325tuple_type_conversion(std::vector<std::string> &strings, AssignTo &output) {
2326
2327 std::size_t index{subtype_count_min<ConvertTo>::value};
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
2344template <class AssignTo, class ConvertTo, std::size_t I>
2345inline typename std::enable_if<(I < type_count_base<AssignTo>::value), bool>::type
2346tuple_conversion(std::vector<std::string> strings, AssignTo &output) {
2347 bool retval = true;
2348 using ConvertToElement = typename std::
2349 conditional<is_tuple_like<ConvertTo>::value, typename std::tuple_element<I, ConvertTo>::type, ConvertTo>::type;
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
2359template <class AssignTo,
2360 class ConvertTo,
2361 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
2362 type_count_base<ConvertTo>::value == 2,
2363 detail::enabler>>
2364bool lexical_conversion(std::vector<std::string> strings, AssignTo &output) {
2365 output.clear();
2366 while(!strings.empty()) {
2367
2368 typename std::remove_const<typename std::tuple_element<0, typename ConvertTo::value_type>::type>::type v1;
2369 typename std::tuple_element<1, typename ConvertTo::value_type>::type v2;
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
2384template <class AssignTo,
2385 class ConvertTo,
2386 enable_if_t<is_tuple_like<AssignTo>::value && is_tuple_like<ConvertTo>::value &&
2387 (type_count_base<ConvertTo>::value != type_count<ConvertTo>::value ||
2388 type_count<ConvertTo>::value > 2),
2389 detail::enabler>>
2390bool 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
2398template <class AssignTo,
2399 class ConvertTo,
2400 enable_if_t<is_mutable_container<AssignTo>::value && is_mutable_container<ConvertTo>::value &&
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>>
2405bool 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
2436template <typename AssignTo,
2437 class ConvertTo,
2438 enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2439 std::is_assignable<ConvertTo &, ConvertTo>::value,
2440 detail::enabler> = detail::dummy>
2441bool 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
2455template <typename AssignTo,
2456 class ConvertTo,
2457 enable_if_t<classify_object<ConvertTo>::value == object_category::wrapper_value &&
2458 !std::is_assignable<AssignTo &, ConvertTo>::value,
2459 detail::enabler> = detail::dummy>
2460bool 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
2475inline 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
2513namespace detail {
2514
2515// Returns false if not a short option. Otherwise, sets opt name and rest and returns true
2516CLI11_INLINE bool split_short(const std::string &current, std::string &name, std::string &rest);
2517
2518// Returns false if not a long option. Otherwise, sets opt name and other side of = and returns true
2519CLI11_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
2522CLI11_INLINE bool split_windows_style(const std::string &current, std::string &name, std::string &value);
2523
2524// Splits a string into multiple long and short names
2525CLI11_INLINE std::vector<std::string> split_names(std::string current);
2526
2528CLI11_INLINE std::vector<std::pair<std::string, std::string>> get_default_flag_values(const std::string &str);
2529
2531CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>
2532get_names(const std::vector<std::string> &input);
2533
2534} // namespace detail
2535
2536
2537
2538namespace detail {
2539
2540CLI11_INLINE bool split_short(const std::string &current, std::string &name, std::string &rest) {
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
2549CLI11_INLINE bool split_long(const std::string &current, std::string &name, std::string &value) {
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
2564CLI11_INLINE bool split_windows_style(const std::string &current, std::string &name, std::string &value) {
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
2579CLI11_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
2590CLI11_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
2616CLI11_INLINE std::tuple<std::vector<std::string>, std::vector<std::string>, std::string>
2617get_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
2654class App;
2655
2659 std::vector<std::string> parents{};
2660
2662 std::string name{};
2663
2665 std::vector<std::string> inputs{};
2666
2668 CLI11_NODISCARD std::string fullname() const {
2669 std::vector<std::string> tmp = parents;
2670 tmp.emplace_back(name);
2671 return detail::join(tmp, ".");
2672 }
2673};
2674
2676class Config {
2677 protected:
2678 std::vector<ConfigItem> items{};
2679
2680 public:
2682 virtual std::string to_config(const App *, bool, bool, std::string) const = 0;
2683
2685 virtual std::vector<ConfigItem> from_config(std::istream &) const = 0;
2686
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
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
2708 virtual ~Config() = default;
2709};
2710
2712class ConfigBase : public Config {
2713 protected:
2715 char commentChar = '#';
2717 char arrayStart = '[';
2719 char arrayEnd = ']';
2721 char arraySeparator = ',';
2723 char valueDelimiter = '=';
2725 char stringQuote = '"';
2727 char characterQuote = '\'';
2729 uint8_t maximumLayers{255};
2731 char parentSeparatorChar{'.'};
2733 int16_t configIndex{-1};
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;
2743 ConfigBase *comment(char cchar) {
2744 commentChar = cchar;
2745 return this;
2746 }
2748 ConfigBase *arrayBounds(char aStart, char aEnd) {
2749 arrayStart = aStart;
2750 arrayEnd = aEnd;
2751 return this;
2752 }
2755 arraySeparator = aSep;
2756 return this;
2757 }
2760 valueDelimiter = vSep;
2761 return this;
2762 }
2764 ConfigBase *quoteCharacter(char qString, char qChar) {
2765 stringQuote = qString;
2766 characterQuote = qChar;
2767 return this;
2768 }
2770 ConfigBase *maxLayers(uint8_t layers) {
2771 maximumLayers = layers;
2772 return this;
2773 }
2776 parentSeparatorChar = sep;
2777 return this;
2778 }
2780 std::string &sectionRef() { return configSection; }
2782 CLI11_NODISCARD const std::string &section() const { return configSection; }
2784 ConfigBase *section(const std::string &sectionName) {
2785 configSection = sectionName;
2786 return this;
2787 }
2788
2790 int16_t &indexRef() { return configIndex; }
2792 CLI11_NODISCARD int16_t index() const { return configIndex; }
2794 ConfigBase *index(int16_t sectionIndex) {
2795 configIndex = sectionIndex;
2796 return this;
2797 }
2798};
2799
2801using ConfigTOML = ConfigBase;
2802
2804class ConfigINI : public ConfigTOML {
2805
2806 public:
2807 ConfigINI() {
2808 commentChar = ';';
2809 arrayStart = '\0';
2810 arrayEnd = '\0';
2811 arraySeparator = ' ';
2812 valueDelimiter = '=';
2813 }
2814};
2815
2816
2817
2818class Option;
2819
2821
2828
2831 protected:
2833 std::function<std::string()> desc_function_{[]() { return std::string{}; }};
2834
2837 std::function<std::string(std::string &)> func_{[](std::string &) { return std::string{}; }};
2839 std::string name_{};
2841 int application_index_ = -1;
2843 bool active_{true};
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;
2853 explicit Validator(std::string validator_desc) : desc_function_([validator_desc]() { return validator_desc; }) {}
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)) {}
2859 Validator &operation(std::function<std::string(std::string &)> op) {
2860 func_ = std::move(op);
2861 return *this;
2862 }
2865 std::string operator()(std::string &str) const;
2866
2869 std::string operator()(const std::string &str) const {
2870 std::string value = str;
2871 return (active_) ? func_(value) : std::string{};
2872 }
2873
2875 Validator &description(std::string validator_desc) {
2876 desc_function_ = [validator_desc]() { return validator_desc; };
2877 return *this;
2878 }
2880 CLI11_NODISCARD Validator description(std::string validator_desc) const;
2881
2883 CLI11_NODISCARD std::string get_description() const {
2884 if(active_) {
2885 return desc_function_();
2886 }
2887 return std::string{};
2888 }
2890 Validator &name(std::string validator_name) {
2891 name_ = std::move(validator_name);
2892 return *this;
2893 }
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 }
2901 CLI11_NODISCARD const std::string &get_name() const { return name_; }
2903 Validator &active(bool active_val = true) {
2904 active_ = active_val;
2905 return *this;
2906 }
2908 CLI11_NODISCARD Validator active(bool active_val = true) const {
2909 Validator newval(*this);
2910 newval.active_ = active_val;
2911 return newval;
2912 }
2913
2915 Validator &non_modifying(bool no_modify = true) {
2916 non_modifying_ = no_modify;
2917 return *this;
2918 }
2921 application_index_ = app_index;
2922 return *this;
2923 }
2925 CLI11_NODISCARD Validator application_index(int app_index) const {
2926 Validator newval(*this);
2927 newval.application_index_ = app_index;
2928 return newval;
2929 }
2931 CLI11_NODISCARD int get_application_index() const { return application_index_; }
2933 CLI11_NODISCARD bool get_active() const { return active_; }
2934
2936 CLI11_NODISCARD bool get_modifying() const { return !non_modifying_; }
2937
2940 Validator operator&(const Validator &other) const;
2941
2944 Validator operator|(const Validator &other) const;
2945
2947 Validator operator!() const;
2948
2949 private:
2950 void _merge_description(const Validator &val1, const Validator &val2, const std::string &merger);
2951};
2952
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.
2960namespace detail {
2961
2963enum class path_type { nonexistent, file, directory };
2964
2966CLI11_INLINE path_type check_path(const char *file) noexcept;
2967
2970 public:
2972};
2973
2976 public:
2978};
2979
2982 public:
2984};
2985
2988 public:
2990};
2991
2993class 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
3003const detail::ExistingFileValidator ExistingFile;
3004
3006const detail::ExistingDirectoryValidator ExistingDirectory;
3007
3009const detail::ExistingPathValidator ExistingPath;
3010
3012const detail::NonexistentPathValidator NonexistentPath;
3013
3015const detail::IPV4Validator ValidIPV4;
3016
3018template <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
3032const TypeValidator<double> Number("NUMBER");
3033
3037 public:
3038 explicit FileOnDefaultPath(std::string default_path, bool enableErrorReturn = true);
3039};
3040
3042class Range : public Validator {
3043 public:
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
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
3076const Range NonNegativeNumber((std::numeric_limits<double>::max)(), "NONNEGATIVE");
3077
3079const Range PositiveNumber((std::numeric_limits<double>::min)(), (std::numeric_limits<double>::max)(), "POSITIVE");
3080
3082class Bound : public Validator {
3083 public:
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
3109 template <typename T> explicit Bound(T max_val) : Bound(static_cast<T>(0), max_val) {}
3110};
3111
3112namespace detail {
3113template <typename T,
3114 enable_if_t<is_copyable_ptr<typename std::remove_reference<T>::type>::value, detail::enabler> = detail::dummy>
3115auto smart_deref(T value) -> decltype(*value) {
3116 return *value;
3117}
3118
3119template <
3120 typename T,
3121 enable_if_t<!is_copyable_ptr<typename std::remove_reference<T>::type>::value, detail::enabler> = detail::dummy>
3122typename std::remove_reference<T>::type &smart_deref(T &value) {
3123 return value;
3124}
3126template <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
3139template <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) {
3146 std::string res{detail::to_string(detail::pair_adaptor<element_t>::first(v))};
3147
3148 if(!key_only) {
3149 res.append("->");
3150 res += detail::to_string(detail::pair_adaptor<element_t>::second(v));
3151 }
3152 return res;
3153 },
3154 ","));
3155 out.push_back('}');
3156 return out;
3157}
3158
3159template <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
3169template <typename T, typename V, enable_if_t<!has_find<T, V>::value, detail::enabler> = detail::dummy>
3170auto 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
3180template <typename T, typename V, enable_if_t<has_find<T, V>::value, detail::enabler> = detail::dummy>
3181auto 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
3188template <typename T, typename V>
3189auto 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) {
3200 V a{detail::pair_adaptor<element_t>::first(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
3211template <typename T>
3212inline 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}
3219template <typename T>
3220inline 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
3225template <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
3241template <typename T>
3242typename std::enable_if<std::is_floating_point<T>::value, bool>::type checked_multiply(T &a, T b) {
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
3253class IsMember : public Validator {
3254 public:
3255 using filter_fn_t = std::function<std::string(std::string)>;
3256
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
3263 template <typename T> explicit IsMember(T &&set) : IsMember(std::forward<T>(set), nullptr) {}
3264
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) {
3297 input = detail::value_string(detail::pair_adaptor<element_t>::first(*(res.second)));
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
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
3319template <typename T> using TransformPairs = std::vector<std::pair<std::string, T>>;
3320
3322class Transformer : public Validator {
3323 public:
3324 using filter_fn_t = std::function<std::string(std::string)>;
3325
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
3332 template <typename T> explicit Transformer(T &&mapping) : Transformer(std::forward<T>(mapping), nullptr) {}
3333
3336 template <typename T, typename F> explicit Transformer(T mapping, F filter_function) {
3337
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) {
3364 input = detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
3365 }
3366 return std::string{};
3367 };
3368 }
3369
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
3381 public:
3382 using filter_fn_t = std::function<std::string(std::string)>;
3383
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
3390 template <typename T> explicit CheckedTransformer(T mapping) : CheckedTransformer(std::move(mapping), nullptr) {}
3391
3394 template <typename T, typename F> explicit CheckedTransformer(T mapping, F filter_function) {
3395
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) {
3431 input = detail::value_string(detail::pair_adaptor<element_t>::second(*res.second));
3432 return std::string{};
3433 }
3434 }
3435 for(const auto &v : detail::smart_deref(mapping)) {
3436 auto output_string = detail::value_string(detail::pair_adaptor<element_t>::second(v));
3437 if(output_string == input) {
3438 return std::string();
3439 }
3440 }
3441
3442 return "Check " + input + " " + tfunc() + " FAILED";
3443 };
3444 }
3445
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
3456inline std::string ignore_case(std::string item) { return detail::to_lower(item); }
3457
3459inline std::string ignore_underscore(std::string item) { return detail::remove_underscore(item); }
3460
3462inline std::string ignore_space(std::string item) {
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
3480 public:
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) {
3523 unit = detail::to_lower(unit);
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:
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
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
3622 public:
3623 using result_t = std::uint64_t;
3624
3632 explicit AsSizeValue(bool kb_is_1000);
3633
3634 private:
3636 static std::map<std::string, result_t> init_mapping(bool kb_is_1000);
3637
3639 static std::map<std::string, result_t> get_mapping(bool kb_is_1000);
3640};
3641
3642namespace detail {
3647CLI11_INLINE std::pair<std::string, std::string> split_program_name(std::string commandline);
3648
3649} // namespace detail
3651
3652
3653
3654
3655CLI11_INLINE std::string Validator::operator()(std::string &str) const {
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
3668CLI11_NODISCARD CLI11_INLINE Validator Validator::description(std::string validator_desc) const {
3669 Validator newval(*this);
3670 newval.desc_function_ = [validator_desc]() { return validator_desc; };
3671 return newval;
3672}
3673
3674CLI11_INLINE Validator Validator::operator&(const Validator &other) const {
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
3696CLI11_INLINE Validator Validator::operator|(const Validator &other) const {
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
3718CLI11_INLINE Validator Validator::operator!() const {
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
3740CLI11_INLINE void
3741Validator::_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
3756namespace detail {
3757
3758#if defined CLI11_HAS_FILESYSTEM && CLI11_HAS_FILESYSTEM > 0
3759CLI11_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
3783CLI11_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
3799CLI11_INLINE ExistingFileValidator::ExistingFileValidator() : Validator("FILE") {
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
3812CLI11_INLINE ExistingDirectoryValidator::ExistingDirectoryValidator() : Validator("DIR") {
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
3825CLI11_INLINE ExistingPathValidator::ExistingPathValidator() : Validator("PATH(existing)") {
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
3835CLI11_INLINE NonexistentPathValidator::NonexistentPathValidator() : Validator("PATH(non-existing)") {
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
3845CLI11_INLINE IPV4Validator::IPV4Validator() : Validator("IPV4") {
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
3867CLI11_INLINE FileOnDefaultPath::FileOnDefaultPath(std::string default_path, bool enableErrorReturn)
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
3891CLI11_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
3899CLI11_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
3917CLI11_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
3926namespace detail {
3927
3928CLI11_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
3975
3976
3977
3978
3979class Option;
3980class App;
3981
3986
3987enum class AppFormatMode {
3988 Normal,
3989 All,
3990 Sub,
3991};
3992
3998 protected:
4001
4003 std::size_t column_width_{30};
4004
4007 std::map<std::string, std::string> labels_{};
4008
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
4021 virtual ~FormatterBase() noexcept {} // NOLINT(modernize-use-equals-default)
4022
4024 virtual std::string make_help(const App *, std::string, AppFormatMode) const = 0;
4025
4029
4031 void label(std::string key, std::string val) { labels_[key] = val; }
4032
4034 void column_width(std::size_t val) { column_width_ = val; }
4035
4039
4041 CLI11_NODISCARD std::string get_label(std::string key) const {
4042 if(labels_.find(key) == labels_.end())
4043 return key;
4044 return labels_.at(key);
4045 }
4046
4048 CLI11_NODISCARD std::size_t get_column_width() const { return column_width_; }
4049
4051};
4052
4054class FormatterLambda final : public FormatterBase {
4055 using funct_t = std::function<std::string(const App *, std::string, AppFormatMode)>;
4056
4058 funct_t lambda_;
4059
4060 public:
4062 explicit FormatterLambda(funct_t funct) : lambda_(std::move(funct)) {}
4063
4065 ~FormatterLambda() noexcept override {} // NOLINT(modernize-use-equals-default)
4066
4068 std::string make_help(const App *app, std::string name, AppFormatMode mode) const override {
4069 return lambda_(app, name, mode);
4070 }
4071};
4072
4075class 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
4085
4088 CLI11_NODISCARD virtual std::string
4089 make_group(std::string group, bool is_positional, std::vector<const Option *> opts) const;
4090
4092 virtual std::string make_positionals(const App *app) const;
4093
4095 std::string make_groups(const App *app, AppFormatMode mode) const;
4096
4098 virtual std::string make_subcommands(const App *app, AppFormatMode mode) const;
4099
4101 virtual std::string make_subcommand(const App *sub) const;
4102
4104 virtual std::string make_expanded(const App *sub) const;
4105
4107 virtual std::string make_footer(const App *app) const;
4108
4110 virtual std::string make_description(const App *app) const;
4111
4113 virtual std::string make_usage(const App *app, std::string name) const;
4114
4116 std::string make_help(const App * /*app*/, std::string, AppFormatMode) const override;
4117
4121
4123 virtual std::string make_option(const Option *opt, bool is_positional) const {
4124 std::stringstream out;
4125 detail::format_help(
4126 out, make_option_name(opt, is_positional) + make_option_opts(opt), make_option_desc(opt), column_width_);
4127 return out.str();
4128 }
4129
4131 virtual std::string make_option_name(const Option *, bool) const;
4132
4134 virtual std::string make_option_opts(const Option *) const;
4135
4137 virtual std::string make_option_desc(const Option *) const;
4138
4140 virtual std::string make_option_usage(const Option *opt) const;
4141
4143};
4144
4145
4146
4147
4148using results_t = std::vector<std::string>;
4150using callback_t = std::function<bool(const results_t &)>;
4151
4152class Option;
4153class App;
4154
4155using Option_p = std::unique_ptr<Option>;
4157enum class MultiOptionPolicy : char {
4158 Throw,
4159 TakeLast,
4160 TakeFirst,
4161 Join,
4162 TakeAll,
4163 Sum
4164};
4165
4168template <typename CRTP> class OptionBase {
4169 friend App;
4170
4171 protected:
4173 std::string group_ = std::string("Options");
4174
4176 bool required_{false};
4177
4179 bool ignore_case_{false};
4180
4183
4185 bool configurable_{true};
4186
4189
4191 char delimiter_{'\0'};
4192
4195
4197 MultiOptionPolicy multi_option_policy_{MultiOptionPolicy::Throw};
4198
4200 template <typename T> void copy_to(T *other) const;
4201
4202 public:
4203 // setters
4204
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
4215 CRTP *required(bool value = true) {
4216 required_ = value;
4217 return static_cast<CRTP *>(this);
4218 }
4219
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
4231 CLI11_NODISCARD const std::string &get_group() const { return group_; }
4232
4234 CLI11_NODISCARD bool get_required() const { return required_; }
4235
4237 CLI11_NODISCARD bool get_ignore_case() const { return ignore_case_; }
4238
4240 CLI11_NODISCARD bool get_ignore_underscore() const { return ignore_underscore_; }
4241
4243 CLI11_NODISCARD bool get_configurable() const { return configurable_; }
4244
4246 CLI11_NODISCARD bool get_disable_flag_override() const { return disable_flag_override_; }
4247
4249 CLI11_NODISCARD char get_delimiter() const { return delimiter_; }
4250
4252 CLI11_NODISCARD bool get_always_capture_default() const { return always_capture_default_; }
4253
4255 CLI11_NODISCARD MultiOptionPolicy get_multi_option_policy() const { return multi_option_policy_; }
4256
4257 // Shortcuts for multi option policy
4258
4260 CRTP *take_last() {
4261 auto *self = static_cast<CRTP *>(this);
4262 self->multi_option_policy(MultiOptionPolicy::TakeLast);
4263 return self;
4264 }
4265
4267 CRTP *take_first() {
4268 auto *self = static_cast<CRTP *>(this);
4269 self->multi_option_policy(MultiOptionPolicy::TakeFirst);
4270 return self;
4271 }
4272
4274 CRTP *take_all() {
4275 auto self = static_cast<CRTP *>(this);
4276 self->multi_option_policy(MultiOptionPolicy::TakeAll);
4277 return self;
4278 }
4279
4281 CRTP *join() {
4282 auto *self = static_cast<CRTP *>(this);
4283 self->multi_option_policy(MultiOptionPolicy::Join);
4284 return self;
4285 }
4286
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
4296 CRTP *configurable(bool value = true) {
4297 configurable_ = value;
4298 return static_cast<CRTP *>(this);
4299 }
4300
4302 CRTP *delimiter(char value = '\0') {
4303 delimiter_ = value;
4304 return static_cast<CRTP *>(this);
4305 }
4306};
4307
4310class OptionDefaults : public OptionBase<OptionDefaults> {
4311 public:
4312 OptionDefaults() = default;
4313
4314 // Methods here need a different implementation if they are Option vs. OptionDefault
4315
4317 OptionDefaults *multi_option_policy(MultiOptionPolicy value = MultiOptionPolicy::Throw) {
4318 multi_option_policy_ = value;
4319 return this;
4320 }
4321
4323 OptionDefaults *ignore_case(bool value = true) {
4324 ignore_case_ = value;
4325 return this;
4326 }
4327
4329 OptionDefaults *ignore_underscore(bool value = true) {
4330 ignore_underscore_ = value;
4331 return this;
4332 }
4333
4336 disable_flag_override_ = value;
4337 return this;
4338 }
4339
4341 OptionDefaults *delimiter(char value = '\0') {
4342 delimiter_ = value;
4343 return this;
4344 }
4345};
4346
4347class Option : public OptionBase<Option> {
4348 friend App;
4349
4350 protected:
4353
4355 std::vector<std::string> snames_{};
4356
4358 std::vector<std::string> lnames_{};
4359
4362 std::vector<std::pair<std::string, std::string>> default_flag_values_{};
4363
4365 std::vector<std::string> fnames_{};
4366
4368 std::string pname_{};
4369
4371 std::string envname_{};
4372
4376
4378 std::string description_{};
4379
4381 std::string default_str_{};
4382
4384 std::string option_text_{};
4385
4389 std::function<std::string()> type_name_{[]() { return std::string(); }};
4390
4392 std::function<std::string()> default_function_{};
4393
4397
4400 int type_size_max_{1};
4402 int type_size_min_{1};
4403
4405 int expected_min_{1};
4407 int expected_max_{1};
4408
4410 std::vector<Validator> validators_{};
4411
4413 std::set<Option *> needs_{};
4414
4416 std::set<Option *> excludes_{};
4417
4421
4423 App *parent_{nullptr};
4424
4426 callback_t callback_{};
4427
4431
4433 results_t results_{};
4435 results_t proc_results_{};
4437 enum class option_state : char {
4438 parsing = 0,
4439 validated = 2,
4440 reduced = 4,
4441 callback_run = 6,
4442 };
4444 option_state current_option_state_{option_state::parsing};
4446 bool allow_extra_args_{false};
4448 bool flag_like_{false};
4450 bool run_callback_for_default_{false};
4452 bool inject_separator_{false};
4454 bool trigger_on_result_{false};
4456 bool force_callback_{false};
4458
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:
4468
4469 Option(const Option &) = delete;
4470 Option &operator=(const Option &) = delete;
4471
4473 CLI11_NODISCARD std::size_t count() const { return results_.size(); }
4474
4476 CLI11_NODISCARD bool empty() const { return results_.empty(); }
4477
4479 explicit operator bool() const { return !empty() || force_callback_; }
4480
4482 void clear() {
4483 results_.clear();
4484 current_option_state_ = option_state::parsing;
4485 }
4486
4490
4492 Option *expected(int value);
4493
4495 Option *expected(int value_min, int value_max);
4496
4499 Option *allow_extra_args(bool value = true) {
4500 allow_extra_args_ = value;
4501 return this;
4502 }
4504 CLI11_NODISCARD bool get_allow_extra_args() const { return allow_extra_args_; }
4506 Option *trigger_on_parse(bool value = true) {
4507 trigger_on_result_ = value;
4508 return this;
4509 }
4511 CLI11_NODISCARD bool get_trigger_on_parse() const { return trigger_on_result_; }
4512
4514 Option *force_callback(bool value = true) {
4515 force_callback_ = value;
4516 return this;
4517 }
4519 CLI11_NODISCARD bool get_force_callback() const { return force_callback_; }
4520
4523 Option *run_callback_for_default(bool value = true) {
4524 run_callback_for_default_ = value;
4525 return this;
4526 }
4528 CLI11_NODISCARD bool get_run_callback_for_default() const { return run_callback_for_default_; }
4529
4531 Option *check(Validator validator, const std::string &validator_name = "");
4532
4534 Option *check(std::function<std::string(const std::string &)> Validator,
4535 std::string Validator_description = "",
4536 std::string Validator_name = "");
4537
4539 Option *transform(Validator Validator, const std::string &Validator_name = "");
4540
4542 Option *transform(const std::function<std::string(std::string)> &func,
4543 std::string transform_description = "",
4544 std::string transform_name = "");
4545
4547 Option *each(const std::function<void(std::string)> &func);
4548
4550 Validator *get_validator(const std::string &Validator_name = "");
4551
4553 Validator *get_validator(int index);
4554
4556 Option *needs(Option *opt) {
4557 if(opt != this) {
4558 needs_.insert(opt);
4559 }
4560 return this;
4561 }
4562
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
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
4579 bool remove_needs(Option *opt);
4580
4582 Option *excludes(Option *opt);
4583
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
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
4600 bool remove_excludes(Option *opt);
4601
4603 Option *envname(std::string name) {
4604 envname_ = std::move(name);
4605 return this;
4606 }
4607
4612 template <typename T = App> Option *ignore_case(bool value = true);
4613
4618 template <typename T = App> Option *ignore_underscore(bool value = true);
4619
4621 Option *multi_option_policy(MultiOptionPolicy value = MultiOptionPolicy::Throw);
4622
4624 Option *disable_flag_override(bool value = true) {
4625 disable_flag_override_ = value;
4626 return this;
4627 }
4631
4633 CLI11_NODISCARD int get_type_size() const { return type_size_min_; }
4634
4636 CLI11_NODISCARD int get_type_size_min() const { return type_size_min_; }
4638 CLI11_NODISCARD int get_type_size_max() const { return type_size_max_; }
4639
4641 CLI11_NODISCARD bool get_inject_separator() const { return inject_separator_; }
4642
4644 CLI11_NODISCARD std::string get_envname() const { return envname_; }
4645
4647 CLI11_NODISCARD std::set<Option *> get_needs() const { return needs_; }
4648
4650 CLI11_NODISCARD std::set<Option *> get_excludes() const { return excludes_; }
4651
4653 CLI11_NODISCARD std::string get_default_str() const { return default_str_; }
4654
4656 CLI11_NODISCARD callback_t get_callback() const { return callback_; }
4657
4659 CLI11_NODISCARD const std::vector<std::string> &get_lnames() const { return lnames_; }
4660
4662 CLI11_NODISCARD const std::vector<std::string> &get_snames() const { return snames_; }
4663
4665 CLI11_NODISCARD const std::vector<std::string> &get_fnames() const { return fnames_; }
4667 CLI11_NODISCARD const std::string &get_single_name() const {
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 }
4680 CLI11_NODISCARD int get_expected() const { return expected_min_; }
4681
4683 CLI11_NODISCARD int get_expected_min() const { return expected_min_; }
4685 CLI11_NODISCARD int get_expected_max() const { return expected_max_; }
4686
4688 CLI11_NODISCARD int get_items_expected_min() const { return type_size_min_ * expected_min_; }
4689
4691 CLI11_NODISCARD int get_items_expected_max() const {
4692 int t = type_size_max_;
4693 return detail::checked_multiply(t, expected_max_) ? t : detail::expected_max_vector_size;
4694 }
4696 CLI11_NODISCARD int get_items_expected() const { return get_items_expected_min(); }
4697
4699 CLI11_NODISCARD bool get_positional() const { return pname_.length() > 0; }
4700
4702 CLI11_NODISCARD bool nonpositional() const { return (snames_.size() + lnames_.size()) > 0; }
4703
4705 CLI11_NODISCARD bool has_description() const { return description_.length() > 0; }
4706
4708 CLI11_NODISCARD const std::string &get_description() const { return description_; }
4709
4711 Option *description(std::string option_description) {
4712 description_ = std::move(option_description);
4713 return this;
4714 }
4715
4716 Option *option_text(std::string text) {
4717 option_text_ = std::move(text);
4718 return this;
4719 }
4720
4721 CLI11_NODISCARD const std::string &get_option_text() const { return option_text_; }
4722
4726
4731 CLI11_NODISCARD std::string get_name(bool positional = false,
4732 bool all_options = false
4733 ) const;
4734
4738
4740 void run_callback();
4741
4743 CLI11_NODISCARD const std::string &matching_name(const Option &other) const;
4744
4746 bool operator==(const Option &other) const { return !matching_name(other).empty(); }
4747
4749 CLI11_NODISCARD bool check_name(const std::string &name) const;
4750
4752 CLI11_NODISCARD bool check_sname(std::string name) const {
4753 return (detail::find_member(std::move(name), snames_, ignore_case_) >= 0);
4754 }
4755
4757 CLI11_NODISCARD bool check_lname(std::string name) const {
4758 return (detail::find_member(std::move(name), lnames_, ignore_case_, ignore_underscore_) >= 0);
4759 }
4760
4762 CLI11_NODISCARD bool check_fname(std::string name) const {
4763 if(fnames_.empty()) {
4764 return false;
4765 }
4766 return (detail::find_member(std::move(name), fnames_, ignore_case_, ignore_underscore_) >= 0);
4767 }
4768
4771 CLI11_NODISCARD std::string get_flag_value(const std::string &name, std::string input_value) const;
4772
4774 Option *add_result(std::string s);
4775
4777 Option *add_result(std::string s, int &results_added);
4778
4780 Option *add_result(std::vector<std::string> s);
4781
4783 CLI11_NODISCARD const results_t &results() const { return results_; }
4784
4786 CLI11_NODISCARD results_t reduced_results() const;
4787
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
4820 template <typename T> CLI11_NODISCARD T as() const {
4821 T output;
4822 results(output);
4823 return output;
4824 }
4825
4827 CLI11_NODISCARD bool get_callback_run() const { return (current_option_state_ == option_state::callback_run); }
4828
4832
4834 Option *type_name_fn(std::function<std::string()> typefun) {
4835 type_name_ = std::move(typefun);
4836 return this;
4837 }
4838
4840 Option *type_name(std::string typeval) {
4841 type_name_fn([typeval]() { return typeval; });
4842 return this;
4843 }
4844
4846 Option *type_size(int option_type_size);
4847
4849 Option *type_size(int option_type_size_min, int option_type_size_max);
4850
4852 void inject_separator(bool value = true) { inject_separator_ = value; }
4853
4855 Option *default_function(const std::function<std::string()> &func) {
4856 default_function_ = func;
4857 return this;
4858 }
4859
4861 Option *capture_default_str() {
4862 if(default_function_) {
4863 default_str_ = default_function_();
4864 }
4865 return this;
4866 }
4867
4869 Option *default_str(std::string val) {
4870 default_str_ = std::move(val);
4871 return this;
4872 }
4873
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
4884 if(run_callback_for_default_ && !trigger_on_result_) {
4885 run_callback(); // run callback sets the state, we need to reset it again
4886 current_option_state_ = option_state::parsing;
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
4903 CLI11_NODISCARD std::string get_type_name() const;
4904
4905 private:
4907 void _validate_results(results_t &res) const;
4908
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
4918 int _add_result(std::string &&result, std::vector<std::string> &res) const;
4919};
4920
4921
4922
4923
4924template <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
4936CLI11_INLINE Option *Option::expected(int value) {
4937 if(value < 0) {
4938 expected_min_ = -value;
4939 if(expected_max_ < expected_min_) {
4940 expected_max_ = expected_min_;
4941 }
4942 allow_extra_args_ = true;
4943 flag_like_ = false;
4944 } else if(value == detail::expected_max_vector_size) {
4945 expected_min_ = 1;
4946 expected_max_ = detail::expected_max_vector_size;
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
4957CLI11_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) {
4963 value_max = detail::expected_max_vector_size;
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
4976CLI11_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
4984CLI11_INLINE Option *Option::check(std::function<std::string(const std::string &)> Validator,
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
4992CLI11_INLINE Option *Option::transform(Validator Validator, const std::string &Validator_name) {
4993 validators_.insert(validators_.begin(), std::move(Validator));
4994 if(!Validator_name.empty())
4995 validators_.front().name(Validator_name);
4996 return this;
4997}
4998
4999CLI11_INLINE Option *Option::transform(const std::function<std::string(std::string)> &func,
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
5014CLI11_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
5024CLI11_INLINE Validator *Option::get_validator(const std::string &Validator_name) {
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
5036CLI11_INLINE Validator *Option::get_validator(int index) {
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
5044CLI11_INLINE bool Option::remove_needs(Option *opt) {
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
5054CLI11_INLINE Option *Option::excludes(Option *opt) {
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
5069CLI11_INLINE bool Option::remove_excludes(Option *opt) {
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
5079template <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
5099template <typename T> Option *Option::ignore_underscore(bool value) {
5100
5101 if(!ignore_underscore_ && value) {
5102 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 {
5115 ignore_underscore_ = value;
5116 }
5117 return this;
5118}
5119
5120CLI11_INLINE Option *Option::multi_option_policy(MultiOptionPolicy value) {
5121 if(value != multi_option_policy_) {
5122 if(multi_option_policy_ == MultiOptionPolicy::Throw && expected_max_ == detail::expected_max_vector_size &&
5123 expected_min_ > 1) { // this bizarre condition is to maintain backwards compatibility
5124 // with the previous behavior of expected_ with vectors
5125 expected_max_ = expected_min_;
5126 }
5127 multi_option_policy_ = value;
5128 current_option_state_ = option_state::parsing;
5129 }
5130 return this;
5131}
5132
5133CLI11_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
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
5186CLI11_INLINE void Option::run_callback() {
5187 if(force_callback_ && results_.empty()) {
5188 add_result(default_str_);
5189 }
5190 if(current_option_state_ == option_state::parsing) {
5191 _validate_results(results_);
5192 current_option_state_ = option_state::validated;
5193 }
5194
5195 if(current_option_state_ < option_state::reduced) {
5196 _reduce_results(proc_results_, results_);
5197 current_option_state_ = option_state::reduced;
5198 }
5199 if(current_option_state_ >= option_state::reduced) {
5200 current_option_state_ = option_state::callback_run;
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
5212CLI11_NODISCARD CLI11_INLINE const std::string &Option::matching_name(const Option &other) const {
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
5233CLI11_NODISCARD CLI11_INLINE bool Option::check_name(const std::string &name) const {
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
5262CLI11_NODISCARD CLI11_INLINE std::string Option::get_flag_value(const std::string &name,
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_
5268 if(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 }
5283 auto ind = detail::find_member(name, fnames_, ignore_case_, ignore_underscore_);
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
5305CLI11_INLINE Option *Option::add_result(std::string s) {
5306 _add_result(std::move(s), results_);
5307 current_option_state_ = option_state::parsing;
5308 return this;
5309}
5310
5311CLI11_INLINE Option *Option::add_result(std::string s, int &results_added) {
5312 results_added = _add_result(std::move(s), results_);
5313 current_option_state_ = option_state::parsing;
5314 return this;
5315}
5316
5317CLI11_INLINE Option *Option::add_result(std::vector<std::string> s) {
5318 current_option_state_ = option_state::parsing;
5319 for(auto &str : s) {
5320 _add_result(std::move(str), results_);
5321 }
5322 return this;
5323}
5324
5325CLI11_NODISCARD CLI11_INLINE results_t Option::reduced_results() const {
5326 results_t res = proc_results_.empty() ? results_ : proc_results_;
5327 if(current_option_state_ < option_state::reduced) {
5328 if(current_option_state_ == option_state::parsing) {
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
5343CLI11_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;
5348 expected_max_ = detail::expected_max_vector_size;
5349 } else {
5350 type_size_max_ = option_type_size;
5351 if(type_size_max_ < detail::expected_max_vector_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
5362CLI11_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
5365 expected_max_ = detail::expected_max_vector_size;
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 }
5380 if(type_size_max_ >= detail::expected_max_vector_size) {
5381 inject_separator_ = true;
5382 }
5383 return this;
5384}
5385
5386CLI11_NODISCARD CLI11_INLINE std::string Option::get_type_name() const {
5387 std::string full_type_name = type_name_();
5388 if(!validators_.empty()) {
5389 for(const auto &Validator : validators_) {
5390 std::string vtype = Validator.get_description();
5391 if(!vtype.empty()) {
5392 full_type_name += ":" + vtype;
5393 }
5394 }
5395 }
5396 return full_type_name;
5397}
5398
5399CLI11_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()) &&
5405 multi_option_policy_ == CLI::MultiOptionPolicy::TakeLast) {
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()) &&
5423 multi_option_policy_ == CLI::MultiOptionPolicy::TakeLast) {
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
5437CLI11_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_) {
5445 case MultiOptionPolicy::TakeAll:
5446 break;
5447 case MultiOptionPolicy::TakeLast: {
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;
5455 case MultiOptionPolicy::TakeFirst: {
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;
5462 case MultiOptionPolicy::Join:
5463 if(results_.size() > 1) {
5464 out.push_back(detail::join(original, std::string(1, (delimiter_ == '\0') ? '\n' : delimiter_)));
5465 }
5466 break;
5467 case MultiOptionPolicy::Sum:
5468 out.push_back(detail::sum_string_vector(original));
5469 break;
5470 case MultiOptionPolicy::Throw:
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
5501CLI11_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
5523CLI11_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
5566namespace detail {
5567enum class Classifier { NONE, POSITIONAL_MARK, SHORT, LONG, WINDOWS_STYLE, SUBCOMMAND, SUBCOMMAND_TERMINATOR };
5568struct AppFriend;
5569} // namespace detail
5570
5571namespace FailureMessage {
5572std::string simple(const App *app, const Error &e);
5573std::string help(const App *app, const Error &e);
5574} // namespace FailureMessage
5575
5577
5578enum class config_extras_mode : char { error = 0, ignore, ignore_all, capture };
5579
5580class App;
5581
5582using App_p = std::shared_ptr<App>;
5583
5584namespace detail {
5586
5587template <typename T, enable_if_t<!std::is_integral<T>::value || (sizeof(T) <= 1U), detail::enabler> = detail::dummy>
5588Option *default_flag_modifiers(Option *opt) {
5589 return opt->always_capture_default();
5590}
5591
5593template <typename T, enable_if_t<std::is_integral<T>::value && (sizeof(T) > 1U), detail::enabler> = detail::dummy>
5594Option *default_flag_modifiers(Option *opt) {
5595 return opt->multi_option_policy(MultiOptionPolicy::Sum)->default_str("0")->force_callback();
5596}
5597
5598} // namespace detail
5599
5600class Option_group;
5602
5605class 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
5614
5616 std::string name_{};
5617
5619 std::string description_{};
5620
5622 bool allow_extras_{false};
5623
5626 config_extras_mode allow_config_extras_{config_extras_mode::ignore};
5627
5629 bool prefix_command_{false};
5630
5633
5635 bool required_{false};
5636
5638 bool disabled_{false};
5639
5642
5646
5648 std::function<void(std::size_t)> pre_parse_callback_{};
5649
5651 std::function<void()> parse_complete_callback_{};
5652
5654 std::function<void()> final_callback_{};
5655
5659
5662
5664 std::vector<Option_p> options_{};
5665
5669
5671 std::string footer_{};
5672
5674 std::function<std::string()> footer_callback_{};
5675
5677 Option *help_ptr_{nullptr};
5678
5680 Option *help_all_ptr_{nullptr};
5681
5683 Option *version_ptr_{nullptr};
5684
5686 std::shared_ptr<FormatterBase> formatter_{new Formatter()};
5687
5689 std::function<std::string(const App *, const Error &e)> failure_message_{FailureMessage::simple};
5690
5694
5695 using missing_t = std::vector<std::pair<detail::Classifier, std::string>>;
5696
5700 missing_t missing_{};
5701
5703 std::vector<Option *> parse_order_{};
5704
5706 std::vector<App *> parsed_subcommands_{};
5707
5709 std::set<App *> exclude_subcommands_{};
5710
5713 std::set<Option *> exclude_options_{};
5714
5717 std::set<App *> need_subcommands_{};
5718
5721 std::set<Option *> need_options_{};
5722
5726
5728 std::vector<App_p> subcommands_{};
5729
5731 bool ignore_case_{false};
5732
5735
5737 bool fallthrough_{false};
5738
5741#ifdef _WIN32
5742 true
5743#else
5744 false
5745#endif
5746 };
5749
5750 enum class startup_mode : char { stable, enabled, disabled };
5753 startup_mode default_startup{startup_mode::stable};
5754
5756 bool configurable_{false};
5757
5760
5763
5766 bool silent_{false};
5767
5769 std::uint32_t parsed_{0U};
5770
5773
5776
5778 std::size_t require_option_min_{0};
5779
5781 std::size_t require_option_max_{0};
5782
5784 App *parent_{nullptr};
5785
5787 std::string group_{"Subcommands"};
5788
5790 std::vector<std::string> aliases_{};
5791
5795
5797 Option *config_ptr_{nullptr};
5798
5800 std::shared_ptr<Config> config_formatter_{new ConfigTOML()};
5801
5803
5805 App(std::string app_description, std::string app_name, App *parent);
5806
5807 public:
5810
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
5821 virtual ~App() = default;
5822
5829 App *callback(std::function<void()> app_callback) {
5831 parse_complete_callback_ = std::move(app_callback);
5832 } else {
5833 final_callback_ = std::move(app_callback);
5834 }
5835 return this;
5836 }
5837
5840 App *final_callback(std::function<void()> app_callback) {
5841 final_callback_ = std::move(app_callback);
5842 return this;
5843 }
5844
5847 App *parse_complete_callback(std::function<void()> pc_callback) {
5848 parse_complete_callback_ = std::move(pc_callback);
5849 return this;
5850 }
5851
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
5860 App *name(std::string app_name = "");
5861
5863 App *alias(std::string app_name);
5864
5866 App *allow_extras(bool allow = true) {
5867 allow_extras_ = allow;
5868 return this;
5869 }
5870
5872 App *required(bool require = true) {
5873 required_ = require;
5874 return this;
5875 }
5876
5878 App *disabled(bool disable = true) {
5879 disabled_ = disable;
5880 return this;
5881 }
5882
5884 App *silent(bool silence = true) {
5885 silent_ = silence;
5886 return this;
5887 }
5888
5890 App *disabled_by_default(bool disable = true) {
5891 if(disable) {
5892 default_startup = startup_mode::disabled;
5893 } else {
5894 default_startup = (default_startup == startup_mode::enabled) ? startup_mode::enabled : startup_mode::stable;
5895 }
5896 return this;
5897 }
5898
5901 App *enabled_by_default(bool enable = true) {
5902 if(enable) {
5903 default_startup = startup_mode::enabled;
5904 } else {
5906 (default_startup == startup_mode::disabled) ? startup_mode::disabled : startup_mode::stable;
5907 }
5908 return this;
5909 }
5910
5912 App *immediate_callback(bool immediate = true);
5913
5915 App *validate_positionals(bool validate = true) {
5916 validate_positionals_ = validate;
5917 return this;
5918 }
5919
5921 App *validate_optional_arguments(bool validate = true) {
5923 return this;
5924 }
5925
5927 App *allow_config_extras(bool allow = true) {
5928 if(allow) {
5929 allow_config_extras_ = config_extras_mode::capture;
5930 allow_extras_ = true;
5931 } else {
5932 allow_config_extras_ = config_extras_mode::error;
5933 }
5934 return this;
5935 }
5936
5938 App *allow_config_extras(config_extras_mode mode) {
5939 allow_config_extras_ = mode;
5940 return this;
5941 }
5942
5944 App *prefix_command(bool allow = true) {
5945 prefix_command_ = allow;
5946 return this;
5947 }
5948
5950 App *ignore_case(bool value = true);
5951
5954 App *allow_windows_style_options(bool value = true) {
5956 return this;
5957 }
5958
5960 App *positionals_at_end(bool value = true) {
5961 positionals_at_end_ = value;
5962 return this;
5963 }
5964
5966 App *configurable(bool value = true) {
5967 configurable_ = value;
5968 return this;
5969 }
5970
5972 App *ignore_underscore(bool value = true);
5973
5975 App *formatter(std::shared_ptr<FormatterBase> fmt) {
5976 formatter_ = fmt;
5977 return this;
5978 }
5979
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
5987 App *config_formatter(std::shared_ptr<Config> fmt) {
5988 config_formatter_ = fmt;
5989 return this;
5990 }
5991
5993 CLI11_NODISCARD bool parsed() const { return parsed_ > 0; }
5994
5997
6001
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
6023 template <typename AssignTo,
6024 typename ConvertTo = AssignTo,
6025 enable_if_t<!std::is_const<ConvertTo>::value, detail::enabler> = detail::dummy>
6026 Option *add_option(std::string option_name,
6027 AssignTo &variable,
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.
6042 opt->type_size(detail::type_count_min<ConvertTo>::value, (std::max)(Tcount, XCcount));
6043 opt->expected(detail::expected_count<ConvertTo>::value);
6044 opt->run_callback_for_default();
6045 return opt;
6046 }
6047
6049 template <typename AssignTo, enable_if_t<!std::is_const<AssignTo>::value, detail::enabler> = detail::dummy>
6050 Option *add_option_no_stream(std::string option_name,
6051 AssignTo &variable,
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>());
6060 opt->type_size(detail::type_count_min<AssignTo>::value, detail::type_count<AssignTo>::value);
6061 opt->expected(detail::expected_count<AssignTo>::value);
6062 opt->run_callback_for_default();
6063 return opt;
6064 }
6065
6067 template <typename ArgType>
6068 Option *add_option_function(std::string option_name,
6069 const std::function<void(const ArgType &)> &func,
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>());
6083 opt->type_size(detail::type_count_min<ArgType>::value, detail::type_count<ArgType>::value);
6084 opt->expected(detail::expected_count<ArgType>::value);
6085 return opt;
6086 }
6087
6089 Option *add_option(std::string option_name) {
6090 return add_option(option_name, CLI::callback_t{}, std::string{}, false);
6091 }
6092
6094 template <typename T,
6095 enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value, detail::enabler> =
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
6102 Option *set_help_flag(std::string flag_name = "", const std::string &help_description = "");
6103
6105 Option *set_help_all_flag(std::string help_name = "", const std::string &help_description = "");
6106
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
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:
6119 Option *_add_flag_internal(std::string flag_name, CLI::callback_t fun, std::string flag_description);
6120
6121 public:
6123 Option *add_flag(std::string flag_name) { return _add_flag_internal(flag_name, CLI::callback_t(), std::string{}); }
6124
6128 template <typename T,
6129 enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value, detail::enabler> =
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
6137 template <typename T,
6138 enable_if_t<!detail::is_mutable_container<T>::value && !std::is_const<T>::value &&
6139 !std::is_constructible<std::function<void(int)>, T>::value,
6140 detail::enabler> = detail::dummy>
6141 Option *add_flag(std::string flag_name,
6142 T &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
6153 template <typename T,
6154 enable_if_t<!std::is_assignable<std::function<void(std::int64_t)> &, T>::value, detail::enabler> =
6155 detail::dummy>
6156 Option *add_flag(std::string flag_name,
6157 std::vector<T> &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))
6168 ->multi_option_policy(MultiOptionPolicy::TakeAll)
6169 ->run_callback_for_default();
6170 }
6171
6173 Option *add_flag_callback(std::string flag_name,
6174 std::function<void(void)> function,
6175 std::string flag_description = "");
6176
6178 Option *add_flag_function(std::string flag_name,
6179 std::function<void(std::int64_t)> function,
6180 std::string flag_description = "");
6181
6182#ifdef CLI11_CPP14
6184 Option *add_flag(std::string flag_name,
6185 std::function<void(std::int64_t)> function,
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
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
6198 bool remove_option(Option *opt);
6199
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
6217
6219 App *add_subcommand(std::string subcommand_name = "", std::string subcommand_description = "");
6220
6222 App *add_subcommand(CLI::App_p subcom);
6223
6225 bool remove_subcommand(App *subcom);
6226
6229 App *get_subcommand(const App *subcom) const;
6230
6232 CLI11_NODISCARD App *get_subcommand(std::string subcom) const;
6233
6235 CLI11_NODISCARD App *get_subcommand(int index = 0) const;
6236
6238 CLI::App_p get_subcommand_ptr(App *subcom) const;
6239
6241 CLI11_NODISCARD CLI::App_p get_subcommand_ptr(std::string subcom) const;
6242
6244 CLI11_NODISCARD CLI::App_p get_subcommand_ptr(int index = 0) const;
6245
6247 CLI11_NODISCARD App *get_option_group(std::string group_name) const;
6248
6252 CLI11_NODISCARD std::size_t count() const { return parsed_; }
6253
6256 CLI11_NODISCARD std::size_t count_all() const;
6257
6259 App *group(std::string group_name) {
6260 group_ = group_name;
6261 return this;
6262 }
6263
6268 return this;
6269 }
6270
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
6287 App *require_subcommand(std::size_t min, std::size_t max) {
6290 return this;
6291 }
6292
6297 return this;
6298 }
6299
6303 App *require_option(int value) {
6304 if(value < 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
6316 App *require_option(std::size_t min, std::size_t max) {
6317 require_option_min_ = min;
6318 require_option_max_ = max;
6319 return this;
6320 }
6321
6324 App *fallthrough(bool value = true) {
6325 fallthrough_ = value;
6326 return this;
6327 }
6328
6331 explicit operator bool() const { return parsed_ > 0; }
6332
6336
6340 virtual void pre_callback() {}
6341
6345 //
6347 void clear();
6348
6351 void parse(int argc, const char *const *argv);
6352
6357 void parse(std::string commandline, bool program_name_included = false);
6358
6361 void parse(std::vector<std::string> &args);
6362
6364 void parse(std::vector<std::string> &&args);
6365
6366 void parse_from_stream(std::istream &input);
6367
6369 void failure_message(std::function<std::string(const App *, const Error &e)> function) {
6370 failure_message_ = function;
6371 }
6372
6374 int exit(const Error &e, std::ostream &out = std::cout, std::ostream &err = std::cerr) const;
6375
6379
6381 CLI11_NODISCARD std::size_t count(std::string option_name) const { return get_option(option_name)->count(); }
6382
6385 CLI11_NODISCARD std::vector<App *> get_subcommands() const { return parsed_subcommands_; }
6386
6389 std::vector<const App *> get_subcommands(const std::function<bool(const App *)> &filter) const;
6390
6393 std::vector<App *> get_subcommands(const std::function<bool(App *)> &filter);
6394
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
6402 CLI11_NODISCARD bool got_subcommand(std::string subcommand_name) const {
6403 return get_subcommand(subcommand_name)->parsed_ > 0;
6404 }
6405
6407 App *excludes(Option *opt) {
6408 if(opt == nullptr) {
6409 throw OptionNotFound("nullptr passed");
6410 }
6411 exclude_options_.insert(opt);
6412 return this;
6413 }
6414
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
6451 bool remove_excludes(Option *opt);
6452
6454 bool remove_excludes(App *app);
6455
6457 bool remove_needs(Option *opt);
6458
6460 bool remove_needs(App *app);
6464
6466 App *footer(std::string footer_string) {
6467 footer_ = std::move(footer_string);
6468 return this;
6469 }
6471 App *footer(std::function<std::string()> footer_function) {
6472 footer_callback_ = std::move(footer_function);
6473 return this;
6474 }
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
6483 CLI11_NODISCARD std::string help(std::string prev = "", AppFormatMode mode = AppFormatMode::Normal) const;
6484
6486 CLI11_NODISCARD std::string version() const;
6490
6492 CLI11_NODISCARD std::shared_ptr<FormatterBase> get_formatter() const { return formatter_; }
6493
6495 CLI11_NODISCARD std::shared_ptr<Config> get_config_formatter() const { return config_formatter_; }
6496
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
6508 CLI11_NODISCARD std::string get_description() const { return description_; }
6509
6511 App *description(std::string app_description) {
6512 description_ = std::move(app_description);
6513 return this;
6514 }
6515
6517 std::vector<const Option *> get_options(const std::function<bool(const Option *)> filter = {}) const;
6518
6520 std::vector<Option *> get_options(const std::function<bool(Option *)> filter = {});
6521
6523 Option *get_option_no_throw(std::string option_name) noexcept;
6524
6526 CLI11_NODISCARD const Option *get_option_no_throw(std::string option_name) const noexcept;
6527
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
6538 Option *get_option(std::string option_name) {
6539 auto *opt = get_option_no_throw(option_name);
6540 if(opt == nullptr) {
6541 throw OptionNotFound(option_name);
6542 }
6543 return opt;
6544 }
6545
6547 const Option *operator[](const std::string &option_name) const { return get_option(option_name); }
6548
6550 const Option *operator[](const char *option_name) const { return get_option(option_name); }
6551
6553 CLI11_NODISCARD bool get_ignore_case() const { return ignore_case_; }
6554
6556 CLI11_NODISCARD bool get_ignore_underscore() const { return ignore_underscore_; }
6557
6559 CLI11_NODISCARD bool get_fallthrough() const { return fallthrough_; }
6560
6562 CLI11_NODISCARD bool get_allow_windows_style_options() const { return allow_windows_style_options_; }
6563
6565 CLI11_NODISCARD bool get_positionals_at_end() const { return positionals_at_end_; }
6566
6568 CLI11_NODISCARD bool get_configurable() const { return configurable_; }
6569
6571 CLI11_NODISCARD const std::string &get_group() const { return group_; }
6572
6574 CLI11_NODISCARD std::string get_footer() const {
6575 return (footer_callback_) ? footer_callback_() + '\n' + footer_ : footer_;
6576 }
6577
6579 CLI11_NODISCARD std::size_t get_require_subcommand_min() const { return require_subcommand_min_; }
6580
6582 CLI11_NODISCARD std::size_t get_require_subcommand_max() const { return require_subcommand_max_; }
6583
6585 CLI11_NODISCARD std::size_t get_require_option_min() const { return require_option_min_; }
6586
6588 CLI11_NODISCARD std::size_t get_require_option_max() const { return require_option_max_; }
6589
6591 CLI11_NODISCARD bool get_prefix_command() const { return prefix_command_; }
6592
6594 CLI11_NODISCARD bool get_allow_extras() const { return allow_extras_; }
6595
6597 CLI11_NODISCARD bool get_required() const { return required_; }
6598
6600 CLI11_NODISCARD bool get_disabled() const { return disabled_; }
6601
6603 CLI11_NODISCARD bool get_silent() const { return silent_; }
6604
6606 CLI11_NODISCARD bool get_immediate_callback() const { return immediate_callback_; }
6607
6609 CLI11_NODISCARD bool get_disabled_by_default() const { return (default_startup == startup_mode::disabled); }
6610
6612 CLI11_NODISCARD bool get_enabled_by_default() const { return (default_startup == startup_mode::enabled); }
6614 CLI11_NODISCARD bool get_validate_positionals() const { return validate_positionals_; }
6616 CLI11_NODISCARD bool get_validate_optional_arguments() const { return validate_optional_arguments_; }
6617
6619 CLI11_NODISCARD config_extras_mode get_allow_config_extras() const { return allow_config_extras_; }
6620
6622 Option *get_help_ptr() { return help_ptr_; }
6623
6625 CLI11_NODISCARD const Option *get_help_ptr() const { return help_ptr_; }
6626
6628 CLI11_NODISCARD const Option *get_help_all_ptr() const { return help_all_ptr_; }
6629
6631 Option *get_config_ptr() { return config_ptr_; }
6632
6634 CLI11_NODISCARD const Option *get_config_ptr() const { return config_ptr_; }
6635
6637 Option *get_version_ptr() { return version_ptr_; }
6638
6640 CLI11_NODISCARD const Option *get_version_ptr() const { return version_ptr_; }
6641
6643 App *get_parent() { return parent_; }
6644
6646 CLI11_NODISCARD const App *get_parent() const { return parent_; }
6647
6649 CLI11_NODISCARD const std::string &get_name() const { return name_; }
6650
6652 CLI11_NODISCARD const std::vector<std::string> &get_aliases() const { return aliases_; }
6653
6656 aliases_.clear();
6657 return this;
6658 }
6659
6661 CLI11_NODISCARD std::string get_display_name(bool with_aliases = false) const;
6662
6664 CLI11_NODISCARD bool check_name(std::string name_to_check) const;
6665
6667 CLI11_NODISCARD std::vector<std::string> get_groups() const;
6668
6670 CLI11_NODISCARD const std::vector<Option *> &parse_order() const { return parse_order_; }
6671
6673 CLI11_NODISCARD std::vector<std::string> remaining(bool recurse = false) const;
6674
6676 CLI11_NODISCARD std::vector<std::string> remaining_for_passthrough(bool recurse = false) const;
6677
6679 CLI11_NODISCARD std::size_t remaining_size(bool recurse = false) const;
6680
6682
6683 protected:
6688 void _validate() const;
6689
6693 void _configure();
6694
6696 void run_callback(bool final_mode = false, bool suppress_final_callback = false);
6697
6699 CLI11_NODISCARD bool _valid_subcommand(const std::string &current, bool ignore_used = true) const;
6700
6702 CLI11_NODISCARD detail::Classifier _recognize(const std::string &current,
6703 bool ignore_used_subcommands = true) const;
6704
6705 // The parse function is now broken into several parts, and part of process
6706
6708 void _process_config_file();
6709
6711 void _process_env();
6712
6714 void _process_callbacks();
6715
6719 void _process_help_flags(bool trigger_help = false, bool trigger_all_help = false) const;
6720
6722 void _process_requirements();
6723
6725 void _process();
6726
6728 void _process_extras();
6729
6732 void _process_extras(std::vector<std::string> &args);
6733
6735 void increment_parsed();
6736
6738 void _parse(std::vector<std::string> &args);
6739
6741 void _parse(std::vector<std::string> &&args);
6742
6744 void _parse_stream(std::istream &input);
6745
6750 void _parse_config(const std::vector<ConfigItem> &args);
6751
6753 bool _parse_single_config(const ConfigItem &item, std::size_t level = 0);
6754
6757 bool _parse_single(std::vector<std::string> &args, bool &positional_only);
6758
6760 CLI11_NODISCARD std::size_t _count_remaining_positionals(bool required_only = false) const;
6761
6763 CLI11_NODISCARD bool _has_remaining_positionals() const;
6764
6768 bool _parse_positional(std::vector<std::string> &args, bool haltOnSubcommand);
6769
6772 CLI11_NODISCARD App *
6773 _find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept;
6774
6779 bool _parse_subcommand(std::vector<std::string> &args);
6780
6783 bool _parse_arg(std::vector<std::string> &args, detail::Classifier current_type);
6784
6786 void _trigger_pre_parse(std::size_t remaining_args);
6787
6790
6792 CLI11_NODISCARD const std::string &_compare_subcommand_names(const App &subcom, const App &base) const;
6793
6795 void _move_to_missing(detail::Classifier val_type, const std::string &val);
6796
6797 public:
6799 void _move_option(Option *opt, App *app);
6800}; // namespace CLI
6801
6803class 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;
6812 Option *add_option(Option *opt) {
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 }
6820 void add_options(Option *opt) { add_option(opt); }
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;
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
6837CLI11_INLINE void TriggerOn(App *trigger_app, App *app_to_enable);
6838
6840CLI11_INLINE void TriggerOn(App *trigger_app, std::vector<App *> apps_to_enable);
6841
6843CLI11_INLINE void TriggerOff(App *trigger_app, App *app_to_enable);
6844
6846CLI11_INLINE void TriggerOff(App *trigger_app, std::vector<App *> apps_to_enable);
6847
6849CLI11_INLINE void deprecate_option(Option *opt, const std::string &replacement = "");
6850
6852inline 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
6858inline 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
6864CLI11_INLINE void retire_option(App *app, Option *opt);
6865
6867CLI11_INLINE void retire_option(App &app, Option *opt);
6868
6870CLI11_INLINE void retire_option(App *app, const std::string &option_name);
6871
6873CLI11_INLINE void retire_option(App &app, const std::string &option_name);
6874
6875namespace FailureMessage {
6876
6878CLI11_INLINE std::string simple(const App *app, const Error &e);
6879
6881CLI11_INLINE std::string help(const App *app, const Error &e);
6882
6883} // namespace FailureMessage
6884
6885namespace detail {
6888#ifdef CLI11_CPP14
6889
6891 template <typename... Args> static decltype(auto) parse_arg(App *app, Args &&...args) {
6892 return app->_parse_arg(std::forward<Args>(args)...);
6893 }
6894
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
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
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
6916};
6917} // namespace detail
6918
6919
6920
6921
6922CLI11_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)
6927 set_help_flag(parent_->help_ptr_->get_name(false, true), parent_->help_ptr_->get_description());
6928 if(parent_->help_all_ptr_ != nullptr)
6929 set_help_all_flag(parent_->help_all_ptr_->get_name(false, true), parent_->help_all_ptr_->get_description());
6930
6933
6934 // INHERITABLE
6952 }
6953}
6954
6955CLI11_INLINE App *App::name(std::string app_name) {
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
6972CLI11_INLINE App *App::alias(std::string app_name) {
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
6990CLI11_INLINE App *App::immediate_callback(bool immediate) {
6991 immediate_callback_ = immediate;
6995 }
6996 } else if(!(final_callback_) && parse_complete_callback_) {
6998 }
6999 return this;
7000}
7001
7002CLI11_INLINE App *App::ignore_case(bool value) {
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
7016CLI11_INLINE App *App::ignore_underscore(bool value) {
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 }
7026 ignore_underscore_ = value;
7027 return this;
7028}
7029
7030CLI11_INLINE Option *App::add_option(std::string option_name,
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
7070CLI11_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
7086CLI11_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
7102CLI11_INLINE Option *
7103App::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
7120CLI11_INLINE Option *
7121App::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
7137CLI11_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);
7142 detail::remove_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 }
7156 opt->multi_option_policy(MultiOptionPolicy::TakeLast);
7157 opt->expected(0);
7158 opt->required(false);
7159 return opt;
7160}
7161
7162CLI11_INLINE Option *App::add_flag_callback(std::string flag_name,
7163 std::function<void(void)> function,
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
7177CLI11_INLINE Option *
7178App::add_flag_function(std::string flag_name,
7179 std::function<void(std::int64_t)> function,
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))
7189 ->multi_option_policy(MultiOptionPolicy::Sum);
7190}
7191
7192CLI11_INLINE Option *App::set_config(std::string option_name,
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
7218CLI11_INLINE bool App::remove_option(Option *opt) {
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
7239CLI11_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
7256CLI11_INLINE App *App::add_subcommand(CLI::App_p subcom) {
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
7269CLI11_INLINE bool App::remove_subcommand(App *subcom) {
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
7285CLI11_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
7294CLI11_NODISCARD CLI11_INLINE App *App::get_subcommand(std::string subcom) const {
7295 auto *subc = _find_subcommand(subcom, false, false);
7296 if(subc == nullptr)
7297 throw OptionNotFound(subcom);
7298 return subc;
7299}
7300
7301CLI11_NODISCARD CLI11_INLINE App *App::get_subcommand(int index) const {
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
7310CLI11_INLINE CLI::App_p App::get_subcommand_ptr(App *subcom) const {
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
7319CLI11_NODISCARD CLI11_INLINE CLI::App_p App::get_subcommand_ptr(std::string subcom) const {
7320 for(const App_p &subcomptr : subcommands_)
7321 if(subcomptr->check_name(subcom))
7322 return subcomptr;
7323 throw OptionNotFound(subcom);
7324}
7325
7326CLI11_NODISCARD CLI11_INLINE CLI::App_p App::get_subcommand_ptr(int index) const {
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
7335CLI11_NODISCARD CLI11_INLINE CLI::App *App::get_option_group(std::string group_name) const {
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
7344CLI11_NODISCARD CLI11_INLINE std::size_t App::count_all() const {
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
7358CLI11_INLINE void App::clear() {
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
7373CLI11_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
7387CLI11_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
7414CLI11_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
7433CLI11_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
7452CLI11_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
7463CLI11_INLINE int App::exit(const Error &e, std::ostream &out, std::ostream &err) const {
7464
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)) {
7486 err << failure_message_(this, e) << std::flush;
7487 }
7488
7489 return e.get_exit_code();
7490}
7491
7492CLI11_INLINE std::vector<const App *> App::get_subcommands(const std::function<bool(const App *)> &filter) const {
7493 std::vector<const App *> subcomms(subcommands_.size());
7494 std::transform(
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
7507CLI11_INLINE std::vector<App *> App::get_subcommands(const std::function<bool(App *)> &filter) {
7508 std::vector<App *> subcomms(subcommands_.size());
7509 std::transform(
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
7521CLI11_INLINE bool App::remove_excludes(Option *opt) {
7522 auto iterator = std::find(std::begin(exclude_options_), std::end(exclude_options_), opt);
7523 if(iterator == std::end(exclude_options_)) {
7524 return false;
7525 }
7526 exclude_options_.erase(iterator);
7527 return true;
7528}
7529
7530CLI11_INLINE bool App::remove_excludes(App *app) {
7531 auto iterator = std::find(std::begin(exclude_subcommands_), std::end(exclude_subcommands_), app);
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
7541CLI11_INLINE bool App::remove_needs(Option *opt) {
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
7550CLI11_INLINE bool App::remove_needs(App *app) {
7551 auto iterator = std::find(std::begin(need_subcommands_), std::end(need_subcommands_), app);
7552 if(iterator == std::end(need_subcommands_)) {
7553 return false;
7554 }
7555 need_subcommands_.erase(iterator);
7556 return true;
7557}
7558
7559CLI11_NODISCARD CLI11_INLINE std::string App::help(std::string prev, AppFormatMode mode) const {
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
7573CLI11_NODISCARD CLI11_INLINE std::string App::version() const {
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 {
7580 version_ptr_->run_callback();
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
7590CLI11_INLINE std::vector<const Option *> App::get_options(const std::function<bool(const Option *)> filter) const {
7591 std::vector<const Option *> options(options_.size());
7592 std::transform(
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
7605CLI11_INLINE std::vector<Option *> App::get_options(const std::function<bool(Option *)> filter) {
7606 std::vector<Option *> options(options_.size());
7607 std::transform(
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
7619CLI11_INLINE Option *App::get_option_no_throw(std::string option_name) noexcept {
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
7637CLI11_NODISCARD CLI11_INLINE const Option *App::get_option_no_throw(std::string option_name) const noexcept {
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
7655CLI11_NODISCARD CLI11_INLINE std::string App::get_display_name(bool with_aliases) const {
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
7671CLI11_NODISCARD CLI11_INLINE bool App::check_name(std::string name_to_check) const {
7672 std::string local_name = name_;
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
7699CLI11_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
7712CLI11_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
7738CLI11_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
7744CLI11_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
7758CLI11_INLINE void App::_validate() const {
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
7793CLI11_INLINE void App::_configure() {
7794 if(default_startup == startup_mode::enabled) {
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
7813CLI11_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) {
7836 }
7837 }
7838}
7839
7840CLI11_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
7853CLI11_NODISCARD CLI11_INLINE detail::Classifier App::_recognize(const std::string &current,
7854 bool ignore_used_subcommands) const {
7855 std::string dummy1, dummy2;
7856
7857 if(current == "--")
7858 return detail::Classifier::POSITIONAL_MARK;
7859 if(_valid_subcommand(current, ignore_used_subcommands))
7860 return detail::Classifier::SUBCOMMAND;
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 }
7869 return detail::Classifier::SHORT;
7870 }
7871 if((allow_windows_style_options_) && (detail::split_windows_style(current, dummy1, dummy2)))
7872 return detail::Classifier::WINDOWS_STYLE;
7873 if((current == "++") && !name_.empty() && parent_ != nullptr)
7874 return detail::Classifier::SUBCOMMAND_TERMINATOR;
7875 return detail::Classifier::NONE;
7876}
7877
7878CLI11_INLINE void App::_process_config_file() {
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
7910CLI11_INLINE void App::_process_env() {
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
7942CLI11_INLINE void App::_process_callbacks() {
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
7966CLI11_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
7988CLI11_INLINE void App::_process_requirements() {
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
8116CLI11_INLINE void App::_process() {
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.
8120 _process_config_file();
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.
8127 _process_callbacks();
8128 _process_help_flags();
8129 throw;
8130 }
8131
8132 _process_callbacks();
8133 _process_help_flags();
8134
8135 _process_requirements();
8136}
8137
8138CLI11_INLINE void App::_process_extras() {
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
8152CLI11_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
8167CLI11_INLINE void App::increment_parsed() {
8168 ++parsed_;
8169 for(App_p &sub : subcommands_) {
8170 if(sub->get_name().empty())
8171 sub->increment_parsed();
8172 }
8173}
8174
8175CLI11_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();
8196 _process_callbacks();
8197 _process_help_flags();
8198 _process_requirements();
8199 run_callback(false, true);
8200 }
8201}
8202
8203CLI11_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
8219CLI11_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
8230CLI11_INLINE void App::_parse_config(const std::vector<ConfigItem> &args) {
8231 for(const ConfigItem &item : args) {
8232 if(!_parse_single_config(item) && allow_config_extras_ == config_extras_mode::error)
8233 throw ConfigError::Extras(item.fullname());
8234 }
8235}
8236
8237CLI11_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 == "--") {
8261 if(configurable_ && parse_complete_callback_) {
8262 _process_callbacks();
8263 _process_requirements();
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
8279 if(get_allow_config_extras() == config_extras_mode::capture)
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()) {
8286 if(get_allow_config_extras() == config_extras_mode::ignore_all) {
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
8317CLI11_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) {
8321 case detail::Classifier::POSITIONAL_MARK:
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;
8330 case detail::Classifier::SUBCOMMAND_TERMINATOR:
8331 // treat this like a positional mark if in the parent app
8332 args.pop_back();
8333 retval = false;
8334 break;
8335 case detail::Classifier::SUBCOMMAND:
8336 retval = _parse_subcommand(args);
8337 break;
8338 case detail::Classifier::LONG:
8339 case detail::Classifier::SHORT:
8340 case detail::Classifier::WINDOWS_STYLE:
8341 // If already parsed a subcommand, don't accept options_
8342 _parse_arg(args, classifier);
8343 break;
8344 case detail::Classifier::NONE:
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
8359CLI11_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
8371CLI11_NODISCARD CLI11_INLINE bool App::_has_remaining_positionals() const {
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
8381CLI11_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());
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() &&
8409 opt->current_option_state_ == Option::option_state::callback_run) {
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 }
8439 if(opt->get_trigger_on_parse() && opt->current_option_state_ == Option::option_state::callback_run) {
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
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 }
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 }
8489 if(parent_ != nullptr && name_.empty()) {
8490 return false;
8491 }
8493 _move_to_missing(detail::Classifier::NONE, positional);
8494 args.pop_back();
8495 if(prefix_command_) {
8496 while(!args.empty()) {
8497 _move_to_missing(detail::Classifier::NONE, args.back());
8498 args.pop_back();
8499 }
8500 }
8501
8502 return true;
8503}
8504
8505CLI11_NODISCARD CLI11_INLINE App *
8506App::_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
8524CLI11_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
8552CLI11_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;
8557 std::string value;
8558 std::string rest;
8559
8560 switch(current_type) {
8561 case detail::Classifier::LONG:
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;
8565 case detail::Classifier::SHORT:
8566 if(!detail::split_short(current, arg_name, rest))
8567 throw HorribleError("Short parsed but missing! You should not see this");
8568 break;
8569 case detail::Classifier::WINDOWS_STYLE:
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;
8573 case detail::Classifier::SUBCOMMAND:
8574 case detail::Classifier::SUBCOMMAND_TERMINATOR:
8575 case detail::Classifier::POSITIONAL_MARK:
8576 case detail::Classifier::NONE:
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;
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 }
8682 if(validate_optional_arguments_) {
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
8723CLI11_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
8741CLI11_INLINE App *App::_get_fallthrough_parent() {
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
8752CLI11_NODISCARD CLI11_INLINE const std::string &App::_compare_subcommand_names(const App &subcom,
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
8803CLI11_INLINE void App::_move_to_missing(detail::Classifier val_type, const std::string &val) {
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
8819CLI11_INLINE void App::_move_option(Option *opt, App *app) {
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
8858CLI11_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
8864CLI11_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
8877CLI11_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
8883CLI11_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
8896CLI11_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
8910CLI11_INLINE void retire_option(App *app, Option *opt) {
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
8934CLI11_INLINE void retire_option(App &app, Option *opt) { retire_option(&app, opt); }
8935
8936CLI11_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
8956CLI11_INLINE void retire_option(App &app, const std::string &option_name) { retire_option(&app, option_name); }
8957
8958namespace FailureMessage {
8959
8960CLI11_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
8978CLI11_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
8989namespace detail {
8990
8991std::string convert_arg_for_ini(const std::string &arg, char stringQuote = '"', char characterQuote = '\'');
8992
8994std::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
9001std::vector<std::string> generate_parents(const std::string &section, std::string &name, char parentSeparator);
9002
9004void checkParentSegments(std::vector<ConfigItem> &output, const std::string &currentSection, char parentSeparator);
9005} // namespace detail
9006
9007
9008
9009
9010namespace detail {
9011
9012CLI11_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
9055CLI11_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
9081CLI11_INLINE std::vector<std::string>
9082generate_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
9106CLI11_INLINE void
9107checkParentSegments(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
9156inline 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) {
9248 detail::remove_quotes(it);
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
9288CLI11_INLINE std::string
9289ConfigBase::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(
9322 opt->reduced_results(), arraySeparator, arrayStart, arrayEnd, stringQuote, characterQuote);
9323
9324 if(value.empty() && default_also) {
9325 if(!opt->get_default_str().empty()) {
9326 value = detail::convert_arg_for_ini(opt->get_default_str(), stringQuote, characterQuote);
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
9387CLI11_INLINE std::string
9388Formatter::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
9399CLI11_INLINE std::string Formatter::make_positionals(const App *app) const {
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
9409CLI11_INLINE std::string Formatter::make_groups(const App *app, AppFormatMode mode) const {
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
9433CLI11_INLINE std::string Formatter::make_description(const App *app) const {
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
9459CLI11_INLINE std::string Formatter::make_usage(const App *app, std::string name) const {
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
9501CLI11_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
9509CLI11_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
9533CLI11_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
9575CLI11_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
9581CLI11_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
9601CLI11_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
9608CLI11_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() << "] ";
9619 if(opt->get_expected_max() == detail::expected_max_vector_size)
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
9643CLI11_INLINE std::string Formatter::make_option_desc(const Option *opt) const { return opt->get_description(); }
9644
9645CLI11_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);
9649 if(opt->get_expected_max() >= detail::expected_max_vector_size)
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
9662PXR_NAMESPACE_CLOSE_SCOPE
Creates a command line program, with very few defaults.
Definition: CLI11.h:5605
Option * add_flag(std::string flag_name)
Add a flag with no description or variable assignment.
Definition: CLI11.h:6123
bool fallthrough_
Allow subcommand fallthrough, so that parent commands can collect commands after subcommand....
Definition: CLI11.h:5737
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
App * get_subcommand(const App *subcom) const
Check to see if a subcommand is part of this command (doesn't have to be in command line) returns the...
Definition: CLI11.h:7285
bool required_
If set to true the subcommand is required to be processed and used, ignored for main app.
Definition: CLI11.h:5635
CLI11_NODISCARD std::size_t get_require_option_max() const
Get the required max option value.
Definition: CLI11.h:6588
bool ignore_case_
If true, the program name is not case sensitive INHERITABLE.
Definition: CLI11.h:5731
CLI11_NODISCARD std::size_t get_require_subcommand_min() const
Get the required min subcommand value.
Definition: CLI11.h:6579
App * silent(bool silence=true)
silence the subcommand from showing up in the processed list
Definition: CLI11.h:5884
CLI11_NODISCARD bool get_positionals_at_end() const
Check the status of the allow windows style options.
Definition: CLI11.h:6565
bool remove_needs(Option *opt)
Removes an option from the needs list of this subcommand.
Definition: CLI11.h:7541
CLI11_NODISCARD const std::vector< std::string > & get_aliases() const
Get the aliases of the current app.
Definition: CLI11.h:6652
std::uint32_t parsed_
Counts the number of times this command/subcommand was parsed.
Definition: CLI11.h:5769
App * fallthrough(bool value=true)
Stop subcommand fallthrough, so that parent commands cannot collect commands after subcommand.
Definition: CLI11.h:6324
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::vector< Option * > parse_order_
This is a list of pointers to options with the original parse order.
Definition: CLI11.h:5703
void run_callback(bool final_mode=false, bool suppress_final_callback=false)
Internal function to run (App) callback, bottom up.
Definition: CLI11.h:7813
OptionDefaults * option_defaults()
Get the OptionDefault object, to set option defaults.
Definition: CLI11.h:5996
App * final_callback(std::function< void()> app_callback)
Set a callback for execution when all parsing and processing has completed aliased as callback.
Definition: CLI11.h:5840
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
bool silent_
indicator that the subcommand is silent and won't show up in subcommands list This is potentially use...
Definition: CLI11.h:5766
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
virtual ~App()=default
virtual destructor
void _process_extras()
Throw an error if anything is left over and should not be.
Definition: CLI11.h:8138
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
std::function< void()> parse_complete_callback_
This is a function that runs when parsing has finished.
Definition: CLI11.h:5651
std::string group_
The group membership INHERITABLE.
Definition: CLI11.h:5787
Option * get_version_ptr()
Get a pointer to the version option.
Definition: CLI11.h:6637
App * ignore_case(bool value=true)
Ignore case. Subcommands inherit value.
Definition: CLI11.h:7002
virtual void pre_callback()
This allows subclasses to inject code before callbacks but after parse.
Definition: CLI11.h:6340
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
bool _parse_subcommand(std::vector< std::string > &args)
Parse a subcommand, modify args and continue.
Definition: CLI11.h:8524
std::vector< Option_p > options_
The list of options, stored locally.
Definition: CLI11.h:5664
App * ignore_underscore(bool value=true)
Ignore underscore. Subcommands inherit value.
Definition: CLI11.h:7016
App(std::string app_description, std::string app_name, App *parent)
Special private constructor for subcommand.
Definition: CLI11.h:6922
Option * get_option_no_throw(std::string option_name) noexcept
Get an option by name (noexcept non-const version)
Definition: CLI11.h:7619
CLI11_NODISCARD const Option * get_version_ptr() const
Get a pointer to the version option. (const)
Definition: CLI11.h:6640
Option * add_option(std::string option_name)
Add option with no description or variable assignment.
Definition: CLI11.h:6089
bool ignore_underscore_
If true, the program should ignore underscores INHERITABLE.
Definition: CLI11.h:5734
CLI11_NODISCARD bool get_disabled_by_default() const
Get the status of disabled by default.
Definition: CLI11.h:6609
CLI11_NODISCARD std::shared_ptr< ConfigBase > get_config_formatter_base() const
Access the config formatter as a configBase pointer.
Definition: CLI11.h:6498
bool _parse_single_config(const ConfigItem &item, std::size_t level=0)
Fill in a single config option.
Definition: CLI11.h:8237
Option * get_help_ptr()
Get a pointer to the help flag.
Definition: CLI11.h:6622
Option * help_all_ptr_
A pointer to the help all flag if there is one INHERITABLE.
Definition: CLI11.h:5680
CLI11_NODISCARD bool _has_remaining_positionals() const
Count the required remaining positional arguments.
Definition: CLI11.h:8371
bool allow_windows_style_options_
Allow '/' for options for Windows like options. Defaults to true on Windows, false otherwise....
Definition: CLI11.h:5740
const Option * operator[](const char *option_name) const
Shortcut bracket operator for getting a pointer to an option.
Definition: CLI11.h:6550
CLI11_NODISCARD bool get_immediate_callback() const
Get the status of disabled.
Definition: CLI11.h:6606
Option * add_flag(std::string flag_name, T &flag_result, std::string flag_description="")
Other type version accepts all other types that are not vectors such as bool, enum,...
Definition: CLI11.h:6141
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
bool immediate_callback_
Flag indicating that the callback for the subcommand should be executed immediately on parse completi...
Definition: CLI11.h:5645
CLI11_NODISCARD const Option * get_help_all_ptr() const
Get a pointer to the help all flag. (const)
Definition: CLI11.h:6628
CLI11_NODISCARD const std::string & get_name() const
Get the name of the current app.
Definition: CLI11.h:6649
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
void increment_parsed()
Internal function to recursively increment the parsed counter on the current app as well unnamed subc...
Definition: CLI11.h:8167
CLI11_NODISCARD bool get_ignore_underscore() const
Check the status of ignore_underscore.
Definition: CLI11.h:6556
App * allow_config_extras(config_extras_mode mode)
ignore extras in config files
Definition: CLI11.h:5938
App * require_option(int value)
Require an option to be given (does not affect help call) The number required can be given.
Definition: CLI11.h:6303
bool positionals_at_end_
specify that positional arguments come at the end of the argument sequence not inheritable
Definition: CLI11.h:5748
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 _process()
Process callbacks and such.
Definition: CLI11.h:8116
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
CLI11_NODISCARD bool get_validate_optional_arguments() const
Get the status of validating optional vector arguments.
Definition: CLI11.h:6616
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
App * allow_config_extras(bool allow=true)
ignore extras in config files
Definition: CLI11.h:5927
CLI11_NODISCARD std::shared_ptr< Config > get_config_formatter() const
Access the config formatter.
Definition: CLI11.h:6495
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
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
App * allow_windows_style_options(bool value=true)
Allow windows style options, such as /opt.
Definition: CLI11.h:5954
std::string name_
Subcommand name or program name (from parser if name is empty)
Definition: CLI11.h:5616
App * validate_positionals(bool validate=true)
Set the subcommand to validate positional arguments before assigning.
Definition: CLI11.h:5915
CLI11_NODISCARD std::size_t count_all() const
Get a count of all the arguments processed in options and subcommands, this excludes arguments which ...
Definition: CLI11.h:7344
const Option * operator[](const std::string &option_name) const
Shortcut bracket operator for getting a pointer to an option.
Definition: CLI11.h:6547
App * allow_extras(bool allow=true)
Remove the error when extras are left over on the command line.
Definition: CLI11.h:5866
App * require_subcommand()
The argumentless form of require subcommand requires 1 or more subcommands.
Definition: CLI11.h:6265
App * footer(std::function< std::string()> footer_function)
Set footer.
Definition: CLI11.h:6471
std::set< Option * > need_options_
This is a list of options which are required by this app, the list is not mutual, listed options do n...
Definition: CLI11.h:5721
CLI11_NODISCARD bool get_validate_positionals() const
Get the status of validating positionals.
Definition: CLI11.h:6614
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_NODISCARD std::vector< std::string > get_groups() const
Get the groups available directly from this option (in order)
Definition: CLI11.h:7699
App * require_subcommand(std::size_t min, std::size_t max)
Explicitly control the number of subcommands required.
Definition: CLI11.h:6287
CLI11_NODISCARD bool get_fallthrough() const
Check the status of fallthrough.
Definition: CLI11.h:6559
App * group(std::string group_name)
Changes the group membership.
Definition: CLI11.h:6259
App * alias(std::string app_name)
Set an alias for the app.
Definition: CLI11.h:6972
void _validate() const
Check the options to make sure there are no conflicts.
Definition: CLI11.h:7758
Option * add_flag(std::string flag_name, T &flag_description)
Add flag with description but with no variable assignment or callback takes a constant string,...
Definition: CLI11.h:6131
std::size_t require_option_max_
Max number of options allowed. 0 is unlimited (not inheritable)
Definition: CLI11.h:5781
CLI11_NODISCARD bool get_allow_extras() const
Get the status of allow extras.
Definition: CLI11.h:6594
void _process_requirements()
Verify required options and cross requirements. Subcommands too (only if selected).
Definition: CLI11.h:7988
Option * add_option(std::string option_name, AssignTo &variable, std::string option_description="")
Add option for assigning to a variable.
Definition: CLI11.h:6026
bool _parse_positional(std::vector< std::string > &args, bool haltOnSubcommand)
Parse a positional, go up the tree to check.
Definition: CLI11.h:8381
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
App * parse_complete_callback(std::function< void()> pc_callback)
Set a callback to execute when parsing has completed for the app.
Definition: CLI11.h:5847
App * excludes(Option *opt)
Sets excluded options for the subcommand.
Definition: CLI11.h:6407
std::vector< App * > parsed_subcommands_
This is a list of the subcommands collected, in order.
Definition: CLI11.h:5706
CLI11_NODISCARD std::size_t _count_remaining_positionals(bool required_only=false) const
Count the required remaining positional arguments.
Definition: CLI11.h:8359
CLI11_NODISCARD const Option * get_help_ptr() const
Get a pointer to the help flag. (const)
Definition: CLI11.h:6625
CLI11_NODISCARD const std::string & get_group() const
Get the group of this subcommand.
Definition: CLI11.h:6571
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
void _process_callbacks()
Process callbacks. Runs on all subcommands.
Definition: CLI11.h:7942
std::set< App * > exclude_subcommands_
this is a list of subcommands that are exclusionary to this one
Definition: CLI11.h:5709
App * required(bool require=true)
Remove the error when extras are left over on the command line.
Definition: CLI11.h:5872
App * preparse_callback(std::function< void(std::size_t)> pp_callback)
Set a callback to execute prior to parsing.
Definition: CLI11.h:5854
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_NODISCARD const std::vector< Option * > & parse_order() const
This gets a vector of pointers with the original parse order.
Definition: CLI11.h:6670
App * footer(std::string footer_string)
Set footer.
Definition: CLI11.h:6466
App * parent_
A pointer to the parent if this is a subcommand.
Definition: CLI11.h:5784
CLI11_NODISCARD std::size_t get_require_option_min() const
Get the required min option value.
Definition: CLI11.h:6585
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
bool remove_excludes(Option *opt)
Removes an option from the excludes list of this subcommand.
Definition: CLI11.h:7521
CLI11_NODISCARD bool parsed() const
Check to see if this subcommand was parsed, true only if received on command line.
Definition: CLI11.h:5993
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
App * formatter_fn(std::function< std::string(const App *, std::string, AppFormatMode)> fmt)
Set the help formatter.
Definition: CLI11.h:5981
Option * help_ptr_
A pointer to the help flag if there is one INHERITABLE.
Definition: CLI11.h:5677
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
CLI11_NODISCARD bool get_configurable() const
Check the status of the allow windows style options.
Definition: CLI11.h:6568
App * prefix_command(bool allow=true)
Do not parse anything after the first unrecognized option and return.
Definition: CLI11.h:5944
CLI11_NODISCARD bool get_ignore_case() const
Check the status of ignore_case.
Definition: CLI11.h:6553
void _configure()
configure subcommands to enable parsing through the current object set the correct fallthrough and pr...
Definition: CLI11.h:7793
std::function< void()> final_callback_
This is a function that runs when all processing has completed.
Definition: CLI11.h:5654
CLI11_NODISCARD std::string get_footer() const
Generate and return the footer.
Definition: CLI11.h:6574
void _process_config_file()
Read and process a configuration file (main app only)
Definition: CLI11.h:7878
CLI11_NODISCARD std::vector< App * > get_subcommands() const
Get a subcommand pointer list to the currently selected subcommands (after parsing by default,...
Definition: CLI11.h:6385
missing_t missing_
Pair of classifier, string for missing options.
Definition: CLI11.h:5700
bool prefix_command_
If true, return immediately on an unrecognized option (implies allow_extras) INHERITABLE.
Definition: CLI11.h:5629
CLI11_NODISCARD App * _find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept
Locate a subcommand by name with two conditions, should disabled subcommands be ignored,...
Definition: CLI11.h:8506
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
App * description(std::string app_description)
Set the description of the app.
Definition: CLI11.h:6511
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 * excludes(App *app)
Sets excluded subcommands for the subcommand.
Definition: CLI11.h:6416
CLI11_NODISCARD config_extras_mode get_allow_config_extras() const
Get the status of allow extras.
Definition: CLI11.h:6619
App * formatter(std::shared_ptr< FormatterBase > fmt)
Set the help formatter.
Definition: CLI11.h:5975
bool disabled_
If set to true the subcommand is disabled and cannot be used, ignored for main app.
Definition: CLI11.h:5638
CLI11_NODISCARD std::shared_ptr< FormatterBase > get_formatter() const
Access the formatter.
Definition: CLI11.h:6492
void _process_env()
Get envname options if not yet passed. Runs on all subcommands.
Definition: CLI11.h:7910
bool validate_optional_arguments_
If set to true optional vector arguments are validated before assigning INHERITABLE.
Definition: CLI11.h:5762
App * enabled_by_default(bool enable=true)
Set the subcommand to be enabled by default, so on clear(), at the start of each parse it is enabled ...
Definition: CLI11.h:5901
std::set< Option * > exclude_options_
This is a list of options which are exclusionary to this App, if the options were used this subcomman...
Definition: CLI11.h:5713
App * require_option(std::size_t min, std::size_t max)
Explicitly control the number of options required.
Definition: CLI11.h:6316
void _parse(std::vector< std::string > &args)
Internal parse function.
Definition: CLI11.h:8175
CLI11_NODISCARD const Option * get_config_ptr() const
Get a pointer to the config option. (const)
Definition: CLI11.h:6634
std::set< App * > need_subcommands_
this is a list of subcommands or option groups that are required by this one, the list is not mutual,...
Definition: CLI11.h:5717
void clear()
Reset the parsed data.
Definition: CLI11.h:7358
CLI11_NODISCARD std::string get_description() const
Get the app or subcommand description.
Definition: CLI11.h:6508
Option * add_option(std::string option_name, callback_t option_callback, std::string option_description="", bool defaulted=false, std::function< std::string()> func={})
Add an option, will automatically understand the type for common types.
Definition: CLI11.h:7030
CLI11_NODISCARD std::string help(std::string prev="", AppFormatMode mode=AppFormatMode::Normal) const
Makes a help message, using the currently configured formatter Will only do one subcommand at a time.
Definition: CLI11.h:7559
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
App * name(std::string app_name="")
Set a name for the app (empty will use parser to set the name)
Definition: CLI11.h:6955
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
App * clear_aliases()
clear all the aliases of the current App
Definition: CLI11.h:6655
Option * get_config_ptr()
Get a pointer to the config option.
Definition: CLI11.h:6631
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
std::vector< App_p > subcommands_
Storage for subcommand list.
Definition: CLI11.h:5728
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_NODISCARD bool get_allow_windows_style_options() const
Check the status of the allow windows style options.
Definition: CLI11.h:6562
std::shared_ptr< FormatterBase > formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer)
Definition: CLI11.h:5686
CLI11_NODISCARD std::vector< std::string > remaining(bool recurse=false) const
This returns the missing options from the current subcommand.
Definition: CLI11.h:7712
std::function< std::string(const App *, const Error &e)> failure_message_
The error message printing function INHERITABLE.
Definition: CLI11.h:5689
std::string footer_
Footer to put after all options in the help output INHERITABLE.
Definition: CLI11.h:5671
std::vector< std::string > aliases_
Alias names for the subcommand.
Definition: CLI11.h:5790
App * disabled(bool disable=true)
Disable the subcommand or option group.
Definition: CLI11.h:5878
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
bool configurable_
if set to true the subcommand can be triggered via configuration files INHERITABLE
Definition: CLI11.h:5756
CLI11_NODISCARD bool get_disabled() const
Get the status of disabled.
Definition: CLI11.h:6600
CLI11_NODISCARD std::size_t count() const
No argument version of count counts the number of times this subcommand was passed in.
Definition: CLI11.h:6252
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
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 check_name(std::string name_to_check) const
Check the name, case insensitive and underscore insensitive if set.
Definition: CLI11.h:7671
void _process_help_flags(bool trigger_help=false, bool trigger_all_help=false) const
Run help flag processing if any are found.
Definition: CLI11.h:7966
Option * version_ptr_
A pointer to a version flag if there is one.
Definition: CLI11.h:5683
bool _parse_single(std::vector< std::string > &args, bool &positional_only)
Parse "one" argument (some may eat more than one), delegate to parent if fails, add to missing if mis...
Definition: CLI11.h:8317
std::shared_ptr< Config > config_formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer)
Definition: CLI11.h:5800
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
App * configurable(bool value=true)
Specify that the subcommand can be triggered by a config file.
Definition: CLI11.h:5966
bool validate_positionals_
If set to true positional options are validated before assigning INHERITABLE.
Definition: CLI11.h:5759
App * require_option()
The argumentless form of require option requires 1 or more options be used.
Definition: CLI11.h:6294
CLI11_NODISCARD bool get_prefix_command() const
Get the prefix command status.
Definition: CLI11.h:6591
config_extras_mode allow_config_extras_
If ignore, allow extra arguments in the ini file (ie, don't throw an error).
Definition: CLI11.h:5626
void _trigger_pre_parse(std::size_t remaining_args)
Trigger the pre_parse callback if needed.
Definition: CLI11.h:8723
App * validate_optional_arguments(bool validate=true)
Set the subcommand to validate optional vector arguments before assigning.
Definition: CLI11.h:5921
CLI11_NODISCARD bool get_required() const
Get the status of required.
Definition: CLI11.h:6597
void _parse_config(const std::vector< ConfigItem > &args)
Parse one config param, return false if not found in any subcommand, remove if it is.
Definition: CLI11.h:8230
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
Option * get_option(std::string option_name)
Get an option by name (non-const version)
Definition: CLI11.h:6538
App * get_parent()
Get the parent of this subcommand (or nullptr if main app)
Definition: CLI11.h:6643
CLI11_NODISCARD const Option * get_option(std::string option_name) const
Get an option by name.
Definition: CLI11.h:6529
App * immediate_callback(bool immediate=true)
Set the subcommand callback to be executed immediately on subcommand completion.
Definition: CLI11.h:6990
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
OptionDefaults option_defaults_
The default values for options, customizable and changeable INHERITABLE.
Definition: CLI11.h:5661
startup_mode default_startup
specify the startup mode for the app stable=no change, enabled= startup enabled, disabled=startup dis...
Definition: CLI11.h:5753
std::size_t require_subcommand_min_
Minimum required subcommands (not inheritable!)
Definition: CLI11.h:5772
bool pre_parse_called_
Flag indicating that the pre_parse_callback has been triggered.
Definition: CLI11.h:5641
void _parse_stream(std::istream &input)
Internal function to parse a stream.
Definition: CLI11.h:8219
App * callback(std::function< void()> app_callback)
Set a callback for execution when all parsing and processing has completed.
Definition: CLI11.h:5829
CLI11_NODISCARD std::string config_to_str(bool default_also=false, bool write_description=false) const
Produce a string that could be read in as a config of the current values of the App.
Definition: CLI11.h:6477
CLI11_NODISCARD std::string version() const
Displays a version string.
Definition: CLI11.h:7573
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
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
std::string description_
Description of the current program/subcommand.
Definition: CLI11.h:5619
CLI11_NODISCARD bool get_silent() const
Get the status of silence.
Definition: CLI11.h:6603
CLI11_NODISCARD const App * get_parent() const
Get the parent of this subcommand (or nullptr if main app) (const version)
Definition: CLI11.h:6646
bool allow_extras_
If true, allow extra arguments (ie, don't throw an error). INHERITABLE.
Definition: CLI11.h:5622
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
CLI11_NODISCARD bool get_enabled_by_default() const
Get the status of disabled by default.
Definition: CLI11.h:6612
void parse(int argc, const char *const *argv)
Parses the command line - throws errors.
Definition: CLI11.h:7373
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 * require_subcommand(int value)
Require a subcommand to be given (does not affect help call) The number required can be given.
Definition: CLI11.h:6274
bool _parse_arg(std::vector< std::string > &args, detail::Classifier current_type)
Parse a short (false) or long (true) argument, must be at the top of the list return true if the argu...
Definition: CLI11.h:8552
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
bool got_subcommand(const App *subcom) const
Check to see if given subcommand was selected.
Definition: CLI11.h:6396
std::size_t require_option_min_
Minimum required options (not inheritable!)
Definition: CLI11.h:5778
CLI11_NODISCARD std::size_t get_require_subcommand_max() const
Get the required max subcommand value.
Definition: CLI11.h:6582
Option * config_ptr_
Pointer to the config option.
Definition: CLI11.h:5797
App * config_formatter(std::shared_ptr< Config > fmt)
Set the config formatter.
Definition: CLI11.h:5987
Thrown when the wrong number of arguments has been received.
Definition: CLI11.h:875
Multiply a number by a factor using given mapping.
Definition: CLI11.h:3479
Options
Adjust AsNumberWithUnit behavior.
Definition: CLI11.h:3485
Converts a human-readable size string (with unit literal) to uin64_t size.
Definition: CLI11.h:3621
AsSizeValue(bool kb_is_1000)
If kb_is_1000 is true, interpret 'kb', 'k' as 1000 and 'kib', 'ki' as 1024 (same applies to higher or...
Definition: CLI11.h:3891
Thrown on construction of a bad name.
Definition: CLI11.h:742
Produce a bounded range (factory). Min and max are inclusive.
Definition: CLI11.h:3082
Bound(T min_val, T max_val)
This bounds a value with min and max inclusive.
Definition: CLI11.h:3088
Bound(T max_val)
Range of one value is 0 to value.
Definition: CLI11.h:3109
Usually something like –help-all on command line.
Definition: CLI11.h:790
-h or –help on command line
Definition: CLI11.h:784
-v or –version on command line
Definition: CLI11.h:797
translate named items to other or a value set
Definition: CLI11.h:3380
CheckedTransformer(std::initializer_list< std::pair< std::string, std::string > > values, Args &&...args)
This allows in-place construction.
Definition: CLI11.h:3386
CheckedTransformer(T mapping)
direct map of std::string to std::string
Definition: CLI11.h:3390
CheckedTransformer(T mapping, F filter_function)
This checks to see if an item is in a set: pointer or copy version.
Definition: CLI11.h:3394
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
This converter works with INI/TOML files; to write INI files use ConfigINI.
Definition: CLI11.h:2712
CLI11_NODISCARD const std::string & section() const
get the section
Definition: CLI11.h:2782
ConfigBase * valueSeparator(char vSep)
Specify the delimiter between a name and value.
Definition: CLI11.h:2759
ConfigBase * arrayDelimiter(char aSep)
Specify the delimiter character for an array.
Definition: CLI11.h:2754
ConfigBase * parentSeparator(char sep)
Specify the separator to use for parent layers.
Definition: CLI11.h:2775
ConfigBase * quoteCharacter(char qString, char qChar)
Specify the quote characters used around strings and characters.
Definition: CLI11.h:2764
int16_t & indexRef()
get a reference to the configuration index
Definition: CLI11.h:2790
ConfigBase * section(const std::string &sectionName)
specify a particular section of the configuration file to use
Definition: CLI11.h:2784
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 & sectionRef()
get a reference to the configuration section
Definition: CLI11.h:2780
CLI11_NODISCARD int16_t index() const
get the section index
Definition: CLI11.h:2792
ConfigBase * arrayBounds(char aStart, char aEnd)
Specify the start and end characters for an array.
Definition: CLI11.h:2748
ConfigBase * comment(char cchar)
Specify the configuration for comment characters.
Definition: CLI11.h:2743
ConfigBase * maxLayers(uint8_t layers)
Specify the maximum number of parents.
Definition: CLI11.h:2770
Thrown when extra values are found in an INI file.
Definition: CLI11.h:936
This class provides a converter for configuration files.
Definition: CLI11.h:2676
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
virtual CLI11_NODISCARD std::string to_flag(const ConfigItem &item) const
Get a flag value.
Definition: CLI11.h:2688
virtual std::string to_config(const App *, bool, bool, std::string) const =0
Convert an app into a configuration.
virtual std::vector< ConfigItem > from_config(std::istream &) const =0
Convert a configuration into an app.
virtual ~Config()=default
Virtual destructor.
ConfigINI generates a "standard" INI compliant output.
Definition: CLI11.h:2804
Construction errors (not in parsing)
Definition: CLI11.h:709
Thrown when conversion call back fails, such as when an int fails to coerce to a string.
Definition: CLI11.h:817
Class wrapping some of the accessors of Validator.
Definition: CLI11.h:2954
All errors derive from this one.
Definition: CLI11.h:691
Thrown when an excludes option is present.
Definition: CLI11.h:913
Thrown when too many positionals or options are found.
Definition: CLI11.h:920
Thrown when parsing an INI file and it is missing.
Definition: CLI11.h:810
Modify a path if the file is a particular default location, can be used as Check or transform with th...
Definition: CLI11.h:3036
This is the minimum requirements to run a formatter.
Definition: CLI11.h:3997
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 std::size_t get_column_width() const
Get the current column width.
Definition: CLI11.h:4048
virtual std::string make_help(const App *, std::string, AppFormatMode) const =0
This is the key method that puts together help.
void label(std::string key, std::string val)
Set the "REQUIRED" label.
Definition: CLI11.h:4031
std::size_t column_width_
The width of the first column.
Definition: CLI11.h:4003
virtual ~FormatterBase() noexcept
Adding a destructor in this form to work around bug in GCC 4.7.
Definition: CLI11.h:4021
void column_width(std::size_t val)
Set the column width.
Definition: CLI11.h:4034
CLI11_NODISCARD std::string get_label(std::string key) const
Get the current value of a name (REQUIRED, etc.)
Definition: CLI11.h:4041
This is the default Formatter for CLI11.
Definition: CLI11.h:4075
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
std::string make_help(const App *, std::string, AppFormatMode) const override
This puts everything together.
Definition: CLI11.h:9509
virtual std::string make_usage(const App *app, std::string name) const
This displays the usage line.
Definition: CLI11.h:9459
virtual std::string make_description(const App *app) const
This displays the description line.
Definition: CLI11.h:9433
std::string make_groups(const App *app, AppFormatMode mode) const
This prints out all the groups of options.
Definition: CLI11.h:9409
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
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
virtual std::string make_footer(const App *app) const
This prints out all the groups of options.
Definition: CLI11.h:9501
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
virtual std::string make_expanded(const App *sub) const
This prints out a subcommand in help-all.
Definition: CLI11.h:9581
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
virtual CLI11_NODISCARD std::string make_group(std::string group, bool is_positional, std::vector< const Option * > opts) const
This prints out a group of options with title.
Definition: CLI11.h:9388
virtual std::string make_positionals(const App *app) const
This prints out just the positionals "group".
Definition: CLI11.h:9399
virtual std::string make_subcommand(const App *sub) const
This prints out a subcommand.
Definition: CLI11.h:9575
virtual std::string make_subcommands(const App *app, AppFormatMode mode) const
This prints out all the subcommands.
Definition: CLI11.h:9533
This is a specialty override for lambda functions.
Definition: CLI11.h:4054
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
~FormatterLambda() noexcept override
Adding a destructor (mostly to make GCC 4.7 happy)
Definition: CLI11.h:4065
FormatterLambda(funct_t funct)
Create a FormatterLambda with a lambda function.
Definition: CLI11.h:4062
This is just a safety check to verify selection and parsing match - you should not ever see it String...
Definition: CLI11.h:955
Thrown when an option is set to conflicting values (non-vector and multi args, for example)
Definition: CLI11.h:714
Thrown when validation fails before parsing.
Definition: CLI11.h:946
Verify items are in a set.
Definition: CLI11.h:3253
IsMember(std::initializer_list< T > values, Args &&...args)
This allows in-place construction using an initializer list.
Definition: CLI11.h:3259
IsMember(T &&set)
This checks to see if an item is in a set (empty function)
Definition: CLI11.h:3263
IsMember(T set, F filter_function)
This checks to see if an item is in a set: pointer or copy version.
Definition: CLI11.h:3267
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
Extension of App to better manage groups of options.
Definition: CLI11.h:6803
void add_options(Option *opt, Args... args)
Add a bunch of options to the group.
Definition: CLI11.h:6822
void add_options(Option *opt)
Add an existing option to the Option_group.
Definition: CLI11.h:6820
Option * add_option(Option *opt)
Add an existing option to the Option_group.
Definition: CLI11.h:6812
App * add_subcommand(App *subcom)
Add an existing subcommand to be a member of an option_group.
Definition: CLI11.h:6828
Thrown when an option already exists.
Definition: CLI11.h:756
This is the CRTP base class for Option and OptionDefaults.
Definition: CLI11.h:4168
bool required_
True if this is a required option.
Definition: CLI11.h:4176
bool ignore_case_
Ignore the case when matching (option, not value)
Definition: CLI11.h:4179
CRTP * take_all()
Set the multi option policy to take all arguments.
Definition: CLI11.h:4274
CRTP * take_first()
Set the multi option policy to take last.
Definition: CLI11.h:4267
CRTP * join(char delim)
Set the multi option policy to join with a specific delimiter.
Definition: CLI11.h:4288
std::string group_
The group membership.
Definition: CLI11.h:4173
char delimiter_
Specify a delimiter character for vector arguments.
Definition: CLI11.h:4191
bool ignore_underscore_
Ignore underscores when matching (option, not value)
Definition: CLI11.h:4182
CLI11_NODISCARD char get_delimiter() const
Get the current delimiter char.
Definition: CLI11.h:4249
CRTP * mandatory(bool value=true)
Support Plumbum term.
Definition: CLI11.h:4221
CRTP * take_last()
Set the multi option policy to take last.
Definition: CLI11.h:4260
CLI11_NODISCARD bool get_ignore_underscore() const
The status of ignore_underscore.
Definition: CLI11.h:4240
CRTP * join()
Set the multi option policy to join.
Definition: CLI11.h:4281
CRTP * delimiter(char value='\0')
Allow in a configuration file.
Definition: CLI11.h:4302
bool disable_flag_override_
Disable overriding flag values with '=value'.
Definition: CLI11.h:4188
CLI11_NODISCARD const std::string & get_group() const
Get the group of this option.
Definition: CLI11.h:4231
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
CRTP * required(bool value=true)
Set the option as required.
Definition: CLI11.h:4215
CLI11_NODISCARD bool get_configurable() const
The status of configurable.
Definition: CLI11.h:4243
CLI11_NODISCARD bool get_ignore_case() const
The status of ignore case.
Definition: CLI11.h:4237
void copy_to(T *other) const
Copy the contents to another similar class (one based on OptionBase)
Definition: CLI11.h:4924
bool configurable_
Allow this option to be given in a configuration file.
Definition: CLI11.h:4185
CRTP * configurable(bool value=true)
Allow in a configuration file.
Definition: CLI11.h:4296
CLI11_NODISCARD bool get_disable_flag_override() const
The status of configurable.
Definition: CLI11.h:4246
MultiOptionPolicy multi_option_policy_
Policy for handling multiple arguments beyond the expected Max.
Definition: CLI11.h:4197
CLI11_NODISCARD bool get_required() const
True if this is a required option.
Definition: CLI11.h:4234
bool always_capture_default_
Automatically capture default value.
Definition: CLI11.h:4194
CLI11_NODISCARD MultiOptionPolicy get_multi_option_policy() const
The status of the multi option policy.
Definition: CLI11.h:4255
CRTP * group(const std::string &name)
Changes the group membership.
Definition: CLI11.h:4206
This is a version of OptionBase that only supports setting values, for defaults.
Definition: CLI11.h:4310
OptionDefaults * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times.
Definition: CLI11.h:4317
OptionDefaults * disable_flag_override(bool value=true)
Disable overriding flag values with an '=' segment.
Definition: CLI11.h:4335
OptionDefaults * ignore_case(bool value=true)
Ignore the case of the option name.
Definition: CLI11.h:4323
OptionDefaults * ignore_underscore(bool value=true)
Ignore underscores in the option name.
Definition: CLI11.h:4329
OptionDefaults * delimiter(char value='\0')
set a delimiter character to split up single arguments to treat as multiple inputs
Definition: CLI11.h:4341
Thrown when counting a non-existent option.
Definition: CLI11.h:963
Anything that can error in Parse.
Definition: CLI11.h:771
Produce a range (factory). Min and max are inclusive.
Definition: CLI11.h:3042
Range(T min_val, T max_val, const std::string &validator_name=std::string{})
This produces a range with min and max inclusive.
Definition: CLI11.h:3049
Range(T max_val, const std::string &validator_name=std::string{})
Range of one value is 0 to value.
Definition: CLI11.h:3071
Thrown when a required option is missing.
Definition: CLI11.h:840
Thrown when a requires option is missing.
Definition: CLI11.h:906
Does not output a diagnostic in CLI11_PARSE, but allows main() to return with a specific error code.
Definition: CLI11.h:804
This is a successful completion on parsing, supposed to exit.
Definition: CLI11.h:778
Translate named items to other or a value set.
Definition: CLI11.h:3322
Transformer(T &&mapping)
direct map of std::string to std::string
Definition: CLI11.h:3332
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
Transformer(T mapping, F filter_function)
This checks to see if an item is in a set: pointer or copy version.
Definition: CLI11.h:3336
Transformer(std::initializer_list< std::pair< std::string, std::string > > values, Args &&...args)
This allows in-place construction.
Definition: CLI11.h:3328
Validate the input as a particular type.
Definition: CLI11.h:3018
Thrown when validation of results fails.
Definition: CLI11.h:833
Some validators that are provided.
Definition: CLI11.h:2830
bool active_
Enable for Validator to allow it to be disabled if need be.
Definition: CLI11.h:2843
Validator & non_modifying(bool no_modify=true)
Specify whether the Validator can be modifying or not.
Definition: CLI11.h:2915
std::string operator()(std::string &str) const
This is the required operator for a Validator - provided to help users (CLI11 uses the member func di...
Definition: CLI11.h:3655
CLI11_NODISCARD Validator active(bool active_val=true) const
Specify whether the Validator is active or not.
Definition: CLI11.h:2908
CLI11_NODISCARD const std::string & get_name() const
Get the name of the Validator.
Definition: CLI11.h:2901
std::string name_
The name for search purposes of the Validator.
Definition: CLI11.h:2839
CLI11_NODISCARD Validator name(std::string validator_name) const
Specify the type string.
Definition: CLI11.h:2895
int application_index_
A Validator will only apply to an indexed value (-1 is all elements)
Definition: CLI11.h:2841
std::function< std::string(std::string &)> func_
This is the base function that is to be called.
Definition: CLI11.h:2837
CLI11_NODISCARD int get_application_index() const
Get the current value of the application index.
Definition: CLI11.h:2931
Validator operator|(const Validator &other) const
Combining validators is a new validator.
Definition: CLI11.h:3696
std::string operator()(const std::string &str) const
This is the required operator for a Validator - provided to help users (CLI11 uses the member func di...
Definition: CLI11.h:2869
Validator & application_index(int app_index)
Specify the application index of a validator.
Definition: CLI11.h:2920
Validator operator!() const
Create a validator that fails when a given validator succeeds.
Definition: CLI11.h:3718
Validator & name(std::string validator_name)
Specify the type string.
Definition: CLI11.h:2890
CLI11_NODISCARD bool get_active() const
Get a boolean if the validator is active.
Definition: CLI11.h:2933
Validator & description(std::string validator_desc)
Specify the type string.
Definition: CLI11.h:2875
CLI11_NODISCARD std::string get_description() const
Generate type description information for the Validator.
Definition: CLI11.h:2883
CLI11_NODISCARD Validator application_index(int app_index) const
Specify the application index of a validator.
Definition: CLI11.h:2925
Validator operator&(const Validator &other) const
Combining validators is a new validator.
Definition: CLI11.h:3674
Validator & active(bool active_val=true)
Specify whether the Validator is active or not.
Definition: CLI11.h:2903
Validator(std::string validator_desc)
Construct a Validator with just the description string.
Definition: CLI11.h:2853
std::function< std::string()> desc_function_
This is the description function, if empty the description_ will be used.
Definition: CLI11.h:2833
Validator(std::function< std::string(std::string &)> op, std::string validator_desc, std::string validator_name="")
Construct Validator from basic information.
Definition: CLI11.h:2855
Validator & operation(std::function< std::string(std::string &)> op)
Set the Validator operation function.
Definition: CLI11.h:2859
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
Check for an existing directory (returns error message if check fails)
Definition: CLI11.h:2975
Check for an existing file (returns error message if check fails)
Definition: CLI11.h:2969
Check for an existing path.
Definition: CLI11.h:2981
Validate the given string is a legal ipv4 address.
Definition: CLI11.h:2993
Check for an non-existing path.
Definition: CLI11.h:2987
Check for complex.
Definition: CLI11.h:1146
Check for input streamability.
Definition: CLI11.h:1135
GF_API std::ostream & operator<<(std::ostream &, const GfBBox3d &)
Output a GfBBox3d using the format [(range) matrix zeroArea].
STL namespace.
Holds values to load into Options.
Definition: CLI11.h:2657
std::vector< std::string > inputs
Listing of inputs.
Definition: CLI11.h:2665
std::string name
This is the name.
Definition: CLI11.h:2662
std::vector< std::string > parents
This is the list of parents.
Definition: CLI11.h:2659
CLI11_NODISCARD std::string fullname() const
The list of parents and name joined by ".".
Definition: CLI11.h:2668
This can be specialized to override the type deduction for IsMember.
Definition: CLI11.h:1025
This class is simply to allow tests access to App's protected functions.
Definition: CLI11.h:6887
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
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
static App * get_fallthrough_parent(App *app)
Wrap the fallthrough parent function to make sure that is working correctly.
Definition: CLI11.h:6915
Handy helper to access the element_type generically.
Definition: CLI11.h:1038
Combination of the element type and value type - remove pointer (including smart pointers) and get th...
Definition: CLI11.h:1046
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
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
Adaptor for set-like structure: This just wraps a normal container in a few utilities that do almost ...
Definition: CLI11.h:1049
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
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
forward declare the subtype_count_min structure
Definition: CLI11.h:1342
Set of overloads to get the type size of an object.
Definition: CLI11.h:1339
This will only trigger for actual void type.
Definition: CLI11.h:1315
This will only trigger for actual void type.
Definition: CLI11.h:1345
template to get the underlying value type if it exists or use a default
Definition: CLI11.h:1307
Check to see if something is bool (fail check by default)
Definition: CLI11.h:1005
Check to see if something is copyable pointer.
Definition: CLI11.h:1020
Check to see if something is a shared pointer.
Definition: CLI11.h:1011
A copy of std::void_t from C++17 (helper for C++11 and C++14)
Definition: CLI11.h:996