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