30void cmd_args::check_for_key(std::string
const key__)
const
34 s <<
"command line parameter --" << key__ <<
" was not specified";
35 throw std::runtime_error(s.str());
41 register_key(
"--help",
"print this help and exit");
44cmd_args::cmd_args(
int argn__,
char** argv__, std::initializer_list<std::pair<std::string, std::string>> keys__)
46 register_key(
"--help",
"print this help and exit");
47 for (
auto key : keys__) {
48 register_key(
"--" + key.first, key.second);
50 parse_args(argn__, argv__);
53void cmd_args::register_key(std::string
const key__, std::string
const description__)
55 key_desc_.push_back(std::pair<std::string, std::string>(key__, description__));
58 std::string key = key__.substr(2, key__.length());
60 if (key[key.length() - 1] ==
'=') {
61 key = key.substr(0, key.length() - 1);
67 s <<
"key (" << key <<
") is already registered";
68 throw std::runtime_error(s.str());
74void cmd_args::parse_args(
int argn__,
char** argv__)
76 for (
int i = 1; i < argn__; i++) {
77 std::string str(argv__[i]);
78 if (str.length() < 3 || str[0] !=
'-' || str[1] !=
'-') {
80 s <<
"wrong key: " << str;
81 throw std::runtime_error(s.str());
84 size_t k = str.find(
"=");
87 if (k != std::string::npos) {
88 key = str.substr(2, k - 2);
89 val = str.substr(k + 1, str.length());
91 key = str.substr(2, str.length());
96 s <<
"key " <<
key <<
" is not found";
97 throw std::runtime_error(s.str());
100 if (
known_keys_[key] == 0 && k != std::string::npos) {
101 throw std::runtime_error(
"this key must not have a value");
104 if (
known_keys_[key] == 1 && k == std::string::npos) {
105 throw std::runtime_error(
"this key must have a value");
108 if (
keys_.count(key) != 0) {
110 s <<
"key (" <<
key <<
") is already added";
111 throw std::runtime_error(s.str());
116 if (this->exist(
"help")) {
117 printf(
"Usage: %s [options]\n", argv__[0]);
123void cmd_args::print_help()
125 int max_key_width = 0;
126 for (
int i = 0; i < (int)
key_desc_.size(); i++) {
127 max_key_width = std::max(max_key_width, (
int)
key_desc_[i].first.length());
130 std::printf(
"Options:\n");
132 for (
int i = 0; i < (int)
key_desc_.size(); i++) {
133 std::printf(
" %s",
key_desc_[i].first.c_str());
134 int k = (int)
key_desc_[i].first.length();
136 for (
int j = 0; j < max_key_width - k + 1; j++) {
140 std::printf(
"%s\n",
key_desc_[i].second.c_str());
std::vector< std::pair< std::string, std::string > > key_desc_
Helper string for each key.
std::map< std::string, int > known_keys_
Mapping between a key and its kind (with or without value).
std::map< std::string, std::string > keys_
Key to value mapping.
Contains definition and implementation of cmd_args class.
@ key
the parser read a key of a value in an object
Namespace of the SIRIUS library.