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