File size: 2,717 Bytes
68888be | 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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | // Command-line parser: positionals, --key value, --flag.
#pragma once
#include <cstdint>
#include <cstdlib>
#include <map>
#include <string>
#include <vector>
#include "common/base.h"
namespace hk {
struct Args {
std::vector<std::string> pos;
std::map<std::string, std::string> kv;
static Args parse(int argc, char** argv, int first) {
Args a;
for (int i = first; i < argc; ++i) {
std::string s = argv[i];
if (s.size() > 2 && s[0] == '-' && s[1] == '-') {
std::string key = s.substr(2);
size_t eq = key.find('=');
if (eq != std::string::npos) {
a.kv[key.substr(0, eq)] = key.substr(eq + 1);
} else if (i + 1 < argc && !(argv[i + 1][0] == '-' && argv[i + 1][1] == '-')) {
a.kv[key] = argv[++i];
} else {
a.kv[key] = "true";
}
} else {
a.pos.push_back(s);
}
}
return a;
}
bool has(const std::string& k) const { return kv.count(k) != 0; }
bool flag(const std::string& k) const {
auto it = kv.find(k);
return it != kv.end() && it->second != "false" && it->second != "0";
}
std::string str(const std::string& k, const std::string& def = "") const {
auto it = kv.find(k);
return it == kv.end() ? def : it->second;
}
int64_t num(const std::string& k, int64_t def) const {
auto it = kv.find(k);
return it == kv.end() ? def : (int64_t)strtoll(it->second.c_str(), nullptr, 10);
}
double real(const std::string& k, double def) const {
auto it = kv.find(k);
return it == kv.end() ? def : strtod(it->second.c_str(), nullptr);
}
const std::string& need_pos(size_t i, const char* what) const {
HK_CHECK(i < pos.size(), "missing argument: %s", what);
return pos[i];
}
// unknown options are an error, so a typo is not silently ignored
void allow(std::initializer_list<const char*> known) const {
for (const auto& e : kv) {
bool ok = false;
for (const char* k : known) ok = ok || e.first == k;
HK_CHECK(ok, "unknown option --%s", e.first.c_str());
}
}
};
// "1,2,3" -> {1, 2, 3}
inline std::vector<int32_t> parse_int_list(const std::string& s) {
std::vector<int32_t> v;
size_t i = 0;
while (i < s.size()) {
size_t j = s.find_first_of(", \n\t\r", i);
if (j == std::string::npos) j = s.size();
if (j > i) v.push_back((int32_t)strtol(s.substr(i, j - i).c_str(), nullptr, 10));
i = j + 1;
}
return v;
}
} // namespace hk
|