$mermaidjs
CLI11 2.7.2
C++11 Command Line Interface Parser
Loading...
Searching...
No Matches
App_inl.hpp
1// Copyright (c) 2017-2026, University of Cincinnati, developed by Henry Schreiner
2// under NSF AWARD 1414736 and by the respective contributors.
3// All rights reserved.
4//
5// SPDX-License-Identifier: BSD-3-Clause
6
7#pragma once
8
9// IWYU pragma: private, include "CLI/CLI.hpp"
10
11// This include is only needed for IDEs to discover symbols
12#include "../App.hpp"
13
14#include "../Argv.hpp"
15#include "../Encoding.hpp"
16
17// [CLI11:public_includes:set]
18#include <algorithm>
19#include <cerrno>
20#include <cstddef>
21#include <cstdint>
22#include <exception>
23#include <functional>
24#include <iostream>
25#include <iterator>
26#include <memory>
27#include <set>
28#include <stdexcept>
29#include <string>
30#include <utility>
31#include <vector>
32// [CLI11:public_includes:end]
33
34namespace CLI {
35// [CLI11:app_inl_hpp:verbatim]
36
37CLI11_INLINE App::App(std::string app_description, std::string app_name, App *parent)
38 : name_(std::move(app_name)), description_(std::move(app_description)), parent_(parent) {
39 // Inherit if not from a nullptr
40 if(parent_ != nullptr) {
41 if(parent_->help_ptr_ != nullptr)
42 set_help_flag(parent_->help_ptr_->get_name(false, true), parent_->help_ptr_->get_description());
43 if(parent_->help_all_ptr_ != nullptr)
44 set_help_all_flag(parent_->help_all_ptr_->get_name(false, true), parent_->help_all_ptr_->get_description());
45
47 option_defaults_ = parent_->option_defaults_;
48
49 // INHERITABLE
50 failure_message_ = parent_->failure_message_;
51 allow_extras_ = parent_->allow_extras_;
52 allow_config_extras_ = parent_->allow_config_extras_;
53 prefix_command_ = parent_->prefix_command_;
54 immediate_callback_ = parent_->immediate_callback_;
55 ignore_case_ = parent_->ignore_case_;
56 ignore_underscore_ = parent_->ignore_underscore_;
57 fallthrough_ = parent_->fallthrough_;
58 validate_positionals_ = parent_->validate_positionals_;
59 validate_optional_arguments_ = parent_->validate_optional_arguments_;
60 configurable_ = parent_->configurable_;
61 allow_windows_style_options_ = parent_->allow_windows_style_options_;
62 group_ = parent_->group_;
63 usage_ = parent_->usage_;
64 footer_ = parent_->footer_;
65 formatter_ = parent_->formatter_;
66 config_formatter_ = parent_->config_formatter_;
67 require_subcommand_max_ = parent_->require_subcommand_max_;
68 allow_prefix_matching_ = parent_->allow_prefix_matching_;
69 }
70}
71
72CLI11_INLINE App::App(std::string app_description, std::string app_name) : App(app_description, app_name, nullptr) {
73 set_help_flag("-h,--help", "Print this help message and exit");
74}
75
76CLI11_NODISCARD CLI11_INLINE char **App::ensure_utf8(char **argv) {
77#ifdef _WIN32
78 (void)argv;
79
80 normalized_argv_ = detail::compute_win32_argv();
81
82 if(!normalized_argv_view_.empty()) {
83 normalized_argv_view_.clear();
84 }
85
86 normalized_argv_view_.reserve(normalized_argv_.size());
87 for(auto &arg : normalized_argv_) {
88 // using const_cast is well-defined, string is known to not be const.
89 normalized_argv_view_.push_back(const_cast<char *>(arg.data()));
90 }
91
92 return normalized_argv_view_.data();
93#else
94 return argv;
95#endif
96}
97
98CLI11_INLINE App *App::callback(std::function<void()> app_callback) {
100 parse_complete_callback_ = std::move(app_callback);
101 } else {
102 final_callback_ = std::move(app_callback);
103 }
104 return this;
105}
106
107CLI11_INLINE App *App::name(std::string app_name) {
108
109 if(parent_ != nullptr) {
110 std::string oname = name_;
111 name_ = app_name;
112 const auto &res = _compare_subcommand_names(*this, *_get_fallthrough_parent());
113 if(!res.empty()) {
114 name_ = oname;
115 throw(OptionAlreadyAdded(app_name + " conflicts with existing subcommand names"));
116 }
117 } else {
118 name_ = app_name;
119 }
120 has_automatic_name_ = false;
121 return this;
122}
123
124CLI11_INLINE App *App::alias(std::string app_name) {
125 if(app_name.empty() || !detail::valid_alias_name_string(app_name)) {
126 throw IncorrectConstruction("Aliases may not be empty or contain newlines or null characters");
127 }
128 if(parent_ != nullptr) {
129 aliases_.push_back(app_name);
130 const auto &res = _compare_subcommand_names(*this, *_get_fallthrough_parent());
131 if(!res.empty()) {
132 aliases_.pop_back();
133 throw(OptionAlreadyAdded("alias already matches an existing subcommand: " + app_name));
134 }
135 } else {
136 aliases_.push_back(app_name);
137 }
138
139 return this;
140}
141
142CLI11_INLINE App *App::disabled_by_default(bool disable) {
143 if(disable) {
144 default_startup = startup_mode::disabled;
145 } else {
146 default_startup = (default_startup == startup_mode::enabled) ? startup_mode::enabled : startup_mode::stable;
147 }
148 return this;
149}
150
151CLI11_INLINE App *App::enabled_by_default(bool enable) {
152 if(enable) {
153 default_startup = startup_mode::enabled;
154 } else {
155 default_startup = (default_startup == startup_mode::disabled) ? startup_mode::disabled : startup_mode::stable;
156 }
157 return this;
158}
159
160CLI11_INLINE App *App::allow_config_extras(bool allow) {
161 if(allow) {
162 allow_config_extras_ = ConfigExtrasMode::Capture;
163 allow_extras_ = ExtrasMode::Capture;
164 } else {
165 allow_config_extras_ = ConfigExtrasMode::Error;
166 }
167 return this;
168}
169
170CLI11_INLINE App *App::immediate_callback(bool immediate) {
171 immediate_callback_ = immediate;
175 }
178 }
179 return this;
180}
181
182CLI11_INLINE App *App::ignore_case(bool value) {
183 if(value && !ignore_case_) {
184 ignore_case_ = true;
185 auto *p = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
186 const auto &match = _compare_subcommand_names(*this, *p);
187 if(!match.empty()) {
188 ignore_case_ = false; // we are throwing so need to be exception invariant
189 throw OptionAlreadyAdded("ignore case would cause subcommand name conflicts: " + match);
190 }
191 }
192 ignore_case_ = value;
193 return this;
194}
195
196CLI11_INLINE App *App::ignore_underscore(bool value) {
197 if(value && !ignore_underscore_) {
198 ignore_underscore_ = true;
199 auto *p = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
200 const auto &match = _compare_subcommand_names(*this, *p);
201 if(!match.empty()) {
202 ignore_underscore_ = false;
203 throw OptionAlreadyAdded("ignore underscore would cause subcommand name conflicts: " + match);
204 }
205 }
206 ignore_underscore_ = value;
207 return this;
208}
209
210CLI11_INLINE Option *App::add_option(std::string option_name,
211 callback_t option_callback,
212 std::string option_description,
213 bool defaulted,
214 std::function<std::string()> func) {
215 Option myopt{option_name, option_description, option_callback, this, allow_non_standard_options_};
216
217 // do a quick search in current subcommand for options
218 auto res =
219 std::find_if(std::begin(options_), std::end(options_), [&myopt](const Option_p &v) { return *v == myopt; });
220 if(res != options_.end()) {
221 const auto &matchname = (*res)->matching_name(myopt);
222 throw(OptionAlreadyAdded("added option matched existing option name: " + matchname));
223 }
225 const App *top_level_parent = this;
226 while(top_level_parent->name_.empty() && top_level_parent->parent_ != nullptr) {
227 top_level_parent = top_level_parent->parent_;
228 }
229
230 if(myopt.lnames_.empty() && myopt.snames_.empty()) {
231 // if the option is positional only there is additional potential for ambiguities in config files and needs
232 // to be checked
233 std::string test_name = "--" + myopt.get_single_name();
234 if(test_name.size() == 3) {
235 test_name.erase(0, 1);
236 }
237 // if we are in option group
238 const auto *op = top_level_parent->get_option_no_throw(test_name);
239 if(op != nullptr && op->get_configurable()) {
240 throw(OptionAlreadyAdded("added option positional name matches existing option: " + test_name));
241 }
242 // need to check if there is another positional with the same name that also doesn't have any long or
243 // short names
244 op = top_level_parent->get_option_no_throw(myopt.get_single_name());
245 if(op != nullptr && op->lnames_.empty() && op->snames_.empty()) {
246 throw(OptionAlreadyAdded("unable to disambiguate with existing option: " + test_name));
247 }
248 } else if(top_level_parent != this) {
249 for(auto &ln : myopt.lnames_) {
250 const auto *op = top_level_parent->get_option_no_throw(ln);
251 if(op != nullptr && op->get_configurable()) {
252 throw(OptionAlreadyAdded("added option matches existing positional option: " + ln));
253 }
254 op = top_level_parent->get_option_no_throw("--" + ln);
255 if(op != nullptr && op->get_configurable()) {
256 throw(OptionAlreadyAdded("added option matches existing option: --" + ln));
257 }
258 if(ln.size() == 1 || top_level_parent->get_allow_non_standard_option_names()) {
259 op = top_level_parent->get_option_no_throw("-" + ln);
260 if(op != nullptr && op->get_configurable()) {
261 throw(OptionAlreadyAdded("added option matches existing option: -" + ln));
262 }
263 }
264 }
265 for(auto &sn : myopt.snames_) {
266 const auto *op = top_level_parent->get_option_no_throw(sn);
267 if(op != nullptr && op->get_configurable()) {
268 throw(OptionAlreadyAdded("added option matches existing positional option: " + sn));
269 }
270 op = top_level_parent->get_option_no_throw("-" + sn);
271 if(op != nullptr && op->get_configurable()) {
272 throw(OptionAlreadyAdded("added option matches existing option: -" + sn));
273 }
274 op = top_level_parent->get_option_no_throw("--" + sn);
275 if(op != nullptr && op->get_configurable()) {
276 throw(OptionAlreadyAdded("added option matches existing option: --" + sn));
277 }
278 }
279 }
280 if(allow_non_standard_options_ && !myopt.snames_.empty()) {
281
282 for(auto &sname : myopt.snames_) {
283 if(sname.length() > 1) {
284 std::string test_name;
285 test_name.push_back('-');
286 test_name.push_back(sname.front());
287 const auto *op = top_level_parent->get_option_no_throw(test_name);
288 if(op != nullptr) {
289 throw(OptionAlreadyAdded("added option interferes with existing short option: " + sname));
290 }
291 }
292 }
293 for(auto &opt : top_level_parent->get_options()) {
294 for(const auto &osn : opt->snames_) {
295 if(osn.size() > 1) {
296 std::string test_name;
297 test_name.push_back(osn.front());
298 if(myopt.check_sname(test_name)) {
299 throw(OptionAlreadyAdded("added option interferes with existing non standard option: " + osn));
300 }
301 }
302 }
303 }
304 }
305 options_.emplace_back();
306 Option_p &option = options_.back();
307 option.reset(new Option(option_name, option_description, option_callback, this, allow_non_standard_options_));
308
309 // Set the default string capture function
310 option->default_function(func);
311
312 // For compatibility with CLI11 1.7 and before, capture the default string here
313 if(defaulted)
314 option->capture_default_str();
315
316 // Transfer defaults to the new option
317 option_defaults_.copy_to(option.get());
318
319 // Don't bother to capture if we already did
320 if(!defaulted && option->get_always_capture_default())
321 option->capture_default_str();
322
323 return option.get();
324}
325
326CLI11_INLINE Option *App::add_option(std::string option_name) {
327 return add_option(option_name, CLI::callback_t{}, std::string{}, false);
328}
329
330CLI11_INLINE Option *App::set_help_flag(std::string flag_name, const std::string &help_description) {
331 // take flag_description by const reference otherwise add_flag tries to assign to help_description
332 if(help_ptr_ != nullptr) {
334 help_ptr_ = nullptr;
335 }
336
337 // Empty name will simply remove the help flag
338 if(!flag_name.empty()) {
339 help_ptr_ = add_flag(flag_name, help_description);
340 help_ptr_->configurable(false)->callback_priority(CallbackPriority::First);
341 }
342
343 return help_ptr_;
344}
345
346CLI11_INLINE Option *App::set_help_all_flag(std::string help_name, const std::string &help_description) {
347 // take flag_description by const reference otherwise add_flag tries to assign to flag_description
348 if(help_all_ptr_ != nullptr) {
350 help_all_ptr_ = nullptr;
351 }
352
353 // Empty name will simply remove the help all flag
354 if(!help_name.empty()) {
355 help_all_ptr_ = add_flag(help_name, help_description);
356 help_all_ptr_->configurable(false)->callback_priority(CallbackPriority::First);
357 }
358
359 return help_all_ptr_;
360}
361
362CLI11_INLINE Option *
363App::set_version_flag(std::string flag_name, const std::string &versionString, const std::string &version_help) {
364 // take flag_description by const reference otherwise add_flag tries to assign to version_description
365 if(version_ptr_ != nullptr) {
367 version_ptr_ = nullptr;
368 }
369
370 // Empty name will simply remove the version flag
371 if(!flag_name.empty()) {
373 flag_name, [versionString]() { throw(CLI::CallForVersion(versionString, 0)); }, version_help);
374 version_ptr_->configurable(false)->callback_priority(CallbackPriority::First);
375 }
376
377 return version_ptr_;
378}
379
380CLI11_INLINE Option *
381App::set_version_flag(std::string flag_name, std::function<std::string()> vfunc, const std::string &version_help) {
382 if(version_ptr_ != nullptr) {
384 version_ptr_ = nullptr;
385 }
386
387 // Empty name will simply remove the version flag
388 if(!flag_name.empty()) {
390 add_flag_callback(flag_name, [vfunc]() { throw(CLI::CallForVersion(vfunc(), 0)); }, version_help);
391 version_ptr_->configurable(false)->callback_priority(CallbackPriority::First);
392 }
393
394 return version_ptr_;
395}
396
397CLI11_INLINE Option *App::_add_flag_internal(std::string flag_name, CLI::callback_t fun, std::string flag_description) {
398 Option *opt = nullptr;
399 if(detail::has_default_flag_values(flag_name)) {
400 // check for default values and if it has them
401 auto flag_defaults = detail::get_default_flag_values(flag_name);
402 detail::remove_default_flag_values(flag_name);
403 opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description), false);
404 for(const auto &fname : flag_defaults)
405 opt->fnames_.push_back(fname.first);
406 opt->default_flag_values_ = std::move(flag_defaults);
407 } else {
408 opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description), false);
409 }
410 // flags cannot have positional values
411 if(opt->get_positional()) {
412 auto pos_name = opt->get_name(true);
413 remove_option(opt);
414 throw IncorrectConstruction::PositionalFlag(pos_name);
415 }
416 opt->multi_option_policy(MultiOptionPolicy::TakeLast);
417 opt->expected(0);
418 opt->required(false);
419 return opt;
420}
421
422CLI11_INLINE Option *App::add_flag(std::string flag_name) {
423 return _add_flag_internal(flag_name, CLI::callback_t(), std::string{});
424}
425
426CLI11_INLINE Option *App::add_flag_callback(std::string flag_name,
427 std::function<void(void)> function,
428 std::string flag_description) {
429
430 CLI::callback_t fun = [function](const CLI::results_t &res) {
431 using CLI::detail::lexical_cast;
432 bool trigger{false};
433 auto result = lexical_cast(res[0], trigger);
434 if(result && trigger) {
435 function();
436 }
437 return result;
438 };
439 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
440}
441
442CLI11_INLINE Option *
443App::add_flag_function(std::string flag_name,
444 std::function<void(std::int64_t)> function,
445 std::string flag_description) {
446
447 CLI::callback_t fun = [function](const CLI::results_t &res) {
448 using CLI::detail::lexical_cast;
449 std::int64_t flag_count{0};
450 lexical_cast(res[0], flag_count);
451 function(flag_count);
452 return true;
453 };
454 return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
455 ->multi_option_policy(MultiOptionPolicy::Sum);
456}
457
458CLI11_INLINE Option *App::set_config(std::string option_name,
459 std::string default_filename,
460 const std::string &help_message,
461 bool config_required) {
462
463 // Remove existing config if present
464 if(config_ptr_ != nullptr) {
466 config_ptr_ = nullptr; // need to remove the config_ptr completely
467 }
468
469 // Only add config if option passed
470 if(!option_name.empty()) {
471 config_ptr_ = add_option(option_name, help_message);
472 if(config_required) {
473 config_ptr_->required();
474 }
475 if(!default_filename.empty()) {
476 config_ptr_->default_str(std::move(default_filename));
477 config_ptr_->force_callback_ = true;
478 }
479 config_ptr_->configurable(false);
480 // set the option to take the last value and reverse given by default
481 config_ptr_->multi_option_policy(MultiOptionPolicy::Reverse);
482 }
483
484 return config_ptr_;
485}
486
487CLI11_INLINE bool App::remove_option(Option *opt) {
488 // Make sure no links exist
489 for(Option_p &op : options_) {
490 op->remove_needs(opt);
491 op->remove_excludes(opt);
492 }
493
494 if(help_ptr_ == opt)
495 help_ptr_ = nullptr;
496 if(help_all_ptr_ == opt)
497 help_all_ptr_ = nullptr;
498 if(config_ptr_ == opt)
499 config_ptr_ = nullptr;
500
501 auto iterator =
502 std::find_if(std::begin(options_), std::end(options_), [opt](const Option_p &v) { return v.get() == opt; });
503 if(iterator != std::end(options_)) {
504 options_.erase(iterator);
505 return true;
506 }
507 return false;
508}
509
510CLI11_INLINE App *App::add_subcommand(std::string subcommand_name, std::string subcommand_description) {
511 if(!subcommand_name.empty() && !detail::valid_name_string(subcommand_name)) {
512 if(!detail::valid_first_char(subcommand_name[0])) {
514 "Subcommand name starts with invalid character, '!' and '-' and control characters");
515 }
516 for(auto c : subcommand_name) {
517 if(!detail::valid_later_char(c)) {
518 throw IncorrectConstruction(std::string("Subcommand name contains invalid character ('") + c +
519 "'), all characters are allowed except"
520 "'=',':','{','}', ' ', and control characters");
521 }
522 }
523 }
524 CLI::App_p subcom = std::shared_ptr<App>(new App(std::move(subcommand_description), subcommand_name, this));
525 return add_subcommand(std::move(subcom));
526}
527
528CLI11_INLINE App *App::add_subcommand(CLI::App_p subcom) {
529 if(!subcom)
530 throw IncorrectConstruction("passed App is not valid");
531 auto *ckapp = (name_.empty() && parent_ != nullptr) ? _get_fallthrough_parent() : this;
532 const auto &mstrg = _compare_subcommand_names(*subcom, *ckapp);
533 if(!mstrg.empty()) {
534 throw(OptionAlreadyAdded("subcommand name or alias matches existing subcommand: " + mstrg));
535 }
536 subcom->parent_ = this;
537 subcommands_.push_back(std::move(subcom));
538 return subcommands_.back().get();
539}
540
541CLI11_INLINE bool App::remove_subcommand(App *subcom) {
542 // Make sure no links exist
543 for(App_p &sub : subcommands_) {
544 sub->remove_excludes(subcom);
545 sub->remove_needs(subcom);
546 }
547
548 auto iterator = std::find_if(
549 std::begin(subcommands_), std::end(subcommands_), [subcom](const App_p &v) { return v.get() == subcom; });
550 if(iterator != std::end(subcommands_)) {
551 subcommands_.erase(iterator);
552 return true;
553 }
554 return false;
555}
556
557CLI11_INLINE App *App::get_subcommand(const App *subcom) const {
558 if(subcom == nullptr)
559 throw OptionNotFound("nullptr passed");
560 for(const App_p &subcomptr : subcommands_)
561 if(subcomptr.get() == subcom)
562 return subcomptr.get();
563 throw OptionNotFound(subcom->get_name());
564}
565
566CLI11_NODISCARD CLI11_INLINE App *App::get_subcommand(std::string subcom) const {
567 auto *subc = _find_subcommand(subcom, false, false);
568 if(subc == nullptr)
569 throw OptionNotFound(subcom);
570 return subc;
571}
572
573CLI11_NODISCARD CLI11_INLINE App *App::get_subcommand_no_throw(std::string subcom) const noexcept {
574 return _find_subcommand(subcom, false, false);
575}
576
577CLI11_NODISCARD CLI11_INLINE App *App::get_subcommand(int index) const {
578 if(index >= 0) {
579 auto uindex = static_cast<unsigned>(index);
580 if(uindex < subcommands_.size())
581 return subcommands_[uindex].get();
582 }
583 throw OptionNotFound(std::to_string(index));
584}
585
586CLI11_INLINE CLI::App_p App::get_subcommand_ptr(App *subcom) const {
587 if(subcom == nullptr)
588 throw OptionNotFound("nullptr passed");
589 for(const App_p &subcomptr : subcommands_)
590 if(subcomptr.get() == subcom)
591 return subcomptr;
592 throw OptionNotFound(subcom->get_name());
593}
594
595CLI11_NODISCARD CLI11_INLINE CLI::App_p App::get_subcommand_ptr(std::string subcom) const {
596 for(const App_p &subcomptr : subcommands_)
597 if(subcomptr->check_name(subcom))
598 return subcomptr;
599 throw OptionNotFound(subcom);
600}
601
602CLI11_NODISCARD CLI11_INLINE CLI::App_p App::get_subcommand_ptr(int index) const {
603 if(index >= 0) {
604 auto uindex = static_cast<unsigned>(index);
605 if(uindex < subcommands_.size())
606 return subcommands_[uindex];
607 }
608 throw OptionNotFound(std::to_string(index));
609}
610
611CLI11_NODISCARD CLI11_INLINE CLI::App *App::get_option_group(std::string group_name) const {
612 for(const App_p &app : subcommands_) {
613 if(app->name_.empty() && app->group_ == group_name) {
614 return app.get();
615 }
616 }
617 throw OptionNotFound(group_name);
618}
619
620CLI11_NODISCARD CLI11_INLINE std::size_t App::count_all() const {
621 std::size_t cnt{0};
622 for(const auto &opt : options_) {
623 cnt += opt->count();
624 }
625 for(const auto &sub : subcommands_) {
626 cnt += sub->count_all();
627 }
628 if(!get_name().empty()) { // for named subcommands add the number of times the subcommand was called
629 cnt += parsed_;
630 }
631 return cnt;
632}
633
634CLI11_INLINE void App::clear() {
635
636 parsed_ = 0;
637 pre_parse_called_ = false;
638
639 missing_.clear();
640 parsed_subcommands_.clear();
641 parse_order_.clear();
642 for(const Option_p &opt : options_) {
643 opt->clear();
644 }
645 for(const App_p &subc : subcommands_) {
646 subc->clear();
647 }
648}
649
650CLI11_INLINE void App::parse(int argc, const char *const *argv) { parse_char_t(argc, argv); }
651CLI11_INLINE void App::parse(int argc, const wchar_t *const *argv) { parse_char_t(argc, argv); }
652
653namespace detail {
654
655// Do nothing or perform narrowing
656CLI11_INLINE const char *maybe_narrow(const char *str) { return str; }
657CLI11_INLINE std::string maybe_narrow(const wchar_t *str) { return narrow(str); }
658
659} // namespace detail
660
661template <class CharT> CLI11_INLINE void App::parse_char_t(int argc, const CharT *const *argv) {
662 // Guard against an empty (or invalid) argv; argc==0 is achievable via execve with an empty argv
663 if(argc < 1) {
664 parse(std::vector<std::string>{});
665 return;
666 }
667
668 // If the name is not set, read from command line
669 if(name_.empty() || has_automatic_name_) {
670 has_automatic_name_ = true;
671 name_ = detail::maybe_narrow(argv[0]);
672 }
673
674 std::vector<std::string> args;
675 args.reserve(static_cast<std::size_t>(argc) - 1U);
676 for(auto i = static_cast<std::size_t>(argc) - 1U; i > 0U; --i)
677 args.emplace_back(detail::maybe_narrow(argv[i]));
678
679 parse(std::move(args));
680}
681
682CLI11_INLINE void App::parse(std::string commandline, bool program_name_included) {
683
684 if(program_name_included) {
685 auto nstr = detail::split_program_name(commandline);
686 if((name_.empty()) || (has_automatic_name_)) {
687 has_automatic_name_ = true;
688 name_ = nstr.first;
689 }
690 commandline = std::move(nstr.second);
691 } else {
692 detail::trim(commandline);
693 }
694 // the next section of code is to deal with quoted arguments after an '=' or ':' for windows like operations
695 if(!commandline.empty()) {
696 commandline = detail::find_and_modify(commandline, "=", detail::escape_detect);
698 commandline = detail::find_and_modify(commandline, ":", detail::escape_detect);
699 }
700
701 auto args = detail::split_up(std::move(commandline));
702 // remove all empty strings
703 args.erase(std::remove(args.begin(), args.end(), std::string{}), args.end());
704 try {
705 detail::remove_quotes(args);
706 } catch(const std::invalid_argument &arg) {
707 throw CLI::ParseError(arg.what(), CLI::ExitCodes::InvalidError);
708 }
709 std::reverse(args.begin(), args.end());
710 parse(std::move(args));
711}
712
713CLI11_INLINE void App::parse(std::wstring commandline, bool program_name_included) {
714 parse(narrow(commandline), program_name_included);
715}
716
717CLI11_INLINE void App::_parse_setup() {
718 // Clear if parsed
719 if(parsed_ > 0)
720 clear();
721
722 // parsed_ is incremented in commands/subcommands,
723 // but placed here to make sure this is cleared when
724 // running parse after an error is thrown, even by _validate or _configure.
725 parsed_ = 1;
726 _validate();
727 _configure();
728 // set the parent as nullptr as this object should be the top now
729 parent_ = nullptr;
730 parsed_ = 0;
731}
732
733CLI11_INLINE void App::parse(std::vector<std::string> &args) {
734 _parse_setup();
735 _parse(args);
736 run_callback();
737}
738
739CLI11_INLINE void App::parse(std::vector<std::string> &&args) {
740 _parse_setup();
741 _parse(std::move(args));
742 run_callback();
743}
744
745CLI11_INLINE void App::parse_from_stream(std::istream &input) {
746 if(parsed_ == 0) {
747 _validate();
748 _configure();
749 // set the parent as nullptr as this object should be the top now
750 }
751
752 _parse_stream(input);
753 run_callback();
754}
755
756CLI11_INLINE int App::exit(const Error &e, std::ostream &out, std::ostream &err) const {
757
759 if(e.get_name() == "RuntimeError")
760 return e.get_exit_code();
762 if(e.get_name() == "CallForHelp") {
763 out << help();
764 return e.get_exit_code();
765 }
766
767 if(e.get_name() == "CallForAllHelp") {
768 out << help("", AppFormatMode::All);
769 return e.get_exit_code();
770 }
771
772 if(e.get_name() == "CallForVersion") {
773 out << e.what() << '\n';
774 return e.get_exit_code();
775 }
776
777 if(e.get_exit_code() != static_cast<int>(ExitCodes::Success)) {
779 err << failure_message_(this, e) << std::flush;
780 }
781
782 return e.get_exit_code();
783}
784
785CLI11_INLINE int App::exit(const Error &e) const { return exit(e, std::cout, std::cerr); }
786
787CLI11_INLINE int App::exit(const Error &e, std::ostream &out) const { return exit(e, out, std::cerr); }
788
789CLI11_INLINE std::vector<const App *> App::get_subcommands(const std::function<bool(const App *)> &filter) const {
790 std::vector<const App *> subcomms(subcommands_.size());
791 std::transform(
792 std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](const App_p &v) { return v.get(); });
793
794 if(filter) {
795 subcomms.erase(std::remove_if(std::begin(subcomms),
796 std::end(subcomms),
797 [&filter](const App *app) { return !filter(app); }),
798 std::end(subcomms));
799 }
800
801 return subcomms;
802}
803
804CLI11_INLINE std::vector<App *> App::get_subcommands(const std::function<bool(App *)> &filter) {
805 std::vector<App *> subcomms(subcommands_.size());
806 std::transform(
807 std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](const App_p &v) { return v.get(); });
808
809 if(filter) {
810 subcomms.erase(
811 std::remove_if(std::begin(subcomms), std::end(subcomms), [&filter](App *app) { return !filter(app); }),
812 std::end(subcomms));
813 }
814
815 return subcomms;
816}
817
818CLI11_INLINE App *App::require_subcommand(int value) {
819 if(value < 0) {
821 require_subcommand_max_ = static_cast<std::size_t>(-value);
822 } else {
823 require_subcommand_min_ = static_cast<std::size_t>(value);
824 require_subcommand_max_ = static_cast<std::size_t>(value);
825 }
826 return this;
827}
828
829CLI11_INLINE App *App::require_option(int value) {
830 if(value < 0) {
832 require_option_max_ = static_cast<std::size_t>(-value);
833 } else {
834 require_option_min_ = static_cast<std::size_t>(value);
835 require_option_max_ = static_cast<std::size_t>(value);
836 }
837 return this;
838}
839
840CLI11_INLINE bool App::got_subcommand(const App *subcom) const {
841 // get subcom needed to verify that this was a real subcommand
842 return get_subcommand(subcom)->parsed_ > 0;
843}
844
845CLI11_NODISCARD CLI11_INLINE bool App::got_subcommand(std::string subcommand_name) const noexcept {
846 App *sub = get_subcommand_no_throw(subcommand_name);
847 return (sub != nullptr) ? (sub->parsed_ > 0) : false;
848}
849
850CLI11_INLINE App *App::excludes(Option *opt) {
851 if(opt == nullptr) {
852 throw OptionNotFound("nullptr passed");
853 }
854 exclude_options_.insert(opt);
855 return this;
856}
857
858CLI11_INLINE App *App::excludes(App *app) {
859 if(app == nullptr) {
860 throw OptionNotFound("nullptr passed");
861 }
862 if(app == this) {
863 throw OptionNotFound("cannot self reference in excludes");
864 }
865 auto res = exclude_subcommands_.insert(app);
866 // subcommand exclusion should be symmetric
867 if(res.second) {
868 app->exclude_subcommands_.insert(this);
869 }
870 return this;
871}
872
873CLI11_INLINE App *App::needs(Option *opt) {
874 if(opt == nullptr) {
875 throw OptionNotFound("nullptr passed");
876 }
877 need_options_.insert(opt);
878 return this;
879}
880
881CLI11_INLINE App *App::needs(App *app) {
882 if(app == nullptr) {
883 throw OptionNotFound("nullptr passed");
884 }
885 if(app == this) {
886 throw OptionNotFound("cannot self reference in needs");
887 }
888 need_subcommands_.insert(app);
889 return this;
890}
891
892CLI11_INLINE bool App::remove_excludes(Option *opt) {
893 auto iterator = std::find(std::begin(exclude_options_), std::end(exclude_options_), opt);
894 if(iterator == std::end(exclude_options_)) {
895 return false;
896 }
897 exclude_options_.erase(iterator);
898 return true;
899}
900
901CLI11_INLINE bool App::remove_excludes(App *app) {
902 auto iterator = std::find(std::begin(exclude_subcommands_), std::end(exclude_subcommands_), app);
903 if(iterator == std::end(exclude_subcommands_)) {
904 return false;
905 }
906 auto *other_app = *iterator;
907 exclude_subcommands_.erase(iterator);
908 other_app->remove_excludes(this);
909 return true;
910}
911
912CLI11_INLINE bool App::remove_needs(Option *opt) {
913 auto iterator = std::find(std::begin(need_options_), std::end(need_options_), opt);
914 if(iterator == std::end(need_options_)) {
915 return false;
916 }
917 need_options_.erase(iterator);
918 return true;
919}
920
921CLI11_INLINE bool App::remove_needs(App *app) {
922 auto iterator = std::find(std::begin(need_subcommands_), std::end(need_subcommands_), app);
923 if(iterator == std::end(need_subcommands_)) {
924 return false;
925 }
926 need_subcommands_.erase(iterator);
927 return true;
928}
929
930CLI11_NODISCARD CLI11_INLINE std::string App::config_to_str() const {
931 return config_to_str(ConfigOutputMode::Active, false);
932}
933
934CLI11_NODISCARD CLI11_INLINE std::string App::config_to_str(ConfigOutputMode mode, bool write_description) const {
935 return config_formatter_->to_config(this, mode, write_description, "");
936}
937
938CLI11_NODISCARD CLI11_INLINE std::string App::config_to_str(bool default_also, bool write_description) const {
939 return config_to_str(default_also ? ConfigOutputMode::AllDefaults : ConfigOutputMode::Active, write_description);
940}
941
942CLI11_NODISCARD CLI11_INLINE std::string App::get_usage() const {
943 return (usage_callback_) ? usage_callback_() + '\n' + usage_ : usage_;
944}
945
946CLI11_NODISCARD CLI11_INLINE std::string App::get_footer() const {
947 return (footer_callback_) ? footer_callback_() + '\n' + footer_ : footer_;
948}
949
950CLI11_NODISCARD CLI11_INLINE std::string App::help(std::string prev, AppFormatMode mode) const {
951 if(prev.empty())
952 prev = get_name();
953 else
954 prev += " " + get_name();
955
956 // Delegate to subcommand if needed
957 auto selected_subcommands = get_subcommands();
958 if(!selected_subcommands.empty()) {
959 return selected_subcommands.back()->help(prev, mode);
960 }
961 return formatter_->make_help(this, prev, mode);
962}
963
964CLI11_NODISCARD CLI11_INLINE std::string App::version() const {
965 std::string val;
966 if(version_ptr_ != nullptr) {
967 // copy the results for reuse later
968 results_t rv = version_ptr_->results();
969 version_ptr_->clear();
970 version_ptr_->add_result("true");
971 try {
972 version_ptr_->run_callback();
973 } catch(const CLI::CallForVersion &cfv) {
974 val = cfv.what();
975 }
976 version_ptr_->clear();
977 version_ptr_->add_result(rv);
978 }
979 return val;
980}
981
982CLI11_INLINE std::vector<const Option *> App::get_options(const std::function<bool(const Option *)> filter) const {
983 std::vector<const Option *> options(options_.size());
984 std::transform(
985 std::begin(options_), std::end(options_), std::begin(options), [](const Option_p &val) { return val.get(); });
986
987 if(filter) {
988 options.erase(std::remove_if(std::begin(options),
989 std::end(options),
990 [&filter](const Option *opt) { return !filter(opt); }),
991 std::end(options));
992 }
993 for(const auto &subcp : subcommands_) {
994 // also check down into nameless subcommands
995 const App *subc = subcp.get();
996 if(subc->get_name().empty() && !subc->get_group().empty() && subc->get_group().front() == '+') {
997 std::vector<const Option *> subcopts = subc->get_options(filter);
998 options.insert(options.end(), subcopts.begin(), subcopts.end());
999 }
1000 }
1001 if(fallthrough_ && parent_ != nullptr && !name_.empty()) {
1002 const auto *fallthrough_parent = _get_fallthrough_parent();
1003 std::vector<const Option *> subcopts = fallthrough_parent->get_options(filter);
1004 for(const auto *opt : subcopts) {
1005 if(std::find_if(options.begin(), options.end(), [opt](const Option *opt2) {
1006 return opt->check_name(opt2->get_name());
1007 }) == options.end()) {
1008 options.push_back(opt);
1009 }
1010 }
1011 }
1012 return options;
1013}
1014
1015CLI11_INLINE std::vector<Option *> App::get_options(const std::function<bool(Option *)> filter) {
1016 std::vector<Option *> options(options_.size());
1017 std::transform(
1018 std::begin(options_), std::end(options_), std::begin(options), [](const Option_p &val) { return val.get(); });
1019
1020 if(filter) {
1021 options.erase(
1022 std::remove_if(std::begin(options), std::end(options), [&filter](Option *opt) { return !filter(opt); }),
1023 std::end(options));
1024 }
1025 for(auto &subc : subcommands_) {
1026 // purposely differs from the const overload: help formatting (const) only merges '+' groups, while
1027 // config generation (this overload) must mirror the parser and descend into every nameless subcommand
1028 if(subc->get_name().empty() || (!subc->get_group().empty() && subc->get_group().front() == '+')) {
1029 auto subcopts = subc->get_options(filter);
1030 options.insert(options.end(), subcopts.begin(), subcopts.end());
1031 }
1032 }
1033 if(fallthrough_ && parent_ != nullptr && !name_.empty()) {
1034 auto *fallthrough_parent = _get_fallthrough_parent();
1035 std::vector<Option *> subcopts = fallthrough_parent->get_options(filter);
1036 for(auto *opt : subcopts) {
1037 if(std::find_if(options.begin(), options.end(), [opt](Option *opt2) {
1038 return opt->check_name(opt2->get_name());
1039 }) == options.end()) {
1040 options.push_back(opt);
1041 }
1042 }
1043 }
1044 return options;
1045}
1046
1048CLI11_NODISCARD CLI11_INLINE const Option *App::get_option(std::string option_name) const {
1049 const auto *opt = get_option_no_throw(option_name);
1050 if(opt == nullptr) {
1051 if(fallthrough_ && parent_ != nullptr && name_.empty()) {
1052 // as a special case option groups with fallthrough enabled can also check the parent for options if the
1053 // option is not found in the group this will not recurse as the internal call is to the no_throw version
1054 // which will not check the parent again for option groups even with fallthrough enabled
1055 return _get_fallthrough_parent()->get_option(option_name);
1056 }
1057 throw OptionNotFound(option_name);
1058 }
1059 return opt;
1060}
1061
1063CLI11_NODISCARD CLI11_INLINE Option *App::get_option(std::string option_name) {
1064 auto *opt = get_option_no_throw(option_name);
1065 if(opt == nullptr) {
1066 if(fallthrough_ && parent_ != nullptr && name_.empty()) {
1067 // as a special case option groups with fallthrough enabled can also check the parent for options if the
1068 // option is not found in the group this will not recurse as the internal call is to the no_throw version
1069 // which will not check the parent again for option groups even with fallthrough enabled
1070 return _get_fallthrough_parent()->get_option(option_name);
1071 }
1072 throw OptionNotFound(option_name);
1073 }
1074 return opt;
1075}
1076
1077CLI11_NODISCARD CLI11_INLINE Option *App::get_option_no_throw(std::string option_name) noexcept {
1078 for(Option_p &opt : options_) {
1079 if(opt->check_name(option_name)) {
1080 return opt.get();
1081 }
1082 }
1083 for(auto &subc : subcommands_) {
1084 // also check down into nameless subcommands
1085 if(subc->get_name().empty()) {
1086 auto *opt = subc->get_option_no_throw(option_name);
1087 if(opt != nullptr) {
1088 return opt;
1089 }
1090 }
1091 }
1092 if(fallthrough_ && parent_ != nullptr && !name_.empty()) {
1093 // if there is fallthrough and a parent and this is not an option_group then also check the parent for the
1094 // option
1095 return _get_fallthrough_parent()->get_option_no_throw(option_name);
1096 }
1097 return nullptr;
1098}
1099
1100CLI11_NODISCARD CLI11_INLINE const Option *App::get_option_no_throw(std::string option_name) const noexcept {
1101 for(const Option_p &opt : options_) {
1102 if(opt->check_name(option_name)) {
1103 return opt.get();
1104 }
1105 }
1106 for(const auto &subc : subcommands_) {
1107 // also check down into nameless subcommands
1108 if(subc->get_name().empty()) {
1109 auto *opt = subc->get_option_no_throw(option_name);
1110 if(opt != nullptr) {
1111 return opt;
1112 }
1113 }
1114 }
1115 if(fallthrough_ && parent_ != nullptr && !name_.empty()) {
1116 return _get_fallthrough_parent()->get_option_no_throw(option_name);
1117 }
1118 return nullptr;
1119}
1120
1121CLI11_NODISCARD CLI11_INLINE std::string App::get_display_name(bool with_aliases) const {
1122 if(name_.empty()) {
1123 return std::string("[Option Group: ") + get_group() + "]";
1124 }
1125 if(aliases_.empty() || !with_aliases) {
1126 return name_;
1127 }
1128 std::string dispname = name_;
1129 for(const auto &lalias : aliases_) {
1130 dispname.push_back(',');
1131 dispname.push_back(' ');
1132 dispname.append(lalias);
1133 }
1134 return dispname;
1135}
1136
1137CLI11_NODISCARD CLI11_INLINE bool App::check_name(std::string name_to_check) const {
1138 auto result = check_name_detail(std::move(name_to_check));
1139 return (result != NameMatch::none);
1140}
1141
1142CLI11_NODISCARD CLI11_INLINE App::NameMatch App::check_name_detail(std::string name_to_check) const {
1143 std::string local_name = name_;
1144 if(ignore_underscore_) {
1145 local_name = detail::remove_underscore(name_);
1146 name_to_check = detail::remove_underscore(name_to_check);
1147 }
1148 if(ignore_case_) {
1149 local_name = detail::to_lower(local_name);
1150 name_to_check = detail::to_lower(name_to_check);
1151 }
1152
1153 if(local_name == name_to_check) {
1154 return App::NameMatch::exact;
1155 }
1156 if(allow_prefix_matching_ && name_to_check.size() < local_name.size()) {
1157 if(local_name.compare(0, name_to_check.size(), name_to_check) == 0) {
1158 return App::NameMatch::prefix;
1159 }
1160 }
1161 for(std::string les : aliases_) { // NOLINT(performance-for-range-copy)
1162 if(ignore_underscore_) {
1163 les = detail::remove_underscore(les);
1164 }
1165 if(ignore_case_) {
1166 les = detail::to_lower(les);
1167 }
1168 if(les == name_to_check) {
1169 return App::NameMatch::exact;
1170 }
1171 if(allow_prefix_matching_ && name_to_check.size() < les.size()) {
1172 if(les.compare(0, name_to_check.size(), name_to_check) == 0) {
1173 return App::NameMatch::prefix;
1174 }
1175 }
1176 }
1177 return App::NameMatch::none;
1178}
1179
1180CLI11_NODISCARD CLI11_INLINE std::vector<std::string> App::get_groups() const {
1181 std::vector<std::string> groups;
1182
1183 for(const Option_p &opt : options_) {
1184 // Add group if it is not already in there
1185 if(std::find(groups.begin(), groups.end(), opt->get_group()) == groups.end()) {
1186 groups.push_back(opt->get_group());
1187 }
1188 }
1189
1190 return groups;
1191}
1192
1193CLI11_NODISCARD CLI11_INLINE std::vector<std::string> App::remaining(bool recurse) const {
1194 std::vector<std::string> miss_list;
1195 for(const std::pair<detail::Classifier, std::string> &miss : missing_) {
1196 miss_list.push_back(std::get<1>(miss));
1197 }
1198 // Get from a subcommand that may allow extras
1199 if(recurse) {
1200 if(allow_extras_ == ExtrasMode::Error || allow_extras_ == ExtrasMode::Ignore) {
1201 for(const auto &sub : subcommands_) {
1202 if(sub->name_.empty() && !sub->missing_.empty()) {
1203 for(const std::pair<detail::Classifier, std::string> &miss : sub->missing_) {
1204 miss_list.push_back(std::get<1>(miss));
1205 }
1206 }
1207 }
1208 }
1209 // Recurse into subcommands
1210
1211 for(const App *sub : parsed_subcommands_) {
1212 std::vector<std::string> output = sub->remaining(recurse);
1213 std::copy(std::begin(output), std::end(output), std::back_inserter(miss_list));
1214 }
1215 }
1216 return miss_list;
1217}
1218
1219CLI11_NODISCARD CLI11_INLINE std::vector<std::string> App::remaining_for_passthrough(bool recurse) const {
1220 std::vector<std::string> miss_list = remaining(recurse);
1221 std::reverse(std::begin(miss_list), std::end(miss_list));
1222 return miss_list;
1223}
1224
1225CLI11_NODISCARD CLI11_INLINE std::size_t App::remaining_size(bool recurse) const {
1226 auto remaining_options = static_cast<std::size_t>(std::count_if(
1227 std::begin(missing_), std::end(missing_), [](const std::pair<detail::Classifier, std::string> &val) {
1228 return val.first != detail::Classifier::POSITIONAL_MARK;
1229 }));
1230
1231 if(recurse) {
1232 for(const App_p &sub : subcommands_) {
1233 remaining_options += sub->remaining_size(recurse);
1234 }
1235 }
1236 return remaining_options;
1237}
1238
1239CLI11_INLINE void App::_validate() const {
1240 // count the number of positional only args
1241 auto pcount = std::count_if(std::begin(options_), std::end(options_), [](const Option_p &opt) {
1242 return opt->get_items_expected_max() >= detail::expected_max_vector_size && !opt->nonpositional();
1243 });
1244 if(pcount > 1) {
1245 auto pcount_req = std::count_if(std::begin(options_), std::end(options_), [](const Option_p &opt) {
1246 return opt->get_items_expected_max() >= detail::expected_max_vector_size && !opt->nonpositional() &&
1247 opt->get_required();
1248 });
1249 if(pcount - pcount_req > 1) {
1250 throw InvalidError(name_);
1251 }
1252 }
1253
1254 std::size_t nameless_subs{0};
1255 for(const App_p &app : subcommands_) {
1256 app->_validate();
1257 if(app->get_name().empty())
1258 ++nameless_subs;
1259 }
1260
1261 if(require_option_min_ > 0) {
1262 if(require_option_max_ > 0) {
1264 throw(InvalidError("Required min options greater than required max options", ExitCodes::InvalidError));
1265 }
1266 }
1267 if(require_option_min_ > (options_.size() + nameless_subs)) {
1268 throw(
1269 InvalidError("Required min options greater than number of available options", ExitCodes::InvalidError));
1270 }
1271 }
1272}
1273
1274CLI11_INLINE void App::_configure() {
1275 if(default_startup == startup_mode::enabled) {
1276 disabled_ = false;
1277 } else if(default_startup == startup_mode::disabled) {
1278 disabled_ = true;
1279 }
1280 for(const App_p &app : subcommands_) {
1281 if(app->has_automatic_name_) {
1282 app->name_.clear();
1283 }
1284 if(app->name_.empty()) {
1285 app->fallthrough_ = false; // make sure fallthrough_ is false to prevent infinite loop
1286 app->prefix_command_ = PrefixCommandMode::Off;
1287 }
1288 // make sure the parent is set to be this object in preparation for parse
1289 app->parent_ = this;
1290 app->_configure();
1291 }
1292}
1293
1294CLI11_INLINE void App::run_callback(bool final_mode, bool suppress_final_callback) {
1295 pre_callback();
1296 // in the main app if immediate_callback_ is set it runs the main callback before the used subcommands
1297 if(!final_mode && parse_complete_callback_) {
1299 }
1300 // run the callbacks for the received subcommands
1301 for(App *subc : get_subcommands()) {
1302 if(subc->parent_ == this) {
1303 subc->run_callback(true, suppress_final_callback);
1304 }
1305 }
1306 // now run callbacks for option_groups
1307 for(auto &subc : subcommands_) {
1308 if(subc->name_.empty() && subc->count_all() > 0) {
1309 subc->run_callback(true, suppress_final_callback);
1310 }
1311 }
1312
1313 // finally run the main callback
1314 if(final_callback_ && (parsed_ > 0) && (!suppress_final_callback)) {
1315 if(!name_.empty() || count_all() > 0 || parent_ == nullptr) {
1317 }
1318 }
1319}
1320
1321CLI11_NODISCARD CLI11_INLINE bool App::_valid_subcommand(const std::string &current, bool ignore_used) const {
1322 // Don't match if max has been reached - but still check parents (only when fallthrough is enabled)
1324 return subcommand_fallthrough_ && parent_ != nullptr && parent_->_valid_subcommand(current, ignore_used);
1325 }
1326 auto *com = _find_subcommand(current, true, ignore_used);
1327 if(com != nullptr) {
1328 return true;
1329 }
1330 // Check parent if exists, else return false
1332 return parent_ != nullptr && parent_->_valid_subcommand(current, ignore_used);
1333 }
1334 return false;
1335}
1336
1337CLI11_NODISCARD CLI11_INLINE detail::Classifier App::_recognize(const std::string &current,
1338 bool ignore_used_subcommands) const {
1339 std::string dummy1, dummy2;
1340
1341 if(current == "--")
1342 return detail::Classifier::POSITIONAL_MARK;
1343 if(_valid_subcommand(current, ignore_used_subcommands))
1344 return detail::Classifier::SUBCOMMAND;
1345 if(detail::split_long(current, dummy1, dummy2))
1346 return detail::Classifier::LONG;
1347 if(detail::split_short(current, dummy1, dummy2)) {
1348 if((dummy1[0] >= '0' && dummy1[0] <= '9') ||
1349 (dummy1[0] == '.' && !dummy2.empty() && (dummy2[0] >= '0' && dummy2[0] <= '9'))) {
1350 // it looks like a number but check if it could be an option
1351 if(get_option_no_throw(std::string{'-', dummy1[0]}) == nullptr) {
1352 return detail::Classifier::NONE;
1353 }
1354 }
1355 return detail::Classifier::SHORT;
1356 }
1357 if((allow_windows_style_options_) && (detail::split_windows_style(current, dummy1, dummy2)))
1358 return detail::Classifier::WINDOWS_STYLE;
1359 if((current == "++") && !name_.empty() && parent_ != nullptr)
1360 return detail::Classifier::SUBCOMMAND_TERMINATOR;
1361 auto dotloc = current.find_first_of('.');
1362 if(dotloc != std::string::npos) {
1363 auto *cm = _find_subcommand(current.substr(0, dotloc), true, ignore_used_subcommands);
1364 if(cm != nullptr) {
1365 auto res = cm->_recognize(current.substr(dotloc + 1), ignore_used_subcommands);
1366 if(res == detail::Classifier::SUBCOMMAND) {
1367 return res;
1368 }
1369 }
1370 }
1371 return detail::Classifier::NONE;
1372}
1373
1374CLI11_INLINE bool App::_process_config_file(const std::string &config_file, bool throw_error) {
1375 auto path_result = detail::check_path(config_file.c_str());
1376 if(path_result == detail::path_type::file) {
1377 try {
1378 std::vector<ConfigItem> values = config_formatter_->from_file(config_file);
1379 _parse_config(values);
1380 return true;
1381 } catch(const FileError &) {
1382 if(throw_error) {
1383 throw;
1384 }
1385 return false;
1386 }
1387 } else if(throw_error) {
1388 throw FileError::Missing(config_file);
1389 } else {
1390 return false;
1391 }
1392}
1393
1394CLI11_INLINE void App::_process_config_file() {
1395 if(config_ptr_ != nullptr) {
1396 bool config_required = config_ptr_->get_required();
1397 auto file_given = config_ptr_->count() > 0;
1398 if(!(file_given || config_ptr_->envname_.empty())) {
1399 std::string ename_string = detail::get_environment_value(config_ptr_->envname_);
1400 if(!ename_string.empty()) {
1401 config_ptr_->add_result(ename_string);
1402 }
1403 }
1404 config_ptr_->run_callback();
1405
1406 auto config_files = config_ptr_->as<std::vector<std::string>>();
1407 bool files_used{file_given};
1408 if(config_files.empty() || config_files.front().empty()) {
1409 if(config_required) {
1410 throw FileError("config file is required but none was given");
1411 }
1412 return;
1413 }
1414 for(const auto &config_file : config_files) {
1415 if(_process_config_file(config_file, config_required || file_given)) {
1416 files_used = true;
1417 }
1418 }
1419 if(!files_used) {
1420 // this is done so the count shows as 0 if no callbacks were processed
1421 config_ptr_->clear();
1422 bool force = config_ptr_->force_callback_;
1423 config_ptr_->force_callback_ = false;
1424 config_ptr_->run_callback();
1425 config_ptr_->force_callback_ = force;
1426 }
1427 }
1428}
1429
1430CLI11_INLINE void App::_process_env() {
1431 for(const Option_p &opt : options_) {
1432 if(opt->count() == 0 && !opt->envname_.empty()) {
1433 std::string ename_string = detail::get_environment_value(opt->envname_);
1434 if(!ename_string.empty()) {
1435 std::string result = ename_string;
1436 result = opt->_validate(result, 0);
1437 if(result.empty()) {
1438 opt->add_result(ename_string);
1439 }
1440 }
1441 }
1442 }
1443
1444 for(App_p &sub : subcommands_) {
1445 if(sub->get_name().empty() || (sub->count_all() > 0 && !sub->parse_complete_callback_)) {
1446 // only process environment variables if the callback has actually been triggered already
1447 sub->_process_env();
1448 }
1449 }
1450}
1451
1452CLI11_INLINE void App::_process_callbacks(CallbackPriority priority) {
1453
1454 for(App_p &sub : subcommands_) {
1455 // process the priority option_groups first
1456 if(sub->get_name().empty() && sub->parse_complete_callback_) {
1457 if(sub->count_all() > 0) {
1458 sub->_process_callbacks(priority);
1459 if(priority == CallbackPriority::Normal) {
1460 // only run the subcommand callback at normal priority
1461 sub->run_callback();
1462 }
1463 }
1464 }
1465 }
1466
1467 for(const Option_p &opt : options_) {
1468 if(opt->get_callback_priority() == priority) {
1469 if((*opt) && !opt->get_callback_run()) {
1470 opt->run_callback();
1471 }
1472 }
1473 }
1474 for(App_p &sub : subcommands_) {
1475 if(!sub->parse_complete_callback_) {
1476 sub->_process_callbacks(priority);
1477 }
1478 }
1479}
1480
1481CLI11_INLINE void App::_process_help_flags(CallbackPriority priority, bool trigger_help, bool trigger_all_help) const {
1482 const Option *help_ptr = get_help_ptr();
1483 const Option *help_all_ptr = get_help_all_ptr();
1484
1485 if(help_ptr != nullptr && help_ptr->count() > 0 && help_ptr->get_callback_priority() == priority) {
1486 trigger_help = true;
1487 }
1488 if(help_all_ptr != nullptr && help_all_ptr->count() > 0 && help_all_ptr->get_callback_priority() == priority) {
1489 trigger_all_help = true;
1490 }
1491
1492 // If there were parsed subcommands, call those. First subcommand wins if there are multiple ones.
1493 if(!parsed_subcommands_.empty()) {
1494 for(const App *sub : parsed_subcommands_) {
1495 sub->_process_help_flags(priority, trigger_help, trigger_all_help);
1496 }
1497
1498 // Only the final subcommand should call for help. All help wins over help.
1499 } else if(trigger_all_help) {
1500 throw CallForAllHelp();
1501 } else if(trigger_help) {
1502 throw CallForHelp();
1503 }
1504}
1505
1506CLI11_INLINE void App::_process_requirements() {
1507 // check excludes
1508 bool excluded{false};
1509 std::string excluder;
1510 for(const auto &opt : exclude_options_) {
1511 if(opt->count() > 0) {
1512 excluded = true;
1513 excluder = opt->get_name();
1514 }
1515 }
1516 for(const auto &subc : exclude_subcommands_) {
1517 if(subc->count_all() > 0) {
1518 excluded = true;
1519 excluder = subc->get_display_name();
1520 }
1521 }
1522 if(excluded) {
1523 if(count_all() > 0) {
1524 throw ExcludesError(get_display_name(), excluder);
1525 }
1526 // if we are excluded but didn't receive anything, just return
1527 return;
1528 }
1529
1530 // check excludes
1531 bool missing_needed{false};
1532 std::string missing_need;
1533 for(const auto &opt : need_options_) {
1534 if(opt->count() == 0) {
1535 missing_needed = true;
1536 missing_need = opt->get_name();
1537 }
1538 }
1539 for(const auto &subc : need_subcommands_) {
1540 if(subc->count_all() == 0) {
1541 missing_needed = true;
1542 missing_need = subc->get_display_name();
1543 }
1544 }
1545 if(missing_needed) {
1546 if(count_all() > 0) {
1547 throw RequiresError(get_display_name(), missing_need);
1548 }
1549 // if we missing something but didn't have any options, just return
1550 return;
1551 }
1552
1553 std::size_t used_options = 0;
1554 for(const Option_p &opt : options_) {
1555
1556 if(opt->count() != 0) {
1557 ++used_options;
1558 }
1559 // Required but empty
1560 if(opt->get_required() && opt->count() == 0) {
1561 throw RequiredError(opt->get_name());
1562 }
1563 // Requires
1564 for(const Option *opt_req : opt->needs_)
1565 if(opt->count() > 0 && opt_req->count() == 0)
1566 throw RequiresError(opt->get_name(), opt_req->get_name());
1567 // Excludes
1568 for(const Option *opt_ex : opt->excludes_)
1569 if(opt->count() > 0 && opt_ex->count() != 0)
1570 throw ExcludesError(opt->get_name(), opt_ex->get_name());
1571 }
1572 // check for the required number of subcommands
1573 if(require_subcommand_min_ > 0) {
1574 auto selected_subcommands = get_subcommands();
1575 if(require_subcommand_min_ > selected_subcommands.size())
1576 throw RequiredError::Subcommand(require_subcommand_min_);
1577 }
1578
1579 // Max error cannot occur, the extra subcommand will parse as an ExtrasError or a remaining item.
1580
1581 // run this loop to check how many unnamed subcommands were actually used since they are considered options
1582 // from the perspective of an App
1583 for(App_p &sub : subcommands_) {
1584 if(sub->disabled_)
1585 continue;
1586 if(sub->name_.empty() && sub->count_all() > 0) {
1587 ++used_options;
1588 }
1589 }
1590
1591 if(require_option_min_ > used_options || (require_option_max_ > 0 && require_option_max_ < used_options)) {
1592 auto option_list = detail::join(options_, [this](const Option_p &ptr) {
1593 if(ptr.get() == help_ptr_ || ptr.get() == help_all_ptr_) {
1594 return std::string{};
1595 }
1596 return ptr->get_name(false, true);
1597 });
1598
1599 auto subc_list = get_subcommands([](App *app) { return ((app->get_name().empty()) && (!app->disabled_)); });
1600 if(!subc_list.empty()) {
1601 option_list += "," + detail::join(subc_list, [](const App *app) { return app->get_display_name(); });
1602 }
1603 throw RequiredError::Option(require_option_min_, require_option_max_, used_options, option_list);
1604 }
1605
1606 // now process the requirements for subcommands if needed
1607 for(App_p &sub : subcommands_) {
1608 if(sub->disabled_)
1609 continue;
1610 if(sub->name_.empty() && sub->required_ == false) {
1611 if(sub->count_all() == 0) {
1612 if(require_option_min_ > 0 && require_option_min_ <= used_options) {
1613 continue;
1614 // if we have met the requirement and there is nothing in this option group skip checking
1615 // requirements
1616 }
1617 if(require_option_max_ > 0 && used_options >= require_option_min_) {
1618 continue;
1619 // if we have met the requirement and there is nothing in this option group skip checking
1620 // requirements
1621 }
1622 }
1623 }
1624 if(sub->count() > 0 || sub->name_.empty()) {
1625 sub->_process_requirements();
1626 }
1627
1628 if(sub->required_ && sub->count_all() == 0) {
1629 throw(CLI::RequiredError(sub->get_display_name()));
1630 }
1631 }
1632}
1633
1634CLI11_INLINE void App::_process() {
1635 // help takes precedence over other potential errors and config and environment shouldn't be processed if help
1636 // throws
1637 _process_callbacks(CallbackPriority::FirstPreHelp);
1638 _process_help_flags(CallbackPriority::First);
1639 _process_callbacks(CallbackPriority::First);
1640
1641 std::exception_ptr config_exception;
1642 try {
1643 // the config file might generate a FileError but that should not be processed until later in the process
1644 // to allow for help, version and other errors to generate first.
1646
1647 // process env shouldn't throw but no reason to process it if config generated an error
1648 _process_env();
1649 } catch(const CLI::FileError &) {
1650 config_exception = std::current_exception();
1651 }
1652 // callbacks and requirements processing can generate exceptions which should take priority
1653 // over the config file error if one exists.
1654 _process_callbacks(CallbackPriority::PreRequirementsCheckPreHelp);
1655 _process_help_flags(CallbackPriority::PreRequirementsCheck);
1656 _process_callbacks(CallbackPriority::PreRequirementsCheck);
1657
1659
1660 _process_callbacks(CallbackPriority::NormalPreHelp);
1661 _process_help_flags(CallbackPriority::Normal);
1662 _process_callbacks(CallbackPriority::Normal);
1663
1664 if(config_exception) {
1665 std::rethrow_exception(config_exception);
1666 }
1667
1668 _process_callbacks(CallbackPriority::LastPreHelp);
1669 _process_help_flags(CallbackPriority::Last);
1670 _process_callbacks(CallbackPriority::Last);
1671}
1672
1673CLI11_INLINE void App::_process_extras() {
1674 if(allow_extras_ == ExtrasMode::Error && prefix_command_ == PrefixCommandMode::Off) {
1675 if(remaining_size() > 0) {
1676 throw ExtrasError(name_, remaining(false));
1677 }
1678 }
1679 if(allow_extras_ == ExtrasMode::Error && prefix_command_ == PrefixCommandMode::SeparatorOnly) {
1680 if(remaining_size() > 0) {
1681 auto rem = remaining(false);
1682 if(rem.front() != "--") {
1683 throw ExtrasError(name_, std::move(rem));
1684 }
1685 }
1686 }
1687 for(App_p &sub : subcommands_) {
1688 if(sub->count() > 0)
1689 sub->_process_extras();
1690 }
1691}
1692
1693CLI11_INLINE void App::increment_parsed() {
1694 ++parsed_;
1695 for(App_p &sub : subcommands_) {
1696 if(sub->get_name().empty())
1697 sub->increment_parsed();
1698 }
1699}
1700
1701CLI11_INLINE void App::_process_completion_callbacks(bool with_help_flags) {
1702 _process_callbacks(CallbackPriority::FirstPreHelp);
1703 if(with_help_flags) {
1704 _process_help_flags(CallbackPriority::First);
1705 }
1706 _process_callbacks(CallbackPriority::First);
1707 if(with_help_flags) {
1708 _process_env();
1709 }
1710 _process_callbacks(CallbackPriority::PreRequirementsCheckPreHelp);
1711 if(with_help_flags) {
1712 _process_help_flags(CallbackPriority::PreRequirementsCheck);
1713 }
1714 _process_callbacks(CallbackPriority::PreRequirementsCheck);
1716 _process_callbacks(CallbackPriority::NormalPreHelp);
1717 if(with_help_flags) {
1718 _process_help_flags(CallbackPriority::Normal);
1719 }
1720 _process_callbacks(CallbackPriority::Normal);
1721 _process_callbacks(CallbackPriority::LastPreHelp);
1722 if(with_help_flags) {
1723 _process_help_flags(CallbackPriority::Last);
1724 }
1725 _process_callbacks(CallbackPriority::Last);
1726 run_callback(false, with_help_flags);
1727}
1728
1729CLI11_INLINE void App::_parse(std::vector<std::string> &args) {
1731 _trigger_pre_parse(args.size());
1732 bool positional_only = false;
1733
1734 while(!args.empty()) {
1735 if(!_parse_single(args, positional_only)) {
1736 break;
1737 }
1738 }
1739
1740 if(parent_ == nullptr) {
1741 _process();
1742
1743 // Throw error if any items are left over (depending on settings)
1745 // Convert missing (pairs) to extras (string only) ready for processing in another app
1746 args = remaining_for_passthrough(false);
1747 } else if(parse_complete_callback_) {
1749 }
1750}
1751
1752CLI11_INLINE void App::_parse(std::vector<std::string> &&args) {
1753 // this can only be called by the top level in which case parent == nullptr by definition
1754 // operation is simplified
1756 _trigger_pre_parse(args.size());
1757 bool positional_only = false;
1758
1759 while(!args.empty()) {
1760 if(!_parse_single(args, positional_only)) {
1761 break; // LCOV_EXCL_LINE _parse_single cannot return false at the top level
1762 }
1763 }
1764 _process();
1765
1766 // Throw error if any items are left over (depending on settings)
1768}
1769
1770CLI11_INLINE void App::_parse_stream(std::istream &input) {
1771 auto values = config_formatter_->from_config(input);
1772 _parse_config(values);
1774 _trigger_pre_parse(values.size());
1775 _process();
1776
1777 // Throw error if any items are left over (depending on settings)
1779}
1780
1781CLI11_INLINE void App::_parse_config(const std::vector<ConfigItem> &args) {
1782 for(const ConfigItem &item : args) {
1783 if(!_parse_single_config(item) && allow_config_extras_ == ConfigExtrasMode::Error)
1784 throw ConfigError::Extras(item.fullname());
1785 }
1786}
1787
1788CLI11_INLINE bool
1789App::_add_flag_like_result(Option *op, const ConfigItem &item, const std::vector<std::string> &inputs) {
1790 if(item.inputs.size() <= 1) {
1791 // Flag parsing
1792 auto res = config_formatter_->to_flag(item);
1793 bool converted{false};
1794 if(op->get_disable_flag_override()) {
1795 auto val = detail::to_flag_value(res);
1796 if(val == 1) {
1797 res = op->get_flag_value(item.name, "{}");
1798 converted = true;
1799 }
1800 }
1801
1802 if(!converted) {
1803 errno = 0;
1804 if(res != "{}" || op->get_expected_max() <= 1) {
1805 res = op->get_flag_value(item.name, res);
1806 }
1807 }
1808
1809 op->add_result(res);
1810 return true;
1811 }
1812 if(static_cast<int>(inputs.size()) > op->get_items_expected_max() &&
1813 op->get_multi_option_policy() != MultiOptionPolicy::TakeAll &&
1814 op->get_multi_option_policy() != MultiOptionPolicy::Join) {
1815 if(op->get_items_expected_max() > 1) {
1816 throw ArgumentMismatch::AtMost(item.fullname(), op->get_items_expected_max(), inputs.size());
1817 }
1818
1819 if(!op->get_disable_flag_override()) {
1820 throw ConversionError::TooManyInputsFlag(item.fullname());
1821 }
1822 // if the disable flag override is set then we must have the flag values match a known flag value
1823 // this is true regardless of the output value, so an array input is possible and must be accounted for
1824 for(const auto &res : inputs) {
1825 bool valid_value{false};
1826 if(op->default_flag_values_.empty()) {
1827 if(res == "true" || res == "false" || res == "1" || res == "0") {
1828 valid_value = true;
1829 }
1830 } else {
1831 for(const auto &valid_res : op->default_flag_values_) {
1832 if(valid_res.second == res) {
1833 valid_value = true;
1834 break;
1835 }
1836 }
1837 }
1838
1839 if(valid_value) {
1840 op->add_result(res);
1841 } else {
1842 throw InvalidError("invalid flag argument given");
1843 }
1844 }
1845 return true;
1846 }
1847 return false;
1848}
1849
1850CLI11_INLINE bool App::_parse_single_config(const ConfigItem &item, std::size_t level) {
1851
1852 if(level < item.parents.size()) {
1853 auto *subcom = get_subcommand_no_throw(item.parents.at(level));
1854 return (subcom != nullptr) ? subcom->_parse_single_config(item, level + 1) : false;
1855 }
1856 // check for section open
1857 if(item.name == "++") {
1858 if(configurable_) {
1861 if(parent_ != nullptr) {
1862 parent_->parsed_subcommands_.push_back(this);
1863 }
1864 }
1865 return true;
1866 }
1867 // check for section close
1868 if(item.name == "--") {
1871 }
1872 return true;
1873 }
1874 Option *op = get_option_no_throw("--" + item.name);
1875 if(op == nullptr) {
1876 if(item.name.size() == 1) {
1877 op = get_option_no_throw("-" + item.name);
1878 }
1879 if(op == nullptr) {
1880 op = get_option_no_throw(item.name);
1881 }
1882 } else if(!op->get_configurable()) {
1883 if(item.name.size() == 1) {
1884 auto *testop = get_option_no_throw("-" + item.name);
1885 if(testop != nullptr && testop->get_configurable()) {
1886 op = testop;
1887 }
1888 }
1889 }
1890 if(op == nullptr || !op->get_configurable()) {
1891 const std::string &iname = item.name;
1892 auto options = get_options([&iname](const CLI::Option *opt) {
1893 return (opt->get_configurable() &&
1894 (opt->check_name(iname) || opt->check_lname(iname) || opt->check_sname(iname)));
1895 });
1896 if(!options.empty()) {
1897 op = options[0];
1898 }
1899 }
1900 if(op == nullptr) {
1901 // If the option was not present
1902 if(get_allow_config_extras() == config_extras_mode::capture) {
1903 // Should we worry about classifying the extras properly?
1904 missing_.emplace_back(detail::Classifier::NONE, item.fullname());
1905 for(const auto &input : item.inputs) {
1906 missing_.emplace_back(detail::Classifier::NONE, input);
1907 }
1908 }
1909 return false;
1910 }
1911
1912 if(!op->get_configurable()) {
1913 if(get_allow_config_extras() == config_extras_mode::ignore_all) {
1914 return false;
1915 }
1916 throw ConfigError::NotConfigurable(item.fullname());
1917 }
1918 if(op->empty()) {
1919 std::vector<std::string> buffer; // a buffer to use for copying and modifying inputs in a few cases
1920 bool useBuffer{false};
1921 if(item.multiline) {
1922 if(!op->get_inject_separator()) {
1923 buffer = item.inputs;
1924 buffer.erase(std::remove(buffer.begin(), buffer.end(), "%%"), buffer.end());
1925 useBuffer = true;
1926 }
1927 }
1928 const std::vector<std::string> &inputs = (useBuffer) ? buffer : item.inputs;
1929 if(op->get_expected_min() == 0) {
1930 if(_add_flag_like_result(op, item, inputs)) {
1931 return true;
1932 }
1933 }
1934 op->add_result(inputs);
1935 op->run_callback();
1936 }
1937
1938 return true;
1939}
1940
1941CLI11_INLINE bool App::_parse_single(std::vector<std::string> &args, bool &positional_only) {
1942 bool retval = true;
1943 detail::Classifier classifier = positional_only ? detail::Classifier::NONE : _recognize(args.back());
1944 switch(classifier) {
1945 case detail::Classifier::POSITIONAL_MARK:
1946 args.pop_back();
1947 positional_only = true;
1948 if(get_prefix_command()) {
1949 // don't care about extras mode here
1950 missing_.emplace_back(classifier, "--");
1951 while(!args.empty()) {
1952 missing_.emplace_back(detail::Classifier::NONE, args.back());
1953 args.pop_back();
1954 }
1955 } else if((!_has_remaining_positionals()) && (parent_ != nullptr)) {
1956 retval = false;
1957 } else {
1958 _move_to_missing(classifier, "--");
1959 }
1960 break;
1961 case detail::Classifier::SUBCOMMAND_TERMINATOR:
1962 // treat this like a positional mark if in the parent app
1963 args.pop_back();
1964 retval = false;
1965 break;
1966 case detail::Classifier::SUBCOMMAND:
1967 retval = _parse_subcommand(args);
1968 break;
1969 case detail::Classifier::LONG:
1970 case detail::Classifier::SHORT:
1971 case detail::Classifier::WINDOWS_STYLE:
1972 // If already parsed a subcommand, don't accept options_
1973 retval = _parse_arg(args, classifier, false);
1974 break;
1975 case detail::Classifier::NONE:
1976 // Probably a positional or something for a parent (sub)command
1977 retval = _parse_positional(args, false);
1978 if(retval && positionals_at_end_) {
1979 positional_only = true;
1980 }
1981 break;
1982 // LCOV_EXCL_START
1983 default:
1984 throw HorribleError("unrecognized classifier (you should not see this!)");
1985 // LCOV_EXCL_STOP
1986 }
1987 return retval;
1988}
1989
1990CLI11_NODISCARD CLI11_INLINE std::size_t App::_count_remaining_positionals(bool required_only) const {
1991 std::size_t retval = 0;
1992 for(const Option_p &opt : options_) {
1993 if(opt->get_positional() && (!required_only || opt->get_required())) {
1994 if(opt->get_items_expected_min() > 0 && static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
1995 retval += static_cast<std::size_t>(opt->get_items_expected_min()) - opt->count();
1996 }
1997 }
1998 }
1999 return retval;
2000}
2001
2002CLI11_NODISCARD CLI11_INLINE bool App::_has_remaining_positionals() const {
2003 for(const Option_p &opt : options_) {
2004 if(opt->get_positional() && ((static_cast<int>(opt->count()) < opt->get_items_expected_min()))) {
2005 return true;
2006 }
2007 }
2008
2009 return false;
2010}
2011
2012CLI11_INLINE bool App::_parse_positional(std::vector<std::string> &args, bool haltOnSubcommand) {
2013
2014 const std::string &positional = args.back();
2015 Option *posOpt{nullptr};
2016
2018 // deal with the case of required arguments at the end which should take precedence over other arguments
2019 auto arg_rem = args.size();
2020 auto remreq = _count_remaining_positionals(true);
2021 if(arg_rem <= remreq) {
2022 for(const Option_p &opt : options_) {
2023 if(opt->get_positional() && opt->required_) {
2024 if(static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
2026 std::string pos = positional;
2027 pos = opt->_validate(pos, 0);
2028 if(!pos.empty()) {
2029 continue;
2030 }
2031 }
2032 posOpt = opt.get();
2033 break;
2034 }
2035 }
2036 }
2037 }
2038 }
2039 if(posOpt == nullptr) {
2040 for(const Option_p &opt : options_) {
2041 // Eat options, one by one, until done
2042 if(opt->get_positional() &&
2043 (static_cast<int>(opt->count()) < opt->get_items_expected_max() || opt->get_allow_extra_args())) {
2045 std::string pos = positional;
2046 pos = opt->_validate(pos, 0);
2047 if(!pos.empty()) {
2048 continue;
2049 }
2050 }
2051 posOpt = opt.get();
2052 break;
2053 }
2054 }
2055 }
2056 if(posOpt != nullptr) {
2057 parse_order_.push_back(posOpt);
2058 if(posOpt->get_inject_separator()) {
2059 if(!posOpt->results().empty() && !posOpt->results().back().empty()) {
2060 posOpt->add_result(std::string{});
2061 }
2062 }
2063 results_t prev;
2065 prev = posOpt->results();
2066 posOpt->clear();
2067 }
2068 if(posOpt->get_expected_min() == 0) {
2069 ConfigItem item;
2070 item.name = posOpt->pname_;
2071 item.inputs.push_back(positional);
2072 // input is singular guaranteed to return true in that case
2073 _add_flag_like_result(posOpt, item, item.inputs);
2074 } else {
2075 posOpt->add_result(positional);
2076 }
2077
2078 if(posOpt->get_trigger_on_parse()) {
2079 if(!posOpt->empty()) {
2080 posOpt->run_callback();
2081 } else {
2082 if(!prev.empty()) {
2083 posOpt->add_result(prev);
2084 }
2085 }
2086 }
2087
2088 args.pop_back();
2089 return true;
2090 }
2091
2092 for(auto &subc : subcommands_) {
2093 if((subc->name_.empty()) && (!subc->disabled_)) {
2094 if(subc->_parse_positional(args, false)) {
2095 if(!subc->pre_parse_called_) {
2096 subc->_trigger_pre_parse(args.size());
2097 }
2098 return true;
2099 }
2100 }
2101 }
2102 // let the parent deal with it if possible
2103 if(parent_ != nullptr && fallthrough_) {
2104 return _get_fallthrough_parent()->_parse_positional(args, static_cast<bool>(parse_complete_callback_));
2105 }
2107 auto *com = _find_subcommand(args.back(), true, false);
2108 if(com != nullptr && (require_subcommand_max_ == 0 || require_subcommand_max_ > parsed_subcommands_.size())) {
2109 if(haltOnSubcommand) {
2110 return false;
2111 }
2112 args.pop_back();
2113 com->_parse(args);
2114 return true;
2115 }
2119 auto *parent_app = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
2120 com = parent_app->_find_subcommand(args.back(), true, false);
2121 if(com != nullptr && (com->parent_->require_subcommand_max_ == 0 ||
2122 com->parent_->require_subcommand_max_ > com->parent_->parsed_subcommands_.size())) {
2123 return false;
2124 }
2125 }
2127 std::vector<std::string> rargs(args.rbegin(), args.rend());
2128 throw CLI::ExtrasError(name_, rargs);
2129 }
2131 if(parent_ != nullptr && name_.empty()) {
2132 return false;
2133 }
2135 _move_to_missing(detail::Classifier::NONE, positional);
2136 args.pop_back();
2137 if(get_prefix_command()) {
2138 while(!args.empty()) {
2139 missing_.emplace_back(detail::Classifier::NONE, args.back());
2140 args.pop_back();
2141 }
2142 }
2143
2144 return true;
2145}
2146
2147CLI11_NODISCARD CLI11_INLINE App *
2148App::_find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept {
2149 App *bcom{nullptr};
2150 for(const App_p &com : subcommands_) {
2151 if(com->disabled_ && ignore_disabled)
2152 continue;
2153 if(com->get_name().empty()) {
2154 auto *subc = com->_find_subcommand(subc_name, ignore_disabled, ignore_used);
2155 if(subc != nullptr) {
2156 if(bcom != nullptr) {
2157 return nullptr;
2158 }
2159 bcom = subc;
2161 return bcom;
2162 }
2163 }
2164 }
2165 auto res = com->check_name_detail(subc_name);
2166 if(res != NameMatch::none) {
2167 if((!*com) || !ignore_used) {
2168 if(res == NameMatch::exact) {
2169 return com.get();
2170 }
2171 if(bcom != nullptr) {
2172 return nullptr;
2173 }
2174 bcom = com.get();
2176 return bcom;
2177 }
2178 }
2179 }
2180 }
2181 return bcom;
2182}
2183
2184CLI11_INLINE bool App::_parse_subcommand(std::vector<std::string> &args) {
2185 if(_count_remaining_positionals(/* required */ true) > 0) {
2186 _parse_positional(args, false);
2187 return true;
2188 }
2189 auto *com = _find_subcommand(args.back(), true, true);
2190 if(com == nullptr) {
2191 // the main way to get here is using .notation
2192 auto dotloc = args.back().find_first_of('.');
2193 if(dotloc != std::string::npos) {
2194 com = _find_subcommand(args.back().substr(0, dotloc), true, true);
2195 if(com != nullptr) {
2196 args.back() = args.back().substr(dotloc + 1);
2197 args.push_back(com->get_display_name());
2198 }
2199 }
2200 }
2201 if(com != nullptr) {
2202 args.pop_back();
2203 if(!com->silent_) {
2204 parsed_subcommands_.push_back(com);
2205 }
2206 com->_parse(args);
2207 auto *parent_app = com->parent_;
2208 while(parent_app != this) {
2209 parent_app->_trigger_pre_parse(args.size());
2210 if(!com->silent_) {
2211 parent_app->parsed_subcommands_.push_back(com);
2212 }
2213 parent_app = parent_app->parent_;
2214 }
2215 return true;
2216 }
2217
2218 if(parent_ == nullptr)
2219 throw HorribleError("Subcommand " + args.back() + " missing");
2220 return false;
2221}
2222
2223CLI11_INLINE bool
2224App::_parse_arg(std::vector<std::string> &args, detail::Classifier current_type, bool local_processing_only) {
2225
2226 std::string current = args.back();
2227
2228 std::string arg_name;
2229 std::string value;
2230 std::string rest;
2231
2232 switch(current_type) {
2233 case detail::Classifier::LONG:
2234 if(!detail::split_long(current, arg_name, value))
2235 throw HorribleError("Long parsed but missing (you should not see this):" + args.back());
2236 break;
2237 case detail::Classifier::SHORT:
2238 if(!detail::split_short(current, arg_name, rest))
2239 throw HorribleError("Short parsed but missing! You should not see this");
2240 break;
2241 case detail::Classifier::WINDOWS_STYLE:
2242 if(!detail::split_windows_style(current, arg_name, value))
2243 throw HorribleError("windows option parsed but missing! You should not see this");
2244 break;
2245 case detail::Classifier::SUBCOMMAND:
2246 case detail::Classifier::SUBCOMMAND_TERMINATOR:
2247 case detail::Classifier::POSITIONAL_MARK:
2248 case detail::Classifier::NONE:
2249 default:
2250 throw HorribleError("parsing got called with invalid option! You should not see this");
2251 }
2252
2253 auto op_ptr =
2254 std::find_if(std::begin(options_), std::end(options_), [&arg_name, current_type](const Option_p &opt) {
2255 if(current_type == detail::Classifier::LONG)
2256 return opt->check_lname(arg_name);
2257 if(current_type == detail::Classifier::SHORT)
2258 return opt->check_sname(arg_name);
2259 // this will only get called for detail::Classifier::WINDOWS_STYLE
2260 return opt->check_lname(arg_name) || opt->check_sname(arg_name);
2261 });
2262
2263 // Option not found
2264 while(op_ptr == std::end(options_)) {
2265 // using while so we can break
2266 for(auto &subc : subcommands_) {
2267 if(subc->name_.empty() && !subc->disabled_) {
2268 if(subc->_parse_arg(args, current_type, local_processing_only)) {
2269 if(!subc->pre_parse_called_) {
2270 subc->_trigger_pre_parse(args.size());
2271 }
2272 return true;
2273 }
2274 }
2275 }
2276 if(allow_non_standard_options_ && current_type == detail::Classifier::SHORT && current.size() > 2) {
2277 std::string narg_name;
2278 std::string nvalue;
2279 detail::split_long(std::string{'-'} + current, narg_name, nvalue);
2280 op_ptr = std::find_if(std::begin(options_), std::end(options_), [narg_name](const Option_p &opt) {
2281 return opt->check_sname(narg_name);
2282 });
2283 if(op_ptr != std::end(options_)) {
2284 arg_name = narg_name;
2285 value = nvalue;
2286 rest.clear();
2287 break;
2288 }
2289 }
2290
2291 // don't capture missing if this is a nameless subcommand and nameless subcommands can't fallthrough
2292 if(parent_ != nullptr && name_.empty()) {
2293 return false;
2294 }
2295
2296 // now check for '.' notation of subcommands
2297 auto dotloc = arg_name.find_first_of('.', 1);
2298 if(dotloc != std::string::npos && dotloc < arg_name.size() - 1) {
2299 // using dot notation is equivalent to single argument subcommand
2300 auto *sub = _find_subcommand(arg_name.substr(0, dotloc), true, false);
2301 if(sub != nullptr && require_subcommand_max_ != 0 &&
2303 std::find(parsed_subcommands_.begin(), parsed_subcommands_.end(), sub) == parsed_subcommands_.end()) {
2304 // the maximum number of subcommands is reached, so a new one cannot be started
2305 sub = nullptr;
2306 }
2307 if(sub != nullptr) {
2308 std::string v = args.back();
2309 auto saved_type = current_type;
2310 args.pop_back();
2311 arg_name = arg_name.substr(dotloc + 1);
2312 // rebuild the argument from the already-split name/value so this works regardless of the
2313 // original prefix style ('--', '-', or windows '/')
2314 std::size_t pushed = 1;
2315 if(arg_name.size() > 1) {
2316 args.push_back("--" + arg_name + (value.empty() ? std::string{} : "=" + value));
2317 current_type = detail::Classifier::LONG;
2318 } else {
2319 if(!value.empty()) {
2320 // '=' not allowed in short form arguments, so pass the value as a separate argument
2321 args.push_back(value);
2322 ++pushed;
2323 }
2324 args.push_back(std::string{'-'} + arg_name);
2325 current_type = detail::Classifier::SHORT;
2326 }
2327 std::string dummy1, dummy2;
2328 bool val = false;
2329 if((current_type == detail::Classifier::SHORT && detail::valid_first_char(args.back()[1])) ||
2330 detail::split_long(args.back(), dummy1, dummy2)) {
2331 val = sub->_parse_arg(args, current_type, true);
2332 }
2333
2334 if(val) {
2335 if(!sub->silent_) {
2336 parsed_subcommands_.push_back(sub);
2337 }
2338 // deal with preparsing
2340 _trigger_pre_parse(args.size());
2341 // run the parse complete callback since the subcommand processing is now complete
2342 if(sub->parse_complete_callback_) {
2343 sub->_process_completion_callbacks(true);
2344 }
2345 return true;
2346 }
2347 // restore the arguments and classification to what they were before the attempt so that
2348 // fallthrough to a parent re-splits the original argument with the correct splitter
2349 for(std::size_t i = 0; i < pushed; ++i) {
2350 args.pop_back();
2351 }
2352 args.push_back(v);
2353 current_type = saved_type;
2354 }
2355 }
2356 if(local_processing_only) {
2357 return false;
2358 }
2359 // If a subcommand, try the main command
2360 if(parent_ != nullptr && fallthrough_)
2361 return _get_fallthrough_parent()->_parse_arg(args, current_type, false);
2362
2363 // Otherwise, add to missing. In PositionalOnly mode an unrecognized option is left as an
2364 // extra and parsing continues so later registered options are still matched (#1374).
2365 args.pop_back();
2366 _move_to_missing(current_type, current);
2367 if(get_prefix_command_mode() == PrefixCommandMode::On) {
2368 while(!args.empty()) {
2369 missing_.emplace_back(detail::Classifier::NONE, args.back());
2370 args.pop_back();
2371 }
2372 } else if(allow_extras_ == ExtrasMode::AssumeSingleArgument) {
2373 if(!args.empty() && _recognize(args.back(), false) == detail::Classifier::NONE) {
2374 _move_to_missing(detail::Classifier::NONE, args.back());
2375 args.pop_back();
2376 }
2377 } else if(allow_extras_ == ExtrasMode::AssumeMultipleArguments) {
2378 while(!args.empty() && _recognize(args.back(), false) == detail::Classifier::NONE) {
2379 _move_to_missing(detail::Classifier::NONE, args.back());
2380 args.pop_back();
2381 }
2382 }
2383 return true;
2384 }
2385
2386 args.pop_back();
2387
2388 // Get a reference to the pointer to make syntax bearable
2389 Option_p &op = *op_ptr;
2391 if(op->get_inject_separator()) {
2392 if(!op->results().empty() && !op->results().back().empty()) {
2393 op->add_result(std::string{});
2394 }
2395 }
2396 if(op->get_trigger_on_parse() && op->current_option_state_ == Option::option_state::callback_run) {
2397 op->clear();
2398 }
2399 int min_num = (std::min)(op->get_type_size_min(), op->get_items_expected_min());
2400 int max_num = op->get_items_expected_max();
2401 // check container like options to limit the argument size to a single type if the allow_extra_flags argument is
2402 // set. 16 is somewhat arbitrary (needs to be at least 4)
2403 if(max_num >= detail::expected_max_vector_size / 16 && !op->get_allow_extra_args()) {
2404 auto tmax = op->get_type_size_max();
2405 max_num = detail::checked_multiply(tmax, op->get_expected_min()) ? tmax : detail::expected_max_vector_size;
2406 }
2407 // Make sure we always eat the minimum for unlimited vectors
2408 int collected = 0; // total number of arguments collected
2409 int result_count = 0; // local variable for number of results in a single arg string
2410 // deal with purely flag like things
2411 if(max_num == 0) {
2412 auto res = op->get_flag_value(arg_name, value);
2413 op->add_result(res);
2414 parse_order_.push_back(op.get());
2415 } else if(!value.empty()) { // --this=value
2416 op->add_result(value, result_count);
2417 parse_order_.push_back(op.get());
2418 collected += result_count;
2419 // -Trest
2420 } else if(!rest.empty()) {
2421 op->add_result(rest, result_count);
2422 parse_order_.push_back(op.get());
2423 rest = "";
2424 collected += result_count;
2425 }
2426
2427 // gather the minimum number of arguments
2428 while(min_num > collected && !args.empty()) {
2429 std::string current_ = args.back();
2430 args.pop_back();
2431 op->add_result(current_, result_count);
2432 parse_order_.push_back(op.get());
2433 collected += result_count;
2434 }
2435
2436 if(min_num > collected) { // if we have run out of arguments and the minimum was not met
2437 throw ArgumentMismatch::TypedAtLeast(op->get_name(), min_num, op->get_type_name());
2438 }
2439
2440 // now check for optional arguments
2441 if(max_num > collected || op->get_allow_extra_args()) { // we allow optional arguments
2442 auto remreqpos = _count_remaining_positionals(true);
2443 // we have met the minimum now optionally check up to the maximum
2444 while((collected < max_num || op->get_allow_extra_args()) && !args.empty() &&
2445 _recognize(args.back(), false) == detail::Classifier::NONE) {
2446 // If any required positionals remain, don't keep eating
2447 if(remreqpos >= args.size()) {
2448 break;
2449 }
2451 std::string arg = args.back();
2452 arg = op->_validate(arg, 0);
2453 if(!arg.empty()) {
2454 break;
2455 }
2456 }
2457 op->add_result(args.back(), result_count);
2458 parse_order_.push_back(op.get());
2459 args.pop_back();
2460 collected += result_count;
2461 }
2462
2463 // Allow -- to end an unlimited list and "eat" it
2464 if(!args.empty() && _recognize(args.back()) == detail::Classifier::POSITIONAL_MARK)
2465 args.pop_back();
2466 // optional flag that didn't receive anything now get the default value
2467 if(min_num == 0 && max_num > 0 && collected == 0) {
2468 auto res = op->get_flag_value(arg_name, std::string{});
2469 op->add_result(res);
2470 parse_order_.push_back(op.get());
2471 }
2472 }
2473 // if we only partially completed a type then add an empty string if allowed for later processing
2474 if(min_num > 0 && (collected % op->get_type_size_max()) != 0) {
2475 if(op->get_type_size_max() != op->get_type_size_min()) {
2476 op->add_result(std::string{});
2477 } else {
2478 throw ArgumentMismatch::PartialType(op->get_name(), op->get_type_size_min(), op->get_type_name());
2479 }
2480 }
2481 if(op->get_trigger_on_parse()) {
2482 op->run_callback();
2483 }
2484 if(!rest.empty()) {
2485 rest = "-" + rest;
2486 args.push_back(rest);
2487 }
2488 return true;
2489}
2490
2491CLI11_INLINE void App::_trigger_pre_parse(std::size_t remaining_args) {
2492 if(!pre_parse_called_) {
2493 pre_parse_called_ = true;
2495 pre_parse_callback_(remaining_args);
2496 }
2497 } else if(immediate_callback_) {
2498 if(!name_.empty()) {
2499 auto pcnt = parsed_;
2500 missing_t extras = std::move(missing_);
2501 clear();
2502 parsed_ = pcnt;
2503 pre_parse_called_ = true;
2504 missing_ = std::move(extras);
2505 }
2506 }
2507}
2508
2509CLI11_INLINE App *App::_get_fallthrough_parent() noexcept {
2510 if(parent_ == nullptr) {
2511 return nullptr;
2512 }
2513 auto *fallthrough_parent = parent_;
2514 while((fallthrough_parent->parent_ != nullptr) && (fallthrough_parent->get_name().empty())) {
2515 fallthrough_parent = fallthrough_parent->parent_;
2516 }
2517 return fallthrough_parent;
2518}
2519
2520CLI11_INLINE const App *App::_get_fallthrough_parent() const noexcept {
2521 if(parent_ == nullptr) {
2522 return nullptr;
2523 }
2524 const auto *fallthrough_parent = parent_;
2525 while((fallthrough_parent->parent_ != nullptr) && (fallthrough_parent->get_name().empty())) {
2526 fallthrough_parent = fallthrough_parent->parent_;
2527 }
2528 return fallthrough_parent;
2529}
2530
2531CLI11_NODISCARD CLI11_INLINE const std::string &App::_compare_subcommand_names(const App &subcom,
2532 const App &base) const {
2533 static const std::string estring;
2534 if(subcom.disabled_) {
2535 return estring;
2536 }
2537 for(const auto &subc : base.subcommands_) {
2538 if(subc.get() != &subcom) {
2539 if(subc->disabled_) {
2540 continue;
2541 }
2542 if(!subcom.get_name().empty()) {
2543 if(subc->check_name(subcom.get_name())) {
2544 return subcom.get_name();
2545 }
2546 }
2547 if(!subc->get_name().empty()) {
2548 if(subcom.check_name(subc->get_name())) {
2549 return subc->get_name();
2550 }
2551 }
2552 for(const auto &les : subcom.aliases_) {
2553 if(subc->check_name(les)) {
2554 return les;
2555 }
2556 }
2557 // this loop is needed in case of ignore_underscore or ignore_case on one but not the other
2558 for(const auto &les : subc->aliases_) {
2559 if(subcom.check_name(les)) {
2560 return les;
2561 }
2562 }
2563 // if the subcommand is an option group we need to check deeper
2564 if(subc->get_name().empty()) {
2565 const auto &cmpres = _compare_subcommand_names(subcom, *subc);
2566 if(!cmpres.empty()) {
2567 return cmpres;
2568 }
2569 }
2570 // if the test subcommand is an option group we need to check deeper
2571 if(subcom.get_name().empty()) {
2572 const auto &cmpres = _compare_subcommand_names(*subc, subcom);
2573 if(!cmpres.empty()) {
2574 return cmpres;
2575 }
2576 }
2577 }
2578 }
2579 return estring;
2580}
2581
2582CLI11_INLINE bool capture_extras(ExtrasMode mode) {
2583 return mode == ExtrasMode::Capture || mode == ExtrasMode::AssumeSingleArgument ||
2584 mode == ExtrasMode::AssumeMultipleArguments;
2585}
2586CLI11_INLINE void App::_move_to_missing(detail::Classifier val_type, const std::string &val) {
2587 if(allow_extras_ == ExtrasMode::ErrorImmediately) {
2588 throw ExtrasError(name_, std::vector<std::string>{val});
2589 }
2590 if(capture_extras(allow_extras_) || subcommands_.empty() || get_prefix_command()) {
2591 if(allow_extras_ != ExtrasMode::Ignore) {
2592 missing_.emplace_back(val_type, val);
2593 }
2594 return;
2595 }
2596 // allow extra arguments to be placed in an option group if it is allowed there
2597 for(auto &subc : subcommands_) {
2598 if(subc->name_.empty() && capture_extras(subc->allow_extras_)) {
2599 subc->missing_.emplace_back(val_type, val);
2600 return;
2601 }
2602 }
2603 if(allow_extras_ != ExtrasMode::Ignore) {
2604 // if we haven't found any place to put them yet put them in missing
2605 missing_.emplace_back(val_type, val);
2606 }
2607}
2608
2609CLI11_INLINE void App::_move_option(Option *opt, App *app) {
2610 if(opt == nullptr) {
2611 throw OptionNotFound("the option is NULL");
2612 }
2613 // verify that the give app is actually a subcommand
2614 bool found = false;
2615 for(auto &subc : subcommands_) {
2616 if(app == subc.get()) {
2617 found = true;
2618 }
2619 }
2620 if(!found) {
2621 throw OptionNotFound("The Given app is not a subcommand");
2622 }
2623
2624 if((help_ptr_ == opt) || (help_all_ptr_ == opt))
2625 throw OptionAlreadyAdded("cannot move help options");
2626
2627 if(config_ptr_ == opt)
2628 throw OptionAlreadyAdded("cannot move config file options");
2629
2630 auto iterator =
2631 std::find_if(std::begin(options_), std::end(options_), [opt](const Option_p &v) { return v.get() == opt; });
2632 if(iterator != std::end(options_)) {
2633 const auto &opt_p = *iterator;
2634 if(std::find_if(std::begin(app->options_), std::end(app->options_), [&opt_p](const Option_p &v) {
2635 return (*v == *opt_p);
2636 }) == std::end(app->options_)) {
2637 // only erase after the insertion was successful
2638 app->options_.push_back(std::move(*iterator));
2639 options_.erase(iterator);
2640 } else {
2641 throw OptionAlreadyAdded("option was not located: " + opt->get_name());
2642 }
2643 } else {
2644 throw OptionNotFound("could not locate the given Option");
2645 }
2646}
2647
2648CLI11_INLINE Option_group::Option_group(std::string group_description, std::string group_name, App *parent)
2649 : App(std::move(group_description), "", parent) {
2650 group(group_name);
2651 // option groups should have automatic fallthrough
2652 if(group_name.empty() || group_name.front() == '+') {
2653 // help will not be used by default in these contexts
2654 set_help_flag("");
2656 }
2657}
2658
2659CLI11_INLINE Option *Option_group::add_option(Option *opt) {
2660 if(get_parent() == nullptr) {
2661 throw OptionNotFound("Unable to locate the specified option");
2662 }
2663 get_parent()->_move_option(opt, this);
2664 return opt;
2665}
2666
2667CLI11_INLINE void Option_group::add_options(Option *opt) { add_option(opt); }
2668
2669CLI11_INLINE App *Option_group::add_subcommand(App *subcom) {
2670 App_p subc = subcom->get_parent()->get_subcommand_ptr(subcom);
2671 subc->get_parent()->remove_subcommand(subcom);
2672 add_subcommand(std::move(subc));
2673 return subcom;
2674}
2675
2676CLI11_INLINE void TriggerOn(App *trigger_app, App *app_to_enable) {
2677 app_to_enable->enabled_by_default(false);
2678 app_to_enable->disabled_by_default();
2679 trigger_app->preparse_callback([app_to_enable](std::size_t) { app_to_enable->disabled(false); });
2680}
2681
2682CLI11_INLINE void TriggerOn(App *trigger_app, std::vector<App *> apps_to_enable) {
2683 for(auto &app : apps_to_enable) {
2684 app->enabled_by_default(false);
2685 app->disabled_by_default();
2686 }
2687
2688 trigger_app->preparse_callback([apps_to_enable](std::size_t) {
2689 for(const auto &app : apps_to_enable) {
2690 app->disabled(false);
2691 }
2692 });
2693}
2694
2695CLI11_INLINE void TriggerOff(App *trigger_app, App *app_to_enable) {
2696 app_to_enable->disabled_by_default(false);
2697 app_to_enable->enabled_by_default();
2698 trigger_app->preparse_callback([app_to_enable](std::size_t) { app_to_enable->disabled(); });
2699}
2700
2701CLI11_INLINE void TriggerOff(App *trigger_app, std::vector<App *> apps_to_enable) {
2702 for(auto &app : apps_to_enable) {
2703 app->disabled_by_default(false);
2704 app->enabled_by_default();
2705 }
2706
2707 trigger_app->preparse_callback([apps_to_enable](std::size_t) {
2708 for(const auto &app : apps_to_enable) {
2709 app->disabled();
2710 }
2711 });
2712}
2713
2714CLI11_INLINE void deprecate_option(Option *opt, const std::string &replacement) {
2715 Validator deprecate_warning{[opt, replacement](std::string &) {
2716 std::cout << opt->get_name() << " is deprecated please use '" << replacement
2717 << "' instead\n";
2718 return std::string();
2719 },
2720 "DEPRECATED"};
2721 deprecate_warning.application_index(0);
2722 opt->check(deprecate_warning);
2723 if(!replacement.empty()) {
2724 opt->description(opt->get_description() + " DEPRECATED: please use '" + replacement + "' instead");
2725 }
2726}
2727
2728CLI11_INLINE void deprecate_option(App *app, const std::string &option_name, const std::string &replacement) {
2729 auto *opt = app->get_option(option_name);
2730 deprecate_option(opt, replacement);
2731}
2732
2733CLI11_INLINE void deprecate_option(App &app, const std::string &option_name, const std::string &replacement) {
2734 auto *opt = app.get_option(option_name);
2735 deprecate_option(opt, replacement);
2736}
2737
2738CLI11_INLINE void retire_option(App *app, Option *opt) {
2739 App temp;
2740 auto *option_copy = temp.add_option(opt->get_name(false, true))
2741 ->type_size(opt->get_type_size_min(), opt->get_type_size_max())
2742 ->expected(opt->get_expected_min(), opt->get_expected_max())
2743 ->allow_extra_args(opt->get_allow_extra_args());
2744
2745 app->remove_option(opt);
2746 auto *opt2 = app->add_option(option_copy->get_name(false, true), "option has been retired and has no effect");
2747 opt2->type_name("RETIRED")
2748 ->default_str("RETIRED")
2749 ->type_size(option_copy->get_type_size_min(), option_copy->get_type_size_max())
2750 ->expected(option_copy->get_expected_min(), option_copy->get_expected_max())
2751 ->allow_extra_args(option_copy->get_allow_extra_args());
2752
2753 // LCOV_EXCL_START
2754 // something odd with coverage on new compilers
2755 Validator retired_warning{[opt2](std::string &) {
2756 std::cout << "WARNING " << opt2->get_name() << " is retired and has no effect\n";
2757 return std::string();
2758 },
2759 ""};
2760 // LCOV_EXCL_STOP
2761 retired_warning.application_index(0);
2762 opt2->check(retired_warning);
2763}
2764
2765CLI11_INLINE void retire_option(App &app, Option *opt) { retire_option(&app, opt); }
2766
2767CLI11_INLINE void retire_option(App *app, const std::string &option_name) {
2768
2769 auto *opt = app->get_option_no_throw(option_name);
2770 if(opt != nullptr) {
2771 retire_option(app, opt);
2772 return;
2773 }
2774 auto *opt2 = app->add_option(option_name, "option has been retired and has no effect")
2775 ->type_name("RETIRED")
2776 ->expected(0, 1)
2777 ->default_str("RETIRED");
2778 // LCOV_EXCL_START
2779 // something odd with coverage on new compilers
2780 Validator retired_warning{[opt2](std::string &) {
2781 std::cout << "WARNING " << opt2->get_name() << " is retired and has no effect\n";
2782 return std::string();
2783 },
2784 ""};
2785 // LCOV_EXCL_STOP
2786 retired_warning.application_index(0);
2787 opt2->check(retired_warning);
2788}
2789
2790CLI11_INLINE void retire_option(App &app, const std::string &option_name) { retire_option(&app, option_name); }
2791
2792namespace FailureMessage {
2793
2794CLI11_INLINE std::string simple(const App *app, const Error &e) {
2795 std::string header = std::string(e.what()) + "\n";
2796 std::vector<std::string> names;
2797
2798 // Collect names
2799 if(app->get_help_ptr() != nullptr)
2800 names.push_back(app->get_help_ptr()->get_name());
2801
2802 if(app->get_help_all_ptr() != nullptr)
2803 names.push_back(app->get_help_all_ptr()->get_name());
2804
2805 // If any names found, suggest those
2806 if(!names.empty())
2807 header += "Run with " + detail::join(names, " or ") + " for more information.\n";
2808
2809 return header;
2810}
2811
2812CLI11_INLINE std::string help(const App *app, const Error &e) {
2813 std::string header = std::string("ERROR: ") + e.get_name() + ": " + e.what() + "\n";
2814 header += app->help();
2815 return header;
2816}
2817
2818} // namespace FailureMessage
2819
2820// [CLI11:app_inl_hpp:end]
2821} // namespace CLI
Creates a command line program, with very few defaults.
Definition App.hpp:115
CLI11_NODISCARD Option * get_option_no_throw(std::string option_name) noexcept
Get an option by name (noexcept non-const version).
Definition App_inl.hpp:1077
bool subcommand_fallthrough_
Allow subcommands to fallthrough, so that parent commands can trigger other subcommands after subcomm...
Definition App.hpp:257
CLI11_NODISCARD std::string help(std::string prev="", AppFormatMode mode=AppFormatMode::Normal) const
Definition App_inl.hpp:950
CLI11_NODISCARD std::size_t remaining_size(bool recurse=false) const
This returns the number of remaining options, minus the – separator.
Definition App_inl.hpp:1225
CLI11_NODISCARD bool _has_remaining_positionals() const
Count the required remaining positional arguments.
Definition App_inl.hpp:2002
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 App_inl.hpp:1337
App * immediate_callback(bool immediate=true)
Set the subcommand callback to be executed immediately on subcommand completion.
Definition App_inl.hpp:170
Option * set_help_flag(std::string flag_name="", const std::string &help_description="")
Set a help flag, replace the existing one if present.
Definition App_inl.hpp:330
bool allow_non_standard_options_
indicator that the subcommand should allow non-standard option arguments, such as -single_dash_flag
Definition App.hpp:289
CLI11_NODISCARD std::string get_footer() const
Generate and return the footer.
Definition App_inl.hpp:946
Option * config_ptr_
Pointer to the config option.
Definition App.hpp:323
CLI11_NODISCARD bool get_allow_non_standard_option_names() const
Get the status of allowing non standard option names.
Definition App.hpp:1128
void _move_to_missing(detail::Classifier val_type, const std::string &val)
Helper function to place extra values in the most appropriate position.
Definition App_inl.hpp:2586
CLI11_NODISCARD App * _get_fallthrough_parent() noexcept
Get the appropriate parent to fallthrough to which is the first one that has a name or the main app.
Definition App_inl.hpp:2509
std::size_t require_option_min_
Minimum required options (not inheritable!).
Definition App.hpp:304
NameMatch
enumeration of matching possibilities
Definition App.hpp:1198
App * ignore_underscore(bool value=true)
Ignore underscore. Subcommands inherit value.
Definition App_inl.hpp:196
std::size_t require_subcommand_max_
Max number of subcommands allowed (parsing stops after this number). 0 is unlimited INHERITABLE.
Definition App.hpp:301
std::vector< App_p > subcommands_
Storage for subcommand list.
Definition App.hpp:244
CLI11_NODISCARD std::vector< std::string > remaining(bool recurse=false) const
This returns the missing options from the current subcommand.
Definition App_inl.hpp:1193
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 App_inl.hpp:1219
std::uint32_t parsed_
Counts the number of times this command/subcommand was parsed.
Definition App.hpp:295
CLI11_NODISCARD App * get_option_group(std::string group_name) const
Check to see if an option group is part of this App.
Definition App_inl.hpp:611
App * require_subcommand()
The argumentless form of require subcommand requires 1 or more subcommands.
Definition App.hpp:811
std::string usage_
Usage to put after program/subcommand description in the help output INHERITABLE.
Definition App.hpp:181
OptionDefaults option_defaults_
The default values for options, customizable and changeable INHERITABLE.
Definition App.hpp:171
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 App_inl.hpp:142
void _process_requirements()
Verify required options and cross requirements. Subcommands too (only if selected).
Definition App_inl.hpp:1506
CLI11_NODISCARD std::size_t count_all() const
Definition App_inl.hpp:620
void _parse_setup()
Definition App_inl.hpp:717
bool disabled_
If set to true the subcommand is disabled and cannot be used, ignored for main app.
Definition App.hpp:148
CLI11_NODISCARD bool get_prefix_command() const
Get the prefix command status.
Definition App.hpp:1107
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 App_inl.hpp:363
bool remove_needs(Option *opt)
Removes an option from the needs list of this subcommand.
Definition App_inl.hpp:912
CLI11_NODISCARD std::string get_usage() const
Generate and return the usage.
Definition App_inl.hpp:942
Option * get_help_ptr()
Get a pointer to the help flag.
Definition App.hpp:1152
void _configure()
Definition App_inl.hpp:1274
CLI11_NODISCARD std::size_t _count_remaining_positionals(bool required_only=false) const
Count the required remaining positional arguments.
Definition App_inl.hpp:1990
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 App_inl.hpp:443
void parse(int argc, const char *const *argv)
Definition App_inl.hpp:650
void _process_config_file()
Read and process a configuration file (main app only).
Definition App_inl.hpp:1394
std::string footer_
Footer to put after all options in the help output INHERITABLE.
Definition App.hpp:187
void increment_parsed()
Internal function to recursively increment the parsed counter on the current app as well unnamed subc...
Definition App_inl.hpp:1693
CLI11_NODISCARD bool check_name(std::string name_to_check) const
Definition App_inl.hpp:1137
CLI11_NODISCARD const Option * get_option(std::string option_name) const
Get an option by name.
Definition App_inl.hpp:1048
Option * version_ptr_
A pointer to a version flag if there is one.
Definition App.hpp:199
CLI11_NODISCARD const Option * get_help_all_ptr() const
Get a pointer to the help all flag. (const).
Definition App.hpp:1158
bool remove_subcommand(App *subcom)
Removes a subcommand from the App. Takes a subcommand pointer. Returns true if found and removed.
Definition App_inl.hpp:541
App * parent_
A pointer to the parent if this is a subcommand.
Definition App.hpp:310
std::set< Option * > exclude_options_
Definition App.hpp:229
void _trigger_pre_parse(std::size_t remaining_args)
Trigger the pre_parse callback if needed.
Definition App_inl.hpp:2491
App * group(std::string group_name)
Changes the group membership.
Definition App.hpp:805
App * enabled_by_default(bool enable=true)
Definition App_inl.hpp:151
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 App_inl.hpp:586
std::function< std::string()> footer_callback_
This is a function that generates a footer to put after all other options in help output.
Definition App.hpp:190
ExtrasMode allow_extras_
If true, allow extra arguments (ie, don't throw an error). INHERITABLE.
Definition App.hpp:132
PrefixCommandMode prefix_command_
If true, cease processing on an unrecognized option (implies allow_extras) INHERITABLE.
Definition App.hpp:139
int exit(const Error &e, std::ostream &out, std::ostream &err) const
Print a nice error message and return the exit code.
Definition App_inl.hpp:756
std::function< void()> parse_complete_callback_
This is a function that runs when parsing has finished.
Definition App.hpp:161
virtual void pre_callback()
Definition App.hpp:874
App * get_parent()
Get the parent of this subcommand (or nullptr if main app).
Definition App.hpp:1173
void _validate() const
Definition App_inl.hpp:1239
std::string name_
Subcommand name or program name (from parser if name is empty).
Definition App.hpp:126
std::vector< App * > parsed_subcommands_
This is a list of the subcommands collected, in order.
Definition App.hpp:222
bool ignore_underscore_
If true, the program should ignore underscores INHERITABLE.
Definition App.hpp:250
missing_t missing_
Definition App.hpp:216
void run_callback(bool final_mode=false, bool suppress_final_callback=false)
Internal function to run (App) callback, bottom up.
Definition App_inl.hpp:1294
bool allow_prefix_matching_
indicator to allow subcommands to match with prefix matching
Definition App.hpp:292
std::size_t require_subcommand_min_
Minimum required subcommands (not inheritable!).
Definition App.hpp:298
CLI11_NODISCARD NameMatch check_name_detail(std::string name_to_check) const
Definition App_inl.hpp:1142
void _process_env()
Get envname options if not yet passed. Runs on all subcommands.
Definition App_inl.hpp:1430
std::function< std::string(const App *, const Error &e)> failure_message_
The error message printing function INHERITABLE.
Definition App.hpp:205
void _parse_stream(std::istream &input)
Internal function to parse a stream.
Definition App_inl.hpp:1770
CLI11_NODISCARD std::string get_display_name(bool with_aliases=false) const
Get a display name for an app.
Definition App_inl.hpp:1121
bool has_automatic_name_
If set to true the name was automatically generated from the command line vs a user set name.
Definition App.hpp:142
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 App_inl.hpp:2531
void clear()
Reset the parsed data.
Definition App_inl.hpp:634
App * get_subcommand(const App *subcom) const
Definition App_inl.hpp:557
CLI11_NODISCARD std::string version() const
Displays a version string.
Definition App_inl.hpp:964
CLI11_NODISCARD App * get_subcommand_no_throw(std::string subcom) const noexcept
Definition App_inl.hpp:573
bool _add_flag_like_result(Option *op, const ConfigItem &item, const std::vector< std::string > &inputs)
store the results for a flag like option
Definition App_inl.hpp:1789
std::vector< Option_p > options_
The list of options, stored locally.
Definition App.hpp:174
Option * help_all_ptr_
A pointer to the help all flag if there is one INHERITABLE.
Definition App.hpp:196
bool validate_optional_arguments_
If set to true optional vector arguments are validated before assigning INHERITABLE.
Definition App.hpp:282
App * allow_config_extras(bool allow=true)
ignore extras in config files
Definition App_inl.hpp:160
std::function< void()> final_callback_
This is a function that runs when all processing has completed.
Definition App.hpp:164
bool remove_option(Option *opt)
Removes an option from the App. Takes an option pointer. Returns true if found and removed.
Definition App_inl.hpp:487
App * require_option()
The argumentless form of require option requires 1 or more options be used.
Definition App.hpp:831
App(std::string app_description, std::string app_name, App *parent)
Special private constructor for subcommand.
Definition App_inl.hpp:37
std::function< std::string()> usage_callback_
This is a function that generates a usage to put after program/subcommand description in help output.
Definition App.hpp:184
App * add_subcommand(std::string subcommand_name="", std::string subcommand_description="")
Add a subcommand. Inherits INHERITABLE and OptionDefaults, and help flag.
Definition App_inl.hpp:510
App * preparse_callback(std::function< void(std::size_t)> pp_callback)
Definition App.hpp:381
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 App_inl.hpp:426
bool positionals_at_end_
specify that positional arguments come at the end of the argument sequence not inheritable
Definition App.hpp:268
void _process()
Process callbacks and such.
Definition App_inl.hpp:1634
bool immediate_callback_
Definition App.hpp:155
bool _parse_single(std::vector< std::string > &args, bool &positional_only)
Definition App_inl.hpp:1941
App * name(std::string app_name="")
Set a name for the app (empty will use parser to set the name).
Definition App_inl.hpp:107
CLI11_NODISCARD std::string config_to_str() const
Definition App_inl.hpp:930
void _move_option(Option *opt, App *app)
function that could be used by subclasses of App to shift options around into subcommands
Definition App_inl.hpp:2609
void _process_extras()
Throw an error if anything is left over and should not be.
Definition App_inl.hpp:1673
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 App_inl.hpp:1321
CLI11_NODISCARD PrefixCommandMode get_prefix_command_mode() const
Get the prefix command status.
Definition App.hpp:1110
bool configurable_
if set to true the subcommand can be triggered via configuration files INHERITABLE
Definition App.hpp:276
CLI11_NODISCARD std::vector< std::string > get_groups() const
Get the groups available directly from this option (in order).
Definition App_inl.hpp:1180
void _parse_config(const std::vector< ConfigItem > &args)
Definition App_inl.hpp:1781
std::string description_
Description of the current program/subcommand.
Definition App.hpp:129
bool got_subcommand(const App *subcom) const
Check to see if given subcommand was selected.
Definition App_inl.hpp:840
std::size_t require_option_max_
Max number of options allowed. 0 is unlimited (not inheritable).
Definition App.hpp:307
std::vector< std::string > aliases_
Alias names for the subcommand.
Definition App.hpp:316
std::set< App * > exclude_subcommands_
this is a list of subcommands that are exclusionary to this one
Definition App.hpp:225
void _process_completion_callbacks(bool with_help_flags)
Definition App_inl.hpp:1701
ConfigExtrasMode allow_config_extras_
Definition App.hpp:136
bool _parse_positional(std::vector< std::string > &args, bool haltOnSubcommand)
Definition App_inl.hpp:2012
bool ignore_case_
If true, the program name is not case-sensitive INHERITABLE.
Definition App.hpp:247
CLI11_NODISCARD const std::string & get_group() const
Get the group of this subcommand.
Definition App.hpp:1086
bool _parse_arg(std::vector< std::string > &args, detail::Classifier current_type, bool local_processing_only)
Definition App_inl.hpp:2224
std::function< void(std::size_t)> pre_parse_callback_
This is a function that runs prior to the start of parsing.
Definition App.hpp:158
App * callback(std::function< void()> app_callback)
Definition App_inl.hpp:98
std::string group_
The group membership INHERITABLE.
Definition App.hpp:313
App * alias(std::string app_name)
Set an alias for the app.
Definition App_inl.hpp:124
bool pre_parse_called_
Flag indicating that the pre_parse_callback has been triggered.
Definition App.hpp:151
Option * help_ptr_
A pointer to the help flag if there is one INHERITABLE.
Definition App.hpp:193
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 App_inl.hpp:458
App * ignore_case(bool value=true)
Ignore case. Subcommands inherit value.
Definition App_inl.hpp:182
bool remove_excludes(Option *opt)
Removes an option from the excludes list of this subcommand.
Definition App_inl.hpp:892
CLI11_NODISCARD std::vector< App * > get_subcommands() const
Definition App.hpp:932
CLI11_NODISCARD config_extras_mode get_allow_config_extras() const
Get the status of allow extras.
Definition App.hpp:1147
bool _parse_subcommand(std::vector< std::string > &args)
Definition App_inl.hpp:2184
bool fallthrough_
Definition App.hpp:254
std::set< Option * > need_options_
Definition App.hpp:237
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 App_inl.hpp:982
std::set< App * > need_subcommands_
Definition App.hpp:233
Option * add_option(std::string option_name, callback_t option_callback, std::string option_description="", bool defaulted=false, std::function< std::string()> func={})
Definition App_inl.hpp:210
std::vector< Option * > parse_order_
This is a list of pointers to options with the original parse order.
Definition App.hpp:219
void _parse(std::vector< std::string > &args)
Internal parse function.
Definition App_inl.hpp:1729
bool validate_positionals_
If set to true positional options are validated before assigning INHERITABLE.
Definition App.hpp:279
bool _parse_single_config(const ConfigItem &item, std::size_t level=0)
Fill in a single config option.
Definition App_inl.hpp:1850
void _process_help_flags(CallbackPriority priority, bool trigger_help=false, bool trigger_all_help=false) const
Definition App_inl.hpp:1481
startup_mode default_startup
Definition App.hpp:273
void _process_callbacks(CallbackPriority priority)
Process callbacks. Runs on all subcommands.
Definition App_inl.hpp:1452
CLI11_NODISCARD char ** ensure_utf8(char **argv)
Convert the contents of argv to UTF-8. Only does something on Windows, does nothing elsewhere.
Definition App_inl.hpp:76
CLI11_NODISCARD App * _find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept
Definition App_inl.hpp:2148
Option * add_flag(std::string flag_name)
Add a flag with no description or variable assignment.
Definition App_inl.hpp:422
CLI11_NODISCARD const std::string & get_name() const
Get the name of the current app.
Definition App.hpp:1179
App * disabled(bool disable=true)
Disable the subcommand or option group.
Definition App.hpp:411
std::shared_ptr< FormatterBase > formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer).
Definition App.hpp:202
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 App_inl.hpp:346
bool allow_windows_style_options_
Allow '/' for options for Windows like options. Defaults to true on Windows, false otherwise....
Definition App.hpp:260
std::shared_ptr< Config > config_formatter_
This is the formatter for help printing. Default provided. INHERITABLE (same pointer).
Definition App.hpp:326
App * excludes(Option *opt)
Sets excluded options for the subcommand.
Definition App_inl.hpp:850
Usually something like –help-all on command line.
Definition Error.hpp:179
-h or –help on command line
Definition Error.hpp:173
-v or –version on command line
Definition Error.hpp:186
All errors derive from this one.
Definition Error.hpp:73
Thrown when an excludes option is present.
Definition Error.hpp:302
Thrown when too many positionals or options are found.
Definition Error.hpp:309
Thrown when parsing an INI file and it is missing.
Definition Error.hpp:199
Definition Error.hpp:344
Thrown when an option is set to conflicting values (non-vector and multi args, for example).
Definition Error.hpp:97
Thrown when validation fails before parsing.
Definition Error.hpp:335
void add_options(Option *opt)
Add an existing option to the Option_group.
Definition App_inl.hpp:2667
Option * add_option(Option *opt)
Add an existing option to the Option_group.
Definition App_inl.hpp:2659
App * add_subcommand(App *subcom)
Add an existing subcommand to be a member of an option_group.
Definition App_inl.hpp:2669
Thrown when an option already exists.
Definition Error.hpp:145
CLI11_NODISCARD CallbackPriority get_callback_priority() const
The priority of callback.
Definition Option.hpp:163
CLI11_NODISCARD bool get_required() const
True if this is a required option.
Definition Option.hpp:139
CLI11_NODISCARD MultiOptionPolicy get_multi_option_policy() const
The status of the multi option policy.
Definition Option.hpp:160
CLI11_NODISCARD bool get_configurable() const
The status of configurable.
Definition Option.hpp:148
bool required_
True if this is a required option.
Definition Option.hpp:78
CLI11_NODISCARD bool get_disable_flag_override() const
The status of configurable.
Definition Option.hpp:151
CLI11_NODISCARD const std::string & get_group() const
Get the group of this option.
Definition Option.hpp:136
CRTP * required(bool value=true)
Set the option as required.
Definition Option.hpp:120
Definition Option.hpp:261
Option * type_size(int option_type_size)
Set a custom option size.
Definition Option_inl.hpp:531
Option * expected(int value)
Set the number of expected arguments.
Definition Option_inl.hpp:56
CLI11_NODISCARD bool get_positional() const
True if the argument can be given directly.
Definition Option.hpp:611
CLI11_NODISCARD bool check_name(const std::string &name) const
Check a name. Requires "-" or "--" for short / long, supports positional name.
Definition Option_inl.hpp:418
@ callback_run
the callback has been executed
Definition Option.hpp:356
option_state current_option_state_
Whether the callback has run (needed for INI parsing).
Definition Option.hpp:359
void clear()
Clear the parsed results (mostly for testing).
Definition Option_inl.hpp:50
std::string pname_
A positional name.
Definition Option.hpp:283
std::set< Option * > needs_
A list of options that are required with this option.
Definition Option.hpp:328
void run_callback()
Process the callback.
Definition Option_inl.hpp:347
CLI11_NODISCARD std::string get_name(bool positional=false, bool all_options=false, bool disable_default_flag_values=false) const
Gets a comma separated list of names. Will include / prefer the positional name if positional is true...
Definition Option_inl.hpp:294
CLI11_NODISCARD bool check_sname(std::string name) const
Requires "-" to be removed from string.
Definition Option.hpp:666
std::set< Option * > excludes_
A list of options that are excluded with this option.
Definition Option.hpp:331
CLI11_NODISCARD bool get_callback_run() const
See if the callback has been run already.
Definition Option.hpp:751
std::vector< std::string > fnames_
a list of flag names with specified default values;
Definition Option.hpp:280
CLI11_NODISCARD int get_items_expected_min() const
The total min number of expected string values to be used.
Definition Option.hpp:600
CLI11_NODISCARD bool check_lname(std::string name) const
Requires "--" to be removed from string.
Definition Option.hpp:671
CLI11_NODISCARD const results_t & results() const
Get the current complete results set.
Definition Option.hpp:697
CLI11_NODISCARD int get_items_expected_max() const
Get the maximum number of items expected to be returned and used for the callback.
Definition Option.hpp:603
std::vector< std::string > snames_
A list of the short names (-a) without the leading dashes.
Definition Option.hpp:270
CLI11_NODISCARD std::size_t count() const
Count the total number of times an option was passed.
Definition Option.hpp:388
Option * allow_extra_args(bool value=true)
Definition Option.hpp:411
Option * multi_option_policy(MultiOptionPolicy value=MultiOptionPolicy::Throw)
Take the last argument if given multiple times (or another policy).
Definition Option_inl.hpp:280
CLI11_NODISCARD bool get_inject_separator() const
Return the inject_separator flag.
Definition Option.hpp:564
CLI11_NODISCARD const std::string & get_single_name() const
Get a single name for the option, first of lname, sname, pname, envname.
Definition Option_inl.hpp:574
CLI11_NODISCARD bool get_trigger_on_parse() const
The status of trigger on parse.
Definition Option.hpp:423
CLI11_NODISCARD std::string get_flag_value(const std::string &name, std::string input_value) const
Definition Option_inl.hpp:447
CLI11_NODISCARD bool empty() const
True if the option was not passed.
Definition Option.hpp:391
CLI11_NODISCARD int get_expected_min() const
The number of times the option expects to be included.
Definition Option.hpp:595
CLI11_NODISCARD int get_expected_max() const
The max number of times the option expects to be included.
Definition Option.hpp:597
Option * default_str(std::string val)
Set the default value string representation (does not change the contained value).
Definition Option.hpp:785
std::string envname_
If given, check the environment for this option.
Definition Option.hpp:286
CLI11_NODISCARD bool get_allow_extra_args() const
Get the current value of allow extra args.
Definition Option.hpp:416
std::vector< std::pair< std::string, std::string > > default_flag_values_
Definition Option.hpp:277
std::vector< std::string > lnames_
A list of the long names (--long) without the leading dashes.
Definition Option.hpp:273
Option * type_name(std::string typeval)
Set a custom option typestring.
Definition Option_inl.hpp:587
Option * add_result(std::string s)
Puts a result at the end.
Definition Option_inl.hpp:493
Thrown when counting a nonexistent option.
Definition Error.hpp:352
Anything that can error in Parse.
Definition Error.hpp:160
Thrown when a required option is missing.
Definition Error.hpp:229
Thrown when a requires option is missing.
Definition Error.hpp:295
Some validators that are provided.
Definition Validators.hpp:55
Validator & application_index(int app_index)
Specify the application index of a validator.
Definition Validators.hpp:128
Holds values to load into Options.
Definition ConfigFwd.hpp:29
CLI11_NODISCARD std::string fullname() const
The list of parents and name joined by ".".
Definition Config_inl.hpp:33
std::vector< std::string > inputs
Listing of inputs.
Definition ConfigFwd.hpp:36
std::string name
This is the name.
Definition ConfigFwd.hpp:34
bool multiline
indicator if a multiline vector separator was inserted
Definition ConfigFwd.hpp:38
std::vector< std::string > parents
This is the list of parents.
Definition ConfigFwd.hpp:31