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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
| #pragma once
#include <algorithm> #include <functional> #include <iomanip> #include <iostream> #include <optional> #include <regex> #include <set> #include <sstream> #include <stdexcept> #include <string> #include <unordered_map> #include <utility> #include <vector>
namespace cmd_parser_detail {
template <typename T> concept Supported = std::disjunction_v<std::is_same<T, std::string>, std::is_same<T, bool>, std::is_same<T, char>, std::is_same<T, int>, std::is_same<T, double>, std::is_same<T, size_t>>;
template <Supported T> static constexpr const char *get_type_id() { if constexpr (std::is_same_v<T, std::string>) { return "string"; } else if constexpr (std::is_same_v<T, bool>) { return "bool"; } else if constexpr (std::is_same_v<T, char>) { return "char"; } else if constexpr (std::is_same_v<T, int>) { return "int"; } else if constexpr (std::is_same_v<T, double>) { return "double"; } else if constexpr (std::is_same_v<T, std::size_t>) { return "size_t"; } else { return "???"; } }
template <Supported T> static std::string get_default_value_str(const T &var) { std::ostringstream ss; ss << var; return ss.str(); }
template <Supported T> static std::string get_usage_str(const std::string &name) { std::ostringstream ss; ss << name << "=" << get_type_id<T>(); return ss.str(); }
template <typename T> static std::optional<T> case_string_to(std::string value) { if constexpr (std::is_same_v<T, std::string>) { return value; } else if constexpr (std::is_same_v<T, bool>) { std::ranges::transform(value, value.begin(), ::tolower); return (value == "true" || value == "yes" || value == "ok" || value == "on" || value == "1"); } else { T result; std::stringstream ss(value);
if (!(ss >> result && ss.eof())) { return std::nullopt; }
return result; } }
inline bool is_valid_full_name(const std::string &name) { static const std::regex full_name_pattern(R"(^--[A-Za-z0-9_]{1,10}$)"); return std::regex_match(name, full_name_pattern); }
inline bool is_valid_short_name(const std::string &name) { static const std::regex short_name_pattern(R"(^-[A-Za-z0-9]?$)"); return name.empty() || std::regex_match(name, short_name_pattern); }
}
class CmdParser { public: class Item { public: Item(std::string first, std::string second) : full_name(std::move(first)), short_name(std::move(second)) { validate(); }
Item(std::string name) : full_name(std::move(name)) { validate(); }
Item(const char *name) : full_name(name) { validate(); }
std::string to_str() const { return short_name.empty() ? full_name : (short_name + ", " + full_name); }
std::string full_name; std::string short_name;
bool operator==(const Item &other) const noexcept { return full_name == other.full_name && short_name == other.short_name; }
struct Hash { std::size_t operator()(const Item &item) const noexcept { std::size_t h1 = std::hash<std::string>{}(item.full_name); std::size_t h2 = std::hash<std::string>{}(item.short_name); return h1 ^ (h2 << 1); } };
private: void validate() { if (!short_name.empty() && !cmd_parser_detail::is_valid_full_name(full_name)) { std::swap(full_name, short_name); }
if (!cmd_parser_detail::is_valid_full_name(full_name)) { throw std::invalid_argument("Invalid full name: " + full_name); } if (!cmd_parser_detail::is_valid_short_name(short_name)) { throw std::invalid_argument("Invalid short name: " + short_name); } } };
CmdParser &add_flag(const Item &flag, const std::string &desc, std::function<void()> caller) { check_and_update_names(flag);
m_flags.insert({flag, FlagInfo{.caller = caller, .desc = desc, .usage_str = flag.full_name}}); return *this; }
CmdParser &add_flag(const Item &flag, const std::string &desc) { return add_flag(flag, desc, []() {}); }
template <cmd_parser_detail::Supported T> CmdParser &add_option(const Item &option, const std::string &desc, bool required, T default_value, std::function<bool(T)> checker) { check_and_update_names(option);
auto checker_wrapper = [checker](const std::string &value_str) { auto parsed = cmd_parser_detail::case_string_to<T>(value_str); if (!parsed.has_value()) { return false; } return checker(parsed.value()); };
std::string type_id = cmd_parser_detail::get_type_id<T>(); std::string usage_str = cmd_parser_detail::get_usage_str<T>(option.full_name); std::string default_value_str = cmd_parser_detail::get_default_value_str<T>(default_value);
m_options.insert({option, OptionInfo{ .checker = checker_wrapper, .desc = desc, .usage_str = usage_str, .type_id = type_id, .default_value_str = default_value_str, .required = required, .value_list = {default_value_str}, }});
return *this; }
template <cmd_parser_detail::Supported T> CmdParser &add_option(const Item &option, const std::string &desc, bool required, std::function<bool(T)> checker) { check_and_update_names(option);
auto checker_wrapper = [checker](const std::string &value_str) { auto parsed = cmd_parser_detail::case_string_to<T>(value_str); if (!parsed.has_value()) { return false; } return checker(parsed.value()); };
std::string usage_str = cmd_parser_detail::get_usage_str<T>(option.full_name); std::string type_id = cmd_parser_detail::get_type_id<T>();
m_options.insert({option, OptionInfo{ .checker = checker_wrapper, .desc = desc, .usage_str = usage_str, .type_id = type_id, .default_value_str = "", .required = required, .value_list = {}, }});
return *this; }
template <cmd_parser_detail::Supported T> CmdParser &add_option(const Item &option, const std::string &desc, bool required, T default_value) { return add_option<T>(option, desc, required, default_value, [](T) { return true; }); }
template <cmd_parser_detail::Supported T> CmdParser &add_option(const Item &option, const std::string &desc, bool required) { return add_option<T>(option, desc, required, [](T) { return true; }); }
std::optional<size_t> get_count(const std::string &name) const { if (const auto *p_flag = get_flag_via_name(name)) { return m_flags.at(*p_flag).count; }
return std::nullopt; }
template <cmd_parser_detail::Supported T> std::optional<T> get_option(const std::string &name) { if (const auto *p_option = get_option_via_name(name)) { std::string cur_type_id = cmd_parser_detail::get_type_id<T>(); if (m_options.at(*p_option).type_id == cur_type_id) { auto &value_list = m_options.at(*p_option).value_list;
if (value_list.empty()) { return std::nullopt; }
auto last_value_str = value_list.back(); return cmd_parser_detail::case_string_to<T>(last_value_str); } } return std::nullopt; }
template <cmd_parser_detail::Supported T> std::optional<std::vector<T>> get_option_all(const std::string &name) { if (const auto *p_option = get_option_via_name(name)) { std::string cur_type_id = cmd_parser_detail::get_type_id<T>(); if (m_options.at(*p_option).type_id == cur_type_id) { auto &value_list = m_options.at(*p_option).value_list;
if (value_list.empty()) { return std::vector<T>{}; }
std::vector<T> result; for (auto &value_str : value_list) { auto parsed = cmd_parser_detail::case_string_to<T>(value_str); if (!parsed.has_value()) { return std::nullopt; } result.push_back(parsed.value()); }
return result; } } return std::nullopt; }
bool parse(int argc, char *argv[]) { if (m_program_name.empty()) { set_program_name(argv[0]); }
if (!(m_unique_names.contains("--help") || m_unique_names.contains("-h"))) { add_flag({"--help", "-h"}, "print help message", [this]() { print_usage(); exit(0); }); }
std::vector<std::string> args = expand_args(argc, argv); return parse_detail(args); }
void parse_check(int argc, char *argv[]) { if (!parse(argc, argv)) { print_usage();
if (argc == 1) { exit(0); } exit(1); } }
void print_usage() const { std::cout << "usage: " << m_program_name << " "; for (const auto &[option, info] : m_options) { if (info.required) { std::cout << info.usage_str << " "; } } std::cout << "...\n";
std::vector<std::pair<std::string, std::string>> flag_descs; std::vector<std::pair<std::string, std::string>> option_descs; std::vector<std::pair<std::string, std::string>> required_option_descs;
size_t max_length = 0;
for (const auto &[option, info] : m_options) { std::string full_desc; if (!info.desc.empty()) { if (!(info.required || info.default_value_str.empty())) { full_desc = info.desc + " (" + info.type_id + " [=" + info.default_value_str + "])"; } else { full_desc = info.desc + " (" + info.type_id + ")"; } } else { full_desc = "(" + info.type_id + ")"; }
max_length = std::max(max_length, option.to_str().size());
if (info.required) { required_option_descs.emplace_back(option.to_str(), full_desc); } else { option_descs.emplace_back(option.to_str(), full_desc); } } for (const auto &[flag, info] : m_flags) { max_length = std::max(max_length, flag.to_str().size());
flag_descs.emplace_back(flag.to_str(), info.desc); }
max_length += 4;
if (!required_option_descs.empty()) { std::cout << " @required options:\n"; } for (const auto &[use_str, desc_str] : required_option_descs) { std::cout << " " << std::left << std::setw(static_cast<int>(max_length)) << use_str << desc_str << '\n'; }
if (!option_descs.empty()) { std::cout << " @options:\n"; } for (const auto &[use_str, desc_str] : option_descs) { std::cout << " " << std::left << std::setw(static_cast<int>(max_length)) << use_str << desc_str << '\n'; }
if (!option_descs.empty()) { std::cout << " @flags:\n"; } for (const auto &[use_str, desc_str] : flag_descs) { std::cout << " " << std::left << std::setw(static_cast<int>(max_length)) << use_str << desc_str << '\n'; } }
const std::vector<std::string> &get_rest() const { return m_rest; }
CmdParser &set_program_name(const std::string &program_name) { m_program_name = program_name; return *this; }
CmdParser &enable_strict_mode() { m_strict_mode = true; return *this; }
CmdParser &disable_strict_mode() { m_strict_mode = false; return *this; }
private: struct OptionInfo { const std::function<bool(const std::string &)> checker;
const std::string desc; const std::string usage_str; const std::string type_id; const std::string default_value_str; const bool required{false};
std::vector<std::string> value_list; };
struct FlagInfo { const std::function<void()> caller;
const std::string desc; const std::string usage_str;
size_t count{0}; };
std::unordered_map<Item, FlagInfo, Item::Hash> m_flags; std::unordered_map<Item, OptionInfo, Item::Hash> m_options; std::set<std::string> m_unique_names; std::vector<std::string> m_rest; std::string m_program_name; bool m_strict_mode{false};
std::vector<std::string> expand_args(int argc, char *argv[]) { std::vector<std::string> result; for (int i = 1; i < argc; ++i) { std::string arg = argv[i];
std::string name; std::string value; if (arg.find('=') != std::string::npos) { size_t equal_pos = arg.find('='); name = arg.substr(0, equal_pos); value = arg.substr(equal_pos + 1); } else { name = arg; }
if (get_option_via_name(name) != nullptr) { result.push_back(name); if (!value.empty()) { result.push_back(value); }
continue; }
if (get_flag_via_name(name) != nullptr && value.empty()) { result.push_back(name); continue; }
if (!m_strict_mode && value.empty()) { if (name.size() > 2 && name[0] == '-' && name[1] != '-') { std::vector<std::string> expand_short_names; bool expand_ok = true; for (size_t j = 1; j < name.size(); ++j) { auto short_name = "-" + std::string(1, name[j]); if (get_flag_via_name(short_name) != nullptr) { expand_short_names.push_back(short_name); } else { expand_ok = false; } }
if (expand_ok) { result.insert(result.end(), expand_short_names.begin(), expand_short_names.end()); continue; } }
if ((get_unique_option_prefix(name)) != nullptr) { const auto *p_matching_name = get_unique_option_prefix(name); value = name.substr(p_matching_name->size());
result.push_back(*p_matching_name); result.push_back(value); continue; } }
result.push_back(arg); }
return result; }
bool parse_detail(std::vector<std::string> args) noexcept { try { size_t arg_size = args.size(); for (size_t i = 0; i < arg_size; ++i) { const std::string& arg = args[i];
if (const auto *p_option = get_option_via_name(arg)) { if (i + 1 >= arg_size) throw std::runtime_error("Missing value for option: " + arg);
const std::string& value = args[++i];
if (m_options.at(*p_option).checker(value)) { m_options.at(*p_option).value_list.push_back(value); } else { std::string msg = "Failed to set option with value: " + p_option->to_str() + " = " + value; throw std::runtime_error(msg); } } else if (const auto *p_flag = get_flag_via_name(arg)) { m_flags.at(*p_flag).count++;
m_flags.at(*p_flag).caller(); } else { m_rest.push_back(arg); } }
for (const auto &[option, info] : m_options) { if (info.required && (info.value_list.empty())) { throw std::runtime_error("Missing required option: " + option.to_str()); } }
return true; } catch (const std::exception &e) { std::cerr << "CmdParser error: " << e.what() << '\n'; return false; } }
const Item *get_flag_via_name(const std::string &name) const { if (cmd_parser_detail::is_valid_full_name(name)) { for (const auto &[flag, _] : m_flags) { if (flag.full_name == name) { return &flag; } } } else if (cmd_parser_detail::is_valid_short_name(name)) { for (const auto &[flag, _] : m_flags) { if (flag.short_name == name) { return &flag; } } } return nullptr; }
const Item *get_option_via_name(const std::string &name) const { if (cmd_parser_detail::is_valid_full_name(name)) { for (const auto &[option, _] : m_options) { if (option.full_name == name) { return &option; } } } else if (cmd_parser_detail::is_valid_short_name(name)) { for (const auto &[option, _] : m_options) { if (option.short_name == name) { return &option; } } } return nullptr; }
void check_and_update_names(const Item &item) { if (m_unique_names.contains(item.full_name)) { std::cerr << "CmdParser error: " << item.full_name << " already exists."; exit(1); } else { m_unique_names.insert(item.full_name); }
if (!item.short_name.empty()) { if (m_unique_names.contains(item.short_name)) { std::cerr << "CmdParser error: " << item.short_name << " already exists."; exit(1); } else { m_unique_names.insert(item.short_name); } } }
const std::string *get_unique_option_prefix(const std::string &str) const { const std::string *match_prefix = nullptr; size_t cnt = 0; for (const auto &[option, _] : m_options) { if (str.find(option.full_name) == 0) { match_prefix = &(option.full_name); cnt += 1; }
if (option.short_name.empty()) continue;
if (str.find(option.short_name) == 0) { match_prefix = &(option.short_name); cnt += 1; } }
if (cnt == 1) { return match_prefix; }
return nullptr; } };
|