Newer
Older
#pragma once
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <sys/stat.h>
#include "ErrorCodes.h"
typedef std::unordered_map<std::string, std::string> KeyValueMap;
typedef std::unordered_set<std::string> AcceptedKeys;
#define ACCEPTED_KEYS { "--input", "--bounds" }
class ParseCommandLine
{
private:
std::string _launchPath;
KeyValueMap _cmdLineMap;
std::vector<ErrorCodes> _errors;
std::vector<std::string> _errorMsgs;
bool directoryExists(const std::string& filepath)
{
size_t directoryIdx = filepath.find_last_of('/');
if (directoryIdx == std::string::npos)
directoryIdx = filepath.find_last_of('\\');
// Isnt a directory. Just a file name to be placed in current path
if (directoryIdx == std::string::npos)
return true;
struct stat sb;
if (stat(filepath.substr(0, directoryIdx).c_str(), &sb) == 0)
return true; // Valid path
else
return false; // directory not found
}
private:
static AcceptedKeys s_validKeys;
inline bool validKey(const std::string& key)
{
return s_validKeys.count(key);
}
public:
ParseCommandLine(int argc, char** argv)
{
_launchPath = argv[0];
for (int i = 1; i < argc; i += 2)
{
std::string key = argv[i];
if (validKey(key))
_cmdLineMap.emplace(key.substr(2), argv[i + 1]);
else
{
_errors.emplace_back(ErrorCodes::InvalidArgument);
_errorMsgs.emplace_back(key);
}
}
if (hasKey("input"))
{
if (!directoryExists(getValue("input")))
{
_errors.emplace_back(ErrorCodes::DirectoryNotFound);
_errorMsgs.emplace_back(getValue("input"));
}
}
}
inline const std::string& getValue(const std::string& key) const
{
return _cmdLineMap.at(key);
}
inline const bool hasKey(const std::string& key) const
{
if (_cmdLineMap.find(key) == _cmdLineMap.end())
return false;
return true;
}
const bool hasErrors() const { return _errors.size() > 0; }
void dumpErrors();
};