247 lines
7.8 KiB
C++
247 lines
7.8 KiB
C++
#pragma once
|
|
|
|
#include <Void/Core/Meta.hpp>
|
|
|
|
#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,
|
|
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_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 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 = "");
|
|
|
|
// Add a required positional argument.
|
|
Parser& positional(std::string_view name,
|
|
std::string_view description, std::string& out);
|
|
|
|
// 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;
|
|
bool* out;
|
|
};
|
|
struct OptionEntry {
|
|
std::string lng, sht, desc, def;
|
|
std::optional<std::string>* out_opt{nullptr};
|
|
std::string* out_str{nullptr};
|
|
std::vector<std::string>* out_many{nullptr};
|
|
};
|
|
struct PosEntry {
|
|
std::string name, desc;
|
|
std::string* out;
|
|
};
|
|
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_;
|
|
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 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)};
|
|
|
|
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{};
|
|
|
|
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>) {
|
|
parser.option(lng, sht, desc, out.[:m:]);
|
|
} else if constexpr (std::same_as<MT, std::vector<std::string>>) {
|
|
parser.option_many(lng, sht, desc, out.[:m:]);
|
|
} else if constexpr (std::same_as<MT, std::string>) {
|
|
const std::string def = out.[:m:];
|
|
parser.option_default(lng, sht, desc, out.[:m:], def);
|
|
}
|
|
// other field types: ignored
|
|
}
|
|
|
|
auto r = parser.parse(argc, argv);
|
|
if (!r) {
|
|
return std::unexpected{r.error()};
|
|
}
|
|
return out;
|
|
}
|
|
|
|
#endif // VOID_HAS_META_REFLECTION
|
|
|
|
} // namespace Void::Argparse
|