Impl arg parsing

This commit is contained in:
Stephen Seo 2021-05-10 14:32:47 +09:00
parent 8672efe385
commit aa49e41a80
3 changed files with 75 additions and 2 deletions

View file

@ -1,7 +1,67 @@
#include "argparse.hpp"
std::unordered_map<std::string, std::string> ArgParse::parseArgs(int argc, char **argv) {
#include <cstring>
#include <stdexcept>
std::unordered_map<std::string, std::string> ArgParse::parseArgs(
int argc,
char **argv,
const std::vector<std::string> &simpleArgs,
const std::vector<std::string> &pairedArgs) {
std::unordered_map<std::string, std::string> mapping;
--argc; ++argv;
std::string temp;
bool mappingFound;
while(argc > 0) {
mappingFound = false;
for(const auto &s : simpleArgs) {
if(s.size() == 1) {
temp = std::string("-") + s;
} else {
temp = std::string("--") + s;
}
if(std::strcmp(temp.c_str(), argv[0]) == 0) {
mapping.insert({s, ""});
mappingFound = true;
break;
}
}
if(mappingFound) {
--argc; ++argv;
continue;
}
for(const auto &s : pairedArgs) {
if(s.size() == 1) {
temp = std::string("-") + s;
} else {
temp = std::string("--") + s;
}
if(std::strncmp(temp.c_str(), argv[0], temp.size()) == 0) {
std::string arg;
if(argv[0][temp.size()] == '=') {
arg = argv[0] + temp.size() + 1;
} else {
if(argc > 1) {
--argc;
++argv;
arg = argv[0];
} else {
throw std::invalid_argument("Paired arg missing pair");
}
}
mapping.insert({s, arg});
mappingFound = true;
break;
}
}
if(!mappingFound) {
throw std::invalid_argument("Got invalid arg");
}
--argc; ++argv;
}
return mapping;
}

View file

@ -3,9 +3,14 @@
#include <string>
#include <unordered_map>
#include <vector>
namespace ArgParse {
std::unordered_map<std::string, std::string> parseArgs(int argc, char **argv);
std::unordered_map<std::string, std::string> parseArgs(
int argc,
char **argv,
const std::vector<std::string> &simpleArgs,
const std::vector<std::string> &pairedArgs);
} // namespace ArgParse
#endif

View file

@ -1,5 +1,13 @@
#include <iostream>
#include "argparse.hpp"
int main(int argc, char **argv) {
auto parsed = ArgParse::parseArgs(argc, argv, {"a", "b"}, {"apple"});
for(auto pair : parsed) {
std::cout << pair.first << ", " << pair.second << std::endl;
}
return 0;
}