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