460 lines
15 KiB
C++
460 lines
15 KiB
C++
#pragma once
|
|
|
|
#include <Void/Core/Meta.hpp>
|
|
|
|
#include <charconv>
|
|
#include <cstdint>
|
|
#include <expected>
|
|
#include <functional>
|
|
#include <memory>
|
|
#include <optional>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <vector>
|
|
|
|
namespace Void::Argparse
|
|
{
|
|
|
|
enum class ParseOutcome : std::uint8_t {
|
|
Ok,
|
|
Help,
|
|
Version,
|
|
Error,
|
|
};
|
|
|
|
struct ParseResult {
|
|
ParseOutcome outcome{ParseOutcome::Ok};
|
|
std::string message{};
|
|
std::vector<std::string> matched_command_path{};
|
|
|
|
[[nodiscard]] bool ok() const noexcept
|
|
{
|
|
return outcome == ParseOutcome::Ok;
|
|
}
|
|
[[nodiscard]] bool is_help() const noexcept
|
|
{
|
|
return outcome == ParseOutcome::Help;
|
|
}
|
|
[[nodiscard]] bool is_version() const noexcept
|
|
{
|
|
return outcome == ParseOutcome::Version;
|
|
}
|
|
[[nodiscard]] bool is_error() const noexcept
|
|
{
|
|
return outcome == ParseOutcome::Error;
|
|
}
|
|
};
|
|
|
|
// ── Parser
|
|
// ────────────────────────────────────────────────────────────────────
|
|
// Fluent command-line argument parser.
|
|
//
|
|
// Supports:
|
|
// --flag, -f boolean flag (default false, set to true by
|
|
// presence)
|
|
// --key=value option with value (= or space separator)
|
|
// --key value option with value
|
|
// option_many(...) repeatable option collecting all occurrences
|
|
// subcommand(...) nested subcommand parsers (e.g. "compdb use")
|
|
// positional args collected in declaration order
|
|
// --help / -h auto-generated help text (ParseOutcome::Help)
|
|
|
|
class Parser
|
|
{
|
|
public:
|
|
|
|
explicit Parser(std::string program, std::string description = {});
|
|
~Parser();
|
|
|
|
Parser(const Parser&) = delete;
|
|
Parser& operator=(const Parser&) = delete;
|
|
Parser(Parser&&) noexcept;
|
|
Parser& operator=(Parser&&) noexcept;
|
|
|
|
// Add a boolean flag.
|
|
// long_name: e.g. "--verbose" short_name: e.g. "-v" (short_name
|
|
// may be "")
|
|
Parser& flag(std::string_view long_name,
|
|
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,
|
|
std::string_view short_name,
|
|
std::string_view description,
|
|
std::optional<std::string>& out);
|
|
|
|
// Add a repeatable option collecting all occurrences into `out`.
|
|
Parser& option_many(std::string_view long_name,
|
|
std::string_view short_name,
|
|
std::string_view description,
|
|
std::vector<std::string>& out);
|
|
|
|
// Add an option with a default value. out is always set after
|
|
// parse().
|
|
Parser& option_default(std::string_view long_name,
|
|
std::string_view short_name,
|
|
std::string_view description,
|
|
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<std::string>& out,
|
|
std::vector<std::string> 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<std::string> 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);
|
|
|
|
// Customize the help placeholder for an option (default "value").
|
|
Parser& value_name(std::string_view long_name,
|
|
std::string_view name);
|
|
|
|
// Accept an extra long spelling for an option or flag.
|
|
Parser& alias(std::string_view long_name, std::string_view alias);
|
|
|
|
// Omit an option or flag from the generated help.
|
|
Parser& hide(std::string_view long_name);
|
|
|
|
// Enable or disable ANSI styling in help text (default: enabled,
|
|
// unless the NO_COLOR environment variable is set).
|
|
Parser& color(bool enabled) noexcept;
|
|
|
|
// 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<std::string> allowed);
|
|
|
|
// Add a variadic trailing positional argument list.
|
|
Parser& positional_many(std::string_view name,
|
|
std::string_view description,
|
|
std::vector<std::string>& out,
|
|
bool required = false);
|
|
|
|
// Register a nested subcommand and return a reference to its
|
|
// Parser. The returned reference remains valid for the lifetime of
|
|
// the parent Parser.
|
|
Parser& subcommand(std::string name, std::string description = {},
|
|
std::function<void()> on_selected = {});
|
|
|
|
// Control whether a parser with subcommands requires one to be
|
|
// selected (default: true when any subcommand is registered).
|
|
Parser& require_subcommand(bool required = true) noexcept;
|
|
|
|
// Parse argc/argv with explicit Ok / Help / Error classification.
|
|
[[nodiscard]] ParseResult
|
|
parse_detailed(int argc, const char* const* argv) const;
|
|
|
|
// Parse argc/argv. Returns error message (or help text) on
|
|
// non-Ok outcome for 1.x compatibility.
|
|
[[nodiscard]] std::expected<void, std::string>
|
|
parse(int argc, const char* const* argv) const;
|
|
|
|
// Returns formatted help text.
|
|
[[nodiscard]] std::string help() const;
|
|
|
|
private:
|
|
|
|
struct FlagEntry {
|
|
std::string lng, sht, desc, alias;
|
|
bool hidden{false};
|
|
bool* out{nullptr};
|
|
int* count_out{nullptr};
|
|
};
|
|
struct OptionEntry {
|
|
std::string lng, sht, desc, def;
|
|
std::string value_name{}, alias{};
|
|
bool hidden{false};
|
|
std::optional<std::string>* out_opt{nullptr};
|
|
std::string* out_str{nullptr};
|
|
std::vector<std::string>* out_many{nullptr};
|
|
std::vector<std::string> allowed{};
|
|
bool required{false};
|
|
std::string env_var{};
|
|
};
|
|
struct PosEntry {
|
|
std::string name, desc;
|
|
std::string* out{nullptr};
|
|
std::vector<std::string> allowed{};
|
|
};
|
|
struct MultiPosEntry {
|
|
std::string name, desc;
|
|
std::vector<std::string>* out{nullptr};
|
|
bool required{false};
|
|
};
|
|
struct SubcommandEntry {
|
|
std::string name;
|
|
std::unique_ptr<Parser> parser;
|
|
std::function<void()> on_selected;
|
|
};
|
|
|
|
std::string program_, description_, version_;
|
|
bool m_color{true};
|
|
std::vector<std::pair<std::string, std::string>> conflicts_;
|
|
std::vector<FlagEntry> flags_;
|
|
std::vector<OptionEntry> options_;
|
|
std::vector<PosEntry> positionals_;
|
|
std::optional<MultiPosEntry> positional_many_;
|
|
std::vector<SubcommandEntry> subcommands_;
|
|
bool has_explicit_require_sub_{false};
|
|
bool require_subcommand_{true};
|
|
};
|
|
|
|
// ── reflective options struct
|
|
// ───────────────────────────────────────────────── Define a struct,
|
|
// annotate its fields, and parse straight into it:
|
|
//
|
|
// struct Opts {
|
|
// [[= arg::Short{'v'}]] [[= arg::Help{"verbose output"}]] bool
|
|
// verbose = false;
|
|
// [[= arg::Help{"output path"}]] std::string
|
|
// out = "a.out"; std::optional<std::string> config; // --config
|
|
// <v>
|
|
// [[= arg::Positional{}]] std::string input;
|
|
// };
|
|
// auto o = Argparse::parse<Opts>(argc, argv); // std::expected<Opts,
|
|
// string>
|
|
//
|
|
// Field → argument: bool → flag, std::string → option with default (the
|
|
// field's initializer), std::optional<std::string> → optional option, a
|
|
// field tagged
|
|
// [[= arg::Positional]] → positional. Other field types are ignored.
|
|
|
|
struct Short {
|
|
char c;
|
|
};
|
|
struct Help {
|
|
Void::Meta::Str text;
|
|
};
|
|
struct Name {
|
|
Void::Meta::Str text;
|
|
}; // long-name override (without "--")
|
|
struct ValueName {
|
|
Void::Meta::Str text;
|
|
}; // help placeholder for an option
|
|
struct Alias {
|
|
Void::Meta::Str text;
|
|
}; // extra long spelling (with "--")
|
|
struct Hide {
|
|
}; // omit from help
|
|
struct Positional {
|
|
};
|
|
|
|
#ifdef VOID_HAS_META_REFLECTION
|
|
|
|
template <typename Opts>
|
|
[[nodiscard]] std::expected<Opts, std::string>
|
|
parse(int argc, const char* const* argv, std::string program = "app",
|
|
std::string description = {})
|
|
{
|
|
Opts out{};
|
|
Parser parser{std::move(program), std::move(description)};
|
|
|
|
// Numeric option sinks: the parser binds text, then converts it with
|
|
// strict validation after a successful parse.
|
|
struct NumericSink {
|
|
std::string text{};
|
|
std::vector<std::string> texts{};
|
|
std::string option{};
|
|
bool many{false};
|
|
std::function<bool(std::string_view)> assign{};
|
|
};
|
|
// Heap-owned so the parser's bound string pointer stays valid when the
|
|
// collection grows.
|
|
std::vector<std::unique_ptr<NumericSink>> numeric_sinks;
|
|
|
|
template for (constexpr auto m : Void::Meta::members_v<Opts>)
|
|
{
|
|
using MT = [:std::meta::type_of(m):];
|
|
constexpr auto nm = Void::Meta::annotation_of<Name>(m);
|
|
const std::string lng =
|
|
std::string{"--"} +
|
|
(nm.has_value() ? std::string{nm->text.view()}
|
|
: std::string{std::meta::identifier_of(m)});
|
|
constexpr auto sh = Void::Meta::annotation_of<Short>(m);
|
|
const std::string sht =
|
|
sh.has_value() ? (std::string{"-"} + sh->c) : std::string{};
|
|
constexpr auto hp = Void::Meta::annotation_of<Help>(m);
|
|
const std::string desc =
|
|
hp.has_value() ? std::string{hp->text.view()} : std::string{};
|
|
constexpr auto vn = Void::Meta::annotation_of<ValueName>(m);
|
|
constexpr auto al = Void::Meta::annotation_of<Alias>(m);
|
|
constexpr bool hidden = Void::Meta::has_annotation<Hide>(m);
|
|
auto decorate = [&] {
|
|
if (vn.has_value()) {
|
|
parser.value_name(lng, vn->text.view());
|
|
}
|
|
if (al.has_value()) {
|
|
parser.alias(lng, al->text.view());
|
|
}
|
|
if (hidden) {
|
|
parser.hide(lng);
|
|
}
|
|
};
|
|
|
|
if constexpr (Void::Meta::has_annotation<Positional>(m)) {
|
|
parser.positional(std::meta::identifier_of(m), desc, out.[:m:]);
|
|
} else if constexpr (std::same_as<MT, bool>) {
|
|
parser.flag(lng, sht, desc, out.[:m:]);
|
|
} else if constexpr (Void::Meta::is_optional_v<MT>) {
|
|
using Inner = typename MT::value_type;
|
|
if constexpr (std::same_as<Inner, std::string>) {
|
|
parser.option(lng, sht, desc, out.[:m:]);
|
|
} else {
|
|
auto sink = std::make_unique<NumericSink>();
|
|
sink->option = lng;
|
|
sink->assign = [target = &out.[:m:]](std::string_view text) {
|
|
if (text.empty()) {
|
|
target->reset();
|
|
return true;
|
|
}
|
|
Inner value{};
|
|
if constexpr (std::is_enum_v<Inner>) {
|
|
const auto parsed = Void::Meta::enum_parse<Inner>(text);
|
|
if (!parsed) {
|
|
return false;
|
|
}
|
|
*target = *parsed;
|
|
return true;
|
|
} else {
|
|
const auto result = std::from_chars(
|
|
text.data(), text.data() + text.size(), value);
|
|
if (result.ec != std::errc{} ||
|
|
result.ptr != text.data() + text.size()) {
|
|
return false;
|
|
}
|
|
*target = value;
|
|
return true;
|
|
}
|
|
};
|
|
parser.option_default(lng, sht, desc, sink->text, "");
|
|
numeric_sinks.push_back(std::move(sink));
|
|
}
|
|
} else if constexpr (std::same_as<MT, std::vector<std::string>>) {
|
|
parser.option_many(lng, sht, desc, out.[:m:]);
|
|
} else if constexpr (Void::Meta::is_vector_v<MT>) {
|
|
using Inner = typename MT::value_type;
|
|
auto sink = std::make_unique<NumericSink>();
|
|
sink->option = lng;
|
|
sink->many = true;
|
|
sink->assign = [target = &out.[:m:]](std::string_view text) {
|
|
Inner value{};
|
|
if constexpr (std::is_enum_v<Inner>) {
|
|
const auto parsed = Void::Meta::enum_parse<Inner>(text);
|
|
if (!parsed) {
|
|
return false;
|
|
}
|
|
value = *parsed;
|
|
} else {
|
|
const auto result = std::from_chars(
|
|
text.data(), text.data() + text.size(), value);
|
|
if (result.ec != std::errc{} ||
|
|
result.ptr != text.data() + text.size()) {
|
|
return false;
|
|
}
|
|
}
|
|
target->push_back(value);
|
|
return true;
|
|
};
|
|
parser.option_many(lng, sht, desc, sink->texts);
|
|
numeric_sinks.push_back(std::move(sink));
|
|
} else if constexpr (std::same_as<MT, std::string>) {
|
|
const std::string def = out.[:m:];
|
|
parser.option_default(lng, sht, desc, out.[:m:], def);
|
|
decorate();
|
|
} else if constexpr (std::is_enum_v<MT>) {
|
|
auto sink = std::make_unique<NumericSink>();
|
|
sink->option = lng;
|
|
sink->text = std::string{Void::Meta::enum_name(out.[:m:])};
|
|
const std::string initial = sink->text;
|
|
std::vector<std::string> allowed;
|
|
for (const auto& entry : Void::Meta::enum_entries<MT>()) {
|
|
allowed.emplace_back(entry.second);
|
|
}
|
|
sink->assign = [target = &out.[:m:], initial](std::string_view text) {
|
|
if (const auto parsed = Void::Meta::enum_parse<MT>(text)) {
|
|
*target = *parsed;
|
|
return true;
|
|
}
|
|
// A default that is not an enumerator name (e.g. a cast value)
|
|
// is left untouched rather than failing the whole parse.
|
|
return text == initial;
|
|
};
|
|
parser.option_default_checked(lng, sht, desc, sink->text, sink->text,
|
|
std::move(allowed));
|
|
numeric_sinks.push_back(std::move(sink));
|
|
} else if constexpr (std::is_arithmetic_v<MT>) {
|
|
auto sink = std::make_unique<NumericSink>();
|
|
sink->option = lng;
|
|
sink->text = std::to_string(out.[:m:]);
|
|
sink->assign = [target = &out.[:m:]](std::string_view text) {
|
|
using DT = std::remove_pointer_t<decltype(target)>;
|
|
DT value{};
|
|
const auto result = std::from_chars(
|
|
text.data(), text.data() + text.size(), value);
|
|
if (result.ec != std::errc{} ||
|
|
result.ptr != text.data() + text.size()) {
|
|
return false;
|
|
}
|
|
*target = value;
|
|
return true;
|
|
};
|
|
parser.option_default(lng, sht, desc, sink->text, sink->text);
|
|
numeric_sinks.push_back(std::move(sink));
|
|
}
|
|
// other field types: ignored
|
|
}
|
|
|
|
auto r = parser.parse(argc, argv);
|
|
if (!r) {
|
|
return std::unexpected{r.error()};
|
|
}
|
|
for (const auto& sink : numeric_sinks) {
|
|
if (sink->many) {
|
|
for (const auto& text : sink->texts) {
|
|
if (!sink->assign(text)) {
|
|
return std::unexpected{"invalid value '" + text +
|
|
"' for " + sink->option};
|
|
}
|
|
}
|
|
} else if (!sink->assign(sink->text)) {
|
|
return std::unexpected{"invalid value '" + sink->text +
|
|
"' for " + sink->option};
|
|
}
|
|
}
|
|
return out;
|
|
}
|
|
|
|
#endif // VOID_HAS_META_REFLECTION
|
|
|
|
} // namespace Void::Argparse
|