Argparse: derive enum option fields with possible values
This commit is contained in:
1 parent
520849f82e
commit
28e253b49c
2 files changed
+44
No files matched your search
@@ -290,6 +290,27 @@ namespace Void::Argparse
|
||||
} else if constexpr (std::same_as<MT, std::string>) {
|
||||
const std::string def = out.[:m:];
|
||||
parser.option_default(lng, sht, desc, out.[:m:], def);
|
||||
} 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;
|
||||
|
||||
@@ -68,3 +68,26 @@ Void::Testing::Test argparse_reflect_numeric_fields()
|
||||
auto bad = Void::Argparse::parse<Options>(3, bad_argv);
|
||||
Void::Testing::expect(!bad.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test argparse_reflect_enum_fields()
|
||||
{
|
||||
enum class Color { Red, Green, Blue };
|
||||
|
||||
struct Options {
|
||||
Color color = Color::Red;
|
||||
};
|
||||
|
||||
const char* default_argv[] = {"app"};
|
||||
auto defaults = Void::Argparse::parse<Options>(1, default_argv);
|
||||
Void::Testing::require(defaults.has_value());
|
||||
Void::Testing::expect(defaults->color == Color::Red);
|
||||
|
||||
const char* argv[] = {"app", "--color", "Blue"};
|
||||
auto parsed = Void::Argparse::parse<Options>(3, argv);
|
||||
Void::Testing::require(parsed.has_value());
|
||||
Void::Testing::expect(parsed->color == Color::Blue);
|
||||
|
||||
const char* bad_argv[] = {"app", "--color", "Purple"};
|
||||
auto bad = Void::Argparse::parse<Options>(3, bad_argv);
|
||||
Void::Testing::expect(!bad.has_value());
|
||||
}
|
||||
Reference in new issue
Block a user