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