-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patharghandler.hpp
66 lines (58 loc) · 1.83 KB
/
arghandler.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <string>
#include <algorithm>
#include <map>
class argshandler {
public:
argshandler(std::string argprefix, bool handlehelp) {
ArgPrefix_ = std::move(argprefix);
HandleHelp_ = handlehelp;
if (HandleHelp_)
AddKnownArg("h", "Shows this help");
}
// this is for auto help handling
void AddKnownArg(std::string name, std::string description) {
KnownArgs_[name] = std::move(description);
}
void HandleArgs(int argc, char* argv[]) {
std::string lastarg;
for (int i = 0; i < argc; i++) {
std::string arg(argv[i]);
if (arg.substr(0, ArgPrefix_.size()) == ArgPrefix_) {
lastarg = arg;
ErasePrefix(arg);
if (HandleHelp_ && arg == "h") {
DoHelp();
} else {
ReceivedArgs_.insert(std::pair<std::string, std::string>(arg, ""));
}
} else {
if (lastarg.find(ArgPrefix_) != std::string::npos) {
ErasePrefix(lastarg);
ReceivedArgs_[lastarg] = arg;
}
lastarg = arg;
}
}
}
std::string GetArg(std::string key) {
auto entry = ReceivedArgs_.find(key);
if (entry != ReceivedArgs_.end()) {
return entry->second;
} else {
return "";
}
}
private:
std::string ArgPrefix_;
bool HandleHelp_;
std::map<std::string, std::string> KnownArgs_;
std::map<std::string, std::string> ReceivedArgs_;
void DoHelp() {
for (auto&& entry : KnownArgs_) {
std::cout << ArgPrefix_ << entry.first << ": " << entry.second << "\n";
}
}
void ErasePrefix(std::string& EraseFrom) {
EraseFrom.erase(0, ArgPrefix_.size());
}
};