Debian Codegraph @

application/argumentparser.h

raw symbols SCIP
1 #ifndef APPLICATION_UTILITIES_ARGUMENTPARSER_H
2 #define APPLICATION_UTILITIES_ARGUMENTPARSER_H
3
4 #include "../conversion/stringconversion.h"
5 #include "../misc/traits.h"
6
7 #include <functional>
8 #include <initializer_list>
9 #include <limits>
10 #include <tuple>
11 #include <vector>
12 #ifdef CPP_UTILITIES_DEBUG_BUILD
13 #include <cassert>
14 #endif
15
16 class ArgumentParserTests; // not a public class (only used for internal tests)
17
18 namespace CppUtilities {
19
20 /*!
21 * \brief Stores information about an application.
22 */
23 struct ApplicationInfo {
24 const char *name = nullptr;
25 const char *author = nullptr;
26 const char *version = nullptr;
27 const char *url = nullptr;
28 const char *domain = nullptr;
29 const char *description = nullptr;
30 const char *license = nullptr;
31 const char *credits = nullptr;
32 std::vector<const char *> dependencyVersions;
33 };
34
35 /*!
36 * \brief Stores global application info used by ArgumentParser::printHelp() and AboutDialog.
37 */
38 CPP_UTILITIES_EXPORT extern ApplicationInfo applicationInfo;
39
40 /*!
41 * \def SET_DEPENDENCY_INFO
42 * \brief Sets meta data about the dependencies the application was linked against which is
43 * used by ArgumentParser::printHelp().
44 * \remarks Reads those data from the config header so "config.h" must be included.
45 */
46 #define SET_DEPENDENCY_INFO ::CppUtilities::applicationInfo.dependencyVersions = DEPENCENCY_VERSIONS
47
48 /*!
49 * \def SET_APPLICATION_INFO
50 * \brief Sets application meta data (including SET_DEPENDENCY_INFO) used by ArgumentParser::printHelp().
51 * \remarks Reads those data from the config header so "config.h" must be included.
52 */
53 #define SET_APPLICATION_INFO \
54 ::CppUtilities::applicationInfo.name = APP_NAME; \
55 ::CppUtilities::applicationInfo.author = APP_AUTHOR; \
56 ::CppUtilities::applicationInfo.version = APP_VERSION; \
57 ::CppUtilities::applicationInfo.url = APP_URL; \
58 ::CppUtilities::applicationInfo.domain = APP_DOMAIN; \
59 ::CppUtilities::applicationInfo.description = APP_DESCRIPTION; \
60 ::CppUtilities::applicationInfo.license = PROJECT_LICENSE; \
61 ::CppUtilities::applicationInfo.credits = APP_CREDITS; \
62 SET_DEPENDENCY_INFO
63
64 class Argument;
65 class ArgumentParser;
66 class ArgumentReader;
67
68 using ArgumentInitializerList = std::initializer_list<Argument *>;
69 using ArgumentVector = std::vector<Argument *>;
70 using ArgumentPredicate = std::function<bool(Argument *)>;
71
72 /*!
73 * \brief The UnknownArgumentBehavior enum specifies the behavior of the argument parser when an unknown
74 * argument is detected.
75 */
76 enum class UnknownArgumentBehavior {
77 Ignore, /**< Unknown arguments are ignored without warnings. */
78 Warn, /**< A warning is printed to std::cerr if an unknown argument is detected. */
79 Fail /**< Further parsing is aborted and a Failure instance with an error message is thrown. */
80 };
81
82 /*!
83 * \brief The ParseArgumentBehavior enum specifies the behavior when parsing arguments.
84 *
85 * This concerns checking constraints, invoking callbacks and handling failures. The values are supposed to be combined
86 * using the |-operator. Note that ParseArgumentBehavior::ReadArguments is always implied.
87 */
88 enum class ParseArgumentBehavior {
89 ReadArguments = 0x0, /**< reads the specified CLI arguments, equivalent to simply calling readArgs() */
90 CheckConstraints = 0x1, /**< whether the constraints should be checked after reading the arguments */
91 InvokeCallbacks = 0x2, /**< whether the callbacks should be invoked after reading the arguments and (maybe) checking the constraints */
92 ExitOnFailure
93 = 0x4, /**< whether the parser should print an error message and terminate the application on failure (rather than throwing an exception) */
94 };
95
96 /// \cond
97 constexpr ParseArgumentBehavior operator|(ParseArgumentBehavior lhs, ParseArgumentBehavior rhs)
98 {
99 return static_cast<ParseArgumentBehavior>(static_cast<unsigned char>(lhs) | static_cast<unsigned char>(rhs));
100 }
101
102 constexpr bool operator&(ParseArgumentBehavior lhs, ParseArgumentBehavior rhs)
103 {
104 return static_cast<bool>(static_cast<unsigned char>(lhs) & static_cast<unsigned char>(rhs));
105 }
106 /// \endcond
107
108 /*!
109 * \brief The ValueCompletionBehavior enum specifies the items to be considered when generating completion for an argument value.
110 * \remarks
111 * - The enumeration items are meant to be combined using the |-operator.
112 * - ValueCompletionBehavior::InvokeCallback is meant to initialize pre-defined values only when required in the callback assigned
113 * via Argument::setCallback(). Hence it makes sense to combine it with ValueCompletionBehavior::PreDefinedValues.
114 * - When ValueCompletionBehavior::InvokeCallback is present, the callback assigned via Argument::setCallback() might be called
115 * even when not all constraints are fulfilled. So, for instance, there might not be all required values present.
116 */
117 enum class ValueCompletionBehavior : unsigned char {
118 None = 0, /**< no auto-completion */
119 PreDefinedValues = 2, /**< values assigned with Argument::setPreDefinedCompletionValues() */
120 Files = 4, /**< files */
121 Directories = 8, /**< directories */
122 FileSystemIfNoPreDefinedValues = 16, /**< files and directories but only if no values have been assigned (default behavior) */
123 AppendEquationSign = 32, /**< an equation sign is appended to values which not contain an equation sign already */
124 InvokeCallback = 64, /**< whether to invoke the callback before reading pre-defined values */
125 };
126
127 /// \cond
128 constexpr ValueCompletionBehavior operator|(ValueCompletionBehavior lhs, ValueCompletionBehavior rhs)
129 {
130 return static_cast<ValueCompletionBehavior>(static_cast<unsigned char>(lhs) | static_cast<unsigned char>(rhs));
131 }
132
133 constexpr bool operator&(ValueCompletionBehavior lhs, ValueCompletionBehavior rhs)
134 {
135 return static_cast<bool>(static_cast<unsigned char>(lhs) & static_cast<unsigned char>(rhs));
136 }
137 /// \endcond
138
139 /*!
140 * \brief Contains functions to convert raw argument values to certain types.
141 *
142 * Extend this namespace by additional convert() functions to allow use of Argument::valuesAs() with your custom types.
143 *
144 * \remarks Still experimental. Might be removed/adjusted in next minor release.
145 */
146 namespace ValueConversion {
147 template <typename TargetType, Traits::EnableIf<std::is_same<TargetType, std::string>> * = nullptr> TargetType convert(const char *value)
148 {
149 return std::string(value);
150 }
151
152 template <typename TargetType, Traits::EnableIf<std::is_arithmetic<TargetType>> * = nullptr> TargetType convert(const char *value)
153 {
154 return stringToNumber<TargetType>(value);
155 }
156
157 /// \cond
158 namespace Helper {
159 struct CPP_UTILITIES_EXPORT ArgumentValueConversionError {
160 const std::string errorMessage;
161 const char *const valueToConvert;
162 const char *const targetTypeName;
163
164 [[noreturn]] void throwFailure(const std::vector<Argument *> &argumentPath) const;
165 };
166
167 template <std::size_t N, typename FirstTargetType, typename... RemainingTargetTypes> struct ArgumentValueConverter {
168 static std::tuple<FirstTargetType, RemainingTargetTypes...> convertValues(std::vector<const char *>::const_iterator firstValue)
169 {
170 return std::tuple_cat(ArgumentValueConverter<1, FirstTargetType>::convertValues(firstValue),
171 ArgumentValueConverter<N - 1, RemainingTargetTypes...>::convertValues(firstValue + 1));
172 }
173 };
174
175 template <typename FirstTargetType, typename... RemainingTargetTypes> struct ArgumentValueConverter<1, FirstTargetType, RemainingTargetTypes...> {
176 static std::tuple<FirstTargetType> convertValues(std::vector<const char *>::const_iterator firstValue)
177 {
178 // FIXME: maybe use std::expected here when available
179 try {
180 return std::make_tuple<FirstTargetType>(ValueConversion::convert<FirstTargetType>(*firstValue));
181 } catch (const ConversionException &exception) {
182 throw ArgumentValueConversionError{ exception.what(), *firstValue, typeid(FirstTargetType).name() };
183 }
184 }
185 };
186 } // namespace Helper
187 /// \endcond
188
189 } // namespace ValueConversion
190
191 /*!
192 * \brief The ArgumentOccurrence struct holds argument values for an occurrence of an argument.
193 */
194 struct CPP_UTILITIES_EXPORT ArgumentOccurrence {
195 ArgumentOccurrence(std::size_t index);
196 ArgumentOccurrence(std::size_t index, const std::vector<Argument *> parentPath, Argument *parent);
197
198 /*!
199 * \brief The index of the occurrence. This is not necessarily the index in the argv array.
200 */
201 std::size_t index;
202
203 /*!
204 * \brief The parameter values which have been specified after the occurrence of the argument.
205 */
206 std::vector<const char *> values;
207
208 /*!
209 * \brief The "path" of the occurrence (the parent elements which have been specified before).
210 * \remarks Empty for top-level occurrences.
211 */
212 std::vector<Argument *> path;
213
214 template <typename... RemainingTargetTypes> std::tuple<RemainingTargetTypes...> convertValues() const;
215
216 private:
217 [[noreturn]] void throwNumberOfValuesNotSufficient(unsigned long valuesToConvert) const;
218 };
219
220 /*!
221 * \brief Converts the present values to the specified target types. There must be as many values present as types are specified.
222 * \throws Throws ArgumentUtilities::Failure when the number of present values is not sufficient or a conversion error occurs.
223 * \remarks Still experimental. Might be removed/adjusted in next minor release.
224 */
225 template <typename... RemainingTargetTypes> std::tuple<RemainingTargetTypes...> ArgumentOccurrence::convertValues() const
226 {
227 constexpr auto valuesToConvert = sizeof...(RemainingTargetTypes);
228 if (values.size() < valuesToConvert) {
229 throwNumberOfValuesNotSufficient(valuesToConvert);
230 }
231 try {
232 return ValueConversion::Helper::ArgumentValueConverter<valuesToConvert, RemainingTargetTypes...>::convertValues(values.cbegin());
233 } catch (const ValueConversion::Helper::ArgumentValueConversionError &error) {
234 error.throwFailure(path);
235 }
236 }
237
238 /*!
239 * \brief Constructs an argument occurrence for the specified \a index.
240 */
241 inline ArgumentOccurrence::ArgumentOccurrence(std::size_t index)
242 : index(index)
243 {
244 }
245
246 /*!
247 * \brief Constructs an argument occurrence.
248 * \param index Specifies the index.
249 * \param parentPath Specifies the path of \a parent.
250 * \param parent Specifies the parent which might be nullptr for top-level occurrences.
251 *
252 * The path of the new occurrence is built from the specified \a parentPath and \a parent.
253 */
254 inline ArgumentOccurrence::ArgumentOccurrence(std::size_t index, const std::vector<Argument *> parentPath, Argument *parent)
255 : index(index)
256 , path(parentPath)
257 {
258 if (parent) {
259 path.push_back(parent);
260 }
261 }
262
263 class CPP_UTILITIES_EXPORT Argument {
264 friend ArgumentParser;
265 friend ArgumentReader;
266 friend ArgumentParserTests;
267
268 public:
269 typedef std::function<void(const ArgumentOccurrence &)> CallbackFunction;
270
271 /// \brief The Flags enum specifies options for treating the argument in a special way.
272 enum class Flags : std::uint64_t {
273 None = 0x0, /**< No flags are present. The default for Argument(). */
274 Combinable
275 = 0x1, /**< It is no error if this argument occurs besides other arguments on the same level. The default for ConfigValueArgument. */
276 Implicit = 0x2, /**< The argument is assumed to be present if its values are present. Only one argument can be implicit at the same level. */
277 Operation = 0x4, /**< The argument is an operation, so no `--` prefix is required when specifying it. The default for OperationArgument(). */
278 Deprecated = 0x8, /**< The argument is considered deprecated and therefore excluded from the help. */
279 Greedy
280 = 0x10, /**< The argument is "greedy" so when Argument::varValueCount is used all subsequent arguments will be considered values of that argument. This is useful to pass remaining arguments down to another argument parser as-is. */
281 };
282
283 Argument(const char *name, char abbreviation = '\0', const char *description = nullptr, const char *example = nullptr);
284 ~Argument();
285
286 // declare getter/setter/properties/operations for argument definition:
287 // - those properties must be set *before* parsing
288 // - they control the behaviour of the parser, eg.
289 // - the name/abbreviation to look for
290 // - constraints to be checked
291 // - callbacks to be invoked
292 // TODO v5: It would make sense to move these to a separate class (eg. ArgumentDefinition) to prevent this one from
293 // becoming to big.
294 const char *name() const;
295 void setName(const char *name);
296 char abbreviation() const;
297 void setAbbreviation(char abbreviation);
298 const char *environmentVariable() const;
299 void setEnvironmentVariable(const char *environmentVariable);
300 const char *description() const;
301 void setDescription(const char *description);
302 const char *example() const;
303 void setExample(const char *example);
304 std::size_t requiredValueCount() const;
305 void setRequiredValueCount(std::size_t requiredValueCount);
306 const std::vector<const char *> &valueNames() const;
307 void setValueNames(std::initializer_list<const char *> valueNames);
308 void appendValueName(const char *valueName);
309 void setConstraints(std::size_t minOccurrences, std::size_t maxOccurrences);
310 const std::vector<Argument *> &path(std::size_t occurrence = 0) const;
311 bool isRequired() const;
312 void setRequired(bool required);
313 Argument::Flags flags() const;
314 void setFlags(Argument::Flags flags);
315 void setFlags(Argument::Flags flags, bool add);
316 bool isCombinable() const;
317 void setCombinable(bool combinable);
318 bool isImplicit() const;
319 void setImplicit(bool implicit);
320 bool denotesOperation() const;
321 void setDenotesOperation(bool denotesOperation);
322 const CallbackFunction &callback() const;
323 void setCallback(CallbackFunction callback);
324 const ArgumentVector &subArguments() const;
325 void setSubArguments(const ArgumentInitializerList &subArguments);
326 void addSubArguments(const ArgumentInitializerList &subArguments);
327 void addSubArgument(Argument *arg);
328 bool hasSubArguments() const;
329 const ArgumentVector &parents() const;
330 void printInfo(std::ostream &os, unsigned char indentation = 0) const;
331
332 // declare getter/setter/properties for bash completion: those properties must be set *before parsing
333 ValueCompletionBehavior valueCompletionBehaviour() const;
334 void setValueCompletionBehavior(ValueCompletionBehavior valueCompletionBehaviour);
335 const char *preDefinedCompletionValues() const;
336 void setPreDefinedCompletionValues(const char *preDefinedCompletionValues);
337
338 // declare getter/read-only properties for parsing results: those properties will be populated when parsing
339 const std::vector<const char *> &values(std::size_t occurrence = 0) const;
340 template <typename... TargetType> std::tuple<TargetType...> valuesAs(std::size_t occurrence = 0) const;
341 template <typename... TargetType> std::vector<std::tuple<TargetType...>> allValuesAs() const;
342
343 const char *firstValue() const;
344 const char *firstValueOr(const char *fallback) const;
345 bool allRequiredValuesPresent(std::size_t occurrence = 0) const;
346 bool isPresent() const;
347 std::size_t occurrences() const;
348 std::size_t index(std::size_t occurrence) const;
349 std::size_t minOccurrences() const;
350 std::size_t maxOccurrences() const;
351 bool isDeprecated() const;
352 const Argument *deprecatedBy() const;
353 void markAsDeprecated(const Argument *deprecatedBy = nullptr);
354 bool isMainArgument() const;
355 bool isParentPresent() const;
356 Argument *conflictsWithArgument() const;
357 Argument *wouldConflictWithArgument() const;
358 Argument *specifiedOperation() const;
359 const std::vector<ArgumentOccurrence> &occurrenceInfo() const;
360 std::vector<ArgumentOccurrence> &occurrenceInfo();
361 void reset();
362 void resetRecursively();
363
364 /*!
365 * \brief Denotes a variable number of values.
366 * \sa setRequiredValueCount()
367 */
368 static constexpr std::size_t varValueCount = std::numeric_limits<std::size_t>::max();
369
370 private:
371 // declare internal getter/setter/properties/operations for argument definition
372 bool matchesDenotation(const char *denotation, std::size_t denotationLength) const;
373
374 const char *m_name;
375 char m_abbreviation;
376 const char *m_environmentVar;
377 const char *m_description;
378 const char *m_example;
379 std::size_t m_minOccurrences;
380 std::size_t m_maxOccurrences;
381 std::size_t m_requiredValueCount;
382 std::vector<const char *> m_valueNames;
383 Flags m_flags;
384 std::vector<ArgumentOccurrence> m_occurrences;
385 ArgumentVector m_subArgs;
386 CallbackFunction m_callbackFunction;
387 ArgumentVector m_parents;
388 const Argument *m_deprecatedBy;
389 bool m_isMainArg;
390 ValueCompletionBehavior m_valueCompletionBehavior;
391 const char *m_preDefinedCompletionValues;
392 };
393
394 /// \cond
395 constexpr Argument::Flags operator|(Argument::Flags lhs, Argument::Flags rhs)
396 {
397 return static_cast<Argument::Flags>(static_cast<unsigned char>(lhs) | static_cast<unsigned char>(rhs));
398 }
399
400 constexpr bool operator&(Argument::Flags lhs, Argument::Flags rhs)
401 {
402 return static_cast<bool>(static_cast<unsigned char>(lhs) & static_cast<unsigned char>(rhs));
403 }
404 /// \endcond
405
406 /*!
407 * \brief Converts the present values for the specified \a occurrence to the specified target types. There must be as many values present as types are specified.
408 * \throws Throws ArgumentUtilities::Failure when the number of present values is not sufficient or a conversion error occurs.
409 * \remarks Still experimental. Might be removed/adjusted in next minor release.
410 */
411 template <typename... TargetType> std::tuple<TargetType...> Argument::valuesAs(std::size_t occurrence) const
412 {
413 return m_occurrences[occurrence].convertValues<TargetType...>();
414 }
415
416 /*!
417 * \brief Converts the present values for all occurrences to the specified target types. For each occurrence, there must be as many values present as types are specified.
418 * \throws Throws ArgumentUtilities::Failure when the number of present values is not sufficient or a conversion error occurs.
419 * \remarks Still experimental. Might be removed/adjusted in next minor release.
420 */
421 template <typename... TargetType> std::vector<std::tuple<TargetType...>> Argument::allValuesAs() const
422 {
423 std::vector<std::tuple<TargetType...>> res;
424 res.reserve(m_occurrences.size());
425 for (const auto &occurrence : m_occurrences) {
426 res.emplace_back(occurrence.convertValues<TargetType...>());
427 }
428 return res;
429 }
430
431 class CPP_UTILITIES_EXPORT HelpArgument : public Argument {
432 public:
433 HelpArgument(ArgumentParser &parser);
434 };
435
436 class CPP_UTILITIES_EXPORT OperationArgument : public Argument {
437 public:
438 OperationArgument(const char *name, char abbreviation = '\0', const char *description = nullptr, const char *example = nullptr);
439 };
440
441 class CPP_UTILITIES_EXPORT ConfigValueArgument : public Argument {
442 public:
443 ConfigValueArgument(const char *name, char abbreviation = '\0', const char *description = nullptr,
444 std::initializer_list<const char *> valueNames = std::initializer_list<const char *>());
445 };
446
447 class CPP_UTILITIES_EXPORT NoColorArgument : public Argument {
448 friend ArgumentParserTests;
449
450 public:
451 NoColorArgument();
452 void apply() const;
453 };
454
455 struct ArgumentCompletionInfo;
456
457 class CPP_UTILITIES_EXPORT ArgumentParser {
458 friend ArgumentParserTests;
459 friend ArgumentReader;
460
461 public:
462 ArgumentParser();
463
464 // declare getter/setter for argument definitions
465 const ArgumentVector &mainArguments() const;
466 void setMainArguments(const ArgumentInitializerList &mainArguments);
467 void addMainArgument(Argument *argument);
468
469 // declare operations which will consider previously assigned argument definitions and maybe modify parsing results
470 void printHelp(std::ostream &os) const;
471 void parseArgs(int argc, const char *const *argv,
472 ParseArgumentBehavior behavior
473 = ParseArgumentBehavior::CheckConstraints | ParseArgumentBehavior::InvokeCallbacks | ParseArgumentBehavior::ExitOnFailure);
474 void readArgs(int argc, const char *const *argv);
475 void resetArgs();
476 void assumeDefaultArgument();
477 void ensureDefaultOperation();
478 void checkConstraints();
479 void invokeCallbacks();
480
481 // declare getter for parsing results
482 unsigned int actualArgumentCount() const;
483 const char *executable() const;
484 UnknownArgumentBehavior unknownArgumentBehavior() const;
485 void setUnknownArgumentBehavior(UnknownArgumentBehavior behavior);
486 Argument *defaultArgument() const;
487 void setDefaultArgument(Argument *argument);
488 Argument *specifiedOperation() const;
489 bool isUncombinableMainArgPresent() const;
490 void setExitFunction(std::function<void(int)> exitFunction);
491 const HelpArgument &helpArg() const;
492 HelpArgument &helpArg();
493 const NoColorArgument &noColorArg() const;
494 NoColorArgument &noColorArg();
495
496 private:
497 // declare internal operations
498 CPP_UTILITIES_IF_DEBUG_BUILD(void verifyArgs(const ArgumentVector &args);)
499 ArgumentCompletionInfo determineCompletionInfo(
500 int argc, const char *const *argv, unsigned int currentWordIndex, const ArgumentReader &reader) const;
501 std::string findSuggestions(int argc, const char *const *argv, unsigned int cursorPos, const ArgumentReader &reader) const;
502 void printBashCompletion(int argc, const char *const *argv, unsigned int cursorPos, const ArgumentReader &reader) const;
503 void checkConstraints(const ArgumentVector &args);
504 static void invokeCallbacks(const ArgumentVector &args);
505 void invokeExit(int code);
506
507 ArgumentVector m_mainArgs;
508 unsigned int m_actualArgc;
509 const char *m_executable;
510 UnknownArgumentBehavior m_unknownArgBehavior;
511 Argument *m_defaultArg;
512 HelpArgument m_helpArg;
513 NoColorArgument m_noColorArg;
514 std::function<void(int)> m_exitFunction;
515 };
516
517 /*!
518 * \brief Returns the name of the argument.
519 *
520 * The parser compares the name with the characters following a "--" prefix to identify arguments.
521 */
522 inline const char *Argument::name() const
523 {
524 return m_name;
525 }
526
527 /*!
528 * \brief Sets the name of the argument.
529 *
530 * The name mustn't be empty, start with a minus or contain white spaces, equation chars, quotes and newlines.
531 *
532 * The parser compares the name with the characters following a "--" prefix to identify arguments.
533 */
534 inline void Argument::setName(const char *name)
535 {
536 #if defined(CPP_UTILITIES_DEBUG_BUILD) && !defined(_MSC_VER)
537 if (name && *name) {
538 assert(*name != '-');
539 for (const char *c = name; *c; ++c) {
540 assert(*c != ' ' && *c != '=' && *c != '\'' && *c != '\"' && *c != '\n' && *c != '\r');
541 }
542 }
543 #endif
544 m_name = name;
545 }
546
547 /*!
548 * \brief Returns the abbreviation of the argument.
549 *
550 * The parser compares the abbreviation with the characters following a "-" prefix to identify arguments.
551 */
552 inline char Argument::abbreviation() const
553 {
554 return m_abbreviation;
555 }
556
557 /*!
558 * \brief Sets the abbreviation of the argument.
559 *
560 * The abbreviation might be empty but mustn't be white spaces, equation char, single quote, double quote or newline.
561 *
562 * The parser compares the abbreviation with the characters following a "-" prefix to identify arguments.
563 */
564 inline void Argument::setAbbreviation(char abbreviation)
565 {
566 CPP_UTILITIES_IF_DEBUG_BUILD(assert(abbreviation != ' ' && abbreviation != '=' && abbreviation != '-' && abbreviation != '\''
567 && abbreviation != '"' && abbreviation != '\n' && abbreviation != '\r'));
568 m_abbreviation = abbreviation;
569 }
570
571 /*!
572 * \brief Returns the environment variable queried when firstValue() is called.
573 * \sa firstValue(), setEnvironmentVariable()
574 */
575 inline const char *Argument::environmentVariable() const
576 {
577 return m_environmentVar;
578 }
579
580 /*!
581 * \brief Sets the environment variable queried when firstValue() is called.
582 * \sa firstValue(), environmentVariable()
583 */
584 inline void Argument::setEnvironmentVariable(const char *environmentVariable)
585 {
586 m_environmentVar = environmentVariable;
587 }
588
589 /*!
590 * \brief Returns the description of the argument.
591 *
592 * The parser uses the description when printing help information.
593 */
594 inline const char *Argument::description() const
595 {
596 return m_description;
597 }
598
599 /*!
600 * \brief Sets the description of the argument.
601 *
602 * The parser uses the description when printing help information.
603 */
604 inline void Argument::setDescription(const char *description)
605 {
606 m_description = description;
607 }
608
609 /*!
610 * \brief Returns the usage example of the argument.
611 *
612 * The parser uses the description when printing help information.
613 */
614 inline const char *Argument::example() const
615 {
616 return m_example;
617 }
618
619 /*!
620 * \brief Sets the a usage example for the argument.
621 *
622 * The parser uses the description when printing help information.
623 */
624 inline void Argument::setExample(const char *example)
625 {
626 m_example = example;
627 }
628
629 /*!
630 * \brief Returns the parameter values for the specified \a occurrence of argument.
631 * \remarks
632 * - The values are set by the parser when parsing the command line arguments.
633 * - The specified \a occurrence must be less than occurrences().
634 */
635 inline const std::vector<const char *> &Argument::values(std::size_t occurrence) const
636 {
637 return m_occurrences[occurrence].values;
638 }
639
640 /*!
641 * \brief Returns the number of values which are required to be given
642 * for this argument.
643 *
644 * The parser will expect that many values when parsing command line arguments.
645 * A negative value indicates a variable number of arguments to be expected.
646 *
647 * The default value is 0, except for ConfigValueArgument instances.
648 *
649 * \sa setRequiredValueCount()
650 * \sa valueNames()
651 * \sa setValueNames()
652 */
653 inline std::size_t Argument::requiredValueCount() const
654 {
655 return m_requiredValueCount;
656 }
657
658 /*!
659 * \brief Sets the number of values which are required to be given
660 * for this argument.
661 *
662 * The parser will expect that many values when parsing command line arguments.
663 * Pass Argument::varValueCount for a variable number of arguments
664 * to be expected.
665 *
666 * \sa requiredValueCount()
667 * \sa valueNames()
668 * \sa setValueNames()
669 */
670 inline void Argument::setRequiredValueCount(std::size_t requiredValueCount)
671 {
672 m_requiredValueCount = requiredValueCount;
673 }
674
675 /*!
676 * \brief Returns the names of the required values.
677 *
678 * These names will be shown when printing information about the argument.
679 *
680 * \sa setValueNames()
681 * \sa appendValueName()
682 */
683 inline const std::vector<const char *> &Argument::valueNames() const
684 {
685 return m_valueNames;
686 }
687
688 /*!
689 * \brief Sets the names of the required values. These names will be used
690 * when printing information about the argument.
691 *
692 * If the number of value names is higher than the number of required values
693 * the additional value names will be ignored.
694 * If the number of value names is lesser than the number of required values
695 * generic values will be used for the missing names.
696 *
697 * \sa appendValueName()
698 * \sa valueNames()
699 * \sa requiredValueCount()
700 */
701 inline void Argument::setValueNames(std::initializer_list<const char *> valueNames)
702 {
703 m_valueNames.assign(valueNames);
704 }
705
706 /*!
707 * \brief Appends a value name. The value names names will be shown
708 * when printing information about the argument.
709 * \sa setValueNames()
710 * \sa valueNames()
711 */
712 inline void Argument::appendValueName(const char *valueName)
713 {
714 m_valueNames.emplace_back(valueName);
715 }
716
717 /*!
718 * \brief Returns an indication whether all required values are present.
719 */
720 inline bool Argument::allRequiredValuesPresent(std::size_t occurrence) const
721 {
722 return m_requiredValueCount == Argument::varValueCount
723 || (m_occurrences[occurrence].values.size() >= static_cast<std::size_t>(m_requiredValueCount));
724 }
725
726 /*!
727 * \brief Returns an indication whether the argument is an implicit argument.
728 * \sa setImplicit()
729 */
730 inline bool Argument::isImplicit() const
731 {
732 return m_flags & Flags::Implicit;
733 }
734
735 /*!
736 * \brief Sets whether the argument is an implicit argument.
737 * \sa isImplicit()
738 */
739 inline void Argument::setImplicit(bool implicit)
740 {
741 setFlags(Flags::Implicit, implicit);
742 }
743
744 /*!
745 * \brief Returns an indication whether the argument could be detected when parsing.
746 */
747 inline bool Argument::isPresent() const
748 {
749 return !m_occurrences.empty();
750 }
751
752 /*!
753 * \brief Returns how often the argument could be detected when parsing.
754 */
755 inline std::size_t Argument::occurrences() const
756 {
757 return m_occurrences.size();
758 }
759
760 /*!
761 * \brief Returns the indices of the argument's occurrences which could be detected when parsing.
762 */
763 inline std::size_t Argument::index(std::size_t occurrence) const
764 {
765 return m_occurrences[occurrence].index;
766 }
767
768 /*!
769 * \brief Returns the minimum number of occurrences.
770 *
771 * If the argument occurs not that many times, the parser will complain.
772 */
773 inline std::size_t Argument::minOccurrences() const
774 {
775 return m_minOccurrences;
776 }
777
778 /*!
779 * \brief Returns the maximum number of occurrences.
780 *
781 * If the argument occurs more often, the parser will complain.
782 */
783 inline std::size_t Argument::maxOccurrences() const
784 {
785 return m_maxOccurrences;
786 }
787
788 inline bool Argument::isDeprecated() const
789 {
790 return m_flags & Flags::Deprecated;
791 }
792
793 /*!
794 * \brief Returns the argument which obsoletes this argument.
795 */
796 inline const Argument *Argument::deprecatedBy() const
797 {
798 return m_deprecatedBy;
799 }
800
801 /*!
802 * \brief Marks the argument as deprecated.
803 *
804 * If another argument should be used instead, specify it via \a deprecatedBy.
805 */
806 inline void Argument::markAsDeprecated(const Argument *deprecatedBy)
807 {
808 setFlags(Flags::Deprecated, true);
809 m_deprecatedBy = deprecatedBy;
810 }
811
812 /*!
813 * \brief Sets the allowed number of occurrences.
814 * \sa minOccurrences()
815 * \sa maxOccurrences()
816 */
817 inline void Argument::setConstraints(std::size_t minOccurrences, std::size_t maxOccurrences)
818 {
819 m_minOccurrences = minOccurrences;
820 m_maxOccurrences = maxOccurrences;
821 }
822
823 /*!
824 * \brief Returns the path of the specified \a occurrence.
825 */
826 inline const std::vector<Argument *> &Argument::path(std::size_t occurrence) const
827 {
828 return m_occurrences[occurrence].path;
829 }
830
831 /*!
832 * \brief Returns an indication whether the argument is mandatory.
833 *
834 * The parser will complain if a mandatory argument is not present.
835 *
836 * The default value is false.
837 *
838 * \sa setRequired()
839 */
840 inline bool Argument::isRequired() const
841 {
842 return m_minOccurrences;
843 }
844
845 /*!
846 * \brief Sets whether this argument is mandatory or not.
847 *
848 * The parser will complain if a mandatory argument is not present.
849 *
850 * * \sa isRequired()
851 */
852 inline void Argument::setRequired(bool required)
853 {
854 if (required) {
855 if (!m_minOccurrences) {
856 m_minOccurrences = 1;
857 }
858 } else {
859 m_minOccurrences = 0;
860 }
861 }
862
863 /*!
864 * \brief Returns Argument::Flags for the argument.
865 */
866 inline Argument::Flags Argument::flags() const
867 {
868 return m_flags;
869 }
870
871 /*!
872 * \brief Replaces all Argument::Flags for the argument with the \a flags.
873 */
874 inline void Argument::setFlags(Argument::Flags flags)
875 {
876 m_flags = flags;
877 }
878
879 /*!
880 * \brief Adds or removes the specified \a flags.
881 */
882 inline void Argument::setFlags(Argument::Flags flags, bool add)
883 {
884 m_flags = add ? (m_flags | flags)
885 : static_cast<Argument::Flags>(static_cast<std::underlying_type<Argument::Flags>::type>(m_flags)
886 & ~static_cast<std::underlying_type<Argument::Flags>::type>(flags));
887 }
888
889 /*!
890 * \brief Returns an indication whether the argument is combinable.
891 *
892 * The parser will complain if two arguments labeled as uncombinable are
893 * present at the same time.
894 *
895 * \sa setCombinable()
896 */
897 inline bool Argument::isCombinable() const
898 {
899 return m_flags & Flags::Combinable;
900 }
901
902 /*!
903 * \brief Sets whether this argument can be combined.
904 *
905 * The parser will complain if two arguments labeled as uncombinable are
906 * present at the same time.
907 *
908 * \sa isCombinable()
909 */
910 inline void Argument::setCombinable(bool combinable)
911 {
912 setFlags(Flags::Combinable, combinable);
913 }
914
915 /*!
916 * \brief Returns whether the argument denotes an operation.
917 *
918 * An argument which denotes an operation might be specified
919 * without "--" or "-" prefix.
920 *
921 * The default value is false, except for OperationArgument instances.
922 *
923 * \sa setDenotesOperation()
924 */
925 inline bool Argument::denotesOperation() const
926 {
927 return m_flags & Flags::Operation;
928 }
929
930 /*!
931 * \brief Sets whether the argument denotes the operation.
932 * \sa denotesOperation()
933 */
934 inline void Argument::setDenotesOperation(bool denotesOperation)
935 {
936 setFlags(Flags::Operation, denotesOperation);
937 }
938
939 /*!
940 * \brief Returns the assigned callback function.
941 * \sa setCallback()
942 */
943 inline const Argument::CallbackFunction &Argument::callback() const
944 {
945 return m_callbackFunction;
946 }
947
948 /*!
949 * \brief Sets a \a callback function which will be called by the parser if
950 * the argument could be found and no parsing errors occurred.
951 * \remarks The \a callback will be called for each occurrence of the argument.
952 * \sa callback()
953 */
954 inline void Argument::setCallback(Argument::CallbackFunction callback)
955 {
956 m_callbackFunction = callback;
957 }
958
959 /*!
960 * \brief Returns the secondary arguments for this argument.
961 *
962 * \sa setSubArguments()
963 * \sa hasSubArguments()
964 */
965 inline const ArgumentVector &Argument::subArguments() const
966 {
967 return m_subArgs;
968 }
969
970 /*!
971 * \brief Returns an indication whether the argument has secondary arguments.
972 *
973 * \sa secondaryArguments()
974 * \sa setSubArguments()
975 */
976 inline bool Argument::hasSubArguments() const
977 {
978 return !m_subArgs.empty();
979 }
980
981 /*!
982 * \brief Returns the parents of this argument.
983 *
984 * If this argument is used as secondary argument, the arguments which
985 * contain this argument as secondary arguments are returned
986 * as "parents" of this argument.
987 *
988 * If this argument is used as a main argument shouldn't be used as
989 * secondary argument at the same time and thus have no parents.
990 */
991 inline const ArgumentVector &Argument::parents() const
992 {
993 return m_parents;
994 }
995
996 /*!
997 * \brief Returns an indication whether the argument is used as main argument.
998 *
999 * An argument used as main argument shouldn't be used as secondary
1000 * arguments at the same time.
1001 */
1002 inline bool Argument::isMainArgument() const
1003 {
1004 return m_isMainArg;
1005 }
1006
1007 /*!
1008 * \brief Returns the items to be considered when generating completion for the values.
1009 *
1010 * By default, files and directories are considered, unless pre-defined values have been
1011 * specified using setPreDefinedCompletionValues().
1012 */
1013 inline ValueCompletionBehavior Argument::valueCompletionBehaviour() const
1014 {
1015 return m_valueCompletionBehavior;
1016 }
1017
1018 /*!
1019 * \brief Sets the items to be considered when generating completion for the values.
1020 *
1021 * By default, files and directories are considered, unless pre-defined values have been
1022 * specified using setPreDefinedCompletionValues().
1023 */
1024 inline void Argument::setValueCompletionBehavior(ValueCompletionBehavior completionValues)
1025 {
1026 m_valueCompletionBehavior = completionValues;
1027 }
1028
1029 /*!
1030 * \brief Returns the assigned values used when generating completion for the values.
1031 */
1032 inline const char *Argument::preDefinedCompletionValues() const
1033 {
1034 return m_preDefinedCompletionValues;
1035 }
1036
1037 /*!
1038 * \brief Assigns the values to be used when generating completion for the values.
1039 */
1040 inline void Argument::setPreDefinedCompletionValues(const char *preDefinedCompletionValues)
1041 {
1042 m_preDefinedCompletionValues = preDefinedCompletionValues;
1043 }
1044
1045 /*!
1046 * \brief Resets occurrences (indices, values and paths).
1047 *
1048 * So parsing results are wiped while the argument definition is preserved.
1049 */
1050 inline void Argument::reset()
1051 {
1052 m_occurrences.clear();
1053 }
1054
1055 inline OperationArgument::OperationArgument(const char *name, char abbreviation, const char *description, const char *example)
1056 : Argument(name, abbreviation, description, example)
1057 {
1058 setDenotesOperation(true);
1059 }
1060
1061 /*!
1062 * \brief Constructs a new ConfigValueArgument with the specified parameter. The initial value of requiredValueCount() is set to size of specified \a valueNames.
1063 */
1064 inline ConfigValueArgument::ConfigValueArgument(
1065 const char *name, char abbreviation, const char *description, std::initializer_list<const char *> valueNames)
1066 : Argument(name, abbreviation, description)
1067 {
1068 setCombinable(true);
1069 setRequiredValueCount(valueNames.size());
1070 setValueNames(valueNames);
1071 }
1072
1073 /*!
1074 * \brief Returns information about all occurrences of the argument which have been detected when parsing.
1075 * \remarks The convenience methods isPresent(), values() and path() provide direct access to these information for a particular occurrence.
1076 */
1077 inline const std::vector<ArgumentOccurrence> &Argument::occurrenceInfo() const
1078 {
1079 return m_occurrences;
1080 }
1081
1082 /*!
1083 * \brief Returns information about all occurrences of the argument which have been detected when parsing.
1084 * \remarks
1085 * This information is meant to be set by the ArgumentParser. Modifying it directly is likely not a good idea. This method has been
1086 * added primarily for testing purposes. In this case it might make sense to skip the actual parsing and just provide some dummy values.
1087 */
1088 inline std::vector<ArgumentOccurrence> &Argument::occurrenceInfo()
1089 {
1090 return m_occurrences;
1091 }
1092
1093 /*!
1094 * \brief Returns the main arguments.
1095 * \sa setMainArguments()
1096 */
1097 inline const ArgumentVector &ArgumentParser::mainArguments() const
1098 {
1099 return m_mainArgs;
1100 }
1101
1102 /*!
1103 * \brief Returns the actual number of arguments that could be found when parsing.
1104 */
1105 inline unsigned int ArgumentParser::actualArgumentCount() const
1106 {
1107 return m_actualArgc;
1108 }
1109
1110 /*!
1111 * \brief Returns the name of the current executable.
1112 */
1113 inline const char *ArgumentParser::executable() const
1114 {
1115 return m_executable;
1116 }
1117
1118 /*!
1119 * \brief Returns how unknown arguments are treated.
1120 *
1121 * The default value is UnknownArgumentBehavior::Fail.
1122 */
1123 inline UnknownArgumentBehavior ArgumentParser::unknownArgumentBehavior() const
1124 {
1125 return m_unknownArgBehavior;
1126 }
1127
1128 /*!
1129 * \brief Sets how unknown arguments are treated.
1130 *
1131 * The default value is UnknownArgumentBehavior::Fail.
1132 */
1133 inline void ArgumentParser::setUnknownArgumentBehavior(UnknownArgumentBehavior behavior)
1134 {
1135 m_unknownArgBehavior = behavior;
1136 }
1137
1138 /*!
1139 * \brief Returns the default argument.
1140 * \remarks The default argument is assumed to be present if no other arguments have been specified.
1141 */
1142 inline Argument *ArgumentParser::defaultArgument() const
1143 {
1144 return m_defaultArg;
1145 }
1146
1147 /*!
1148 * \brief Sets the default argument.
1149 * \remarks The default argument is assumed to be present if no other arguments have been specified.
1150 */
1151 inline void ArgumentParser::setDefaultArgument(Argument *argument)
1152 {
1153 m_defaultArg = argument;
1154 }
1155
1156 /*!
1157 * \brief Checks whether constraints are violated.
1158 * \remarks Automatically called by parseArgs().
1159 * \throws Throws Failure if constraints are violated.
1160 */
1161 inline void ArgumentParser::checkConstraints()
1162 {
1163 checkConstraints(m_mainArgs);
1164 }
1165
1166 /*!
1167 * \brief Invokes all assigned callbacks.
1168 * \remarks Automatically called by parseArgs().
1169 */
1170 inline void ArgumentParser::invokeCallbacks()
1171 {
1172 invokeCallbacks(m_mainArgs);
1173 }
1174
1175 /*!
1176 * \brief Specifies a function quit the application.
1177 * \remarks Currently only used after printing Bash completion. Default is std::exit().
1178 */
1179 inline void ArgumentParser::setExitFunction(std::function<void(int)> exitFunction)
1180 {
1181 m_exitFunction = exitFunction;
1182 }
1183
1184 /*!
1185 * \brief Returns the `--help` argument.
1186 */
1187 inline const HelpArgument &ArgumentParser::helpArg() const
1188 {
1189 return m_helpArg;
1190 }
1191
1192 /*!
1193 * \brief Returns the `--help` argument.
1194 */
1195 inline HelpArgument &ArgumentParser::helpArg()
1196 {
1197 return m_helpArg;
1198 }
1199
1200 /*!
1201 * \brief Returns the `--no-color` argument.
1202 */
1203 inline const NoColorArgument &ArgumentParser::noColorArg() const
1204 {
1205 return m_noColorArg;
1206 }
1207
1208 /*!
1209 * \brief Returns the `--no-color` argument.
1210 */
1211 inline NoColorArgument &ArgumentParser::noColorArg()
1212 {
1213 return m_noColorArg;
1214 }
1215
1216 } // namespace CppUtilities
1217
1218 #endif // APPLICATION_UTILITIES_ARGUMENTPARSER_H