From af8757080f0f588ca0ed99cb41cc538d09a0b16e Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Fri, 4 Dec 2026 00:44:10 +0300 Subject: [PATCH] Argparse: richer Clap-like CLI (version, counts, checked values, required/conflicts/env, combined shorts, typo hints, aligned help) --- include/Void/Configuration/Argparse.hpp | 54 ++- src/Configuration/Argparse.cpp | 425 +++++++++++++++++--- tests/standalone/Configuration/Argparse.cpp | 102 +++++ 3 files changed, 520 insertions(+), 61 deletions(-) diff --git a/include/Void/Configuration/Argparse.hpp b/include/Void/Configuration/Argparse.hpp index f01e936..57ffb55 100644 --- a/include/Void/Configuration/Argparse.hpp +++ b/include/Void/Configuration/Argparse.hpp @@ -17,6 +17,7 @@ namespace Void::Argparse enum class ParseOutcome : std::uint8_t { Ok, Help, + Version, Error, }; @@ -33,6 +34,10 @@ namespace Void::Argparse { return outcome == ParseOutcome::Help; } + [[nodiscard]] bool is_version() const noexcept + { + return outcome == ParseOutcome::Version; + } [[nodiscard]] bool is_error() const noexcept { return outcome == ParseOutcome::Error; @@ -72,6 +77,14 @@ namespace Void::Argparse std::string_view short_name, std::string_view description, bool& out); + // Add a repeatable flag counting occurrences (-vvv -> 3). + Parser& count_flag(std::string_view long_name, + std::string_view short_name, + std::string_view description, int& out); + + // Set the program version exposed as --version / -V. + Parser& version(std::string version); + // Add an option that takes a value. If not provided, out stays // nullopt. Parser& option(std::string_view long_name, @@ -93,10 +106,39 @@ namespace Void::Argparse std::string& out, std::string_view default_value = ""); + // Option restricted to a fixed set of values. + Parser& option_checked(std::string_view long_name, + std::string_view short_name, + std::string_view description, + std::optional& out, + std::vector allowed); + + Parser& option_default_checked( + std::string_view long_name, std::string_view short_name, + std::string_view description, std::string& out, + std::string_view default_value, + std::vector allowed); + + // Mark a previously added option as required. + Parser& require_option(std::string_view long_name); + + // Fallback to an environment variable when the option is absent. + Parser& env(std::string_view long_name, + std::string_view env_var); + + // Two options may not be used together. + Parser& conflicts(std::string_view first, std::string_view second); + // Add a required positional argument. Parser& positional(std::string_view name, std::string_view description, std::string& out); + // Positional restricted to a fixed set of values. + Parser& positional_checked(std::string_view name, + std::string_view description, + std::string& out, + std::vector allowed); + // Add a variadic trailing positional argument list. Parser& positional_many(std::string_view name, std::string_view description, @@ -129,17 +171,22 @@ namespace Void::Argparse struct FlagEntry { std::string lng, sht, desc; - bool* out; + bool* out{nullptr}; + int* count_out{nullptr}; }; struct OptionEntry { std::string lng, sht, desc, def; std::optional* out_opt{nullptr}; std::string* out_str{nullptr}; std::vector* out_many{nullptr}; + std::vector allowed{}; + bool required{false}; + std::string env_var{}; }; struct PosEntry { std::string name, desc; - std::string* out; + std::string* out{nullptr}; + std::vector allowed{}; }; struct MultiPosEntry { std::string name, desc; @@ -152,7 +199,8 @@ namespace Void::Argparse std::function on_selected; }; - std::string program_, description_; + std::string program_, description_, version_; + std::vector> conflicts_; std::vector flags_; std::vector options_; std::vector positionals_; diff --git a/src/Configuration/Argparse.cpp b/src/Configuration/Argparse.cpp index dabbf34..7da58d3 100644 --- a/src/Configuration/Argparse.cpp +++ b/src/Configuration/Argparse.cpp @@ -1,9 +1,34 @@ #include +#include +#include +#include #include namespace Void::Argparse { +namespace +{ +[[nodiscard]] std::size_t edit_distance(std::string_view lhs, + std::string_view rhs) noexcept +{ + std::vector previous(rhs.size() + 1); + std::vector current(rhs.size() + 1); + for (std::size_t j = 0; j <= rhs.size(); ++j) { + previous[j] = j; + } + for (std::size_t i = 1; i <= lhs.size(); ++i) { + current[0] = i; + for (std::size_t j = 1; j <= rhs.size(); ++j) { + const std::size_t cost = lhs[i - 1] == rhs[j - 1] ? 0 : 1; + current[j] = std::min({previous[j] + 1, current[j - 1] + 1, + previous[j - 1] + cost}); + } + previous.swap(current); + } + return previous[rhs.size()]; +} +} // namespace Parser::Parser(std::string program, std::string description) : program_{std::move(program)}, description_{std::move(description)} @@ -19,8 +44,28 @@ Parser& Parser::flag(std::string_view lng, std::string_view desc, bool& out) { - flags_.push_back( - {std::string{lng}, std::string{sht}, std::string{desc}, &out}); + flags_.push_back(FlagEntry{.lng = std::string{lng}, + .sht = std::string{sht}, + .desc = std::string{desc}, + .out = &out}); + return *this; +} + +Parser& Parser::count_flag(std::string_view lng, + std::string_view sht, + std::string_view desc, + int& out) +{ + flags_.push_back(FlagEntry{.lng = std::string{lng}, + .sht = std::string{sht}, + .desc = std::string{desc}, + .count_out = &out}); + return *this; +} + +Parser& Parser::version(std::string version) +{ + version_ = std::move(version); return *this; } @@ -29,8 +74,10 @@ Parser& Parser::option(std::string_view lng, std::string_view desc, std::optional& out) { - options_.push_back( - {std::string{lng}, std::string{sht}, std::string{desc}, {}, &out, nullptr, nullptr}); + options_.push_back(OptionEntry{.lng = std::string{lng}, + .sht = std::string{sht}, + .desc = std::string{desc}, + .out_opt = &out}); return *this; } @@ -39,8 +86,10 @@ Parser& Parser::option_many(std::string_view lng, std::string_view desc, std::vector& out) { - options_.push_back( - {std::string{lng}, std::string{sht}, std::string{desc}, {}, nullptr, nullptr, &out}); + options_.push_back(OptionEntry{.lng = std::string{lng}, + .sht = std::string{sht}, + .desc = std::string{desc}, + .out_many = &out}); return *this; } @@ -51,13 +100,68 @@ Parser& Parser::option_default(std::string_view lng, std::string_view default_value) { out = std::string{default_value}; - options_.push_back({std::string{lng}, - std::string{sht}, - std::string{desc}, - std::string{default_value}, - nullptr, - &out, - nullptr}); + options_.push_back(OptionEntry{.lng = std::string{lng}, + .sht = std::string{sht}, + .desc = std::string{desc}, + .def = std::string{default_value}, + .out_str = &out}); + return *this; +} + +Parser& Parser::option_checked(std::string_view lng, + std::string_view sht, + std::string_view desc, + std::optional& out, + std::vector allowed) +{ + options_.push_back(OptionEntry{.lng = std::string{lng}, + .sht = std::string{sht}, + .desc = std::string{desc}, + .out_opt = &out, + .allowed = std::move(allowed)}); + return *this; +} + +Parser& Parser::option_default_checked(std::string_view lng, + std::string_view sht, + std::string_view desc, + std::string& out, + std::string_view default_value, + std::vector allowed) +{ + out = std::string{default_value}; + options_.push_back(OptionEntry{.lng = std::string{lng}, + .sht = std::string{sht}, + .desc = std::string{desc}, + .def = std::string{default_value}, + .out_str = &out, + .allowed = std::move(allowed)}); + return *this; +} + +Parser& Parser::require_option(std::string_view lng) +{ + for (auto& option : options_) { + if (option.lng == lng) { + option.required = true; + } + } + return *this; +} + +Parser& Parser::env(std::string_view lng, std::string_view env_var) +{ + for (auto& option : options_) { + if (option.lng == lng) { + option.env_var = std::string{env_var}; + } + } + return *this; +} + +Parser& Parser::conflicts(std::string_view first, std::string_view second) +{ + conflicts_.emplace_back(std::string{first}, std::string{second}); return *this; } @@ -65,7 +169,20 @@ Parser& Parser::positional(std::string_view name, std::string_view desc, std::string& out) { - positionals_.push_back({std::string{name}, std::string{desc}, &out}); + positionals_.push_back( + PosEntry{.name = std::string{name}, .desc = std::string{desc}, .out = &out}); + return *this; +} + +Parser& Parser::positional_checked(std::string_view name, + std::string_view desc, + std::string& out, + std::vector allowed) +{ + positionals_.push_back(PosEntry{.name = std::string{name}, + .desc = std::string{desc}, + .out = &out, + .allowed = std::move(allowed)}); return *this; } @@ -109,6 +226,16 @@ ParseResult Parser::parse_detailed(int argc, const char* const* argv) const bool after_double_dash = false; std::vector matched_path; std::vector*> callbacks; + std::map> provided; + + auto assign_option = [&](const Parser* p, const OptionEntry& opt, + std::string value) -> bool { + if (opt.out_opt) *opt.out_opt = value; + if (opt.out_str) *opt.out_str = value; + if (opt.out_many) opt.out_many->push_back(value); + provided[p].push_back(opt.lng); + return true; + }; auto match_flag_or_opt = [&](const Parser* p, std::string_view arg, @@ -117,7 +244,43 @@ ParseResult Parser::parse_detailed(int argc, const char* const* argv) const std::string& err) -> bool { for (const auto& f : p->flags_) { if (arg == f.lng || (!f.sht.empty() && arg == f.sht)) { - *f.out = true; + if (f.count_out) { + ++*f.count_out; + } else { + *f.out = true; + } + provided[p].push_back(f.lng); + matched = true; + return true; + } + } + // Combined short flags: -vv, -vf. + if (arg.size() > 2 && arg[0] == '-' && arg[1] != '-') { + std::vector hits; + bool all_flags = true; + for (std::size_t k = 1; k < arg.size(); ++k) { + const FlagEntry* hit = nullptr; + for (const auto& f : p->flags_) { + if (f.sht.size() == 2 && f.sht[1] == arg[k]) { + hit = &f; + break; + } + } + if (hit == nullptr) { + all_flags = false; + break; + } + hits.push_back(hit); + } + if (all_flags && !hits.empty()) { + for (const auto* f : hits) { + if (f->count_out) { + ++*f->count_out; + } else { + *f->out = true; + } + provided[p].push_back(f->lng); + } matched = true; return true; } @@ -141,9 +304,22 @@ ParseResult Parser::parse_detailed(int argc, const char* const* argv) const } if (found) { const std::string val_str{value}; - if (opt.out_opt) *opt.out_opt = val_str; - if (opt.out_str) *opt.out_str = val_str; - if (opt.out_many) opt.out_many->push_back(val_str); + if (!opt.allowed.empty() && + std::find(opt.allowed.begin(), opt.allowed.end(), + val_str) == opt.allowed.end()) { + err = "invalid value '" + val_str + "' for '" + opt.lng + + "'"; + if (!opt.allowed.empty()) { + err += " (possible values: "; + for (std::size_t k = 0; k < opt.allowed.size(); ++k) { + if (k != 0) err += ", "; + err += opt.allowed[k]; + } + err += ")"; + } + return false; + } + assign_option(p, opt, val_str); matched = true; return true; } @@ -168,6 +344,14 @@ ParseResult Parser::parse_detailed(int argc, const char* const* argv) const .matched_command_path = std::move(matched_path), }; } + if ((arg == "--version" || arg == "-V") && + !active->version_.empty()) { + return ParseResult{ + .outcome = ParseOutcome::Version, + .message = active->program_ + " " + active->version_, + .matched_command_path = std::move(matched_path), + }; + } bool matched = false; std::string err; @@ -183,9 +367,31 @@ ParseResult Parser::parse_detailed(int argc, const char* const* argv) const } if (arg.size() > 1 && arg[0] == '-') { + std::string message = "unknown option: " + std::string{arg}; + if (arg.size() > 2 && arg[1] == '-') { + std::string best; + std::size_t best_distance = 3; + for (const auto& f : active->flags_) { + const auto distance = edit_distance(arg, f.lng); + if (distance < best_distance) { + best_distance = distance; + best = f.lng; + } + } + for (const auto& o : active->options_) { + const auto distance = edit_distance(arg, o.lng); + if (distance < best_distance) { + best_distance = distance; + best = o.lng; + } + } + if (!best.empty()) { + message += "; did you mean '" + best + "'?"; + } + } return ParseResult{ .outcome = ParseOutcome::Error, - .message = "unknown option: " + std::string{arg}, + .message = std::move(message), .matched_command_path = std::move(matched_path), }; } @@ -219,7 +425,20 @@ ParseResult Parser::parse_detailed(int argc, const char* const* argv) const } if (pos_idx < active->positionals_.size()) { - *active->positionals_[pos_idx++].out = std::string{arg}; + auto& entry = active->positionals_[pos_idx]; + const std::string value{arg}; + if (!entry.allowed.empty() && + std::find(entry.allowed.begin(), entry.allowed.end(), value) == + entry.allowed.end()) { + return ParseResult{ + .outcome = ParseOutcome::Error, + .message = "invalid value '" + value + "' for <" + + entry.name + ">", + .matched_command_path = std::move(matched_path), + }; + } + *entry.out = value; + ++pos_idx; } else if (active->positional_many_.has_value() && active->positional_many_->out != nullptr) { active->positional_many_->out->push_back(std::string{arg}); @@ -233,6 +452,61 @@ ParseResult Parser::parse_detailed(int argc, const char* const* argv) const } } + // Environment fallback, required options and conflicts for every parser + // that was used (the parent and any selected subcommand). + { + std::vector parsers; + for (const auto& [parser, _] : provided) { + parsers.push_back(parser); + } + if (std::find(parsers.begin(), parsers.end(), active) == + parsers.end()) { + parsers.push_back(active); + } + for (const Parser* parser : parsers) { + auto used = provided[parser]; + for (const auto& opt : parser->options_) { + if (opt.env_var.empty() || + std::find(used.begin(), used.end(), opt.lng) != + used.end()) { + continue; + } + if (const char* value = std::getenv(opt.env_var.c_str()); + value != nullptr) { + if (opt.out_opt) *opt.out_opt = value; + if (opt.out_str) *opt.out_str = value; + used.push_back(opt.lng); + provided[parser].push_back(opt.lng); + } + } + for (const auto& opt : parser->options_) { + if (opt.required && + std::find(used.begin(), used.end(), opt.lng) == + used.end()) { + return ParseResult{ + .outcome = ParseOutcome::Error, + .message = "missing required option: " + opt.lng, + .matched_command_path = std::move(matched_path), + }; + } + } + for (const auto& [first, second] : parser->conflicts_) { + const bool has_first = + std::find(used.begin(), used.end(), first) != used.end(); + const bool has_second = + std::find(used.begin(), used.end(), second) != used.end(); + if (has_first && has_second) { + return ParseResult{ + .outcome = ParseOutcome::Error, + .message = "options '" + first + "' and '" + second + + "' cannot be used together", + .matched_command_path = std::move(matched_path), + }; + } + } + } + } + if (!active->subcommands_.empty()) { const bool req = active->has_explicit_require_sub_ ? active->require_subcommand_ @@ -292,15 +566,10 @@ std::string Parser::help() const { std::ostringstream os; os << "Usage: " << program_; - for (const auto& f : flags_) os << " [" << f.lng << "]"; - for (const auto& o : options_) { - const std::string_view dn = - std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0); - os << " [" << o.lng << " <" << dn << ">]"; - } if (!subcommands_.empty()) { os << " "; } + os << " [OPTIONS]"; for (const auto& p : positionals_) os << " <" << p.name << ">"; if (positional_many_.has_value()) { os << (positional_many_->required ? " <" : " [") @@ -309,48 +578,88 @@ std::string Parser::help() const } os << "\n"; if (!description_.empty()) os << "\n" << description_ << "\n"; + if (!version_.empty()) os << "\n" << program_ << " " << version_ << "\n"; - if (!subcommands_.empty()) { - os << "\nCommands:\n"; - for (const auto& s : subcommands_) { - os << " " << s.name; - if (!s.parser->description_.empty()) { - os << " " << s.parser->description_; + using Row = std::pair; + auto section = [&](std::string_view title, std::vector rows) { + if (rows.empty()) return; + std::size_t width = 0; + for (const auto& [left, _] : rows) width = std::max(width, left.size()); + width = std::min(width, 30); + os << "\n" << title << ":\n"; + for (const auto& [left, desc] : rows) { + os << " " << left; + if (!desc.empty()) { + if (left.size() >= width) { + os << "\n" << std::string(width + 4, ' '); + } else { + os << std::string(width - left.size() + 2, ' '); + } + os << desc; } os << "\n"; } + }; + + std::vector commands; + for (const auto& s : subcommands_) { + commands.emplace_back(s.name, s.parser->description_); } - if (!positionals_.empty() || positional_many_.has_value()) { - os << "\nArguments:\n"; - for (const auto& p : positionals_) - os << " <" << p.name << "> " << p.desc << "\n"; - if (positional_many_.has_value()) { - os << " <" << positional_many_->name << "...> " - << positional_many_->desc << "\n"; + section("Commands", std::move(commands)); + + std::vector arguments; + for (const auto& p : positionals_) { + std::string desc = p.desc; + if (!p.allowed.empty()) { + desc += " [possible values: "; + for (std::size_t i = 0; i < p.allowed.size(); ++i) { + if (i != 0) desc += ", "; + desc += p.allowed[i]; + } + desc += "]"; } + arguments.emplace_back("<" + p.name + ">", std::move(desc)); } - if (!flags_.empty()) { - os << "\nFlags:\n"; - for (const auto& f : flags_) { - os << " " << f.lng; - if (!f.sht.empty()) os << ", " << f.sht; - os << " " << f.desc << "\n"; + if (positional_many_.has_value()) { + arguments.emplace_back( + "<" + positional_many_->name + "...>", + positional_many_->desc); + } + section("Arguments", std::move(arguments)); + + std::vector flags; + for (const auto& f : flags_) { + std::string left = f.lng; + if (!f.sht.empty()) left += ", " + f.sht; + flags.emplace_back(std::move(left), f.desc); + } + section("Flags", std::move(flags)); + + std::vector options; + for (const auto& o : options_) { + std::string left = o.lng; + if (!o.sht.empty()) left += ", " + o.sht; + left += " "; + std::string desc = o.desc; + if (o.required) desc += " [required]"; + if (!o.def.empty()) desc += " [default: " + o.def + "]"; + if (!o.env_var.empty()) desc += " [env: " + o.env_var + "]"; + if (o.out_many != nullptr) desc += " [repeatable]"; + if (!o.allowed.empty()) { + desc += " [possible values: "; + for (std::size_t i = 0; i < o.allowed.size(); ++i) { + if (i != 0) desc += ", "; + desc += o.allowed[i]; + } + desc += "]"; } + options.emplace_back(std::move(left), std::move(desc)); } - if (!options_.empty()) { - os << "\nOptions:\n"; - for (const auto& o : options_) { - const std::string_view dname = - std::string_view{o.lng}.substr(o.lng.size() > 2 ? 2 : 0); - os << " " << o.lng; - if (!o.sht.empty()) os << ", " << o.sht; - os << " <" << dname << ">"; - if (!o.def.empty()) os << " (default: " << o.def << ")"; - if (o.out_many != nullptr) os << " (repeatable)"; - os << " " << o.desc << "\n"; - } + options.emplace_back("--help, -h", "Print help"); + if (!version_.empty()) { + options.emplace_back("--version, -V", "Print version"); } - os << " --help, -h show this help\n"; + section("Options", std::move(options)); return os.str(); } diff --git a/tests/standalone/Configuration/Argparse.cpp b/tests/standalone/Configuration/Argparse.cpp index 18ebe4a..2f9e04c 100644 --- a/tests/standalone/Configuration/Argparse.cpp +++ b/tests/standalone/Configuration/Argparse.cpp @@ -273,3 +273,105 @@ Void::Testing::Test argparse_subcommands_option_many_and_distinct_outcomes() Void::Testing::expect(!build_selected); } } + +Void::Testing::Test argparse_rich_features() +{ + using namespace Void::Argparse; + + bool verbose = false; + int level = 0; + std::optional mode; + std::string format = "text"; + std::optional required_opt; + + Parser parser{"tool", "rich parser"}; + parser.version("1.2.3"); + parser.flag("--verbose", "-v", "verbose output", verbose) + .count_flag("--level", "-l", "verbosity level", level) + .option_checked("--mode", "-m", "mode", mode, {"fast", "slow"}) + .option_default_checked("--format", "-f", "format", format, "text", + {"text", "json"}) + .option("--required", "-r", "required option", required_opt) + .require_option("--required") + .env("--required", "TOOL_REQUIRED") + .conflicts("--verbose", "--mode"); + + // Checked/default values (avoid the --verbose/--mode conflict here). + const char* argv[] = {"tool", "-ll", "--mode=fast", "--required", "x", + "--format", "json"}; + auto result = parser.parse_detailed(7, argv); + Void::Testing::expect(result.ok()); + Void::Testing::expect(!verbose); + Void::Testing::expect_eq(level, 2); + Void::Testing::require(mode.has_value()); + Void::Testing::expect_eq(*mode, std::string{"fast"}); + Void::Testing::expect_eq(format, std::string{"json"}); + Void::Testing::require(required_opt.has_value()); + Void::Testing::expect_eq(*required_opt, std::string{"x"}); + + // Combined short flags on an independent parser. + { + bool alpha = false; + int beta = 0; + Parser combined{"c"}; + combined.flag("--alpha", "-a", "alpha", alpha) + .count_flag("--beta", "-b", "beta", beta); + const char* combined_argv[] = {"c", "-abb"}; + auto combined_result = combined.parse_detailed(2, combined_argv); + Void::Testing::expect(combined_result.ok()); + Void::Testing::expect(alpha); + Void::Testing::expect_eq(beta, 2); + } + + // Version outcome. + const char* version_argv[] = {"tool", "--version"}; + auto version = parser.parse_detailed(2, version_argv); + Void::Testing::expect(version.is_version()); + Void::Testing::expect_eq(version.message, std::string{"tool 1.2.3"}); + + // Typo suggestion. + const char* typo_argv[] = {"tool", "--verbos"}; + auto typo = parser.parse_detailed(2, typo_argv); + Void::Testing::expect(typo.is_error()); + Void::Testing::expect(typo.message.find("did you mean '--verbose'") != + std::string::npos); + + // Invalid checked value. + const char* bad_value_argv[] = {"tool", "--mode", "medium", "--required", + "x"}; + auto bad_value = parser.parse_detailed(4, bad_value_argv); + Void::Testing::expect(bad_value.is_error()); + Void::Testing::expect(bad_value.message.find("possible values") != + std::string::npos); + + // Missing required option. + const char* missing_argv[] = {"tool"}; + auto missing = parser.parse_detailed(1, missing_argv); + Void::Testing::expect(missing.is_error()); + Void::Testing::expect(missing.message.find("--required") != + std::string::npos); + + // Environment fallback. + ::setenv("TOOL_REQUIRED", "from-env", 1); + required_opt.reset(); + auto from_env = parser.parse_detailed(1, missing_argv); + Void::Testing::expect(from_env.ok()); + Void::Testing::require(required_opt.has_value()); + Void::Testing::expect_eq(*required_opt, std::string{"from-env"}); + ::unsetenv("TOOL_REQUIRED"); + + // Conflicting options. + const char* conflict_argv[] = {"tool", "--verbose", "--mode", "slow", + "--required", "x"}; + auto conflict = parser.parse_detailed(6, conflict_argv); + Void::Testing::expect(conflict.is_error()); + Void::Testing::expect(conflict.message.find("cannot be used together") != + std::string::npos); + + // Aligned help lists the new metadata. + const std::string help = parser.help(); + Void::Testing::expect(help.find("Usage:") != std::string::npos); + Void::Testing::expect(help.find("--mode, -m") != std::string::npos); + Void::Testing::expect(help.find("possible values") != std::string::npos); + Void::Testing::expect(help.find("--version, -V") != std::string::npos); +}