C++ Utilities: application/argumentparser.h Source File

C++ Utilities 5.32.1 Useful C++ classes and routines such as argument parser, IO and conversion utilities

Loading...
Searching...
No Matches
argumentparser.h
Go to the documentation of this file.
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
16class ArgumentParserTests; // not a public class (only used for internal tests)
17
18 namespace CppUtilities {
19
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
38 CPP_UTILITIES_EXPORT extern ApplicationInfo applicationInfo;
39
46#define SET_DEPENDENCY_INFO ::CppUtilities::applicationInfo.dependencyVersions = DEPENCENCY_VERSIONS
47
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
64class Argument;
65class ArgumentParser;
66class ArgumentReader;
67
68 using ArgumentInitializerList = std::initializer_list<Argument *>;
69 using ArgumentVector = std::vector<Argument *>;
70 using ArgumentPredicate = std::function<bool(Argument *)>;
71
76 enum class UnknownArgumentBehavior {
77 Ignore,
78 Warn,
79 Fail
80};
81
88 enum class ParseArgumentBehavior {
89 ReadArguments = 0x0,
90 CheckConstraints = 0x1,
91 InvokeCallbacks = 0x2,
92 ExitOnFailure
93 = 0x4,
94};
95
97constexpr ParseArgumentBehavior operator|(ParseArgumentBehavior lhs, ParseArgumentBehavior rhs)
98{
99 return static_cast<ParseArgumentBehavior>(static_cast<unsigned char>(lhs) | static_cast<unsigned char>(rhs));
100}
101
102constexpr bool operator&(ParseArgumentBehavior lhs, ParseArgumentBehavior rhs)
103{
104 return static_cast<bool>(static_cast<unsigned char>(lhs) & static_cast<unsigned char>(rhs));
105}
107
117 enum class ValueCompletionBehavior : unsigned char {
118 None = 0,
119 PreDefinedValues = 2,
120 Files = 4,
121 Directories = 8,
122 FileSystemIfNoPreDefinedValues = 16,
123 AppendEquationSign = 32,
124 InvokeCallback = 64,
125};
126
128constexpr ValueCompletionBehavior operator|(ValueCompletionBehavior lhs, ValueCompletionBehavior rhs)
129{
130 return static_cast<ValueCompletionBehavior>(static_cast<unsigned char>(lhs) | static_cast<unsigned char>(rhs));
131}
132
133constexpr bool operator&(ValueCompletionBehavior lhs, ValueCompletionBehavior rhs)
134{
135 return static_cast<bool>(static_cast<unsigned char>(lhs) & static_cast<unsigned char>(rhs));
136}
138
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
158namespace Helper {
159struct 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
167template <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
175template <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
188
189} // namespace ValueConversion
190
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
201 std::size_t index;
202
206 std::vector<const char *> values;
207
212 std::vector<Argument *> path;
213
214 template <typename... RemainingTargetTypes> std::tuple<RemainingTargetTypes...> convertValues() const;
215
216private:
217 [[noreturn]] void throwNumberOfValuesNotSufficient(unsigned long valuesToConvert) const;
218};
219
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
241 inline ArgumentOccurrence::ArgumentOccurrence(std::size_t index)
242 : index(index)
243{
244}
245
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
268public:
269 typedef std::function<void(const ArgumentOccurrence &)> CallbackFunction;
270
272 enum class Flags : std::uint64_t {
273 None = 0x0,
274 Combinable
275 = 0x1,
276 Implicit = 0x2,
277 Operation = 0x4,
278 Deprecated = 0x8,
279 Greedy
280 = 0x10,
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
368 static constexpr std::size_t varValueCount = std::numeric_limits<std::size_t>::max();
369
370private:
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
395constexpr 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
400constexpr 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}
405
411 template <typename... TargetType> std::tuple<TargetType...> Argument::valuesAs(std::size_t occurrence) const
412{
413 return m_occurrences[occurrence].convertValues<TargetType...>();
414}
415
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 {
432public:
433 HelpArgument(ArgumentParser &parser);
434};
435
436 class CPP_UTILITIES_EXPORT OperationArgument : public Argument {
437public:
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 {
442public:
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
450public:
451 NoColorArgument();
452 void apply() const;
453};
454
455struct ArgumentCompletionInfo;
456
457 class CPP_UTILITIES_EXPORT ArgumentParser {
458 friend ArgumentParserTests;
459 friend ArgumentReader;
460
461public:
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
496private:
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
522 inline const char *Argument::name() const
523{
524 return m_name;
525}
526
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
552 inline char Argument::abbreviation() const
553{
554 return m_abbreviation;
555}
556
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
575 inline const char *Argument::environmentVariable() const
576{
577 return m_environmentVar;
578}
579
584 inline void Argument::setEnvironmentVariable(const char *environmentVariable)
585{
586 m_environmentVar = environmentVariable;
587}
588
594 inline const char *Argument::description() const
595{
596 return m_description;
597}
598
604 inline void Argument::setDescription(const char *description)
605{
606 m_description = description;
607}
608
614 inline const char *Argument::example() const
615{
616 return m_example;
617}
618
624 inline void Argument::setExample(const char *example)
625{
626 m_example = example;
627}
628
635 inline const std::vector<const char *> &Argument::values(std::size_t occurrence) const
636{
637 return m_occurrences[occurrence].values;
638}
639
653 inline std::size_t Argument::requiredValueCount() const
654{
655 return m_requiredValueCount;
656}
657
670 inline void Argument::setRequiredValueCount(std::size_t requiredValueCount)
671{
672 m_requiredValueCount = requiredValueCount;
673}
674
683 inline const std::vector<const char *> &Argument::valueNames() const
684{
685 return m_valueNames;
686}
687
701 inline void Argument::setValueNames(std::initializer_list<const char *> valueNames)
702{
703 m_valueNames.assign(valueNames);
704}
705
712 inline void Argument::appendValueName(const char *valueName)
713{
714 m_valueNames.emplace_back(valueName);
715}
716
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
730 inline bool Argument::isImplicit() const
731{
732 return m_flags & Flags::Implicit;
733}
734
739 inline void Argument::setImplicit(bool implicit)
740{
741 setFlags(Flags::Implicit, implicit);
742}
743
747 inline bool Argument::isPresent() const
748{
749 return !m_occurrences.empty();
750}
751
755 inline std::size_t Argument::occurrences() const
756{
757 return m_occurrences.size();
758}
759
763 inline std::size_t Argument::index(std::size_t occurrence) const
764{
765 return m_occurrences[occurrence].index;
766}
767
773 inline std::size_t Argument::minOccurrences() const
774{
775 return m_minOccurrences;
776}
777
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
796 inline const Argument *Argument::deprecatedBy() const
797{
798 return m_deprecatedBy;
799}
800
806 inline void Argument::markAsDeprecated(const Argument *deprecatedBy)
807{
808 setFlags(Flags::Deprecated, true);
809 m_deprecatedBy = deprecatedBy;
810}
811
817 inline void Argument::setConstraints(std::size_t minOccurrences, std::size_t maxOccurrences)
818{
819 m_minOccurrences = minOccurrences;
820 m_maxOccurrences = maxOccurrences;
821}
822
826 inline const std::vector<Argument *> &Argument::path(std::size_t occurrence) const
827{
828 return m_occurrences[occurrence].path;
829}
830
840 inline bool Argument::isRequired() const
841{
842 return m_minOccurrences;
843}
844
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
866 inline Argument::Flags Argument::flags() const
867{
868 return m_flags;
869}
870
874 inline void Argument::setFlags(Argument::Flags flags)
875{
876 m_flags = flags;
877}
878
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
897 inline bool Argument::isCombinable() const
898{
899 return m_flags & Flags::Combinable;
900}
901
910 inline void Argument::setCombinable(bool combinable)
911{
912 setFlags(Flags::Combinable, combinable);
913}
914
925 inline bool Argument::denotesOperation() const
926{
927 return m_flags & Flags::Operation;
928}
929
934 inline void Argument::setDenotesOperation(bool denotesOperation)
935{
936 setFlags(Flags::Operation, denotesOperation);
937}
938
943 inline const Argument::CallbackFunction &Argument::callback() const
944{
945 return m_callbackFunction;
946}
947
954 inline void Argument::setCallback(Argument::CallbackFunction callback)
955{
956 m_callbackFunction = callback;
957}
958
965 inline const ArgumentVector &Argument::subArguments() const
966{
967 return m_subArgs;
968}
969
976 inline bool Argument::hasSubArguments() const
977{
978 return !m_subArgs.empty();
979}
980
991 inline const ArgumentVector &Argument::parents() const
992{
993 return m_parents;
994}
995
1002 inline bool Argument::isMainArgument() const
1003{
1004 return m_isMainArg;
1005}
1006
1013 inline ValueCompletionBehavior Argument::valueCompletionBehaviour() const
1014{
1015 return m_valueCompletionBehavior;
1016}
1017
1024 inline void Argument::setValueCompletionBehavior(ValueCompletionBehavior completionValues)
1025{
1026 m_valueCompletionBehavior = completionValues;
1027}
1028
1032 inline const char *Argument::preDefinedCompletionValues() const
1033{
1034 return m_preDefinedCompletionValues;
1035}
1036
1040 inline void Argument::setPreDefinedCompletionValues(const char *preDefinedCompletionValues)
1041{
1042 m_preDefinedCompletionValues = preDefinedCompletionValues;
1043}
1044
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
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
1077 inline const std::vector<ArgumentOccurrence> &Argument::occurrenceInfo() const
1078{
1079 return m_occurrences;
1080}
1081
1088 inline std::vector<ArgumentOccurrence> &Argument::occurrenceInfo()
1089{
1090 return m_occurrences;
1091}
1092
1097 inline const ArgumentVector &ArgumentParser::mainArguments() const
1098{
1099 return m_mainArgs;
1100}
1101
1105 inline unsigned int ArgumentParser::actualArgumentCount() const
1106{
1107 return m_actualArgc;
1108}
1109
1113 inline const char *ArgumentParser::executable() const
1114{
1115 return m_executable;
1116}
1117
1123 inline UnknownArgumentBehavior ArgumentParser::unknownArgumentBehavior() const
1124{
1125 return m_unknownArgBehavior;
1126}
1127
1133 inline void ArgumentParser::setUnknownArgumentBehavior(UnknownArgumentBehavior behavior)
1134{
1135 m_unknownArgBehavior = behavior;
1136}
1137
1142 inline Argument *ArgumentParser::defaultArgument() const
1143{
1144 return m_defaultArg;
1145}
1146
1151 inline void ArgumentParser::setDefaultArgument(Argument *argument)
1152{
1153 m_defaultArg = argument;
1154}
1155
1161 inline void ArgumentParser::checkConstraints()
1162{
1163 checkConstraints(m_mainArgs);
1164}
1165
1170 inline void ArgumentParser::invokeCallbacks()
1171{
1172 invokeCallbacks(m_mainArgs);
1173}
1174
1179 inline void ArgumentParser::setExitFunction(std::function<void(int)> exitFunction)
1180{
1181 m_exitFunction = exitFunction;
1182}
1183
1187 inline const HelpArgument &ArgumentParser::helpArg() const
1188{
1189 return m_helpArg;
1190}
1191
1195 inline HelpArgument &ArgumentParser::helpArg()
1196{
1197 return m_helpArg;
1198}
1199
1203 inline const NoColorArgument &ArgumentParser::noColorArg() const
1204{
1205 return m_noColorArg;
1206}
1207
1211 inline NoColorArgument &ArgumentParser::noColorArg()
1212{
1213 return m_noColorArg;
1214}
1215
1216} // namespace CppUtilities
1217
1218#endif // APPLICATION_UTILITIES_ARGUMENTPARSER_H
CPP_UTILITIES_IF_DEBUG_BUILD
#define CPP_UTILITIES_IF_DEBUG_BUILD(x)
Wraps debug-only lines conveniently.
Definition global.h:118
ArgumentParserTests
The ArgumentParserTests class tests the ArgumentParser and Argument classes.
Definition argumentparsertests.cpp:39
CppUtilities::ArgumentParser::setDefaultArgument
void setDefaultArgument(Argument *argument)
Sets the default argument.
Definition argumentparser.h:1151
CppUtilities::ArgumentParser::helpArg
const HelpArgument & helpArg() const
Returns the --help argument.
Definition argumentparser.h:1187
CppUtilities::ArgumentParser::checkConstraints
void checkConstraints()
Checks whether constraints are violated.
Definition argumentparser.h:1161
CppUtilities::ArgumentParser::ArgumentParser
ArgumentParser()
Constructs a new ArgumentParser.
Definition argumentparser.cpp:772
CppUtilities::ArgumentParser::executable
const char * executable() const
Returns the name of the current executable.
Definition argumentparser.h:1113
CppUtilities::ArgumentParser::readArgs
void readArgs(int argc, const char *const *argv)
Parses the specified command line arguments.
Definition argumentparser.cpp:972
CppUtilities::ArgumentParser::mainArguments
const ArgumentVector & mainArguments() const
Returns the main arguments.
Definition argumentparser.h:1097
CppUtilities::ArgumentParser::actualArgumentCount
unsigned int actualArgumentCount() const
Returns the actual number of arguments that could be found when parsing.
Definition argumentparser.h:1105
CppUtilities::ArgumentParser::isUncombinableMainArgPresent
bool isUncombinableMainArgPresent() const
Checks whether at least one uncombinable main argument is present.
Definition argumentparser.cpp:1097
CppUtilities::ArgumentParser::setUnknownArgumentBehavior
void setUnknownArgumentBehavior(UnknownArgumentBehavior behavior)
Sets how unknown arguments are treated.
Definition argumentparser.h:1133
CppUtilities::ArgumentParser::defaultArgument
Argument * defaultArgument() const
Returns the default argument.
Definition argumentparser.h:1142
CppUtilities::ArgumentParser::setMainArguments
void setMainArguments(const ArgumentInitializerList &mainArguments)
Sets the main arguments for the parser.
Definition argumentparser.cpp:790
CppUtilities::ArgumentParser::setExitFunction
void setExitFunction(std::function< void(int)> exitFunction)
Specifies a function quit the application.
Definition argumentparser.h:1179
CppUtilities::ArgumentParser::printHelp
void printHelp(std::ostream &os) const
Prints help text for all assigned arguments.
Definition argumentparser.cpp:830
CppUtilities::ArgumentParser::addMainArgument
void addMainArgument(Argument *argument)
Adds the specified argument to the main argument.
Definition argumentparser.cpp:821
CppUtilities::ArgumentParser::parseArgs
void parseArgs(int argc, const char *const *argv, ParseArgumentBehavior behavior=ParseArgumentBehavior::CheckConstraints|ParseArgumentBehavior::InvokeCallbacks|ParseArgumentBehavior::ExitOnFailure)
Parses the specified command line arguments.
Definition argumentparser.cpp:936
CppUtilities::ArgumentParser::invokeCallbacks
void invokeCallbacks()
Invokes all assigned callbacks.
Definition argumentparser.h:1170
CppUtilities::ArgumentParser::resetArgs
void resetArgs()
Resets all Argument instances assigned as mainArguments() and sub arguments.
Definition argumentparser.cpp:1034
CppUtilities::ArgumentParser::ensureDefaultOperation
void ensureDefaultOperation()
Ensures a main operation argument is present.
Definition argumentparser.cpp:1066
CppUtilities::ArgumentParser::unknownArgumentBehavior
UnknownArgumentBehavior unknownArgumentBehavior() const
Returns how unknown arguments are treated.
Definition argumentparser.h:1123
CppUtilities::ArgumentParser::noColorArg
const NoColorArgument & noColorArg() const
Returns the --no-color argument.
Definition argumentparser.h:1203
CppUtilities::ArgumentParser::specifiedOperation
Argument * specifiedOperation() const
Returns the first operation argument specified by the user or nullptr if no operation has been specif...
Definition argumentparser.cpp:1084
CppUtilities::ArgumentParser::assumeDefaultArgument
void assumeDefaultArgument()
Assumes the default argument is present (if not already present).
Definition argumentparser.cpp:1052
CppUtilities::Argument
The Argument class is a wrapper for command line argument information.
Definition argumentparser.h:263
CppUtilities::Argument::description
const char * description() const
Returns the description of the argument.
Definition argumentparser.h:594
CppUtilities::Argument::Argument
Argument(const char *name, char abbreviation='\0', const char *description=nullptr, const char *example=nullptr)
Constructs an Argument with the given name, abbreviation and description.
Definition argumentparser.cpp:463
CppUtilities::Argument::varValueCount
static constexpr std::size_t varValueCount
Denotes a variable number of values.
Definition argumentparser.h:368
CppUtilities::Argument::path
const std::vector< Argument * > & path(std::size_t occurrence=0) const
Returns the path of the specified occurrence.
Definition argumentparser.h:826
CppUtilities::Argument::isMainArgument
bool isMainArgument() const
Returns an indication whether the argument is used as main argument.
Definition argumentparser.h:1002
CppUtilities::Argument::subArguments
const ArgumentVector & subArguments() const
Returns the secondary arguments for this argument.
Definition argumentparser.h:965
CppUtilities::Argument::example
const char * example() const
Returns the usage example of the argument.
Definition argumentparser.h:614
CppUtilities::Argument::Flags
Flags
The Flags enum specifies options for treating the argument in a special way.
Definition argumentparser.h:272
CppUtilities::Argument::Flags::Implicit
@ Implicit
Definition argumentparser.h:276
CppUtilities::Argument::Flags::Deprecated
@ Deprecated
Definition argumentparser.h:278
CppUtilities::Argument::Flags::Operation
@ Operation
Definition argumentparser.h:277
CppUtilities::Argument::Flags::Combinable
@ Combinable
Definition argumentparser.h:274
CppUtilities::Argument::isDeprecated
bool isDeprecated() const
Definition argumentparser.h:788
CppUtilities::Argument::valueNames
const std::vector< const char * > & valueNames() const
Returns the names of the required values.
Definition argumentparser.h:683
CppUtilities::Argument::setValueCompletionBehavior
void setValueCompletionBehavior(ValueCompletionBehavior valueCompletionBehaviour)
Sets the items to be considered when generating completion for the values.
Definition argumentparser.h:1024
CppUtilities::Argument::callback
const CallbackFunction & callback() const
Returns the assigned callback function.
Definition argumentparser.h:943
CppUtilities::Argument::occurrenceInfo
const std::vector< ArgumentOccurrence > & occurrenceInfo() const
Returns information about all occurrences of the argument which have been detected when parsing.
Definition argumentparser.h:1077
CppUtilities::Argument::valueCompletionBehaviour
ValueCompletionBehavior valueCompletionBehaviour() const
Returns the items to be considered when generating completion for the values.
Definition argumentparser.h:1013
CppUtilities::Argument::setConstraints
void setConstraints(std::size_t minOccurrences, std::size_t maxOccurrences)
Sets the allowed number of occurrences.
Definition argumentparser.h:817
CppUtilities::Argument::setImplicit
void setImplicit(bool implicit)
Sets whether the argument is an implicit argument.
Definition argumentparser.h:739
CppUtilities::Argument::setValueNames
void setValueNames(std::initializer_list< const char * > valueNames)
Sets the names of the required values.
Definition argumentparser.h:701
CppUtilities::Argument::abbreviation
char abbreviation() const
Returns the abbreviation of the argument.
Definition argumentparser.h:552
CppUtilities::Argument::occurrences
std::size_t occurrences() const
Returns how often the argument could be detected when parsing.
Definition argumentparser.h:755
CppUtilities::Argument::setDenotesOperation
void setDenotesOperation(bool denotesOperation)
Sets whether the argument denotes the operation.
Definition argumentparser.h:934
CppUtilities::Argument::markAsDeprecated
void markAsDeprecated(const Argument *deprecatedBy=nullptr)
Marks the argument as deprecated.
Definition argumentparser.h:806
CppUtilities::Argument::name
const char * name() const
Returns the name of the argument.
Definition argumentparser.h:522
CppUtilities::Argument::setAbbreviation
void setAbbreviation(char abbreviation)
Sets the abbreviation of the argument.
Definition argumentparser.h:564
CppUtilities::Argument::isCombinable
bool isCombinable() const
Returns an indication whether the argument is combinable.
Definition argumentparser.h:897
CppUtilities::Argument::denotesOperation
bool denotesOperation() const
Returns whether the argument denotes an operation.
Definition argumentparser.h:925
CppUtilities::Argument::setDescription
void setDescription(const char *description)
Sets the description of the argument.
Definition argumentparser.h:604
CppUtilities::Argument::appendValueName
void appendValueName(const char *valueName)
Appends a value name.
Definition argumentparser.h:712
CppUtilities::Argument::maxOccurrences
std::size_t maxOccurrences() const
Returns the maximum number of occurrences.
Definition argumentparser.h:783
CppUtilities::Argument::flags
Argument::Flags flags() const
Returns Argument::Flags for the argument.
Definition argumentparser.h:866
CppUtilities::Argument::values
const std::vector< const char * > & values(std::size_t occurrence=0) const
Returns the parameter values for the specified occurrence of argument.
Definition argumentparser.h:635
CppUtilities::Argument::preDefinedCompletionValues
const char * preDefinedCompletionValues() const
Returns the assigned values used when generating completion for the values.
Definition argumentparser.h:1032
CppUtilities::Argument::requiredValueCount
std::size_t requiredValueCount() const
Returns the number of values which are required to be given for this argument.
Definition argumentparser.h:653
CppUtilities::Argument::environmentVariable
const char * environmentVariable() const
Returns the environment variable queried when firstValue() is called.
Definition argumentparser.h:575
CppUtilities::Argument::allValuesAs
std::vector< std::tuple< TargetType... > > allValuesAs() const
Converts the present values for all occurrences to the specified target types.
Definition argumentparser.h:421
CppUtilities::Argument::isImplicit
bool isImplicit() const
Returns an indication whether the argument is an implicit argument.
Definition argumentparser.h:730
CppUtilities::Argument::reset
void reset()
Resets occurrences (indices, values and paths).
Definition argumentparser.h:1050
CppUtilities::Argument::deprecatedBy
const Argument * deprecatedBy() const
Returns the argument which obsoletes this argument.
Definition argumentparser.h:796
CppUtilities::Argument::CallbackFunction
std::function< void(const ArgumentOccurrence &)> CallbackFunction
Definition argumentparser.h:269
CppUtilities::Argument::index
std::size_t index(std::size_t occurrence) const
Returns the indices of the argument's occurrences which could be detected when parsing.
Definition argumentparser.h:763
CppUtilities::Argument::isPresent
bool isPresent() const
Returns an indication whether the argument could be detected when parsing.
Definition argumentparser.h:747
CppUtilities::Argument::setExample
void setExample(const char *example)
Sets the a usage example for the argument.
Definition argumentparser.h:624
CppUtilities::Argument::parents
const ArgumentVector & parents() const
Returns the parents of this argument.
Definition argumentparser.h:991
CppUtilities::Argument::setFlags
void setFlags(Argument::Flags flags)
Replaces all Argument::Flags for the argument with the flags.
Definition argumentparser.h:874
CppUtilities::Argument::minOccurrences
std::size_t minOccurrences() const
Returns the minimum number of occurrences.
Definition argumentparser.h:773
CppUtilities::Argument::allRequiredValuesPresent
bool allRequiredValuesPresent(std::size_t occurrence=0) const
Returns an indication whether all required values are present.
Definition argumentparser.h:720
CppUtilities::Argument::setCombinable
void setCombinable(bool combinable)
Sets whether this argument can be combined.
Definition argumentparser.h:910
CppUtilities::Argument::setCallback
void setCallback(CallbackFunction callback)
Sets a callback function which will be called by the parser if the argument could be found and no par...
Definition argumentparser.h:954
CppUtilities::Argument::isRequired
bool isRequired() const
Returns an indication whether the argument is mandatory.
Definition argumentparser.h:840
CppUtilities::Argument::setRequired
void setRequired(bool required)
Sets whether this argument is mandatory or not.
Definition argumentparser.h:852
CppUtilities::Argument::setPreDefinedCompletionValues
void setPreDefinedCompletionValues(const char *preDefinedCompletionValues)
Assigns the values to be used when generating completion for the values.
Definition argumentparser.h:1040
CppUtilities::Argument::setEnvironmentVariable
void setEnvironmentVariable(const char *environmentVariable)
Sets the environment variable queried when firstValue() is called.
Definition argumentparser.h:584
CppUtilities::Argument::hasSubArguments
bool hasSubArguments() const
Returns an indication whether the argument has secondary arguments.
Definition argumentparser.h:976
CppUtilities::Argument::valuesAs
std::tuple< TargetType... > valuesAs(std::size_t occurrence=0) const
Converts the present values for the specified occurrence to the specified target types.
Definition argumentparser.h:411
CppUtilities::Argument::setRequiredValueCount
void setRequiredValueCount(std::size_t requiredValueCount)
Sets the number of values which are required to be given for this argument.
Definition argumentparser.h:670
CppUtilities::Argument::setName
void setName(const char *name)
Sets the name of the argument.
Definition argumentparser.h:534
CppUtilities::ConfigValueArgument::ConfigValueArgument
ConfigValueArgument(const char *name, char abbreviation='\0', const char *description=nullptr, std::initializer_list< const char * > valueNames=std::initializer_list< const char * >())
Constructs a new ConfigValueArgument with the specified parameter.
Definition argumentparser.h:1064
CppUtilities::HelpArgument
The HelpArgument class prints help information for an argument parser when present (–help,...
Definition argumentparser.h:431
CppUtilities::HelpArgument::HelpArgument
HelpArgument(ArgumentParser &parser)
Constructs a new help argument for the specified parser.
Definition argumentparser.cpp:1753
CppUtilities::NoColorArgument
The NoColorArgument class allows to specify whether use of escape codes or similar technique to provi...
Definition argumentparser.h:447
CppUtilities::NoColorArgument::apply
void apply() const
Sets EscapeCodes::enabled according to the presence of the first instantiation of NoColorArgument.
Definition argumentparser.cpp:1818
CppUtilities::NoColorArgument::NoColorArgument
NoColorArgument()
Constructs a new NoColorArgument argument.
Definition argumentparser.cpp:1796
CppUtilities::OperationArgument::OperationArgument
OperationArgument(const char *name, char abbreviation='\0', const char *description=nullptr, const char *example=nullptr)
Definition argumentparser.h:1055
CPP_UTILITIES_EXPORT
#define CPP_UTILITIES_EXPORT
Marks the symbol to be exported by the c++utilities library.
Definition global.h:14
CppUtilities::FlagEnumClassOperations::operator&
constexpr bool operator&(FlagEnumClass lhs, FlagEnumClass rhs)
Definition flagenumclass.h:54
CppUtilities::ValueConversion
Contains functions to convert raw argument values to certain types.
Definition argumentparser.h:146
CppUtilities::ValueConversion::convert
TargetType convert(const char *value)
Definition argumentparser.h:147
CppUtilities
Contains all utilities provided by the c++utilities library.
Definition argumentparser.h:18
CppUtilities::ArgumentInitializerList
std::initializer_list< Argument * > ArgumentInitializerList
Definition argumentparser.h:68
CppUtilities::IniFileSectionFlags::Implicit
@ Implicit
Definition inifile.h:75
CppUtilities::ArgumentVector
std::vector< Argument * > ArgumentVector
Definition argumentparser.h:69
CppUtilities::UnknownArgumentBehavior
UnknownArgumentBehavior
The UnknownArgumentBehavior enum specifies the behavior of the argument parser when an unknown argume...
Definition argumentparser.h:76
CppUtilities::UnknownArgumentBehavior::Warn
@ Warn
Definition argumentparser.h:78
CppUtilities::UnknownArgumentBehavior::Ignore
@ Ignore
Definition argumentparser.h:77
CppUtilities::stringToNumber
IntegralType stringToNumber(const StringType &string, BaseType base=10)
Converts the given string to an unsigned/signed number assuming string uses the specified base.
Definition stringconversion.h:605
CppUtilities::ParseArgumentBehavior
ParseArgumentBehavior
The ParseArgumentBehavior enum specifies the behavior when parsing arguments.
Definition argumentparser.h:88
CppUtilities::ParseArgumentBehavior::ReadArguments
@ ReadArguments
Definition argumentparser.h:89
CppUtilities::ParseArgumentBehavior::CheckConstraints
@ CheckConstraints
Definition argumentparser.h:90
CppUtilities::ParseArgumentBehavior::ExitOnFailure
@ ExitOnFailure
Definition argumentparser.h:92
CppUtilities::ParseArgumentBehavior::InvokeCallbacks
@ InvokeCallbacks
Definition argumentparser.h:91
CppUtilities::ValueCompletionBehavior
ValueCompletionBehavior
The ValueCompletionBehavior enum specifies the items to be considered when generating completion for ...
Definition argumentparser.h:117
CppUtilities::ValueCompletionBehavior::AppendEquationSign
@ AppendEquationSign
Definition argumentparser.h:123
CppUtilities::ValueCompletionBehavior::None
@ None
Definition argumentparser.h:118
CppUtilities::ValueCompletionBehavior::PreDefinedValues
@ PreDefinedValues
Definition argumentparser.h:119
CppUtilities::ValueCompletionBehavior::Files
@ Files
Definition argumentparser.h:120
CppUtilities::ValueCompletionBehavior::FileSystemIfNoPreDefinedValues
@ FileSystemIfNoPreDefinedValues
Definition argumentparser.h:122
CppUtilities::ValueCompletionBehavior::InvokeCallback
@ InvokeCallback
Definition argumentparser.h:124
CppUtilities::ValueCompletionBehavior::Directories
@ Directories
Definition argumentparser.h:121
CppUtilities::ArgumentPredicate
std::function< bool(Argument *)> ArgumentPredicate
Definition argumentparser.h:70
CppUtilities::applicationInfo
CPP_UTILITIES_EXPORT ApplicationInfo applicationInfo
Stores global application info used by ArgumentParser::printHelp() and AboutDialog.
Definition argumentparser.cpp:436
Fail
#define Fail(msg)
stringconversion.h
CppUtilities::ApplicationInfo
Stores information about an application.
Definition argumentparser.h:23
CppUtilities::ApplicationInfo::author
const char * author
Definition argumentparser.h:25
CppUtilities::ApplicationInfo::dependencyVersions
std::vector< const char * > dependencyVersions
Definition argumentparser.h:32
CppUtilities::ApplicationInfo::description
const char * description
Definition argumentparser.h:29
CppUtilities::ApplicationInfo::license
const char * license
Definition argumentparser.h:30
CppUtilities::ApplicationInfo::name
const char * name
Definition argumentparser.h:24
CppUtilities::ApplicationInfo::credits
const char * credits
Definition argumentparser.h:31
CppUtilities::ApplicationInfo::domain
const char * domain
Definition argumentparser.h:28
CppUtilities::ApplicationInfo::version
const char * version
Definition argumentparser.h:26
CppUtilities::ApplicationInfo::url
const char * url
Definition argumentparser.h:27
CppUtilities::ArgumentCompletionInfo
The ArgumentCompletionInfo struct holds information internally used for shell completion and suggesti...
Definition argumentparser.cpp:47
CppUtilities::ArgumentOccurrence
The ArgumentOccurrence struct holds argument values for an occurrence of an argument.
Definition argumentparser.h:194
CppUtilities::ArgumentOccurrence::index
std::size_t index
The index of the occurrence.
Definition argumentparser.h:201
CppUtilities::ArgumentOccurrence::values
std::vector< const char * > values
The parameter values which have been specified after the occurrence of the argument.
Definition argumentparser.h:206
CppUtilities::ArgumentOccurrence::convertValues
std::tuple< RemainingTargetTypes... > convertValues() const
Converts the present values to the specified target types.
Definition argumentparser.h:225
CppUtilities::ArgumentOccurrence::ArgumentOccurrence
ArgumentOccurrence(std::size_t index)
Constructs an argument occurrence for the specified index.
Definition argumentparser.h:241
CppUtilities::ArgumentOccurrence::path
std::vector< Argument * > path
The "path" of the occurrence (the parent elements which have been specified before).
Definition argumentparser.h:212
traits.h