Files
Library/src/Configuration/Argparse.cpp
T

746 lines
26 KiB
C++

#include <Void/Configuration/Argparse.hpp>
#include <algorithm>
#include <cstdlib>
#include <map>
#include <sstream>
namespace Void::Argparse
{
namespace
{
// ANSI styling is on by default; NO_COLOR (any non-empty value) disables it.
[[nodiscard]] bool terminal_color_enabled() noexcept
{
const char* no_color = std::getenv("NO_COLOR");
return !(no_color != nullptr && *no_color != '\0');
}
[[nodiscard]] std::string paint(bool enabled, std::string_view code,
std::string_view text)
{
if (!enabled) {
return std::string{text};
}
return std::string{code} + std::string{text} + "\033[0m";
}
[[nodiscard]] std::size_t edit_distance(std::string_view lhs,
std::string_view rhs) noexcept
{
std::vector<std::size_t> previous(rhs.size() + 1);
std::vector<std::size_t> 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)}
{
}
Parser::~Parser() = default;
Parser::Parser(Parser&&) noexcept = default;
Parser& Parser::operator=(Parser&&) noexcept = default;
Parser& Parser::flag(std::string_view lng,
std::string_view sht,
std::string_view desc,
bool& 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;
}
Parser& Parser::option(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::optional<std::string>& out)
{
options_.push_back(OptionEntry{.lng = std::string{lng},
.sht = std::string{sht},
.desc = std::string{desc},
.out_opt = &out});
return *this;
}
Parser& Parser::option_many(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::vector<std::string>& out)
{
options_.push_back(OptionEntry{.lng = std::string{lng},
.sht = std::string{sht},
.desc = std::string{desc},
.out_many = &out});
return *this;
}
Parser& Parser::option_default(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::string& out,
std::string_view default_value)
{
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});
return *this;
}
Parser& Parser::option_checked(std::string_view lng,
std::string_view sht,
std::string_view desc,
std::optional<std::string>& out,
std::vector<std::string> 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<std::string> 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;
}
Parser& Parser::value_name(std::string_view lng, std::string_view name)
{
for (auto& option : options_) {
if (option.lng == lng) {
option.value_name = std::string{name};
}
}
return *this;
}
Parser& Parser::alias(std::string_view lng, std::string_view alias)
{
for (auto& flag : flags_) {
if (flag.lng == lng) {
flag.alias = std::string{alias};
}
}
for (auto& option : options_) {
if (option.lng == lng) {
option.alias = std::string{alias};
}
}
return *this;
}
Parser& Parser::hide(std::string_view lng)
{
for (auto& flag : flags_) {
if (flag.lng == lng) {
flag.hidden = true;
}
}
for (auto& option : options_) {
if (option.lng == lng) {
option.hidden = true;
}
}
return *this;
}
Parser& Parser::color(bool enabled) noexcept
{
m_color = enabled;
return *this;
}
Parser& Parser::positional(std::string_view name,
std::string_view desc,
std::string& 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<std::string> allowed)
{
positionals_.push_back(PosEntry{.name = std::string{name},
.desc = std::string{desc},
.out = &out,
.allowed = std::move(allowed)});
return *this;
}
Parser& Parser::positional_many(std::string_view name,
std::string_view desc,
std::vector<std::string>& out,
bool required)
{
positional_many_ = MultiPosEntry{
std::string{name}, std::string{desc}, &out, required};
return *this;
}
Parser& Parser::subcommand(std::string name,
std::string description,
std::function<void()> on_selected)
{
const std::string sub_prog =
program_.empty() ? name : (program_ + " " + name);
auto sub_parser = std::make_unique<Parser>(sub_prog, std::move(description));
Parser* raw = sub_parser.get();
subcommands_.push_back(SubcommandEntry{
.name = std::move(name),
.parser = std::move(sub_parser),
.on_selected = std::move(on_selected),
});
return *raw;
}
Parser& Parser::require_subcommand(bool required) noexcept
{
has_explicit_require_sub_ = true;
require_subcommand_ = required;
return *this;
}
ParseResult Parser::parse_detailed(int argc, const char* const* argv) const
{
const Parser* active = this;
std::size_t pos_idx = 0;
bool after_double_dash = false;
std::vector<std::string> matched_path;
std::vector<const std::function<void()>*> callbacks;
std::map<const Parser*, std::vector<std::string>> 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,
int& i,
bool& matched,
std::string& err) -> bool {
for (const auto& f : p->flags_) {
if (arg == f.lng || (!f.sht.empty() && arg == f.sht) ||
(!f.alias.empty() && arg == f.alias)) {
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<const FlagEntry*> 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;
}
}
for (const auto& opt : p->options_) {
std::string_view value;
bool found = false;
if (arg.size() > opt.lng.size() + 1 &&
arg.substr(0, opt.lng.size()) == opt.lng &&
arg[opt.lng.size()] == '=') {
value = arg.substr(opt.lng.size() + 1);
found = true;
} else if (arg == opt.lng ||
(!opt.sht.empty() && arg == opt.sht) ||
(!opt.alias.empty() && arg == opt.alias)) {
if (i + 1 >= argc) {
err = "option '" + std::string{arg} + "' requires a value";
return false;
}
value = argv[++i];
found = true;
}
if (found) {
const std::string val_str{value};
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;
}
}
matched = false;
return true;
};
for (int i = 1; i < argc; ++i) {
const std::string_view arg{argv[i]};
if (!after_double_dash) {
if (arg == "--") {
after_double_dash = true;
continue;
}
if (arg == "--help" || arg == "-h") {
return ParseResult{
.outcome = ParseOutcome::Help,
.message = active->help(),
.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;
if (!match_flag_or_opt(active, arg, i, matched, err)) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = std::move(err),
.matched_command_path = std::move(matched_path),
};
}
if (matched) {
continue;
}
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 = std::move(message),
.matched_command_path = std::move(matched_path),
};
}
if (pos_idx == 0 && !active->subcommands_.empty()) {
const SubcommandEntry* chosen = nullptr;
for (const auto& sub : active->subcommands_) {
if (sub.name == arg) {
chosen = &sub;
break;
}
}
if (chosen != nullptr) {
matched_path.push_back(chosen->name);
if (chosen->on_selected) {
callbacks.push_back(&chosen->on_selected);
}
active = chosen->parser.get();
pos_idx = 0;
continue;
}
if (active->positionals_.empty() &&
!active->positional_many_.has_value()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "unknown subcommand: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
}
}
if (pos_idx < active->positionals_.size()) {
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});
} else {
return ParseResult{
.outcome = ParseOutcome::Error,
.message =
"unexpected positional argument: " + std::string{arg},
.matched_command_path = std::move(matched_path),
};
}
}
// Environment fallback, required options and conflicts for every parser
// that was used (the parent and any selected subcommand).
{
std::vector<const Parser*> 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_
: true;
if (req) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing subcommand for '" + active->program_ + "'",
.matched_command_path = std::move(matched_path),
};
}
}
for (std::size_t j = pos_idx; j < active->positionals_.size(); ++j) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required argument: <" +
active->positionals_[j].name + ">",
.matched_command_path = std::move(matched_path),
};
}
if (active->positional_many_.has_value() &&
active->positional_many_->required &&
active->positional_many_->out != nullptr &&
active->positional_many_->out->empty()) {
return ParseResult{
.outcome = ParseOutcome::Error,
.message = "missing required arguments: <" +
active->positional_many_->name + ">",
.matched_command_path = std::move(matched_path),
};
}
for (const auto* cb : callbacks) {
(*cb)();
}
return ParseResult{
.outcome = ParseOutcome::Ok,
.message = {},
.matched_command_path = std::move(matched_path),
};
}
std::expected<void, std::string> Parser::parse(int argc,
const char* const* argv) const
{
auto res = parse_detailed(argc, argv);
if (!res.ok()) {
return std::unexpected{std::move(res.message)};
}
return {};
}
std::string Parser::help() const
{
const bool color = m_color && terminal_color_enabled();
const auto style = [color](std::string_view code, std::string_view text) {
return paint(color, code, text);
};
std::ostringstream os;
os << style("\033[1m", "Usage:") << " " << style("\033[1;36m", program_);
if (!subcommands_.empty()) {
os << " " << style("\033[33m", "<command>");
}
os << " " << style("\033[2m", "[OPTIONS]");
for (const auto& p : positionals_) {
os << " " << style("\033[33m", "<" + p.name + ">");
}
if (positional_many_.has_value()) {
os << (positional_many_->required ? " " : " ")
<< style("\033[33m",
(positional_many_->required ? "<" : "[") +
positional_many_->name +
(positional_many_->required ? "...>" : "...]"));
}
os << "\n";
if (!description_.empty()) os << "\n" << description_ << "\n";
if (!version_.empty()) {
os << "\n" << style("\033[2m", program_ + " " + version_) << "\n";
}
using Row = std::pair<std::string, std::string>;
auto section = [&](std::string_view title, std::vector<Row> rows) {
if (rows.empty()) return;
std::size_t width = 0;
for (const auto& [left, _] : rows) width = std::max(width, left.size());
width = std::min<std::size_t>(width, 30);
os << "\n" << style("\033[1;34m", std::string{title} + ":") << "\n";
for (const auto& [left, desc] : rows) {
os << " " << style("\033[36m", left);
if (!desc.empty()) {
if (left.size() >= width) {
os << "\n" << std::string(width + 4, ' ');
} else {
os << std::string(width - left.size() + 2, ' ');
}
os << style("\033[2m", desc);
}
os << "\n";
}
};
std::vector<Row> commands;
for (const auto& s : subcommands_) {
commands.emplace_back(s.name, s.parser->description_);
}
section("Commands", std::move(commands));
std::vector<Row> 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 (positional_many_.has_value()) {
arguments.emplace_back(
"<" + positional_many_->name + "...>",
positional_many_->desc);
}
section("Arguments", std::move(arguments));
std::vector<Row> flags;
for (const auto& f : flags_) {
if (f.hidden) continue;
std::string left = f.lng;
if (!f.sht.empty()) left += ", " + f.sht;
if (!f.alias.empty()) left += ", " + f.alias;
flags.emplace_back(std::move(left), f.desc);
}
section("Flags", std::move(flags));
std::vector<Row> options;
for (const auto& o : options_) {
if (o.hidden) continue;
std::string left = o.lng;
if (!o.sht.empty()) left += ", " + o.sht;
if (!o.alias.empty()) left += ", " + o.alias;
left += " <" + (o.value_name.empty() ? std::string{"value"}
: o.value_name) + ">";
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));
}
options.emplace_back("--help, -h", "Print help");
if (!version_.empty()) {
options.emplace_back("--version, -V", "Print version");
}
section("Options", std::move(options));
return os.str();
}
} // namespace Void::Argparse