C++ Utilities  5.8.0
Useful C++ classes and routines such as argument parser, IO and conversion utilities
argumentparser.cpp
Go to the documentation of this file.
1 #include "./argumentparser.h"
3 #include "./commandlineutils.h"
4 
5 #include "../conversion/stringbuilder.h"
6 #include "../conversion/stringconversion.h"
7 #include "../io/ansiescapecodes.h"
8 #include "../io/path.h"
9 #include "../misc/levenshtein.h"
10 #include "../misc/parseerror.h"
11 
12 #include <algorithm>
13 #include <cstdlib>
14 #include <cstring>
15 #include <iostream>
16 #include <set>
17 #include <sstream>
18 #include <string>
19 
20 #ifdef CPP_UTILITIES_USE_STANDARD_FILESYSTEM
21 #include <filesystem>
22 #endif
23 
24 using namespace std;
25 using namespace std::placeholders;
26 using namespace std::literals;
27 using namespace CppUtilities::EscapeCodes;
28 
33 namespace CppUtilities {
34 
38 enum ArgumentDenotationType : unsigned char {
39  Value = 0,
41  FullName = 2
42 };
43 
49 
50  const Argument *const lastDetectedArg;
51  size_t lastDetectedArgIndex = 0;
52  vector<Argument *> lastDetectedArgPath;
53  list<const Argument *> relevantArgs;
54  list<const Argument *> relevantPreDefinedValues;
55  const char *const *lastSpecifiedArg = nullptr;
56  unsigned int lastSpecifiedArgIndex = 0;
57  bool nextArgumentOrValue = false;
58  bool completeFiles = false, completeDirs = false;
59 };
60 
65 ArgumentCompletionInfo::ArgumentCompletionInfo(const ArgumentReader &reader)
66  : lastDetectedArg(reader.lastArg)
67 {
68 }
69 
71 struct ArgumentSuggestion {
72  ArgumentSuggestion(const char *unknownArg, size_t unknownArgSize, const char *suggestion, bool hasDashPrefix);
73  ArgumentSuggestion(const char *unknownArg, size_t unknownArgSize, const char *suggestion, size_t suggestionSize, bool hasDashPrefix);
74  bool operator<(const ArgumentSuggestion &other) const;
75  bool operator==(const ArgumentSuggestion &other) const;
76  void addTo(multiset<ArgumentSuggestion> &suggestions, size_t limit) const;
77 
78  const char *const suggestion;
79  const size_t suggestionSize;
80  const size_t editingDistance;
81  const bool hasDashPrefix;
82 };
83 
84 ArgumentSuggestion::ArgumentSuggestion(const char *unknownArg, size_t unknownArgSize, const char *suggestion, size_t suggestionSize, bool isOperation)
85  : suggestion(suggestion)
86  , suggestionSize(suggestionSize)
87  , editingDistance(computeDamerauLevenshteinDistance(unknownArg, unknownArgSize, suggestion, suggestionSize))
88  , hasDashPrefix(isOperation)
89 {
90 }
91 
92 ArgumentSuggestion::ArgumentSuggestion(const char *unknownArg, size_t unknownArgSize, const char *suggestion, bool isOperation)
93  : ArgumentSuggestion(unknownArg, unknownArgSize, suggestion, strlen(suggestion), isOperation)
94 {
95 }
96 
97 bool ArgumentSuggestion::operator<(const ArgumentSuggestion &other) const
98 {
99  return editingDistance < other.editingDistance;
100 }
101 
102 void ArgumentSuggestion::addTo(multiset<ArgumentSuggestion> &suggestions, size_t limit) const
103 {
104  if (suggestions.size() >= limit && !(*this < *--suggestions.end())) {
105  return;
106  }
107  suggestions.emplace(*this);
108  while (suggestions.size() > limit) {
109  suggestions.erase(--suggestions.end());
110  }
111 }
113 
126 ArgumentReader::ArgumentReader(ArgumentParser &parser, const char *const *argv, const char *const *end, bool completionMode)
127  : parser(parser)
128  , args(parser.m_mainArgs)
129  , index(0)
130  , argv(argv)
131  , end(end)
132  , lastArg(nullptr)
133  , argDenotation(nullptr)
134  , completionMode(completionMode)
135 {
136 }
137 
141 ArgumentReader &ArgumentReader::reset(const char *const *argv, const char *const *end)
142 {
143  this->argv = argv;
144  this->end = end;
145  index = 0;
146  lastArg = nullptr;
147  argDenotation = nullptr;
148  return *this;
149 }
150 
156 {
157  return read(args);
158 }
159 
163 bool Argument::matchesDenotation(const char *denotation, size_t denotationLength) const
164 {
165  return m_name && !strncmp(m_name, denotation, denotationLength) && *(m_name + denotationLength) == '\0';
166 }
167 
176 {
177  // method is called recursively for sub args to the last argument (which is nullptr in the initial call) is the current parent argument
178  Argument *const parentArg = lastArg;
179  // determine the current path
180  const vector<Argument *> &parentPath = parentArg ? parentArg->path(parentArg->occurrences() - 1) : vector<Argument *>();
181 
182  Argument *lastArgInLevel = nullptr;
183  vector<const char *> *values = nullptr;
184 
185  // iterate through all argument denotations; loop might exit earlier when an denotation is unknown
186  while (argv != end) {
187  // check whether there are still values to read
188  if (values && lastArgInLevel->requiredValueCount() != Argument::varValueCount && values->size() < lastArgInLevel->requiredValueCount()) {
189  // read arg as value and continue with next arg
190  values->emplace_back(argDenotation ? argDenotation : *argv);
191  ++index;
192  ++argv;
193  argDenotation = nullptr;
194  continue;
195  }
196 
197  // determine how denotation must be processed
198  bool abbreviationFound = false;
199  if (argDenotation) {
200  // continue reading children for abbreviation denotation already detected
201  abbreviationFound = false;
203  } else {
204  // determine denotation type
205  argDenotation = *argv;
206  if (!*argDenotation && (!lastArgInLevel || values->size() >= lastArgInLevel->requiredValueCount())) {
207  // skip empty arguments
208  ++index;
209  ++argv;
210  argDenotation = nullptr;
211  continue;
212  }
213  abbreviationFound = false;
215  if (*argDenotation == '-') {
216  ++argDenotation;
218  if (*argDenotation == '-') {
219  ++argDenotation;
221  }
222  }
223  }
224 
225  // try to find matching Argument instance
226  Argument *matchingArg = nullptr;
227  if (argDenotationType != Value) {
228  // determine actual denotation length (everything before equation sign)
229  const char *const equationPos = strchr(argDenotation, '=');
230  const auto argDenotationLength = equationPos ? static_cast<size_t>(equationPos - argDenotation) : strlen(argDenotation);
231 
232  // loop through each "part" of the denotation
233  // names are read at once, but for abbreviations each character is considered individually
234  for (; argDenotationLength; matchingArg = nullptr) {
235  // search for arguments by abbreviation or name depending on the previously determined denotation type
237  for (Argument *const arg : args) {
238  if (arg->abbreviation() && arg->abbreviation() == *argDenotation) {
239  matchingArg = arg;
240  abbreviationFound = true;
241  break;
242  }
243  }
244  } else {
245  for (Argument *const arg : args) {
246  if (arg->matchesDenotation(argDenotation, argDenotationLength)) {
247  matchingArg = arg;
248  break;
249  }
250  }
251  }
252  if (!matchingArg) {
253  break;
254  }
255 
256  // an argument matched the specified denotation so add an occurrence
257  matchingArg->m_occurrences.emplace_back(index, parentPath, parentArg);
258 
259  // prepare reading parameter values
260  values = &matchingArg->m_occurrences.back().values;
261 
262  // read value after equation sign
263  if ((argDenotationType != Abbreviation && equationPos) || (++argDenotation == equationPos)) {
264  values->push_back(equationPos + 1);
265  argDenotation = nullptr;
266  }
267 
268  // read sub arguments, distinguish whether further abbreviations follow
269  ++index;
270  ++parser.m_actualArgc;
271  lastArg = lastArgInLevel = matchingArg;
274  // no further abbreviations follow -> read sub args for next argv
275  ++argv;
276  argDenotation = nullptr;
277  read(lastArg->m_subArgs);
278  argDenotation = nullptr;
279  break;
280  } else {
281  // further abbreviations follow -> remember current arg value
282  const char *const *const currentArgValue = argv;
283  // don't increment argv, keep processing outstanding chars of argDenotation
284  read(lastArg->m_subArgs);
285  // stop further processing if the denotation has been consumed or even the next value has already been loaded
286  if (!argDenotation || currentArgValue != argv) {
287  argDenotation = nullptr;
288  break;
289  }
290  }
291  }
292 
293  // continue with next arg if we've got a match already
294  if (matchingArg) {
295  continue;
296  }
297 
298  // unknown argument might be a sibling of the parent element
299  for (auto parentArgument = parentPath.crbegin(), pathEnd = parentPath.crend();; ++parentArgument) {
300  for (Argument *const sibling : (parentArgument != pathEnd ? (*parentArgument)->subArguments() : parser.m_mainArgs)) {
301  if (sibling->occurrences() < sibling->maxOccurrences()) {
302  // check whether the denoted abbreviation matches the sibling's abbreviatiopn
303  if (argDenotationType == Abbreviation && (sibling->abbreviation() && sibling->abbreviation() == *argDenotation)) {
304  return false;
305  }
306  // check whether the denoted name matches the sibling's name
307  if (sibling->matchesDenotation(argDenotation, argDenotationLength)) {
308  return false;
309  }
310  }
311  }
312  if (parentArgument == pathEnd) {
313  break;
314  }
315  }
316  }
317 
318  // unknown argument might just be a parameter value of the last argument
319  if (lastArgInLevel && values->size() < lastArgInLevel->requiredValueCount()) {
320  values->emplace_back(abbreviationFound ? argDenotation : *argv);
321  ++index;
322  ++argv;
323  argDenotation = nullptr;
324  continue;
325  }
326 
327  // first value might denote "operation"
328  for (Argument *const arg : args) {
329  if (arg->denotesOperation() && arg->name() && !strcmp(arg->name(), *argv)) {
330  (matchingArg = arg)->m_occurrences.emplace_back(index, parentPath, parentArg);
332  ++index;
333  ++argv;
334  break;
335  }
336  }
337 
338  // use the first default argument which is not already present if there is still no match
339  if (!matchingArg && (!completionMode || (argv + 1 != end))) {
340  const bool uncombinableMainArgPresent = parentArg ? false : parser.isUncombinableMainArgPresent();
341  for (Argument *const arg : args) {
342  if (arg->isImplicit() && !arg->isPresent() && !arg->wouldConflictWithArgument()
343  && (!uncombinableMainArgPresent || !arg->isMainArgument())) {
344  (matchingArg = arg)->m_occurrences.emplace_back(index, parentPath, parentArg);
345  break;
346  }
347  }
348  }
349 
350  if (matchingArg) {
351  // an argument matched the specified denotation
352  if (lastArgInLevel == matchingArg) {
353  break; // break required? -> TODO: add test for this condition
354  }
355 
356  // prepare reading parameter values
357  values = &matchingArg->m_occurrences.back().values;
358 
359  // read sub arguments
360  ++parser.m_actualArgc;
361  lastArg = lastArgInLevel = matchingArg;
362  argDenotation = nullptr;
363  read(lastArg->m_subArgs);
364  argDenotation = nullptr;
365  continue;
366  }
367 
368  // argument denotation is unknown -> handle error
369  if (parentArg) {
370  // continue with parent level
371  return false;
372  }
373  if (completionMode) {
374  // ignore unknown denotation
375  ++index;
376  ++argv;
377  argDenotation = nullptr;
378  } else {
379  switch (parser.m_unknownArgBehavior) {
380  case UnknownArgumentBehavior::Warn:
381  cerr << Phrases::Warning << "The specified argument \"" << *argv << "\" is unknown and will be ignored." << Phrases::EndFlush;
382  [[fallthrough]];
383  case UnknownArgumentBehavior::Ignore:
384  // ignore unknown denotation
385  ++index;
386  ++argv;
387  argDenotation = nullptr;
388  break;
390  return false;
391  }
392  }
393  } // while(argv != end)
394  return true;
395 }
396 
403 ostream &operator<<(ostream &os, const Wrapper &wrapper)
404 {
405  // determine max. number of columns
406  static const TerminalSize termSize(determineTerminalSize());
407  const auto maxColumns = termSize.columns ? termSize.columns : numeric_limits<unsigned short>::max();
408 
409  // print wrapped string considering indentation
410  unsigned short currentCol = wrapper.m_indentation.level;
411  for (const char *currentChar = wrapper.m_str; *currentChar; ++currentChar) {
412  const bool wrappingRequired = currentCol >= maxColumns;
413  if (wrappingRequired || *currentChar == '\n') {
414  // insert newline (TODO: wrap only at end of a word)
415  os << '\n';
416  // print indentation (if enough space)
417  if (wrapper.m_indentation.level < maxColumns) {
418  os << wrapper.m_indentation;
419  currentCol = wrapper.m_indentation.level;
420  } else {
421  currentCol = 0;
422  }
423  }
424  if (*currentChar != '\n' && (!wrappingRequired || *currentChar != ' ')) {
425  os << *currentChar;
426  ++currentCol;
427  }
428  }
429  return os;
430 }
431 
433 
435 
436 inline bool notEmpty(const char *str)
437 {
438  return str && *str;
439 }
440 
442 
459 Argument::Argument(const char *name, char abbreviation, const char *description, const char *example)
460  : m_name(name)
461  , m_abbreviation(abbreviation)
462  , m_environmentVar(nullptr)
463  , m_description(description)
464  , m_example(example)
465  , m_minOccurrences(0)
466  , m_maxOccurrences(1)
467  , m_requiredValueCount(0)
468  , m_flags(Flags::None)
469  , m_deprecatedBy(nullptr)
470  , m_isMainArg(false)
471  , m_valueCompletionBehavior(ValueCompletionBehavior::PreDefinedValues | ValueCompletionBehavior::Files | ValueCompletionBehavior::Directories
472  | ValueCompletionBehavior::FileSystemIfNoPreDefinedValues)
473  , m_preDefinedCompletionValues(nullptr)
474 {
475 }
476 
481 {
482 }
483 
491 const char *Argument::firstValue() const
492 {
493  if (!m_occurrences.empty() && !m_occurrences.front().values.empty()) {
494  return m_occurrences.front().values.front();
495  } else if (m_environmentVar) {
496  return getenv(m_environmentVar);
497  } else {
498  return nullptr;
499  }
500 }
501 
505 void Argument::printInfo(ostream &os, unsigned char indentation) const
506 {
507  if (isDeprecated()) {
508  return;
509  }
510  Indentation ident(indentation);
511  os << ident;
512  EscapeCodes::setStyle(os, EscapeCodes::TextAttribute::Bold);
513  if (notEmpty(name())) {
514  if (!denotesOperation()) {
515  os << '-' << '-';
516  }
517  os << name();
518  }
519  if (notEmpty(name()) && abbreviation()) {
520  os << ',' << ' ';
521  }
522  if (abbreviation()) {
523  os << '-' << abbreviation();
524  }
526  if (requiredValueCount()) {
527  unsigned int valueNamesPrint = 0;
528  for (auto i = valueNames().cbegin(), end = valueNames().cend(); i != end && valueNamesPrint < requiredValueCount(); ++i) {
529  os << ' ' << '[' << *i << ']';
530  ++valueNamesPrint;
531  }
533  os << " ...";
534  } else {
535  for (; valueNamesPrint < requiredValueCount(); ++valueNamesPrint) {
536  os << " [value " << (valueNamesPrint + 1) << ']';
537  }
538  }
539  }
540  ident.level += 2;
541  if (notEmpty(description())) {
542  os << '\n' << ident << Wrapper(description(), ident);
543  }
544  if (isRequired()) {
545  os << '\n' << ident << "particularities: mandatory";
546  if (!isMainArgument()) {
547  os << " if parent argument is present";
548  }
549  }
550  if (environmentVariable()) {
551  os << '\n' << ident << "default environment variable: " << Wrapper(environmentVariable(), ident + 30);
552  }
553  os << '\n';
554  bool hasSubArgs = false;
555  for (const auto *const arg : subArguments()) {
556  if (arg->isDeprecated()) {
557  continue;
558  }
559  hasSubArgs = true;
560  arg->printInfo(os, ident.level);
561  }
562  if (notEmpty(example())) {
563  if (ident.level == 2 && hasSubArgs) {
564  os << '\n';
565  }
566  os << ident << "example: " << Wrapper(example(), ident + 9);
567  os << '\n';
568  }
569 }
570 
577 {
578  for (Argument *arg : args) {
579  if (arg != except && arg->isPresent() && !arg->isCombinable()) {
580  return arg;
581  }
582  }
583  return nullptr;
584 }
585 
600 void Argument::setSubArguments(const ArgumentInitializerList &secondaryArguments)
601 {
602  // remove this argument from the parents list of the previous secondary arguments
603  for (Argument *arg : m_subArgs) {
604  arg->m_parents.erase(remove(arg->m_parents.begin(), arg->m_parents.end(), this), arg->m_parents.end());
605  }
606  // assign secondary arguments
607  m_subArgs.assign(secondaryArguments);
608  // add this argument to the parents list of the assigned secondary arguments
609  // and set the parser
610  for (Argument *arg : m_subArgs) {
611  if (find(arg->m_parents.cbegin(), arg->m_parents.cend(), this) == arg->m_parents.cend()) {
612  arg->m_parents.push_back(this);
613  }
614  }
615 }
616 
625 {
626  if (find(m_subArgs.cbegin(), m_subArgs.cend(), arg) != m_subArgs.cend()) {
627  return;
628  }
629  m_subArgs.push_back(arg);
630  if (find(arg->m_parents.cbegin(), arg->m_parents.cend(), this) == arg->m_parents.cend()) {
631  arg->m_parents.push_back(this);
632  }
633 }
634 
640 {
641  if (isMainArgument()) {
642  return true;
643  }
644  for (const Argument *parent : m_parents) {
645  if (parent->isPresent()) {
646  return true;
647  }
648  }
649  return false;
650 }
651 
661 {
662  return isPresent() ? wouldConflictWithArgument() : nullptr;
663 }
664 
674 {
675  if (isCombinable()) {
676  return nullptr;
677  }
678  for (Argument *parent : m_parents) {
679  for (Argument *sibling : parent->subArguments()) {
680  if (sibling != this && sibling->isPresent() && !sibling->isCombinable()) {
681  return sibling;
682  }
683  }
684  }
685  return nullptr;
686 }
687 
693 {
694  for (Argument *arg : m_subArgs) {
695  if (arg->denotesOperation() && arg->isPresent()) {
696  return arg;
697  }
698  }
699  return nullptr;
700 }
701 
707 {
708  for (Argument *arg : m_subArgs) {
709  arg->resetRecursively();
710  }
711  reset();
712 }
713 
731  : m_actualArgc(0)
732  , m_executable(nullptr)
733  , m_unknownArgBehavior(UnknownArgumentBehavior::Fail)
734  , m_defaultArg(nullptr)
735  , m_helpArg(*this)
736 {
737 }
738 
749 {
750  if (!mainArguments.size()) {
751  m_mainArgs.clear();
752  return;
753  }
754  for (Argument *arg : mainArguments) {
755  arg->m_isMainArg = true;
756  }
757  m_mainArgs.assign(mainArguments);
758  if (m_defaultArg || (*mainArguments.begin())->requiredValueCount()) {
759  return;
760  }
761  bool subArgsRequired = false;
762  for (const Argument *subArg : (*mainArguments.begin())->subArguments()) {
763  if (subArg->isRequired()) {
764  subArgsRequired = true;
765  break;
766  }
767  }
768  if (!subArgsRequired) {
769  m_defaultArg = *mainArguments.begin();
770  }
771 }
772 
780 {
781  argument->m_isMainArg = true;
782  m_mainArgs.push_back(argument);
783 }
784 
788 void ArgumentParser::printHelp(ostream &os) const
789 {
790  EscapeCodes::setStyle(os, EscapeCodes::TextAttribute::Bold);
791  bool wroteLine = false;
793  os << applicationInfo.name;
795  os << ',' << ' ';
796  }
797  wroteLine = true;
798  }
800  os << "version " << applicationInfo.version;
801  wroteLine = true;
802  }
803  if (wroteLine) {
804  os << '\n' << '\n';
805  }
807 
810  wroteLine = true;
811  }
812  if (wroteLine) {
813  os << '\n' << '\n';
814  }
815 
816  if (!m_mainArgs.empty()) {
817  bool hasOperations = false, hasTopLevelOptions = false;
818  for (const Argument *const arg : m_mainArgs) {
819  if (arg->denotesOperation()) {
820  hasOperations = true;
821  } else if (strcmp(arg->name(), "help")) {
822  hasTopLevelOptions = true;
823  }
824  if (hasOperations && hasTopLevelOptions) {
825  break;
826  }
827  }
828 
829  // check whether operations are available
830  if (hasOperations) {
831  // split top-level operations and other configurations
832  os << "Available operations:";
833  for (const Argument *const arg : m_mainArgs) {
834  if (!arg->denotesOperation() || arg->isDeprecated() || !strcmp(arg->name(), "help")) {
835  continue;
836  }
837  os << '\n';
838  arg->printInfo(os);
839  }
840  if (hasTopLevelOptions) {
841  os << "\nAvailable top-level options:";
842  for (const Argument *const arg : m_mainArgs) {
843  if (arg->denotesOperation() || arg->isDeprecated() || !strcmp(arg->name(), "help")) {
844  continue;
845  }
846  os << '\n';
847  arg->printInfo(os);
848  }
849  }
850  } else {
851  // just show all args if no operations are available
852  os << "Available arguments:";
853  for (const Argument *const arg : m_mainArgs) {
854  if (arg->isDeprecated() || !strcmp(arg->name(), "help")) {
855  continue;
856  }
857  os << '\n';
858  arg->printInfo(os);
859  }
860  }
861  }
862 
863  if (!applicationInfo.dependencyVersions.empty()) {
864  os << '\n';
866  os << "Linked against: " << *i;
867  for (++i; i != end; ++i) {
868  os << ',' << ' ' << *i;
869  }
870  os << '\n';
871  }
872 
874  os << "\nProject website: " << applicationInfo.url << endl;
875  }
876 }
877 
894 void ArgumentParser::parseArgs(int argc, const char *const *argv, ParseArgumentBehavior behavior)
895 {
896  try {
897  readArgs(argc, argv);
898  if (!argc) {
899  return;
900  }
901  if (behavior & ParseArgumentBehavior::CheckConstraints) {
902  checkConstraints(m_mainArgs);
903  }
904  if (behavior & ParseArgumentBehavior::InvokeCallbacks) {
905  invokeCallbacks(m_mainArgs);
906  }
907  } catch (const ParseError &failure) {
908  if (behavior & ParseArgumentBehavior::ExitOnFailure) {
910  cerr << failure;
911  invokeExit(1);
912  }
913  throw;
914  }
915 }
916 
930 void ArgumentParser::readArgs(int argc, const char *const *argv)
931 {
932  CPP_UTILITIES_IF_DEBUG_BUILD(verifyArgs(m_mainArgs);)
933  m_actualArgc = 0;
934 
935  // the first argument is the executable name
936  if (!argc) {
937  m_executable = nullptr;
938  return;
939  }
940  m_executable = *argv;
941 
942  // check for further arguments
943  if (!--argc) {
944  // no arguments specified -> flag default argument as present if one is assigned
945  if (m_defaultArg) {
946  m_defaultArg->m_occurrences.emplace_back(0);
947  }
948  return;
949  }
950 
951  // check for completion mode: if first arg (after executable name) is "--bash-completion-for", bash completion for the following arguments is requested
952  const bool completionMode = !strcmp(*++argv, "--bash-completion-for");
953 
954  // determine the index of the current word for completion and the number of arguments to be passed to ArgumentReader
955  unsigned int currentWordIndex = 0, argcForReader;
956  if (completionMode) {
957  // the first argument after "--bash-completion-for" is the index of the current word
958  try {
959  currentWordIndex = (--argc ? stringToNumber<unsigned int, string>(*(++argv)) : 0);
960  if (argc) {
961  ++argv;
962  --argc;
963  }
964  } catch (const ConversionException &) {
965  currentWordIndex = static_cast<unsigned int>(argc - 1);
966  }
967  argcForReader = min(static_cast<unsigned int>(argc), currentWordIndex + 1);
968  } else {
969  argcForReader = static_cast<unsigned int>(argc);
970  }
971 
972  // read specified arguments
973  ArgumentReader reader(*this, argv, argv + argcForReader, completionMode);
974  const bool allArgsProcessed(reader.read());
975  m_noColorArg.apply();
976 
977  // fail when not all arguments could be processed, except when in completion mode
978  if (!completionMode && !allArgsProcessed) {
979  const auto suggestions(findSuggestions(argc, argv, static_cast<unsigned int>(argc - 1), reader));
980  throw ParseError(argsToString("The specified argument \"", *reader.argv, "\" is unknown.", suggestions));
981  }
982 
983  // print Bash completion and prevent the applicaton to continue with the regular execution
984  if (completionMode) {
985  printBashCompletion(argc, argv, currentWordIndex, reader);
986  invokeExit(0);
987  }
988 }
989 
995 {
996  for (Argument *arg : m_mainArgs) {
997  arg->resetRecursively();
998  }
999  m_actualArgc = 0;
1000 }
1001 
1008 {
1009  for (Argument *arg : m_mainArgs) {
1010  if (arg->denotesOperation() && arg->isPresent()) {
1011  return arg;
1012  }
1013  }
1014  return nullptr;
1015 }
1016 
1021 {
1022  for (const Argument *arg : m_mainArgs) {
1023  if (!arg->isCombinable() && arg->isPresent()) {
1024  return true;
1025  }
1026  }
1027  return false;
1028 }
1029 
1030 #ifdef CPP_UTILITIES_DEBUG_BUILD
1031 
1045 void ArgumentParser::verifyArgs(const ArgumentVector &args)
1046 {
1047  vector<const Argument *> verifiedArgs;
1048  verifiedArgs.reserve(args.size());
1049  vector<char> abbreviations;
1050  abbreviations.reserve(abbreviations.size() + args.size());
1051  vector<const char *> names;
1052  names.reserve(names.size() + args.size());
1053  bool hasImplicit = false;
1054  for (const Argument *arg : args) {
1055  assert(find(verifiedArgs.cbegin(), verifiedArgs.cend(), arg) == verifiedArgs.cend());
1056  verifiedArgs.push_back(arg);
1057  assert(!arg->isImplicit() || !hasImplicit);
1058  hasImplicit |= arg->isImplicit();
1059  assert(!arg->abbreviation() || find(abbreviations.cbegin(), abbreviations.cend(), arg->abbreviation()) == abbreviations.cend());
1060  abbreviations.push_back(arg->abbreviation());
1061  assert(!arg->name() || find_if(names.cbegin(), names.cend(), [arg](const char *name) { return !strcmp(arg->name(), name); }) == names.cend());
1062  assert(arg->requiredValueCount() == 0 || arg->subArguments().size() == 0);
1063  names.emplace_back(arg->name());
1064  }
1065  for (const Argument *arg : args) {
1066  verifyArgs(arg->subArguments());
1067  }
1068 }
1069 #endif
1070 
1078 bool compareArgs(const Argument *arg1, const Argument *arg2)
1079 {
1080  if (arg1->denotesOperation() && !arg2->denotesOperation()) {
1081  return true;
1082  } else if (!arg1->denotesOperation() && arg2->denotesOperation()) {
1083  return false;
1084  } else {
1085  return strcmp(arg1->name(), arg2->name()) < 0;
1086  }
1087 }
1088 
1093 void insertSiblings(const ArgumentVector &siblings, list<const Argument *> &target)
1094 {
1095  bool onlyCombinable = false;
1096  for (const Argument *sibling : siblings) {
1097  if (sibling->isPresent() && !sibling->isCombinable()) {
1098  onlyCombinable = true;
1099  break;
1100  }
1101  }
1102  for (const Argument *sibling : siblings) {
1103  if ((!onlyCombinable || sibling->isCombinable()) && sibling->occurrences() < sibling->maxOccurrences()) {
1104  target.push_back(sibling);
1105  }
1106  }
1107 }
1108 
1112 ArgumentCompletionInfo ArgumentParser::determineCompletionInfo(
1113  int argc, const char *const *argv, unsigned int currentWordIndex, const ArgumentReader &reader) const
1114 {
1115  ArgumentCompletionInfo completion(reader);
1116 
1117  // determine last detected arg
1118  if (completion.lastDetectedArg) {
1119  completion.lastDetectedArgIndex = static_cast<size_t>(reader.lastArgDenotation - argv);
1120  completion.lastDetectedArgPath = completion.lastDetectedArg->path(completion.lastDetectedArg->occurrences() - 1);
1121  }
1122 
1123  // determine last arg, omitting trailing empty args
1124  if (argc) {
1125  completion.lastSpecifiedArgIndex = static_cast<unsigned int>(argc) - 1;
1126  completion.lastSpecifiedArg = argv + completion.lastSpecifiedArgIndex;
1127  for (; completion.lastSpecifiedArg >= argv && **completion.lastSpecifiedArg == '\0';
1128  --completion.lastSpecifiedArg, --completion.lastSpecifiedArgIndex)
1129  ;
1130  }
1131 
1132  // just return main arguments if no args detected
1133  if (!completion.lastDetectedArg || !completion.lastDetectedArg->isPresent()) {
1134  completion.nextArgumentOrValue = true;
1135  insertSiblings(m_mainArgs, completion.relevantArgs);
1136  completion.relevantArgs.sort(compareArgs);
1137  return completion;
1138  }
1139 
1140  completion.nextArgumentOrValue = currentWordIndex > completion.lastDetectedArgIndex;
1141  if (!completion.nextArgumentOrValue) {
1142  // since the argument could be detected (hopefully unambiguously?) just return it for "final completion"
1143  completion.relevantArgs.push_back(completion.lastDetectedArg);
1144  completion.relevantArgs.sort(compareArgs);
1145  return completion;
1146  }
1147 
1148  // define function to add parameter values of argument as possible completions
1149  const auto addValueCompletionsForArg = [&completion](const Argument *arg) {
1150  if (arg->valueCompletionBehaviour() & ValueCompletionBehavior::PreDefinedValues) {
1151  completion.relevantPreDefinedValues.push_back(arg);
1152  }
1153  if (!(arg->valueCompletionBehaviour() & ValueCompletionBehavior::FileSystemIfNoPreDefinedValues) || !arg->preDefinedCompletionValues()) {
1154  completion.completeFiles = completion.completeFiles || arg->valueCompletionBehaviour() & ValueCompletionBehavior::Files;
1155  completion.completeDirs = completion.completeDirs || arg->valueCompletionBehaviour() & ValueCompletionBehavior::Directories;
1156  }
1157  };
1158 
1159  // detect number of specified values
1160  auto currentValueCount = completion.lastDetectedArg->values(completion.lastDetectedArg->occurrences() - 1).size();
1161  // ignore values which are specified after the current word
1162  if (currentValueCount) {
1163  const auto currentWordIndexRelativeToLastDetectedArg = currentWordIndex - completion.lastDetectedArgIndex;
1164  if (currentValueCount > currentWordIndexRelativeToLastDetectedArg) {
1165  currentValueCount -= currentWordIndexRelativeToLastDetectedArg;
1166  } else {
1167  currentValueCount = 0;
1168  }
1169  }
1170 
1171  // add value completions for implicit child if there are no value specified and there are no values required by the
1172  // last detected argument itself
1173  if (!currentValueCount && !completion.lastDetectedArg->requiredValueCount()) {
1174  for (const Argument *child : completion.lastDetectedArg->subArguments()) {
1175  if (child->isImplicit() && child->requiredValueCount()) {
1176  addValueCompletionsForArg(child);
1177  break;
1178  }
1179  }
1180  }
1181 
1182  // add value completions for last argument if there are further values required
1183  if (completion.lastDetectedArg->requiredValueCount() == Argument::varValueCount
1184  || (currentValueCount < completion.lastDetectedArg->requiredValueCount())) {
1185  addValueCompletionsForArg(completion.lastDetectedArg);
1186  }
1187 
1188  if (completion.lastDetectedArg->requiredValueCount() == Argument::varValueCount
1189  || completion.lastDetectedArg->values(completion.lastDetectedArg->occurrences() - 1).size()
1190  >= completion.lastDetectedArg->requiredValueCount()) {
1191  // sub arguments of the last arg are possible completions
1192  for (const Argument *subArg : completion.lastDetectedArg->subArguments()) {
1193  if (subArg->occurrences() < subArg->maxOccurrences()) {
1194  completion.relevantArgs.push_back(subArg);
1195  }
1196  }
1197 
1198  // siblings of parents are possible completions as well
1199  for (auto parentArgument = completion.lastDetectedArgPath.crbegin(), end = completion.lastDetectedArgPath.crend();; ++parentArgument) {
1200  insertSiblings(parentArgument != end ? (*parentArgument)->subArguments() : m_mainArgs, completion.relevantArgs);
1201  if (parentArgument == end) {
1202  break;
1203  }
1204  }
1205  }
1206 
1207  return completion;
1208 }
1209 
1213 string ArgumentParser::findSuggestions(int argc, const char *const *argv, unsigned int cursorPos, const ArgumentReader &reader) const
1214 {
1215  // determine completion info
1216  const auto completionInfo(determineCompletionInfo(argc, argv, cursorPos, reader));
1217 
1218  // determine the unknown/misspelled argument
1219  const auto *unknownArg(*reader.argv);
1220  auto unknownArgSize(strlen(unknownArg));
1221  // -> refuse suggestions for long args to prevent huge memory allocation for Damerau-Levenshtein algo
1222  if (unknownArgSize > 16) {
1223  return string();
1224  }
1225  // -> remove dashes since argument names internally don't have them
1226  if (unknownArgSize >= 2 && unknownArg[0] == '-' && unknownArg[1] == '-') {
1227  unknownArg += 2;
1228  unknownArgSize -= 2;
1229  }
1230 
1231  // find best suggestions limiting the results to 2
1232  multiset<ArgumentSuggestion> bestSuggestions;
1233  // -> consider relevant arguments
1234  for (const Argument *const arg : completionInfo.relevantArgs) {
1235  ArgumentSuggestion(unknownArg, unknownArgSize, arg->name(), !arg->denotesOperation()).addTo(bestSuggestions, 2);
1236  }
1237  // -> consider relevant values
1238  for (const Argument *const arg : completionInfo.relevantPreDefinedValues) {
1239  if (!arg->preDefinedCompletionValues()) {
1240  continue;
1241  }
1242  for (const char *i = arg->preDefinedCompletionValues(); *i; ++i) {
1243  const char *const wordStart(i);
1244  const char *wordEnd(wordStart + 1);
1245  for (; *wordEnd && *wordEnd != ' '; ++wordEnd)
1246  ;
1247  ArgumentSuggestion(unknownArg, unknownArgSize, wordStart, static_cast<size_t>(wordEnd - wordStart), false).addTo(bestSuggestions, 2);
1248  i = wordEnd;
1249  }
1250  }
1251 
1252  // format suggestion
1253  string suggestionStr;
1254  if (const auto suggestionCount = bestSuggestions.size()) {
1255  // allocate memory
1256  size_t requiredSize = 15;
1257  for (const auto &suggestion : bestSuggestions) {
1258  requiredSize += suggestion.suggestionSize + 2;
1259  if (suggestion.hasDashPrefix) {
1260  requiredSize += 2;
1261  }
1262  }
1263  suggestionStr.reserve(requiredSize);
1264 
1265  // add each suggestion to end up with something like "Did you mean status (1), pause (3), cat (4), edit (5) or rescan-all (8)?"
1266  suggestionStr += "\nDid you mean ";
1267  size_t i = 0;
1268  for (const auto &suggestion : bestSuggestions) {
1269  if (++i == suggestionCount && suggestionCount != 1) {
1270  suggestionStr += " or ";
1271  } else if (i > 1) {
1272  suggestionStr += ", ";
1273  }
1274  if (suggestion.hasDashPrefix) {
1275  suggestionStr += "--";
1276  }
1277  suggestionStr.append(suggestion.suggestion, suggestion.suggestionSize);
1278  }
1279  suggestionStr += '?';
1280  }
1281  return suggestionStr;
1282 }
1283 
1289 void ArgumentParser::printBashCompletion(int argc, const char *const *argv, unsigned int currentWordIndex, const ArgumentReader &reader) const
1290 {
1291  // determine completion info and sort relevant arguments
1292  const auto completionInfo([&] {
1293  auto clutteredCompletionInfo(determineCompletionInfo(argc, argv, currentWordIndex, reader));
1294  clutteredCompletionInfo.relevantArgs.sort(compareArgs);
1295  return clutteredCompletionInfo;
1296  }());
1297 
1298  // read the "opening" (started but not finished argument denotation)
1299  const char *opening = nullptr;
1300  string compoundOpening;
1301  size_t openingLen = 0, compoundOpeningStartLen = 0;
1302  unsigned char openingDenotationType = Value;
1303  if (argc && completionInfo.nextArgumentOrValue) {
1304  if (currentWordIndex < static_cast<unsigned int>(argc)) {
1305  opening = argv[currentWordIndex];
1306  // For some reason completions for eg. "set --values disk=1 tag=a" are splitted so the
1307  // equation sign is an own argument ("set --values disk = 1 tag = a").
1308  // This is not how values are treated by the argument parser. Hence the opening
1309  // must be joined again. In this case only the part after the equation sign needs to be
1310  // provided for completion so compoundOpeningStartLen is set to number of characters to skip.
1311  const size_t minCurrentWordIndex = (completionInfo.lastDetectedArg ? completionInfo.lastDetectedArgIndex : 0);
1312  if (currentWordIndex > minCurrentWordIndex && !strcmp(opening, "=")) {
1313  compoundOpening.reserve(compoundOpeningStartLen = strlen(argv[--currentWordIndex]) + 1);
1314  compoundOpening = argv[currentWordIndex];
1315  compoundOpening += '=';
1316  } else if (currentWordIndex > (minCurrentWordIndex + 1) && !strcmp(argv[currentWordIndex - 1], "=")) {
1317  compoundOpening.reserve((compoundOpeningStartLen = strlen(argv[currentWordIndex -= 2]) + 1) + strlen(opening));
1318  compoundOpening = argv[currentWordIndex];
1319  compoundOpening += '=';
1320  compoundOpening += opening;
1321  }
1322  if (!compoundOpening.empty()) {
1323  opening = compoundOpening.data();
1324  }
1325  } else {
1326  opening = *completionInfo.lastSpecifiedArg;
1327  }
1328  if (*opening == '-') {
1329  ++opening;
1330  ++openingDenotationType;
1331  if (*opening == '-') {
1332  ++opening;
1333  ++openingDenotationType;
1334  }
1335  }
1336  openingLen = strlen(opening);
1337  }
1338 
1339  // print "COMPREPLY" bash array
1340  cout << "COMPREPLY=(";
1341  // -> completions for parameter values
1342  bool noWhitespace = false;
1343  for (const Argument *const arg : completionInfo.relevantPreDefinedValues) {
1344  if (arg->valueCompletionBehaviour() & ValueCompletionBehavior::InvokeCallback && arg->m_callbackFunction) {
1345  arg->m_callbackFunction(arg->isPresent() ? arg->m_occurrences.front() : ArgumentOccurrence(Argument::varValueCount));
1346  }
1347  if (!arg->preDefinedCompletionValues()) {
1348  continue;
1349  }
1350  const bool appendEquationSign = arg->valueCompletionBehaviour() & ValueCompletionBehavior::AppendEquationSign;
1351  if (argc && currentWordIndex <= completionInfo.lastSpecifiedArgIndex && opening) {
1352  if (openingDenotationType != Value) {
1353  continue;
1354  }
1355  bool wordStart = true, ok = false, equationSignAlreadyPresent = false;
1356  size_t wordIndex = 0;
1357  for (const char *i = arg->preDefinedCompletionValues(), *end = opening + openingLen; *i;) {
1358  if (wordStart) {
1359  const char *i1 = i, *i2 = opening;
1360  for (; *i1 && i2 != end && *i1 == *i2; ++i1, ++i2)
1361  ;
1362  if ((ok = (i2 == end))) {
1363  cout << '\'';
1364  }
1365  wordStart = false;
1366  wordIndex = 0;
1367  } else if ((wordStart = (*i == ' ') || (*i == '\n'))) {
1368  equationSignAlreadyPresent = false;
1369  if (ok) {
1370  cout << '\'' << ' ';
1371  }
1372  ++i;
1373  continue;
1374  } else if (*i == '=') {
1375  equationSignAlreadyPresent = true;
1376  }
1377  if (!ok) {
1378  ++i;
1379  continue;
1380  }
1381  if (!compoundOpeningStartLen || wordIndex >= compoundOpeningStartLen) {
1382  if (*i == '\'') {
1383  cout << "'\"'\"'";
1384  } else {
1385  cout << *i;
1386  }
1387  }
1388  ++i;
1389  ++wordIndex;
1390  switch (*i) {
1391  case ' ':
1392  case '\n':
1393  case '\0':
1394  if (appendEquationSign && !equationSignAlreadyPresent) {
1395  cout << '=';
1396  noWhitespace = true;
1397  equationSignAlreadyPresent = false;
1398  }
1399  if (*i == '\0') {
1400  cout << '\'';
1401  }
1402  }
1403  }
1404  cout << ' ';
1405  } else if (const char *i = arg->preDefinedCompletionValues()) {
1406  bool equationSignAlreadyPresent = false;
1407  cout << '\'';
1408  while (*i) {
1409  if (*i == '\'') {
1410  cout << "'\"'\"'";
1411  } else {
1412  cout << *i;
1413  }
1414  switch (*(++i)) {
1415  case '=':
1416  equationSignAlreadyPresent = true;
1417  break;
1418  case ' ':
1419  case '\n':
1420  case '\0':
1421  if (appendEquationSign && !equationSignAlreadyPresent) {
1422  cout << '=';
1423  equationSignAlreadyPresent = false;
1424  }
1425  if (*i != '\0') {
1426  cout << '\'';
1427  if (*(++i)) {
1428  cout << ' ' << '\'';
1429  }
1430  }
1431  }
1432  }
1433  cout << '\'' << ' ';
1434  }
1435  }
1436  // -> completions for further arguments
1437  for (const Argument *const arg : completionInfo.relevantArgs) {
1438  if (argc && currentWordIndex <= completionInfo.lastSpecifiedArgIndex && opening) {
1439  switch (openingDenotationType) {
1440  case Value:
1441  if (!arg->denotesOperation() || strncmp(arg->name(), opening, openingLen)) {
1442  continue;
1443  }
1444  break;
1445  case Abbreviation:
1446  break;
1447  case FullName:
1448  if (strncmp(arg->name(), opening, openingLen)) {
1449  continue;
1450  }
1451  }
1452  }
1453 
1454  if (opening && openingDenotationType == Abbreviation && !completionInfo.nextArgumentOrValue) {
1455  // TODO: add test for this case
1456  cout << '\'' << '-' << opening << arg->abbreviation() << '\'' << ' ';
1457  } else if (completionInfo.lastDetectedArg && reader.argDenotationType == Abbreviation && !completionInfo.nextArgumentOrValue) {
1458  if (reader.argv == reader.end) {
1459  cout << '\'' << *(reader.argv - 1) << '\'' << ' ';
1460  }
1461  } else if (arg->denotesOperation()) {
1462  cout << '\'' << arg->name() << '\'' << ' ';
1463  } else {
1464  cout << '\'' << '-' << '-' << arg->name() << '\'' << ' ';
1465  }
1466  }
1467  // -> completions for files and dirs
1468  // -> if there's already an "opening", determine the dir part and the file part
1469  string actualDir, actualFile;
1470  bool haveFileOrDirCompletions = false;
1471  if (argc && currentWordIndex == completionInfo.lastSpecifiedArgIndex && opening) {
1472  // the "opening" might contain escaped characters which need to be unescaped first (let's hope this covers all possible escapings)
1473  string unescapedOpening(opening);
1474  findAndReplace<string>(unescapedOpening, "\\ ", " ");
1475  findAndReplace<string>(unescapedOpening, "\\,", ",");
1476  findAndReplace<string>(unescapedOpening, "\\[", "[");
1477  findAndReplace<string>(unescapedOpening, "\\]", "]");
1478  findAndReplace<string>(unescapedOpening, "\\!", "!");
1479  findAndReplace<string>(unescapedOpening, "\\#", "#");
1480  findAndReplace<string>(unescapedOpening, "\\$", "$");
1481  findAndReplace<string>(unescapedOpening, "\\'", "'");
1482  findAndReplace<string>(unescapedOpening, "\\\"", "\"");
1483  findAndReplace<string>(unescapedOpening, "\\\\", "\\");
1484  // determine the "directory" part
1485  string dir = directory(unescapedOpening);
1486  if (dir.empty()) {
1487  actualDir = ".";
1488  } else {
1489  if (dir[0] == '\"' || dir[0] == '\'') {
1490  dir.erase(0, 1);
1491  }
1492  if (dir.size() > 1 && (dir[dir.size() - 2] == '\"' || dir[dir.size() - 2] == '\'')) {
1493  dir.erase(dir.size() - 2, 1);
1494  }
1495  actualDir = move(dir);
1496  }
1497  // determine the "file" part
1498  string file = fileName(unescapedOpening);
1499  if (file[0] == '\"' || file[0] == '\'') {
1500  file.erase(0, 1);
1501  }
1502  if (file.size() > 1 && (file[dir.size() - 2] == '\"' || dir[file.size() - 2] == '\'')) {
1503  file.erase(file.size() - 2, 1);
1504  }
1505  actualFile = move(file);
1506  }
1507 
1508  // -> completion for files and dirs
1509 #ifdef CPP_UTILITIES_USE_STANDARD_FILESYSTEM
1510  if (completionInfo.completeFiles || completionInfo.completeDirs) {
1511  try {
1512  const auto replace = "'"s, with = "'\"'\"'"s;
1513  const auto useActualDir = argc && currentWordIndex <= completionInfo.lastSpecifiedArgIndex && opening;
1514  const auto dirEntries = [&] {
1515  filesystem::directory_iterator i;
1516  if (useActualDir) {
1517  i = filesystem::directory_iterator(actualDir);
1518  findAndReplace(actualDir, replace, with);
1519  } else {
1520  i = filesystem::directory_iterator(".");
1521  }
1522  return i;
1523  }();
1524  for (const auto &dirEntry : dirEntries) {
1525  if (!completionInfo.completeDirs && dirEntry.is_directory()) {
1526  continue;
1527  }
1528  if (!completionInfo.completeFiles && !dirEntry.is_directory()) {
1529  continue;
1530  }
1531  auto dirEntryName = dirEntry.path().filename().string();
1532  auto hasStartingQuote = false;
1533  if (useActualDir) {
1534  if (!startsWith(dirEntryName, actualFile)) {
1535  continue;
1536  }
1537  cout << '\'';
1538  hasStartingQuote = true;
1539  if (actualDir != ".") {
1540  cout << actualDir;
1541  }
1542  }
1543  findAndReplace(dirEntryName, replace, with);
1544  if (!hasStartingQuote) {
1545  cout << '\'';
1546  }
1547  cout << dirEntryName << '\'' << ' ';
1548  haveFileOrDirCompletions = true;
1549  }
1550  } catch (const filesystem::filesystem_error &) {
1551  // ignore filesystem errors; there's no good way to report errors when printing bash completion
1552  }
1553  }
1554 #endif
1555  cout << ')';
1556 
1557  // ensure file or dir completions are formatted appropriately
1558  if (haveFileOrDirCompletions) {
1559  cout << "; compopt -o filenames";
1560  }
1561 
1562  // ensure trailing whitespace is ommitted
1563  if (noWhitespace) {
1564  cout << "; compopt -o nospace";
1565  }
1566 
1567  cout << endl;
1568 }
1569 
1575 {
1576  for (const Argument *arg : args) {
1577  const auto occurrences = arg->occurrences();
1578  if (arg->isParentPresent() && occurrences > arg->maxOccurrences()) {
1579  throw ParseError(argsToString("The argument \"", arg->name(), "\" mustn't be specified more than ", arg->maxOccurrences(),
1580  (arg->maxOccurrences() == 1 ? " time." : " times.")));
1581  }
1582  if (arg->isParentPresent() && occurrences < arg->minOccurrences()) {
1583  throw ParseError(argsToString("The argument \"", arg->name(), "\" must be specified at least ", arg->minOccurrences(),
1584  (arg->minOccurrences() == 1 ? " time." : " times.")));
1585  }
1586  Argument *conflictingArgument = nullptr;
1587  if (arg->isMainArgument()) {
1588  if (!arg->isCombinable() && arg->isPresent()) {
1589  conflictingArgument = firstPresentUncombinableArg(m_mainArgs, arg);
1590  }
1591  } else {
1592  conflictingArgument = arg->conflictsWithArgument();
1593  }
1594  if (conflictingArgument) {
1595  throw ParseError(argsToString("The argument \"", conflictingArgument->name(), "\" can not be combined with \"", arg->name(), "\"."));
1596  }
1597  for (size_t i = 0; i != occurrences; ++i) {
1598  if (arg->allRequiredValuesPresent(i)) {
1599  continue;
1600  }
1601  stringstream ss(stringstream::in | stringstream::out);
1602  ss << "Not all parameter for argument \"" << arg->name() << "\" ";
1603  if (i) {
1604  ss << " (" << (i + 1) << " occurrence) ";
1605  }
1606  ss << "provided. You have to provide the following parameter:";
1607  size_t valueNamesPrint = 0;
1608  for (const auto &name : arg->m_valueNames) {
1609  ss << ' ' << name;
1610  ++valueNamesPrint;
1611  }
1612  if (arg->m_requiredValueCount != Argument::varValueCount) {
1613  while (valueNamesPrint < arg->m_requiredValueCount) {
1614  ss << "\nvalue " << (++valueNamesPrint);
1615  }
1616  }
1617  throw ParseError(ss.str());
1618  }
1619 
1620  // check contraints of sub arguments recursively
1621  checkConstraints(arg->m_subArgs);
1622  }
1623 }
1624 
1633 {
1634  for (const Argument *arg : args) {
1635  // invoke the callback for each occurrence of the argument
1636  if (arg->m_callbackFunction) {
1637  for (const auto &occurrence : arg->m_occurrences) {
1638  arg->m_callbackFunction(occurrence);
1639  }
1640  }
1641  // invoke the callbacks for sub arguments recursively
1642  invokeCallbacks(arg->m_subArgs);
1643  }
1644 }
1645 
1649 void ArgumentParser::invokeExit(int code)
1650 {
1651  if (m_exitFunction) {
1652  m_exitFunction(code);
1653  return;
1654  }
1655  std::exit(code);
1656 }
1657 
1668  : Argument("help", 'h', "shows this information")
1669 {
1670  setCallback([&parser](const ArgumentOccurrence &) {
1672  parser.printHelp(cout);
1673  });
1674 }
1675 
1711 #ifdef CPP_UTILITIES_ESCAPE_CODES_ENABLED_BY_DEFAULT
1712  : Argument("no-color", '\0', "disables formatted/colorized output")
1713 #else
1714  : Argument("enable-color", '\0', "enables formatted/colorized output")
1715 #endif
1716 {
1717  setCombinable(true);
1718 
1719  // set the environmentvariable: note that this is not directly used and just assigned for printing help
1720  setEnvironmentVariable("ENABLE_ESCAPE_CODES");
1721 
1722  // default-initialize EscapeCodes::enabled from environment variable
1723  const char *envValue = getenv(environmentVariable());
1724  if (!envValue) {
1725  return;
1726  }
1727  for (; *envValue; ++envValue) {
1728  switch (*envValue) {
1729  case '0':
1730  case ' ':
1731  break;
1732  default:
1733  // enable escape codes if ENABLE_ESCAPE_CODES contains anything else than spaces or zeros
1734  EscapeCodes::enabled = true;
1735  return;
1736  }
1737  }
1738  // disable escape codes if ENABLE_ESCAPE_CODES is empty or only contains spaces and zeros
1739  EscapeCodes::enabled = false;
1740 }
1741 
1746 {
1747  if (isPresent()) {
1748 #ifdef CPP_UTILITIES_ESCAPE_CODES_ENABLED_BY_DEFAULT
1749  EscapeCodes::enabled = false;
1750 #else
1751  EscapeCodes::enabled = true;
1752 #endif
1753  }
1754 }
1755 
1759 void ValueConversion::Helper::ArgumentValueConversionError::throwFailure(const std::vector<Argument *> &argumentPath) const
1760 {
1761  throw ParseError(argumentPath.empty()
1762  ? argsToString("Conversion of top-level value \"", valueToConvert, "\" to type \"", targetTypeName, "\" failed: ", errorMessage)
1763  : argsToString("Conversion of value \"", valueToConvert, "\" (for argument --", argumentPath.back()->name(), ") to type \"",
1764  targetTypeName, "\" failed: ", errorMessage));
1765 }
1766 
1770 void ArgumentOccurrence::throwNumberOfValuesNotSufficient(unsigned long valuesToConvert) const
1771 {
1772  throw ParseError(path.empty()
1773  ? argsToString("Expected ", valuesToConvert, " top-level values to be present but only ", values.size(), " have been specified.")
1774  : argsToString("Expected ", valuesToConvert, " values for argument --", path.back()->name(), " to be present but only ", values.size(),
1775  " have been specified."));
1776 }
1777 
1778 } // namespace CppUtilities
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:459
CppUtilities::ArgumentReader::end
const char *const * end
Points to the end of the argv array.
Definition: argumentparserprivate.h:25
CppUtilities::Argument::setSubArguments
void setSubArguments(const ArgumentInitializerList &subArguments)
Sets the secondary arguments for this arguments.
Definition: argumentparser.cpp:600
CppUtilities::Argument::varValueCount
static constexpr std::size_t varValueCount
Denotes a variable number of values.
Definition: argumentparser.h:361
CppUtilities::ApplicationInfo::dependencyVersions
std::vector< const char * > dependencyVersions
Definition: argumentparser.h:31
CppUtilities::Argument
The Argument class is a wrapper for command line argument information.
Definition: argumentparser.h:262
CppUtilities::FullName
@ FullName
Definition: argumentparser.cpp:41
CppUtilities::ArgumentCompletionInfo
The ArgumentCompletionInfo struct holds information internally used for shell completion and suggesti...
Definition: argumentparser.cpp:47
CppUtilities::ArgumentReader::read
bool read()
Reads the commands line arguments specified when constructing the object.
Definition: argumentparser.cpp:155
CppUtilities::ArgumentParser::checkConstraints
void checkConstraints()
Checks whether contraints are violated.
Definition: argumentparser.h:1152
CppUtilities::Indentation
The Indentation class allows printing indentation conveniently, eg.
Definition: commandlineutils.h:66
CppUtilities::Argument::isParentPresent
bool isParentPresent() const
Returns whether at least one parent argument is present.
Definition: argumentparser.cpp:639
CppUtilities::IniFileParseOptions::None
@ None
CppUtilities::ParseError
The ParseError class is thrown by an ArgumentParser when a parsing error occurs.
Definition: parseerror.h:11
CppUtilities::ArgumentReader::argv
const char *const * argv
Points to the first argument denotation and will be incremented when a denotation has been processed.
Definition: argumentparserprivate.h:23
CppUtilities::ValueCompletionBehavior
ValueCompletionBehavior
The ValueCompletionBehavior enum specifies the items to be considered when generating completion for ...
Definition: argumentparser.h:116
CppUtilities::ArgumentParser::resetArgs
void resetArgs()
Resets all Argument instances assigned as mainArguments() and sub arguments.
Definition: argumentparser.cpp:994
CppUtilities::startsWith
bool startsWith(const StringType &str, const StringType &phrase)
Returns whether str starts with phrase.
Definition: stringconversion.h:213
CppUtilities::Argument::name
const char * name() const
Returns the name of the argument.
Definition: argumentparser.h:513
CppUtilities::ValueCompletionBehavior::None
@ None
CppUtilities::applicationInfo
CPP_UTILITIES_EXPORT ApplicationInfo applicationInfo
Stores global application info used by ArgumentParser::printHelp() and AboutDialog.
Definition: argumentparser.cpp:432
CppUtilities::ApplicationInfo
Stores information about an application.
Definition: argumentparser.h:22
CppUtilities::Argument::occurrences
std::size_t occurrences() const
Returns how often the argument could be detected when parsing.
Definition: argumentparser.h:746
CppUtilities::ArgumentCompletionInfo::lastDetectedArgPath
vector< Argument * > lastDetectedArgPath
Definition: argumentparser.cpp:52
CppUtilities::HelpArgument::HelpArgument
HelpArgument(ArgumentParser &parser)
Constructs a new help argument for the specified parser.
Definition: argumentparser.cpp:1667
CppUtilities::Argument::conflictsWithArgument
Argument * conflictsWithArgument() const
Checks if this arguments conflicts with other arguments.
Definition: argumentparser.cpp:660
CppUtilities::Argument::environmentVariable
const char * environmentVariable() const
Returns the environment variable queried when firstValue() is called.
Definition: argumentparser.h:566
CppUtilities::ArgumentParser::setMainArguments
void setMainArguments(const ArgumentInitializerList &mainArguments)
Sets the main arguments for the parser.
Definition: argumentparser.cpp:748
CppUtilities::Abbreviation
@ Abbreviation
Definition: argumentparser.cpp:40
CppUtilities::ArgumentDenotationType
ArgumentDenotationType
The ArgumentDenotationType enum specifies the type of a given argument denotation.
Definition: argumentparser.cpp:38
CppUtilities::ArgumentParser::mainArguments
const ArgumentVector & mainArguments() const
Returns the main arguments.
Definition: argumentparser.h:1088
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:894
CppUtilities::Argument::isDeprecated
bool isDeprecated() const
Definition: argumentparser.h:779
CppUtilities::Argument::printInfo
void printInfo(std::ostream &os, unsigned char indentation=0) const
Writes the name, the abbreviation and other information about the Argument to the give ostream.
Definition: argumentparser.cpp:505
CppUtilities::Indentation::level
unsigned char level
Definition: commandlineutils.h:79
CppUtilities::firstPresentUncombinableArg
Argument * firstPresentUncombinableArg(const ArgumentVector &args, const Argument *except)
This function return the first present and uncombinable argument of the given list of arguments.
Definition: argumentparser.cpp:576
CppUtilities::ArgumentCompletionInfo::lastDetectedArg
const Argument *const lastDetectedArg
Definition: argumentparser.cpp:50
CppUtilities::Argument::example
const char * example() const
Returns the usage example of the argument.
Definition: argumentparser.h:605
CppUtilities::Argument::subArguments
const ArgumentVector & subArguments() const
Returns the secondary arguments for this argument.
Definition: argumentparser.h:956
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:945
CppUtilities::TerminalSize::columns
unsigned short columns
number of columns
Definition: commandlineutils.h:46
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:644
CppUtilities::TerminalSize
The TerminalSize struct describes a terminal size.
Definition: commandlineutils.h:40
CppUtilities::operator<<
CPP_UTILITIES_EXPORT std::ostream & operator<<(std::ostream &out, Indentation indentation)
Definition: commandlineutils.h:83
CppUtilities::ParseArgumentBehavior::ReadArguments
@ ReadArguments
CppUtilities::findAndReplace
void findAndReplace(StringType1 &str, const StringType2 &find, const StringType3 &replace)
Replaces all occurences of find with relpace in the specified str.
Definition: stringconversion.h:317
CppUtilities::NoColorArgument::apply
void apply() const
Sets EscapeCodes::enabled according to the presense of the first instantiation of NoColorArgument.
Definition: argumentparser.cpp:1745
CppUtilities::max
constexpr T max(T first, T second)
Returns the greatest of the given items.
Definition: math.h:100
CppUtilities::insertSiblings
void insertSiblings(const ArgumentVector &siblings, list< const Argument * > &target)
Inserts the specified siblings in the target list.
Definition: argumentparser.cpp:1093
CppUtilities::ArgumentInitializerList
std::initializer_list< Argument * > ArgumentInitializerList
Definition: argumentparser.h:67
CppUtilities::Argument::specifiedOperation
Argument * specifiedOperation() const
Returns the first operation argument specified by the user or nullptr if no operation has been specif...
Definition: argumentparser.cpp:692
CppUtilities::ArgumentReader::reset
ArgumentReader & reset(const char *const *argv, const char *const *end)
Resets the ArgumentReader to continue reading new argv.
Definition: argumentparser.cpp:141
CppUtilities::ArgumentParser::invokeCallbacks
void invokeCallbacks()
Invokes all assigned callbacks.
Definition: argumentparser.h:1161
CppUtilities::Argument::isRequired
bool isRequired() const
Returns an indication whether the argument is mandatory.
Definition: argumentparser.h:831
CppUtilities::argsToString
StringType argsToString(Args &&... args)
Definition: stringbuilder.h:258
CppUtilities::directory
CPP_UTILITIES_EXPORT std::string directory(const std::string &path)
Returns the directory of the specified path string (including trailing slash).
Definition: path.cpp:35
CppUtilities::Argument::firstValue
const char * firstValue() const
Returns the first parameter value of the first occurrence of the argument.
Definition: argumentparser.cpp:491
CppUtilities::ParseArgumentBehavior
ParseArgumentBehavior
The ParseArgumentBehavior enum specifies the behavior when parsing arguments.
Definition: argumentparser.h:87
CppUtilities::Argument::addSubArgument
void addSubArgument(Argument *arg)
Adds arg as a secondary argument for this argument.
Definition: argumentparser.cpp:624
CppUtilities::Argument::description
const char * description() const
Returns the description of the argument.
Definition: argumentparser.h:585
CppUtilities::NoColorArgument::NoColorArgument
NoColorArgument()
Constructs a new NoColorArgument argument.
Definition: argumentparser.cpp:1710
CppUtilities::ApplicationInfo::url
const char * url
Definition: argumentparser.h:26
CppUtilities::ArgumentReader::parser
ArgumentParser & parser
The associated ArgumentParser instance.
Definition: argumentparserprivate.h:17
CppUtilities
Contains all utilities provides by the c++utilities library.
Definition: argumentparser.h:17
i
constexpr int i
Definition: traitstests.cpp:106
CppUtilities::ApplicationInfo::version
const char * version
Definition: argumentparser.h:25
CppUtilities::ArgumentParser::addMainArgument
void addMainArgument(Argument *argument)
Adds the specified argument to the main argument.
Definition: argumentparser.cpp:779
CppUtilities::EscapeCodes
Encapsulates functions for formatted terminal output using ANSI escape codes.
Definition: ansiescapecodes.h:12
CppUtilities::Argument::isPresent
bool isPresent() const
Returns an indication whether the argument could be detected when parsing.
Definition: argumentparser.h:738
CppUtilities::UnknownArgumentBehavior
UnknownArgumentBehavior
The UnknownArgumentBehavior enum specifies the behavior of the argument parser when an unknown argume...
Definition: argumentparser.h:75
CppUtilities::Value
@ Value
Definition: argumentparser.cpp:39
CppUtilities::Argument::reset
void reset()
Resets occurrences (indices, values and paths).
Definition: argumentparser.h:1041
CppUtilities::computeDamerauLevenshteinDistance
CPP_UTILITIES_EXPORT std::size_t computeDamerauLevenshteinDistance(const char *str1, std::size_t size1, const char *str2, std::size_t size2)
CppUtilities::ApplicationInfo::description
const char * description
Definition: argumentparser.h:28
CppUtilities::Argument::isCombinable
bool isCombinable() const
Returns an indication whether the argument is combinable.
Definition: argumentparser.h:888
CppUtilities::compareArgs
bool compareArgs(const Argument *arg1, const Argument *arg2)
Returns whether arg1 should be listed before arg2 when printing completion.
Definition: argumentparser.cpp:1078
CppUtilities::ArgumentReader
The ArgumentReader class internally encapsulates the process of reading command line arguments.
Definition: argumentparserprivate.h:9
CppUtilities::Argument::path
const std::vector< Argument * > & path(std::size_t occurrence=0) const
Returns the path of the specified occurrence.
Definition: argumentparser.h:817
CppUtilities::ConversionException
The ConversionException class is thrown by the various conversion functions of this library when a co...
Definition: conversionexception.h:11
CppUtilities::ArgumentReader::lastArgDenotation
const char *const * lastArgDenotation
Points to the element in argv where lastArg was encountered. Unspecified if lastArg is not set.
Definition: argumentparserprivate.h:29
CppUtilities::ArgumentReader::argDenotationType
unsigned char argDenotationType
The type of the currently processed abbreviation denotation. Unspecified if argDenotation is not set.
Definition: argumentparserprivate.h:33
CppUtilities::ArgumentParser::isUncombinableMainArgPresent
bool isUncombinableMainArgPresent() const
Checks whether at least one uncombinable main argument is present.
Definition: argumentparser.cpp:1020
CppUtilities::Argument::Flags
Flags
Definition: argumentparser.h:270
CppUtilities::min
constexpr T min(T first, T second)
Returns the smallest of the given items.
Definition: math.h:88
CppUtilities::ArgumentOccurrence::values
std::vector< const char * > values
The parameter values which have been specified after the occurrence of the argument.
Definition: argumentparser.h:205
argumentparser.h
CppUtilities::ArgumentParser::printHelp
void printHelp(std::ostream &os) const
Prints help text for all assigned arguments.
Definition: argumentparser.cpp:788
CppUtilities::Argument::valueNames
const std::vector< const char * > & valueNames() const
Returns the names of the requried values.
Definition: argumentparser.h:674
CppUtilities::Wrapper
The Wrapper class is internally used print text which might needs to be wrapped preserving the indent...
Definition: argumentparserprivate.h:42
CppUtilities::ArgumentReader::lastArg
Argument * lastArg
The last Argument instance which could be detected. Set to nullptr in the initial call....
Definition: argumentparserprivate.h:27
CppUtilities::Argument::resetRecursively
void resetRecursively()
Resets this argument and all sub arguments recursively.
Definition: argumentparser.cpp:706
CppUtilities::Argument::abbreviation
char abbreviation() const
Returns the abbreviation of the argument.
Definition: argumentparser.h:543
CppUtilities::ArgumentParser::readArgs
void readArgs(int argc, const char *const *argv)
Parses the specified command line arguments.
Definition: argumentparser.cpp:930
CppUtilities::Argument::wouldConflictWithArgument
Argument * wouldConflictWithArgument() const
Checks if this argument would conflict with other arguments if it was present.
Definition: argumentparser.cpp:673
CMD_UTILS_START_CONSOLE
#define CMD_UTILS_START_CONSOLE
Definition: commandlineutils.h:31
CppUtilities::ArgumentCompletionInfo::relevantArgs
list< const Argument * > relevantArgs
Definition: argumentparser.cpp:53
CppUtilities::ArgumentOccurrence
The ArgumentOccurrence struct holds argument values for an occurrence of an argument.
Definition: argumentparser.h:193
CppUtilities::ArgumentReader::args
ArgumentVector & args
The Argument instances to store the results. Sub arguments of args are considered as well.
Definition: argumentparserprivate.h:19
CppUtilities::ArgumentVector
std::vector< Argument * > ArgumentVector
Definition: argumentparser.h:68
CPP_UTILITIES_EXPORT
#define CPP_UTILITIES_EXPORT
Marks the symbol to be exported by the c++utilities library.
CppUtilities::Argument::isMainArgument
bool isMainArgument() const
Returns an indication whether the argument is used as main argument.
Definition: argumentparser.h:993
commandlineutils.h
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:1007
argumentparserprivate.h
CppUtilities::operator==
bool operator==(const AsHexNumber< T > &lhs, const AsHexNumber< T > &rhs)
Provides operator == required by CPPUNIT_ASSERT_EQUAL.
Definition: testutils.h:215
CppUtilities::ArgumentOccurrence::path
std::vector< Argument * > path
The "path" of the occurrence (the parent elements which have been specified before).
Definition: argumentparser.h:211
CppUtilities::EscapeCodes::setStyle
void setStyle(std::ostream &stream, TextAttribute displayAttribute=TextAttribute::Reset)
Definition: ansiescapecodes.h:34
CppUtilities::ArgumentReader::ArgumentReader
ArgumentReader(ArgumentParser &parser, const char *const *argv, const char *const *end, bool completionMode=false)
Initializes the internal reader for the specified parser and arguments.
Definition: argumentparser.cpp:126
CppUtilities::fileName
CPP_UTILITIES_EXPORT std::string fileName(const std::string &path)
Returns the file name and extension of the specified path string.
Definition: path.cpp:15
CppUtilities::ArgumentParser
The ArgumentParser class provides a means for handling command line arguments.
Definition: argumentparser.h:450
CppUtilities::ArgumentReader::completionMode
bool completionMode
Whether completion mode is enabled. In this case reading args will be continued even if an denotation...
Definition: argumentparserprivate.h:35
CppUtilities::determineTerminalSize
CPP_UTILITIES_EXPORT TerminalSize determineTerminalSize()
Returns the current size of the terminal.
Definition: commandlineutils.cpp:46
CppUtilities::ArgumentReader::index
size_t index
An index which is incremented when an argument is encountered (the current index is stored in the occ...
Definition: argumentparserprivate.h:21
CppUtilities::UnknownArgumentBehavior::Ignore
@ Ignore
CppUtilities::ArgumentReader::argDenotation
const char * argDenotation
The currently processed abbreviation denotation (should be substring of one of the args in argv)....
Definition: argumentparserprivate.h:31
CppUtilities::ApplicationInfo::name
const char * name
Definition: argumentparser.h:23
CPP_UTILITIES_IF_DEBUG_BUILD
#define CPP_UTILITIES_IF_DEBUG_BUILD(x)
Wraps debug-only lines conveniently.
Definition: global.h:102
CppUtilities::Argument::~Argument
~Argument()
Destroys the Argument.
Definition: argumentparser.cpp:480
CppUtilities::ArgumentCompletionInfo::relevantPreDefinedValues
list< const Argument * > relevantPreDefinedValues
Definition: argumentparser.cpp:54
CppUtilities::ArgumentParser::ArgumentParser
ArgumentParser()
Constructs a new ArgumentParser.
Definition: argumentparser.cpp:730
CppUtilities::EscapeCodes::enabled
CPP_UTILITIES_EXPORT bool enabled
Controls whether the functions inside the EscapeCodes namespace actually make use of escape codes.
Definition: ansiescapecodes.cpp:22
CppUtilities::Argument::denotesOperation
bool denotesOperation() const
Returns whether the argument denotes an operation.
Definition: argumentparser.h:916