Leonetienne/Hazelnupp
Simple, easy to use, command line parameter interface
Public Member Functions | List of all members
Hazelnp::CmdArgsInterface Class Reference

The main class to interface with. More...

#include <CmdArgsInterface.h>

Public Member Functions

 CmdArgsInterface ()
 
 CmdArgsInterface (const int argc, const char *const *argv)
 
 ~CmdArgsInterface ()
 
void Parse (const int argc, const char *const *argv)
 Will parse command line arguments. More...
 
const std::string & GetExecutableName () const
 Will return argv[0], the name of the executable. More...
 
const Valueoperator[] (const std::string &key) const
 Will return the value given a key. More...
 
bool HasParam (const std::string &key) const
 Will check wether a parameter exists given a key, or not. More...
 
void RegisterAbbreviation (const std::string &abbrev, const std::string &target)
 Will register an abbreviation (like -f for –force) More...
 
const std::string & GetAbbreviation (const std::string &abbrev) const
 Will return the long form of an abbreviation (like –force for -f)
Returns "" if no match is found. More...
 
bool HasAbbreviation (const std::string &abbrev) const
 Will check wether or not an abbreviation is registered. More...
 
void ClearAbbreviation (const std::string &abbrevation)
 Will delete the abbreviation for a given parameter. More...
 
void ClearAbbreviations ()
 Will delete all abbreviations. More...
 
void RegisterConstraint (const std::string &key, const ParamConstraint &constraint)
 Will register a constraint for a parameter. More...
 
ParamConstraint GetConstraint (const std::string &parameter) const
 Will return the constraint information for a specific parameter. More...
 
void ClearConstraint (const std::string &parameter)
 Will the constraint of a specific parameter. More...
 
void ClearConstraints ()
 Will delete all constraints. More...
 
void SetCrashOnFail (bool crashOnFail)
 Sets whether to crash the application, and print to stderr, when an exception is raised whilst parsing, or not. More...
 
bool GetCrashOnFail () const
 Gets whether the application crashes on an exception whilst parsing, and prints to stderr. More...
 
void SetCatchHelp (bool catchHelp)
 Sets whether the CmdArgsInterface should automatically catch the –help parameter, print the parameter documentation to stdout, and exit or not. More...
 
bool GetCatchHelp () const
 Retruns whether the CmdArgsInterface should automatically catch the –help parameter, print the parameter documentation to stdout, and exit or not. More...
 
void SetBriefDescription (const std::string &description)
 Sets a brief description of the application to be automatically added to the documentation. More...
 
const std::string & GetBriefDescription ()
 Returns the brief description of the application to be automatically added to the documentation. More...
 
void RegisterDescription (const std::string &parameter, const std::string &description)
 Willl register a short description for a parameter. More...
 
const std::string & GetDescription (const std::string &parameter) const
 Will return a short description for a parameter, if it exists. More...
 
bool HasDescription (const std::string &parameter) const
 Returns whether or not a given parameter has a registered description. More...
 
void ClearDescription (const std::string &parameter)
 Will delete the description of a parameter if it exists. More...
 
void ClearDescriptions ()
 Will delete all parameter descriptions. More...
 
std::string GenerateDocumentation () const
 Will generate a text-based documentation suited to show the user, for example on –help. More...
 

Detailed Description

The main class to interface with.

Definition at line 13 of file CmdArgsInterface.h.

Constructor & Destructor Documentation

◆ CmdArgsInterface() [1/2]

CmdArgsInterface::CmdArgsInterface ( )

Definition at line 15 of file CmdArgsInterface.cpp.

16 {
17  return;
18 }

◆ CmdArgsInterface() [2/2]

CmdArgsInterface::CmdArgsInterface ( const int  argc,
const char *const *  argv 
)

Definition at line 20 of file CmdArgsInterface.cpp.

21 {
22  Parse(argc, argv);
23  return;
24 }

◆ ~CmdArgsInterface()

CmdArgsInterface::~CmdArgsInterface ( )

Definition at line 26 of file CmdArgsInterface.cpp.

27 {
28  for (auto& it : parameters)
29  delete it.second;
30 
31  parameters.clear();
32 
33  return;
34 }

Member Function Documentation

◆ ClearAbbreviation()

void CmdArgsInterface::ClearAbbreviation ( const std::string &  abbrevation)

Will delete the abbreviation for a given parameter.


IMPORTANT: This parameter is the abbreviation! Not the long form!

Definition at line 651 of file CmdArgsInterface.cpp.

652 {
653  parameterAbreviations.erase(abbrevation);
654  return;
655 }

◆ ClearAbbreviations()

void CmdArgsInterface::ClearAbbreviations ( )

Will delete all abbreviations.

Definition at line 657 of file CmdArgsInterface.cpp.

658 {
659  parameterAbreviations.clear();
660  return;
661 }

◆ ClearConstraint()

void CmdArgsInterface::ClearConstraint ( const std::string &  parameter)

Will the constraint of a specific parameter.

Definition at line 612 of file CmdArgsInterface.cpp.

613 {
614  parameterConstraints.erase(parameter);
615  return;
616 }

◆ ClearConstraints()

void CmdArgsInterface::ClearConstraints ( )

Will delete all constraints.

Definition at line 670 of file CmdArgsInterface.cpp.

671 {
672  parameterConstraints.clear();
673  return;
674 }

◆ ClearDescription()

void CmdArgsInterface::ClearDescription ( const std::string &  parameter)

Will delete the description of a parameter if it exists.

Definition at line 412 of file CmdArgsInterface.cpp.

413 {
414  // This will just do nothing if the entry does not exist
415  parameterDescriptions.erase(parameter);
416  return;
417 }

◆ ClearDescriptions()

void Hazelnp::CmdArgsInterface::ClearDescriptions ( )

Will delete all parameter descriptions.

Definition at line 419 of file CmdArgsInterface.cpp.

420 {
421  parameterDescriptions.clear();
422  return;
423 }

◆ GenerateDocumentation()

std::string CmdArgsInterface::GenerateDocumentation ( ) const

Will generate a text-based documentation suited to show the user, for example on –help.

Definition at line 425 of file CmdArgsInterface.cpp.

426 {
427  std::stringstream ss;
428 
429  // Add brief, if available
430  if (briefDescription.length() > 0)
431  ss << briefDescription << std::endl;
432 
433  // Collect parameter information
434  struct ParamDocEntry
435  {
436  std::string abbreviation;
437  std::string description;
438  std::string type;
439  bool required = false;
440  bool typeIsForced = false;
441  std::string defaultVal;
442  std::string incompatibilities;
443  };
444  std::unordered_map<std::string, ParamDocEntry> paramInfos;
445 
446  // Collect descriptions
447  for (const auto& it : parameterDescriptions)
448  {
449  // Do we already have that param in the paramInfo set?
450  if (paramInfos.find(it.first) == paramInfos.end())
451  // No? Create it.
452  paramInfos[it.first] = ParamDocEntry();
453 
454  paramInfos[it.first].description = it.second;
455  }
456 
457  // Collect abbreviations
458  // first value is abbreviation, second is long form
459  for (const auto& it : parameterAbreviations)
460  {
461  // Do we already have that param in the paramInfo set?
462  if (paramInfos.find(it.second) == paramInfos.end())
463  // No? Create it.
464  paramInfos[it.second] = ParamDocEntry();
465 
466  paramInfos[it.second].abbreviation = it.first;
467  }
468 
469  // Collect constraints
470  for (const auto& it : parameterConstraints)
471  {
472  // Do we already have that param in the paramInfo set?
473  if (paramInfos.find(it.first) == paramInfos.end())
474  // No? Create it.
475  paramInfos[it.first] = ParamDocEntry();
476 
477  ParamDocEntry& cached = paramInfos[it.first];
478  cached.required = it.second.required;
479  cached.typeIsForced = it.second.constrainType;
480  cached.type = DataTypeToString(it.second.requiredType);
481 
482  // Build default-value string
483  std::stringstream vec2str_ss;
484  for (const std::string& s : it.second.defaultValue)
485  {
486  vec2str_ss << '\'' << s << '\'';
487 
488  // Add a space if we are not at the last entry
489  if ((void*)&s != (void*)&it.second.defaultValue.back())
490  vec2str_ss << " ";
491  }
492  cached.defaultVal = vec2str_ss.str();
493 
494 
495  // Build incompatibilities string
496  vec2str_ss.str("");
497  for (const std::string& s : it.second.incompatibleParameters)
498  {
499  vec2str_ss << s;
500 
501  // Add a comma-space if we are not at the last entry
502  if ((void*)&s != (void*)&it.second.incompatibleParameters.back())
503  vec2str_ss << ", ";
504  }
505  cached.incompatibilities = vec2str_ss.str();
506  }
507 
508  // Now generate the documentation body
509  if (paramInfos.size() > 0)
510  {
511  ss << std::endl
512  << "==== AVAILABLE PARAMETERS ===="
513  << std::endl << std::endl;
514 
515  std::size_t counter = 0;
516  for (const auto& it : paramInfos)
517  {
518  const ParamDocEntry& pde = it.second;
519 
520  // Put name
521  ss << it.first << " ";
522 
523  // Put abbreviation
524  if (pde.abbreviation.length() > 0)
525  ss << pde.abbreviation << " ";
526 
527  // Put type
528  if (pde.typeIsForced)
529  ss << pde.type << " ";
530 
531  // Put default value
532  if (pde.defaultVal.length() > 0)
533  ss << "default=[" << pde.defaultVal << "] ";
534 
535  // Put incompatibilities
536  if (pde.incompatibilities.length() > 0)
537  ss << "incompatibilities=[" << pde.incompatibilities << "] ";
538 
539  // Put required tag, but only if no default value
540  if ((pde.required) && (pde.defaultVal.length() == 0))
541  ss << "[[REQUIRED]] ";
542 
543  // Put brief description
544  if (pde.description.length() > 0)
545  ss << pde.description;
546 
547  // Omit linebreaks when we're on the last element
548  if (counter < paramInfos.size()-1)
549  ss << std::endl << std::endl;
550 
551  counter++;
552  }
553  }
554 
555  return ss.str();
556 }

◆ GetAbbreviation()

const std::string & CmdArgsInterface::GetAbbreviation ( const std::string &  abbrev) const

Will return the long form of an abbreviation (like –force for -f)
Returns "" if no match is found.

Definition at line 638 of file CmdArgsInterface.cpp.

639 {
640  if (!HasAbbreviation(abbrev))
642 
643  return parameterAbreviations.find(abbrev)->second;
644 }

◆ GetBriefDescription()

const std::string & CmdArgsInterface::GetBriefDescription ( )

Returns the brief description of the application to be automatically added to the documentation.

Definition at line 385 of file CmdArgsInterface.cpp.

386 {
387  return briefDescription;
388 }

◆ GetCatchHelp()

bool CmdArgsInterface::GetCatchHelp ( ) const

Retruns whether the CmdArgsInterface should automatically catch the –help parameter, print the parameter documentation to stdout, and exit or not.

Definition at line 374 of file CmdArgsInterface.cpp.

375 {
376  return catchHelp;
377 }

◆ GetConstraint()

ParamConstraint CmdArgsInterface::GetConstraint ( const std::string &  parameter) const

Will return the constraint information for a specific parameter.

Definition at line 607 of file CmdArgsInterface.cpp.

608 {
609  return parameterConstraints.find(parameter)->second;
610 }

◆ GetCrashOnFail()

bool CmdArgsInterface::GetCrashOnFail ( ) const

Gets whether the application crashes on an exception whilst parsing, and prints to stderr.

Definition at line 363 of file CmdArgsInterface.cpp.

364 {
365  return crashOnFail;
366 }

◆ GetDescription()

const std::string & Hazelnp::CmdArgsInterface::GetDescription ( const std::string &  parameter) const

Will return a short description for a parameter, if it exists.


Empty string if it does not exist.

Definition at line 396 of file CmdArgsInterface.cpp.

397 {
398  // Do we already have a description for this parameter?
399  if (!HasDescription(parameter))
400  // No? Then return ""
402 
403  // We do? Then return it
404  return parameterDescriptions.find(parameter)->second;
405 }

◆ GetExecutableName()

const std::string & CmdArgsInterface::GetExecutableName ( ) const

Will return argv[0], the name of the executable.

Definition at line 618 of file CmdArgsInterface.cpp.

619 {
620  return executableName;
621 }

◆ HasAbbreviation()

bool CmdArgsInterface::HasAbbreviation ( const std::string &  abbrev) const

Will check wether or not an abbreviation is registered.

Definition at line 646 of file CmdArgsInterface.cpp.

647 {
648  return parameterAbreviations.find(abbrev) != parameterAbreviations.end();
649 }

◆ HasDescription()

bool CmdArgsInterface::HasDescription ( const std::string &  parameter) const

Returns whether or not a given parameter has a registered description.

Definition at line 407 of file CmdArgsInterface.cpp.

408 {
409  return parameterDescriptions.find(parameter) != parameterDescriptions.end();
410 }

◆ HasParam()

bool CmdArgsInterface::HasParam ( const std::string &  key) const

Will check wether a parameter exists given a key, or not.

Definition at line 199 of file CmdArgsInterface.cpp.

200 {
201  return parameters.find(key) != parameters.end();
202 }

◆ operator[]()

const Value & CmdArgsInterface::operator[] ( const std::string &  key) const

Will return the value given a key.

Definition at line 623 of file CmdArgsInterface.cpp.

624 {
625  // Throw exception if param is unknown
626  if (!HasParam(key))
628 
629  return *parameters.find(key)->second->GetValue();
630 }

◆ Parse()

void CmdArgsInterface::Parse ( const int  argc,
const char *const *  argv 
)

Will parse command line arguments.

Definition at line 36 of file CmdArgsInterface.cpp.

37 {
38  try
39  {
40  // Populate raw arguments
41  PopulateRawArgs(argc, argv);
42 
43  // Expand abbreviations
44  ExpandAbbreviations();
45 
46  executableName = std::string(rawArgs[0]);
47 
48  // Read and parse all parameters
49  std::size_t i = 1;
50  while (i < rawArgs.size())
51  {
52  if ((rawArgs[i].length() > 2) && (rawArgs[i].substr(0, 2) == "--"))
53  {
54  Parameter* param = nullptr;
55  i = ParseNextParameter(i, param);
56 
57  parameters.insert(std::pair<std::string, Parameter*>(param->Key(), param));
58  }
59  else
60  i++;
61  }
62 
63  // Apply constraints such as default values, and required parameters.
64  // Types have already been enforced.
65  // Dont apply constraints when we are just printind the param docs
66  if ((!catchHelp) || (!HasParam("--help")))
67  ApplyConstraints();
68  }
70  {
71  if (crashOnFail)
72  {
73  std::cout << GenerateDocumentation() << std::endl << std::endl;
74  std::cerr << "Parameter error: " << exc.What() << std::endl;
75  quick_exit(-1000);
76  }
77  else
78  throw exc; // yeet
79  }
80  catch (const HazelnuppConstraintMissingValue& exc)
81  {
82  if (crashOnFail)
83  {
84  std::cout << GenerateDocumentation() << std::endl << std::endl;
85  std::cerr << "Parameter error: " << exc.What() << std::endl;
86  quick_exit(-1001);
87  }
88  else
89  throw exc; // yeet
90  }
91  catch (const HazelnuppConstraintTypeMissmatch& exc)
92  {
93  if (crashOnFail)
94  {
95  std::cout << GenerateDocumentation() << std::endl << std::endl;
96  std::cerr << "Parameter error: " << exc.What() << std::endl;
97  quick_exit(-1002);
98  }
99  else
100  throw exc; // yeet
101  }
102  catch (const HazelnuppConstraintException& exc)
103  {
104  if (crashOnFail)
105  {
106  std::cout << GenerateDocumentation() << std::endl << std::endl;
107  std::cerr << "Parameter error: " << exc.What() << std::endl;
108  quick_exit(-1003);
109  }
110  else
111  throw exc; // yeet
112  }
113  catch (const HazelnuppException& exc)
114  {
115  if (crashOnFail)
116  {
117  std::cout << GenerateDocumentation() << std::endl << std::endl;
118  std::cerr << "Parameter error: " << exc.What() << std::endl;
119  quick_exit(-1004);
120  }
121  else
122  throw exc; // yeet
123  }
124 
125  // Catch --help parameter
126  if ((catchHelp) && (HasParam("--help")))
127  {
128  std::cout << GenerateDocumentation() << std::endl;
129  quick_exit(0);
130  }
131 
132  return;
133 }

◆ RegisterAbbreviation()

void CmdArgsInterface::RegisterAbbreviation ( const std::string &  abbrev,
const std::string &  target 
)

Will register an abbreviation (like -f for –force)

Definition at line 632 of file CmdArgsInterface.cpp.

633 {
634  parameterAbreviations.insert(std::pair<std::string, std::string>(abbrev, target));
635  return;
636 }

◆ RegisterConstraint()

void CmdArgsInterface::RegisterConstraint ( const std::string &  key,
const ParamConstraint constraint 
)

Will register a constraint for a parameter.

IMPORTANT: Any parameter can only have ONE constraint. Applying a new one will overwrite the old one! Construct the ParamConstraint struct yourself to combine Require, TypeSafety and Incompatibilities! You can also use the ParamConstraint constructor!

Definition at line 663 of file CmdArgsInterface.cpp.

664 {
665  // Magic syntax, wooo
666  (parameterConstraints[key] = constraint).key = key;
667  return;
668 }

◆ RegisterDescription()

void Hazelnp::CmdArgsInterface::RegisterDescription ( const std::string &  parameter,
const std::string &  description 
)

Willl register a short description for a parameter.


Will overwrite existing descriptions for that parameter.

Definition at line 390 of file CmdArgsInterface.cpp.

391 {
392  parameterDescriptions[parameter] = description;
393  return;
394 }

◆ SetBriefDescription()

void CmdArgsInterface::SetBriefDescription ( const std::string &  description)

Sets a brief description of the application to be automatically added to the documentation.

Definition at line 379 of file CmdArgsInterface.cpp.

380 {
381  briefDescription = description;
382  return;
383 }

◆ SetCatchHelp()

void CmdArgsInterface::SetCatchHelp ( bool  catchHelp)

Sets whether the CmdArgsInterface should automatically catch the –help parameter, print the parameter documentation to stdout, and exit or not.

Definition at line 368 of file CmdArgsInterface.cpp.

369 {
370  this->catchHelp = catchHelp;
371  return;
372 }

◆ SetCrashOnFail()

void CmdArgsInterface::SetCrashOnFail ( bool  crashOnFail)

Sets whether to crash the application, and print to stderr, when an exception is raised whilst parsing, or not.

Definition at line 676 of file CmdArgsInterface.cpp.

677 {
678  this->crashOnFail = crashOnFail;
679  return;
680 }

The documentation for this class was generated from the following files:
Hazelnp::HazelnuppConstraintIncompatibleParameters
Gets thrown when a parameter constrained to be incompatible with other parameters gets supplied along...
Definition: HazelnuppException.h:101
Hazelnp::CmdArgsInterface::HasAbbreviation
bool HasAbbreviation(const std::string &abbrev) const
Will check wether or not an abbreviation is registered.
Definition: CmdArgsInterface.cpp:646
Hazelnp::HazelnuppInvalidKeyException
Gets thrown when an non-existent key gets dereferenced.
Definition: HazelnuppException.h:29
Hazelnp::HazelnuppException::What
const std::string & What() const
Will return an error message.
Definition: HazelnuppException.h:18
Hazelnp::HazelnuppConstraintException
Gets thrown something bad happens because of parameter constraints.
Definition: HazelnuppException.h:47
Hazelnp::CmdArgsInterface::HasParam
bool HasParam(const std::string &key) const
Will check wether a parameter exists given a key, or not.
Definition: CmdArgsInterface.cpp:199
Hazelnp::Parameter
Definition: Parameter.h:8
Hazelnp::Placeholders::g_emptyString
static const std::string g_emptyString
The only purpose of this is to provide the ability to return an empty string as an error for std::str...
Definition: Placeholders.h:9
Hazelnp::CmdArgsInterface::HasDescription
bool HasDescription(const std::string &parameter) const
Returns whether or not a given parameter has a registered description.
Definition: CmdArgsInterface.cpp:407
Hazelnp::HazelnuppException
Generic hazelnupp exception.
Definition: HazelnuppException.h:11
Hazelnp::Parameter::Key
const std::string & Key() const
Will return the key of this parameter.
Definition: Parameter.cpp:21
Hazelnp::HazelnuppConstraintMissingValue
Gets thrown when a parameter constrained to be required is not provided, and has no default value set...
Definition: HazelnuppException.h:80
Hazelnp::HazelnuppConstraintTypeMissmatch
Gets thrown when a parameter is of a type that does not match the required type, and is not convertib...
Definition: HazelnuppException.h:56
Hazelnp::CmdArgsInterface::Parse
void Parse(const int argc, const char *const *argv)
Will parse command line arguments.
Definition: CmdArgsInterface.cpp:36
Hazelnp::CmdArgsInterface::GenerateDocumentation
std::string GenerateDocumentation() const
Will generate a text-based documentation suited to show the user, for example on –help.
Definition: CmdArgsInterface.cpp:425
Hazelnp::DataTypeToString
static std::string DataTypeToString(DATA_TYPE type)
Definition: DataType.h:17