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