25#ifndef TCLAP_CMD_LINE_H
26#define TCLAP_CMD_LINE_H
66 if (std::ranges::any_of(*
this, [arg](
const Arg *existing) {
70 "Argument with same flag/name already exists!",
79 [[nodiscard]]
bool showAsGroup()
const override {
return false; }
168 const std::string &messageId,
const std::string &fallback)
const = 0;
171 template <
typename T>
176 const std::string &messageId,
177 const std::string &fallback)
const override {
218 void _createIgnoreRestArgument();
219 void _createHelpAndVersionArguments();
220 void _refreshBuiltinDescriptions();
222 void _setProgramName(std::vector<std::string> &args);
223 int _parseArguments(std::vector<std::string> &args);
224 bool _processArgument(
int &index, std::vector<std::string> &args,
226 void _validateRequiredArguments(
int requiredCount);
231 bool _helpAndVersion;
236 bool _ignoreUnmatched;
256 CmdLine(std::string message,
const char delimiter =
' ',
257 std::string version =
"none",
bool helpAndVersion =
true);
303 void xorAdd(
const std::vector<Arg *> &xors)
override;
310 void parse(
int argc,
const char *
const *argv)
override;
317 void parse(std::vector<std::string> &args);
340 return _helpAndVersion;
363 void reset()
override;
376 template <
typename T>
379 _refreshBuiltinDescriptions();
386 const std::string &messageId,
387 const std::string &fallback)
const override {
407 _progName(
"not_set_yet"),
408 _message(std::move(m)),
409 _version(std::move(v)),
412 _hasOptionalUnlabeledArg(false),
413 _registrationActive(false),
416 _output(&_defaultOutput),
417 _handleExceptions(true),
418 _messageTranslator(nullptr),
421 _versionArg(nullptr),
422 _helpAndVersion(help),
423 _ignoreUnmatched(false),
428inline void CmdLine::_constructor() {
431 _createIgnoreRestArgument();
432 if (_helpAndVersion) _createHelpAndVersionArguments();
435inline void CmdLine::_createIgnoreRestArgument() {
436 Visitor *v =
new IgnoreRestVisitor(*
this);
437 auto *ignore =
new SwitchArg(
440 "Ignores the rest of the labeled arguments following this flag."),
449inline void CmdLine::_createHelpAndVersionArguments() {
450 Visitor *v =
new HelpVisitor(
this, &
_output);
452 new SwitchArg(
"h",
"help",
454 "Displays usage information and exits."),
460 v =
new VersionVisitor(
this, &
_output);
461 auto *vers =
new SwitchArg(
464 "Displays version information and exits."),
477inline void CmdLine::_refreshBuiltinDescriptions() {
480 "ignore_rest_description",
481 "Ignores the rest of the labeled arguments following this flag."));
485 "help_description",
"Displays usage information and exits."));
489 "version_description",
"Displays version information and exits."));
493inline void CmdLine::_setProgramName(std::vector<std::string> &args) {
496 throw CmdLineParseException(
497 "The args vector must not be empty, "
498 "the first entry should contain the "
504 args.erase(args.begin());
507inline int CmdLine::_parseArguments(std::vector<std::string> &args) {
508 int requiredCount = 0;
509 for (
int i = 0;
static_cast<unsigned int>(i) < args.size(); i++) {
510 bool matched = _processArgument(i, args, requiredCount);
516 if (!matched && !
ignoreRest() && !_ignoreUnmatched)
518 CmdLineParseException(
"Couldn't find match "
523 return requiredCount;
526inline bool CmdLine::_processArgument(
int &index,
527 std::vector<std::string> &args,
528 int &requiredCount) {
532 bool alreadySet = arg.isSet();
533 bool ignore = arg.isIgnoreable() &&
ignoreRest();
534 if (!ignore && arg.processArg(&index, args)) {
535 requiredCount += (!alreadySet && arg.isRequired()) ? 1 : 0;
543inline void CmdLine::_validateRequiredArguments(
int requiredCount) {
544 std::list<ArgGroup *> missingArgGroups;
548 bool missingRequired = group->validate();
549 if (missingRequired) {
550 missingArgGroups.push_back(group);
554 if (requiredCount <
_numRequired || !missingArgGroups.empty()) {
559 throw(CmdLineParseException(
565 auto *group =
new OneOf(*
this);
568 for (
Arg *arg : args) {
574 std::vector<Arg *> ors;
585 : _cmd(cmd), _args(cmd.
_argList), _numRequired(cmd._numRequired),
586 _hasOptionalUnlabeledArg(cmd._hasOptionalUnlabeledArg), _bindings() {
596 for (
auto it = _bindings.rbegin();
597 it != _bindings.rend(); ++it)
598 it->first->_parserDelimiter = it->second;
605 validateConflicts(arg);
606 validatePositionalOrder(arg);
607 _bindings.emplace_back(&arg, arg._parserDelimiter);
621 void validateConflicts(
const Arg &arg)
const {
622 if (std::ranges::any_of(_args, [&arg](
const Arg *existing) {
630 "Argument with same flag/name already exists!", arg.
longID());
634 void validatePositionalOrder(Arg &arg) {
635 if (!arg.hasLabel()) {
636 if (_hasOptionalUnlabeledArg)
637 throw SpecificationException(
638 "You can't specify ANY Unlabeled Arg following an optional "
639 "Unlabeled Arg", arg.longID());
640 if (!arg.isRequired() && !arg.acceptsMultipleValues())
641 _hasOptionalUnlabeledArg =
true;
645 using Bindings = std::vector<std::pair<Arg *, const char *>>;
647 std::list<Arg *> _args;
649 bool _hasOptionalUnlabeledArg;
657 groups.push_back(&group);
659 for (
Arg *arg : group) registration.
add(*arg);
670 registration.
add(*a);
676 members.push_back(a);
678 registration.
add(*a);
687 std::vector<std::string> args(argv, argv + argc);
693 bool shouldExit =
false;
697 _setProgramName(args);
698 const int requiredCount = _parseArguments(args);
699 _validateRequiredArguments(requiredCount);
722 if (shouldExit) exit(estat);
728 return s.find_first_not_of(
Arg::blankChar(), 1) == std::string::npos;
732 const std::list<ArgGroup *> &missing) {
735 std::string missingArgList;
737 if (arg->isRequired() && !arg->isSet()) {
738 missingArgList += arg->getName();
739 missingArgList +=
", ";
744 for (
const ArgGroup *group : missing) {
745 missingArgList += group->getName();
746 missingArgList +=
", ";
750 missingArgList = missingArgList.substr(0, missingArgList.length() - 2);
755 "Required arguments missing: ");
758 "Required argument missing: ");
760 msg += missingArgList;
779 _ignoreUnmatched = ignore;
Groups arguments for presentation without imposing a selection rule.
Interface that allows adding an Arg to a "container".
A simple class that defines and argument exception.
ArgGroup is the base class for implementing groups of arguments that are mutually exclusive (it repla...
CmdLineInterface * _parser
std::list< Arg * > Container
A virtual base class that defines the essential data for all arguments.
static std::string flagStartString()
virtual std::string longID(const std::string &valueId="val") const
Returns a long ID for the usage.
bool conflictsWith(const Arg &a) const noexcept
Checks declared registration conflicts: the same object, the same name, or the same nonempty short fl...
static constexpr char blankChar() noexcept
The char used as a place holder when SwitchArgs are combined.
static constexpr char flagStartChar() noexcept
virtual void addToList(std::list< Arg * > &argList) const
Adds this to the specified list of Args.
static std::string nameStartString()
static std::string ignoreNameString()
The name used to identify the ignore rest argument.
virtual bool isRequired() const
Indicates whether the argument is required.
virtual void setDescription(const std::string &desc)
Updates the argument description.
The base class that manages the command line definition and passes along the parsing to the appropria...
The interface that any output object must implement.
virtual void failure(CmdLineInterface &c, ArgException &e)=0
Generates some sort of output for a failure.
Thrown from CmdLine when the arguments on the command line are not properly specified,...
Registration(const Registration &)=delete
Registration(CmdLine &cmd)
Registration & operator=(const Registration &)=delete
The base class that manages the command line definition and passes along the parsing to the appropria...
std::list< Arg * > _argList
The list of arguments that will be tested against the command line.
void setMessageTranslator(const T &translator)
Sets an optional message translator callback.
std::string getVersion() const override
Returns the version string.
std::list< ArgGroup * > getArgGroups() override
Returns the list of ArgGroups.
void reset() override
Allows the CmdLine object to be reused.
SwitchArg * _ignoreArg
Built-in arguments whose descriptions may need refreshing when the translator changes.
bool _emptyCombined(const std::string &s)
Checks whether a name/flag string matches entirely matches the Arg::blankChar.
std::string getProgramName() const override
Returns the program name string.
int _numRequired
The number of arguments that are required to be present on the command line.
void addToArgList(Arg *a) override
CmdLine & operator=(const CmdLine &rhs)=delete
std::string _version
The version to be displayed with the –version switch.
bool _handleExceptions
Should CmdLine handle parsing exceptions internally?
std::string _message
A message used to describe the program.
StandaloneArgs _standaloneArgs
void setOutput(CmdLineOutput *co) override
CmdLineOutput * _output
Object that handles all output for the CmdLine.
char _delimiter
The character that is used to separate the argument flag/name from the value.
void ignoreUnmatched(const bool ignore)
Allows unmatched args to be ignored.
CmdLine(const CmdLine &rhs)=delete
Prevent accidental copying.
std::unique_ptr< MessageTranslator > _messageTranslator
std::list< ArgGroup * > _argGroups
Some args have set constraints on them (i.e., exactly or at most one must be specified.
DeferDelete _deleteOnExit
Add pointers that should be deleted as part of cleanup when this object is destroyed.
std::string _progName
The name of the program.
bool hasHelpAndVersion() const override
Indicates whether or not the help and version switches were created automatically.
std::list< Arg * > getArgList() const override
bool hasExceptionHandling() const
Returns the current state of the internal exception handling.
std::string translateMessage(const std::string &messageId, const std::string &fallback) const override
Translates a built-in message.
void setExceptionHandling(const bool state)
Disables or enables CmdLine's internal parsing exception handling.
StdOutput _defaultOutput
Default output handler if nothing is specified.
std::string getMessage() const override
Returns the message string.
char getDelimiter() const override
Returns the delimiter string.
void xorAdd(Arg &a, Arg &b) override
void missingArgsException(const std::list< ArgGroup * > &missing)
Throws an exception listing the missing args.
~CmdLine() override=default
Deletes any resources allocated by a CmdLine object.
bool ignoreRest() override
Whether to ignore the rest.
bool attachGroup(ArgGroup &group) override
ArgContainer & add(Arg &a) override
Adds an argument to the list of arguments to be parsed.
bool _hasOptionalUnlabeledArg
void beginIgnoring() override
Begin ignoring arguments since the "--" argument was specified.
void parse(int argc, const char *const *argv) override
Parses the command line.
DeferDelete can be used by objects that need to allocate arbitrary other objects to live for the dura...
Thrown when TCLAP thinks the program should exit.
int getExitStatus() const noexcept
Implements a group of arguments where exactly one must be selected.
Thrown from Arg and CmdLine when an Arg is improperly specified, e.g.
bool showAsGroup() const override
If arguments in this group should show up as grouped in help.
ArgContainer & add(Arg *arg) override
Add an argument to this arg group.
A class that isolates any output from the CmdLine object so that it may be easily modified.
A simple switch argument.
std::string basename(std::string s)
std::string translate(const std::string &messageId, const std::string &fallback) const override
MessageTranslatorImpl(const T &translator)
Optional callback used to localize user-facing strings.
virtual ~MessageTranslator()=default
virtual std::string translate(const std::string &messageId, const std::string &fallback) const =0