# Leonetienne/Hazelnupp: Hazelnupp/Hazelnupp.cpp Source File

Hazelnupp.cpp
Go to the documentation of this file.
#include "Hazelnupp.h"
#include "VoidValue.h"
#include "IntValue.h"
#include "FloatValue.h"
#include "StringValue.h"
#include "ListValue.h"
#include "HazelnuppException.h"
#include "Placeholders.h"
#include "StringTools.h"
#include <iostream>
#include <cstdlib>
using namespace Hazelnp;
Hazelnupp::Hazelnupp()
{
return;
}
Hazelnupp::Hazelnupp(const int argc, const char* const* argv)
{
Parse(argc, argv);
return;
}
Hazelnupp::~Hazelnupp()
{
for (auto& it : parameters)
delete it.second;
parameters.clear();
return;
}
void Hazelnupp::Parse(const int argc, const char* const* argv)
{
try
{
// Populate raw arguments
PopulateRawArgs(argc, argv);
// Expand abbreviations
ExpandAbbreviations();
executableName = std::string(rawArgs[0]);
std::size_t i = 1;
while (i < rawArgs.size())
{
if ((rawArgs[i].length() > 2) && (rawArgs[i].substr(0, 2) == "--"))
{
Parameter* param = nullptr;
i = ParseNextParameter(i, param);
parameters.insert(std::pair<std::string, Parameter*>(param->Key(), param));
}
else
i++;
}
// Apply constraints such as default values, and required parameters.
// Types have already been enforced.
// Dont apply constraints when we are just printind the param docs
if ((!catchHelp) || (!HasParam("--help")))
ApplyConstraints();
}
catch (const HazelnuppConstraintTypeMissmatch& exc)
{
if (crashOnFail)
{
std::cout << GenerateDocumentation() << std::endl << std::endl;
std::cerr << "Parameter error: " << exc.What() << std::endl;
quick_exit(-1009);
}
else
throw exc; // yeet
}
catch (const HazelnuppConstraintMissingValue& exc)
{
if (crashOnFail)
{
std::cout << GenerateDocumentation() << std::endl << std::endl;
std::cerr << "Parameter error: " << exc.What() << std::endl;
quick_exit(-1010);
}
else
throw exc; // yeet
}
// Catch --help parameter
if ((catchHelp) && (HasParam("--help")))
{
std::cout << GenerateDocumentation() << std::endl;
quick_exit(0);
}
return;
}
std::size_t Hazelnupp::ParseNextParameter(const std::size_t parIndex, Parameter*& out_Par)
{
std::size_t i = parIndex;
const std::string key = rawArgs[parIndex];
std::vector<std::string> values;
// Get values
for (i++; i < rawArgs.size(); i++)
// If not another parameter
if ((rawArgs[i].length() < 2) || (rawArgs[i].substr(0, 2) != "--"))
values.emplace_back(rawArgs[i]);
else
{
break;
}
// Fetch constraint info
const ParamConstraint* pcn = GetConstraintForKey(key);
Value* parsedVal = ParseValue(values, pcn);
if (parsedVal != nullptr)
{
out_Par = new Parameter(key, parsedVal);
delete parsedVal;
parsedVal = nullptr;
}
else
throw std::runtime_error("Unable to parse parameter!");
return i;
}
void Hazelnupp::PopulateRawArgs(const int argc, const char* const* argv)
{
rawArgs.clear();
rawArgs.reserve(argc);
for (int i = 0; i < argc; i++)
rawArgs.emplace_back(std::string(argv[i]));
return;
}
void Hazelnupp::ExpandAbbreviations()
{
// Abort if no abbreviations
if (parameterAbreviations.size() == 0)
return;
for (std::string& arg : rawArgs)
{
// Is arg registered as an abbreviation?
auto abbr = parameterAbreviations.find(arg);
if (abbr != parameterAbreviations.end())
{
// Yes: replace arg with the long form
arg = abbr->second;
}
}
return;
}
bool Hazelnupp::HasParam(const std::string& key) const
{
return parameters.find(key) != parameters.end();
}
Value* Hazelnupp::ParseValue(const std::vector<std::string>& values, const ParamConstraint* constraint)
{
// This is the raw (unconverted) data type the user provided
DATA_TYPE rawInputType;
// Constraint values
const bool constrainType = (constraint != nullptr) && (constraint->constrainType);
// Void-type
if (values.size() == 0)
{
rawInputType = DATA_TYPE::VOID;
// Is a list forced via a constraint? If yes, return an empty list
if ((constrainType) &&
(constraint->requiredType == DATA_TYPE::LIST))
return new ListValue();
// Is a string forced via a constraint? If yes, return an empty string
else if ((constrainType) &&
(constraint->requiredType == DATA_TYPE::STRING))
return new StringValue("");
// Is an int or float forced via constraint? If yes, throw an exception
else if ((constrainType) &&
((constraint->requiredType == DATA_TYPE::INT) ||
(constraint->requiredType == DATA_TYPE::FLOAT)))
throw HazelnuppConstraintTypeMissmatch(
constraint->key,
constraint->requiredType,
rawInputType,
GetDescription(constraint->key)
);
// Else, just return the void type
return new VoidValue;
}
// Force void type by constraint
else if ((constrainType) &&
(constraint->requiredType == DATA_TYPE::VOID))
{
return new VoidValue;
}
// List-type
else if (values.size() > 1)
{
rawInputType = DATA_TYPE::LIST;
// Should the type be something other than list?
if ((constrainType) &&
(constraint->requiredType != DATA_TYPE::LIST))
{
throw HazelnuppConstraintTypeMissmatch(
constraint->key,
constraint->requiredType,
rawInputType,
GetDescription(constraint->key)
);
}
ListValue* newList = new ListValue();
for (const std::string& val : values)
{
Value* tmp = ParseValue({ val });
newList->AddValue(tmp);
delete tmp;
}
return newList;
}
// Now we're only dealing with a single value
const std::string& val = values[0];
// String
if (!StringTools::IsNumeric(val, true))
{
rawInputType = DATA_TYPE::STRING;
// Is the type not supposed to be a string?
// void and list are already sorted out
if ((constrainType) &&
(constraint->requiredType != DATA_TYPE::STRING))
{
// We can only force a list-value from here
if (constraint->requiredType == DATA_TYPE::LIST)
{
ListValue* list = new ListValue();
Value* tmp = ParseValue({ val });
list->AddValue(tmp);
delete tmp;
tmp = nullptr;
return list;
}
// Else it is not possible to convert to a numeric
else
throw HazelnuppConstraintTypeMissmatch(
constraint->key,
constraint->requiredType,
rawInputType,
GetDescription(constraint->key)
);
}
return new StringValue(val);
}
// In this case we have a numeric value.
// We should still produce a string if requested
if ((constrainType) &&
(constraint->requiredType == DATA_TYPE::STRING))
return new StringValue(val);
// Numeric
bool isInt;
long double num;
if (StringTools::ParseNumber(val, isInt, num))
{
rawInputType = isInt ? DATA_TYPE::INT : DATA_TYPE::FLOAT;
// Is the type constrained?
// (only int and float left)
if (constrainType)
{
// Must it be an integer?
if (constraint->requiredType == DATA_TYPE::INT)
return new IntValue((long long int)num);
// Must it be a floating point?
else if (constraint->requiredType == DATA_TYPE::FLOAT)
return new FloatValue(num);
// Else it must be a List
else
{
ListValue* list = new ListValue();
Value* tmp = ParseValue({ val });
list->AddValue(tmp);
delete tmp;
tmp = nullptr;
return list;
}
}
// Type is not constrained
else
{
// Integer
if (isInt)
return new IntValue((long long int)num);
// Double
return new FloatValue(num);
}
}
// Failed
return nullptr;
}
bool Hazelnupp::GetCrashOnFail() const
{
return crashOnFail;
}
void Hazelnupp::SetCatchHelp(bool catchHelp)
{
this->catchHelp = catchHelp;
return;
}
bool Hazelnupp::GetCatchHelp() const
{
return catchHelp;
}
void Hazelnupp::SetBriefDescription(const std::string& description)
{
briefDescription = description;
return;
}
const std::string& Hazelnupp::GetBriefDescription()
{
return briefDescription;
}
void Hazelnp::Hazelnupp::RegisterDescription(const std::string& parameter, const std::string& description)
{
parameterDescriptions[parameter] = description;
return;
}
const std::string& Hazelnp::Hazelnupp::GetDescription(const std::string& parameter) const
{
// Do we already have a description for this parameter?
if (!HasDescription(parameter))
// No? Then return ""
return Placeholders::g_emptyString;
// We do? Then return it
return parameterDescriptions.find(parameter)->second;
}
bool Hazelnupp::HasDescription(const std::string& parameter) const
{
return parameterDescriptions.find(parameter) != parameterDescriptions.end();
}
void Hazelnupp::ClearDescription(const std::string& parameter)
{
// This will just do nothing if the entry does not exist
parameterDescriptions.erase(parameter);
return;
}
void Hazelnp::Hazelnupp::ClearDescriptions()
{
parameterDescriptions.clear();
return;
}
std::string Hazelnupp::GenerateDocumentation() const
{
std::stringstream ss;
// Add brief, if available
if (briefDescription.length() > 0)
ss << briefDescription << std::endl;
// Collect parameter information
struct ParamDocEntry
{
std::string abbreviation;
std::string description;
std::string type;
bool required = false;
bool typeIsForced = false;
std::string defaultVal;
};
std::unordered_map<std::string, ParamDocEntry> paramInfos;
// Collect descriptions
for (const auto& it : parameterDescriptions)
{
// Do we already have that param in the paramInfo set?
if (paramInfos.find(it.first) == paramInfos.end())
// No? Create it.
paramInfos[it.first] = ParamDocEntry();
paramInfos[it.first].description = it.second;
}
// Collect abbreviations
// first value is abbreviation, second is long form
for (const auto& it : parameterAbreviations)
{
// Do we already have that param in the paramInfo set?
if (paramInfos.find(it.second) == paramInfos.end())
// No? Create it.
paramInfos[it.second] = ParamDocEntry();
paramInfos[it.second].abbreviation = it.first;
}
// Collect constraints
for (const auto& it : parameterConstraints)
{
// Do we already have that param in the paramInfo set?
if (paramInfos.find(it.first) == paramInfos.end())
// No? Create it.
paramInfos[it.first] = ParamDocEntry();
ParamDocEntry& cached = paramInfos[it.first];
cached.required = it.second.required;
cached.typeIsForced = it.second.constrainType;
cached.type = DataTypeToString(it.second.requiredType);
std::stringstream defaultValueSs;
for (const std::string& s : it.second.defaultValue)
{
defaultValueSs << '\'' << s << '\'';
// Add a space if we are not at the last entry
if ((void*)&s != (void*)&it.second.defaultValue.back())
defaultValueSs << " ";
}
cached.defaultVal = defaultValueSs.str();
}
// Now generate the documentatino body
if (paramInfos.size() > 0)
{
ss << std::endl
<< "==== AVAILABLE PARAMETERS ===="
<< std::endl << std::endl;
std::size_t counter = 0;
for (const auto& it : paramInfos)
{
const ParamDocEntry& pde = it.second;
// Put name
ss << it.first << " ";
// Put abbreviation
if (pde.abbreviation.length() > 0)
ss << pde.abbreviation << " ";
// Put type
if (pde.typeIsForced)
ss << pde.type << " ";
// Put default value
if (pde.defaultVal.length() > 0)
ss << "default=[" << pde.defaultVal << "] ";
// Put required tag, but only if no default value
if ((pde.required) && (pde.defaultVal.length() == 0))
ss << "[[REQUIRED]] ";
// Put brief description
if (pde.description.length() > 0)
ss << pde.description;
// Omit linebreaks when we're on the last element
if (counter < paramInfos.size()-1)
ss << std::endl << std::endl;
counter++;
}
}
return ss.str();
}
void Hazelnupp::ApplyConstraints()
{
// Enforce required parameters / default values
for (const auto& pc : parameterConstraints)
// Parameter in question is not supplied
if (!HasParam(pc.second.key))
{
// Do we have a default value?
if (pc.second.defaultValue.size() > 0)
{
// Then create it now, by its default value
Value* tmp = ParseValue(pc.second.defaultValue, &pc.second);
parameters.insert(std::pair<std::string, Parameter*>(
pc.second.key,
new Parameter(pc.second.key, tmp)
));
delete tmp;
tmp = nullptr;
}
// So we do not have a default value...
else
{
// Is it important to have the missing parameter?
if (pc.second.required)
// Throw an error message then
throw HazelnuppConstraintMissingValue(
pc.second.key,
GetDescription(pc.second.key)
);
}
}
return;
}
ParamConstraint Hazelnupp::GetConstraint(const std::string& parameter) const
{
return parameterConstraints.find(parameter)->second;
}
void Hazelnupp::ClearConstraint(const std::string& parameter)
{
parameterConstraints.erase(parameter);
return;
}
const std::string& Hazelnupp::GetExecutableName() const
{
return executableName;
}
const Value& Hazelnupp::operator[](const std::string& key) const
{
// Throw exception if param is unknown
if (!HasParam(key))
throw HazelnuppInvalidKeyException();
return *parameters.find(key)->second->GetValue();
}
void Hazelnupp::RegisterAbbreviation(const std::string& abbrev, const std::string& target)
{
parameterAbreviations.insert(std::pair<std::string, std::string>(abbrev, target));
return;
}
const std::string& Hazelnupp::GetAbbreviation(const std::string& abbrev) const
{
if (!HasAbbreviation(abbrev))
return Placeholders::g_emptyString;
return parameterAbreviations.find(abbrev)->second;
}
bool Hazelnupp::HasAbbreviation(const std::string& abbrev) const
{
return parameterAbreviations.find(abbrev) != parameterAbreviations.end();
}
void Hazelnupp::ClearAbbreviation(const std::string& abbrevation)
{
parameterAbreviations.erase(abbrevation);
return;
}
void Hazelnupp::ClearAbbreviations()
{
parameterAbreviations.clear();
return;
}
void Hazelnupp::RegisterConstraint(const std::string& key, const ParamConstraint& constraint)
{
// Magic syntax, wooo
(parameterConstraints[key] = constraint).key = key;
return;
}
void Hazelnupp::ClearConstraints()
{
parameterConstraints.clear();
return;
}
void Hazelnupp::SetCrashOnFail(bool crashOnFail)
{
this->crashOnFail = crashOnFail;
return;
}
const ParamConstraint* Hazelnupp::GetConstraintForKey(const std::string& key) const
{
const auto constraint = parameterConstraints.find(key);
if (constraint == parameterConstraints.end())
return nullptr;
return &constraint->second;
}
HazelnuppException.h
Hazelnp
Definition: DataType.h:4
Hazelnp::IntValue
Specializations for integer values (uses long long int)
Definition: IntValue.h:8
Hazelnp::StringTools::IsNumeric
static bool IsNumeric(const std::string &str, const bool allowDecimalPoint=false)
Will return true if the given string consists only of digits (including signage)
Definition: StringTools.cpp:56
Hazelnp::StringTools::ParseNumber
static bool ParseNumber(const std::string &str, bool &out_isInt, long double &out_number)
Will convert the number in str to a number.
Definition: StringTools.cpp:82
Hazelnp::Hazelnupp::GetBriefDescription
const std::string & GetBriefDescription()
Returns the brief description of the application to be automatically added to the documentation.
Definition: Hazelnupp.cpp:351
Hazelnp::Hazelnupp::ClearConstraints
void ClearConstraints()
Will delete all constraints.
Definition: Hazelnupp.cpp:605
Hazelnp::HazelnuppInvalidKeyException
Gets thrown when an non-existent key gets dereferenced.
Definition: HazelnuppException.h:29
Hazelnp::Hazelnupp::GetExecutableName
const std::string & GetExecutableName() const
Will return argv[0], the name of the executable.
Definition: Hazelnupp.cpp:553
Hazelnp::Hazelnupp::GenerateDocumentation
std::string GenerateDocumentation() const
Will generate a text-based documentation suited to show the user, for example on –help.
Definition: Hazelnupp.cpp:391
Hazelnp::Hazelnupp::GetConstraint
ParamConstraint GetConstraint(const std::string &parameter) const
Will return the constraint information for a specific parameter.
Definition: Hazelnupp.cpp:542
Hazelnp::Hazelnupp::~Hazelnupp
~Hazelnupp()
Definition: Hazelnupp.cpp:26
Hazelnp::Hazelnupp::operator[]
const Value & operator[](const std::string &key) const
Will return the value given a key.
Definition: Hazelnupp.cpp:558
StringValue.h
Hazelnp::HazelnuppException::What
const std::string & What() const
Will return an error message.
Definition: HazelnuppException.h:18
IntValue.h
Hazelnp::Hazelnupp::Hazelnupp
Hazelnupp()
Definition: Hazelnupp.cpp:15
Placeholders.h
Hazelnp::Hazelnupp::ClearAbbreviations
void ClearAbbreviations()
Will delete all abbreviations.
Definition: Hazelnupp.cpp:592
Hazelnp::DATA_TYPE::VOID
@ VOID
Hazelnp::FloatValue
Specializations for floating point values (uses long double)
Definition: FloatValue.h:9
Hazelnp::ParamConstraint::requiredType
DATA_TYPE requiredType
Constrain the parameter to this value. Requires constrainType to be set to true.
Definition: ParamConstraint.h:51
Hazelnp::Hazelnupp::SetBriefDescription
void SetBriefDescription(const std::string &description)
Sets a brief description of the application to be automatically added to the documentation.
Definition: Hazelnupp.cpp:345
Hazelnp::Value
Abstract class for values.
Definition: Value.h:10
Hazelnp::Hazelnupp::GetCrashOnFail
bool GetCrashOnFail() const
Gets whether the application crashes on an exception whilst parsing, and prints to stderr.
Definition: Hazelnupp.cpp:329
Hazelnp::Hazelnupp::HasDescription
bool HasDescription(const std::string &parameter) const
Returns whether or not a given parameter has a registered description.
Definition: Hazelnupp.cpp:373
Hazelnp::Hazelnupp::SetCatchHelp
void SetCatchHelp(bool catchHelp)
Sets whether the Hazelnupp should automatically catch the –help parameter, print the parameter docume...
Definition: Hazelnupp.cpp:334
Hazelnp::Hazelnupp::GetCatchHelp
bool GetCatchHelp() const
Retruns whether the Hazelnupp should automatically catch the –help parameter, print the parameter doc...
Definition: Hazelnupp.cpp:340
Hazelnp::DATA_TYPE::LIST
@ LIST
Hazelnp::Parameter
Definition: Parameter.h:8
Hazelnp::ParamConstraint
Definition: ParamConstraint.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::Hazelnupp::HasParam
bool HasParam(const std::string &key) const
Will check wether a parameter exists given a key, or not.
Definition: Hazelnupp.cpp:165
Hazelnp::Hazelnupp::Parse
void Parse(const int argc, const char *const *argv)
Will parse command line arguments.
Definition: Hazelnupp.cpp:36
ListValue.h
Hazelnp::ParamConstraint::constrainType
bool constrainType
Should this parameter be forced to be of a certain type? Remember to set constrainTo to the wanted ...
Definition: ParamConstraint.h:48
Hazelnp::Hazelnupp::ClearDescription
void ClearDescription(const std::string &parameter)
Will delete the description of a parameter if it exists.
Definition: Hazelnupp.cpp:378
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::Hazelnupp::RegisterAbbreviation
void RegisterAbbreviation(const std::string &abbrev, const std::string &target)
Will register an abbreviation (like -f for –force)
Definition: Hazelnupp.cpp:567
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
VoidValue.h
Hazelnp::Hazelnupp::GetAbbreviation
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.
Definition: Hazelnupp.cpp:573
Hazelnp::Hazelnupp::ClearDescriptions
void ClearDescriptions()
Will delete all parameter descriptions.
Definition: Hazelnupp.cpp:385
Hazelnupp.h
Hazelnp::ListValue::AddValue
void AddValue(const Value *value)
Will add this value to the list.
Definition: ListValue.cpp:33
Hazelnp::Hazelnupp::RegisterConstraint
void RegisterConstraint(const std::string &key, const ParamConstraint &constraint)
Will register a constraint for a parameter.
Definition: Hazelnupp.cpp:598
Hazelnp::VoidValue
Specializations for void values.
Definition: VoidValue.h:8
Hazelnp::Hazelnupp::GetDescription
const std::string & GetDescription(const std::string &parameter) const
Will return a short description for a parameter, if it exists.
Definition: Hazelnupp.cpp:362
Hazelnp::DATA_TYPE::FLOAT
@ FLOAT
Hazelnp::DATA_TYPE::INT
@ INT
Hazelnp::Hazelnupp::ClearConstraint
void ClearConstraint(const std::string &parameter)
Will the constraint of a specific parameter.
Definition: Hazelnupp.cpp:547
FloatValue.h
Hazelnp::DATA_TYPE
DATA_TYPE
The different data types a paramater can be.
Definition: DataType.h:8
Hazelnp::Hazelnupp::HasAbbreviation
bool HasAbbreviation(const std::string &abbrev) const
Will check wether or not an abbreviation is registered.
Definition: Hazelnupp.cpp:581
Hazelnp::DATA_TYPE::STRING
@ STRING
Hazelnp::Hazelnupp::SetCrashOnFail
void SetCrashOnFail(bool crashOnFail)
Sets whether to crash the application, and print to stderr, when an exception is raised whilst parsin...
Definition: Hazelnupp.cpp:611
Hazelnp::Hazelnupp::RegisterDescription
void RegisterDescription(const std::string &parameter, const std::string &description)
Willl register a short description for a parameter.
Definition: Hazelnupp.cpp:356
Hazelnp::DataTypeToString
static std::string DataTypeToString(DATA_TYPE type)
Definition: DataType.h:17
Hazelnp::Hazelnupp::ClearAbbreviation
void ClearAbbreviation(const std::string &abbrevation)
Will delete the abbreviation for a given parameter.
Definition: Hazelnupp.cpp:586
Hazelnp::ListValue
Specializations for list values (uses std::vector<Value*>)
Definition: ListValue.h:9
Hazelnp::StringValue
Specializations for string values (uses std::string)
Definition: StringValue.h:9
StringTools.h