From 7c20cf820b5abb2e2c41bcc4983ecdf49d461683 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Thu, 26 Nov 2026 20:51:56 +0100 Subject: [PATCH 1/8] Add rfl::Hidden wrapper to omit CLI options from usage and help --- include/rfl.hpp | 1 + include/rfl/Hidden.hpp | 130 ++++++++++++++++++++++ include/rfl/cli/options.hpp | 18 +++ include/rfl/cli/usage.hpp | 3 + include/rfl/internal/is_default_val_v.hpp | 12 ++ include/rfl/internal/is_hidden.hpp | 25 +++++ include/rfl/parsing/Parser_default.hpp | 4 +- tests/cli/test_hidden.cpp | 66 +++++++++++ 8 files changed, 258 insertions(+), 1 deletion(-) create mode 100644 include/rfl/Hidden.hpp create mode 100644 include/rfl/internal/is_hidden.hpp create mode 100644 tests/cli/test_hidden.cpp diff --git a/include/rfl.hpp b/include/rfl.hpp index dc5ace36a..b56864c05 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -30,6 +30,7 @@ #include "rfl/Flatten.hpp" #include "rfl/Generic.hpp" #include "rfl/Hex.hpp" +#include "rfl/Hidden.hpp" #include "rfl/ImplicitValue.hpp" #include "rfl/Literal.hpp" #include "rfl/NamedTuple.hpp" diff --git a/include/rfl/Hidden.hpp b/include/rfl/Hidden.hpp new file mode 100644 index 000000000..92d4f681d --- /dev/null +++ b/include/rfl/Hidden.hpp @@ -0,0 +1,130 @@ +#ifndef RFL_HIDDEN_HPP_ +#define RFL_HIDDEN_HPP_ + +#include +#include + +#include "default.hpp" + +namespace rfl { + +/// Marks a CLI option or positional argument as hidden from generated usage +/// and help text (`rfl::cli::usage` and `rfl::cli::read_app`), while still +/// parsing it normally. +/// For non-CLI formats (JSON, YAML, etc.), this is transparent. +template +struct Hidden { + /// The underlying type. + using Type = T; + + /// Every format reads and writes the underlying value directly. + using ReflectionType = Type; + + Hidden() + requires std::is_default_constructible_v + : value_(Type()) {} + + Hidden(const Type& _value) : value_(_value) {} + + Hidden(Type&& _value) noexcept(std::is_nothrow_move_constructible_v) + : value_(std::move(_value)) {} + + Hidden(Hidden&& _field) = default; + + Hidden(const Hidden& _field) = default; + + template + Hidden(const Hidden& _field) : value_(_field.get()) {} + + template + Hidden(Hidden&& _field) noexcept(std::is_nothrow_constructible_v) + : value_(std::move(_field.value_)) {} + + template + requires std::is_convertible_v + Hidden(const U& _value) : value_(_value) {} + + template + requires std::is_convertible_v + Hidden(U&& _value) noexcept(std::is_nothrow_constructible_v) + : value_(std::forward(_value)) {} + + template + requires std::is_default_constructible_v + Hidden(const Default&) : value_(Type()) {} + + ~Hidden() = default; + + const Type& get() const noexcept { return value_; } + + Type& get() noexcept { return value_; } + + Type& operator*() noexcept { return value_; } + + const Type& operator*() const noexcept { return value_; } + + Type& operator()() noexcept { return value_; } + + const Type& operator()() const noexcept { return value_; } + + Type* operator->() noexcept { return &value_; } + + const Type* operator->() const noexcept { return &value_; } + + auto& operator=(const Type& _value) { + value_ = _value; + return *this; + } + + auto& operator=(Type&& _value) noexcept( + std::is_nothrow_move_assignable_v) { + value_ = std::move(_value); + return *this; + } + + template + requires std::is_convertible_v + auto& operator=(const U& _value) { + value_ = _value; + return *this; + } + + template + requires std::is_default_constructible_v + auto& operator=(const Default&) { + value_ = Type(); + return *this; + } + + Hidden& operator=(const Hidden& _field) = default; + + Hidden& operator=(Hidden&& _field) = default; + + template + auto& operator=(const Hidden& _field) { + value_ = _field.get(); + return *this; + } + + template + auto& operator=(Hidden&& _field) { + value_ = std::move(_field.value_); + return *this; + } + + void set(const Type& _value) { value_ = _value; } + + void set(Type&& _value) { value_ = std::move(_value); } + + Type& value() noexcept { return value_; } + + const Type& value() const noexcept { return value_; } + + const Type& reflection() const { return value_; } + + Type value_; +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index a815aef52..3b9f81e74 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -14,6 +15,7 @@ #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" +#include "../Hidden.hpp" #include "../ImplicitValue.hpp" #include "../Positional.hpp" #include "../Rename.hpp" @@ -23,6 +25,7 @@ #include "../internal/has_reflection_type_v.hpp" #include "../internal/has_reflector.hpp" #include "../internal/is_extra_fields.hpp" +#include "../internal/is_hidden.hpp" #include "../internal/is_named_tuple.hpp" #include "../internal/is_positional.hpp" #include "../internal/is_short.hpp" @@ -105,6 +108,10 @@ struct Options { /// `--servers.eu.port` is looked up as `port`. std::map> open_prefix_options; + /// Paths of fields wrapped in rfl::Hidden, which are parsed normally but + /// omitted from usage() and --help. + std::set hidden_options; + /// Whether options that match no field are an error (rfl::NoExtraFields). bool reject_unknown = false; @@ -264,6 +271,7 @@ template struct cli_annotations { static constexpr bool is_short = false; static constexpr bool is_positional = false; + static constexpr bool is_hidden = false; static constexpr size_t num_implicit_value = 0; static constexpr rfl::internal::StringLiteral<1> short_name = ""; static constexpr int count = 0; @@ -312,6 +320,11 @@ struct cli_annotations> : cli_annotations_t { static constexpr auto implicit_value = _implicit; }; +template +struct cli_annotations> : cli_annotations_t { + static constexpr bool is_hidden = true; +}; + /// The CLI metadata of the _i-th field of a NamedTuple. InnerType is the /// declared type of the field, whichever wrappers it consists of. template @@ -323,6 +336,7 @@ struct field_info { static constexpr bool is_positional = Annotations::is_positional; static constexpr bool is_short = Annotations::is_short; + static constexpr bool is_hidden = Annotations::is_hidden; static constexpr bool has_implicit_value = Annotations::num_implicit_value > 0; @@ -379,6 +393,7 @@ auto unwrap_option_type() { else if constexpr (rfl::internal::is_short_v || rfl::internal::is_positional_v || rfl::internal::is_implicit_value_v + || rfl::internal::is_hidden_v || parsing::is_rename_v || parsing::is_default_val_v || parsing::is_skip_v) { @@ -544,6 +559,9 @@ void collect_value_options(Options* _options) { template void add_option(const std::string& _path, Options* _options) { using U = unwrapped_option_t; + if constexpr (cli_annotations_t::is_hidden) { + _options->hidden_options.insert(_path); + } if constexpr (cli_annotations_t::num_implicit_value > 0) { _options->long_options[_path] = implicit_value_option(); diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 2c04b69b6..25352df9b 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -435,6 +435,9 @@ class UsageCollector { for (const auto& [name, type] : _object.types_) { auto arg = UsageArg{}; arg.name = is_root ? name : _parent.name + path_separator + name; + if (options_->hidden_options.contains(arg.name)) { + continue; + } // Children of an optional object are only needed if it is given. arg.required = _parent.required; if (is_root) { diff --git a/include/rfl/internal/is_default_val_v.hpp b/include/rfl/internal/is_default_val_v.hpp index 3ac5314c7..b5106f5f8 100644 --- a/include/rfl/internal/is_default_val_v.hpp +++ b/include/rfl/internal/is_default_val_v.hpp @@ -7,6 +7,7 @@ #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" +#include "../Hidden.hpp" #include "../ImplicitValue.hpp" #include "../Positional.hpp" #include "../Rename.hpp" @@ -49,6 +50,9 @@ template class is_default_val> : public is_default_val { }; +template +class is_default_val> : public is_default_val {}; + template constexpr bool is_default_val_v = is_default_val>>::value; @@ -76,6 +80,14 @@ template >> : public is_unwrapped_default_val {}; +template +class is_unwrapped_default_val> + : public is_unwrapped_default_val {}; + +template +class is_unwrapped_default_val>> + : public is_unwrapped_default_val {}; + template constexpr bool is_unwrapped_default_val_v = is_unwrapped_default_val< std::remove_cvref_t>>::value; diff --git a/include/rfl/internal/is_hidden.hpp b/include/rfl/internal/is_hidden.hpp new file mode 100644 index 000000000..d2c197256 --- /dev/null +++ b/include/rfl/internal/is_hidden.hpp @@ -0,0 +1,25 @@ +#ifndef RFL_INTERNAL_ISHIDDEN_HPP_ +#define RFL_INTERNAL_ISHIDDEN_HPP_ + +#include + +#include "../Hidden.hpp" + +namespace rfl::internal { + +template +class is_hidden; + +template +class is_hidden : public std::false_type {}; + +template +class is_hidden> : public std::true_type {}; + +template +constexpr bool is_hidden_v = + is_hidden>>::value; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index d284b5245..a665b7cc2 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -18,6 +18,7 @@ #include "../internal/is_basic_type.hpp" #include "../internal/is_deprecated.hpp" #include "../internal/is_description.hpp" +#include "../internal/is_hidden.hpp" #include "../internal/is_implicit_value.hpp" #include "../internal/is_literal.hpp" #include "../internal/is_validator.hpp" @@ -553,7 +554,8 @@ struct Parser { return ParserPositional::to_schema(_definitions); - } else if constexpr (rfl::internal::is_implicit_value::value) { + } else if constexpr (rfl::internal::is_implicit_value::value || + rfl::internal::is_hidden::value) { // Read and written through its ReflectionType, but described as the // type itself rather than as a named reference, like rfl::Short. return Parser::to_schema( diff --git a/tests/cli/test_hidden.cpp b/tests/cli/test_hidden.cpp new file mode 100644 index 000000000..0f0f4961e --- /dev/null +++ b/tests/cli/test_hidden.cpp @@ -0,0 +1,66 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_hidden { + +struct SortConfig { + rfl::Short<"v", rfl::Description<"Verbose output", rfl::DefaultVal>> + verbose = false; + rfl::Hidden>> strategy; + rfl::Positional>>> + input_filenames; +}; + +struct HiddenFlattened { + rfl::Short<"d", rfl::Hidden>> debug_level = 0; +}; + +struct WrapperOrderConfig { + rfl::Description<"Visible", std::optional> visible; + rfl::Flatten extra; +}; + +TEST(cli, test_hidden_parsed_but_omitted_from_usage) { + const std::vector args = {"-v", "-s", "multipass", "a.osm", + "b.osm"}; + const auto res = + rfl::cli::read>(args); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_TRUE(res->verbose.value().value().get()); + EXPECT_EQ(res->strategy.value().value(), "multipass"); + ASSERT_TRUE(res->input_filenames.value().value().has_value()); + EXPECT_EQ(*res->input_filenames.value().value(), + (std::vector{"a.osm", "b.osm"})); + + const auto short_usage = rfl::cli::usage("osmium sort", false); + ASSERT_TRUE(short_usage) << short_usage.error().what(); + EXPECT_EQ(*short_usage, "Usage: osmium sort [-v|--verbose[=]]\n"); + + const auto detailed = rfl::cli::usage("osmium sort", true); + ASSERT_TRUE(detailed) << detailed.error().what(); + EXPECT_EQ(detailed->find("strategy"), std::string::npos); + EXPECT_EQ(detailed->find("input-filenames"), std::string::npos); + EXPECT_NE(detailed->find("--verbose"), std::string::npos); +} + +TEST(cli, test_hidden_inside_short_and_flatten) { + const std::vector args = {"--visible=hi", "-d", "3"}; + const auto res = rfl::cli::read(args); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res->visible.value(), "hi"); + EXPECT_EQ(res->extra().debug_level.value().value().get(), 3); + + const auto detailed = rfl::cli::usage("app", true); + ASSERT_TRUE(detailed) << detailed.error().what(); + EXPECT_NE(detailed->find("--visible"), std::string::npos); + EXPECT_EQ(detailed->find("debug-level"), std::string::npos); +} + +} // namespace test_hidden From e9b2247a23f88ae039bb35374fd1186b1a4ff55c Mon Sep 17 00:00:00 2001 From: clockblocker Date: Thu, 26 Nov 2026 20:51:56 +0100 Subject: [PATCH 2/8] Add rfl::Group wrapper for named help sections in rfl::cli::usage --- include/rfl.hpp | 1 + include/rfl/Group.hpp | 136 ++++++++++++++++++++++ include/rfl/cli/options.hpp | 18 +++ include/rfl/cli/usage.hpp | 52 ++++++++- include/rfl/internal/is_default_val_v.hpp | 13 +++ include/rfl/internal/is_group.hpp | 26 +++++ include/rfl/parsing/Parser_default.hpp | 4 +- tests/cli/test_group.cpp | 63 ++++++++++ 8 files changed, 306 insertions(+), 7 deletions(-) create mode 100644 include/rfl/Group.hpp create mode 100644 include/rfl/internal/is_group.hpp create mode 100644 tests/cli/test_group.cpp diff --git a/include/rfl.hpp b/include/rfl.hpp index b56864c05..825544c50 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -29,6 +29,7 @@ #include "rfl/Field.hpp" #include "rfl/Flatten.hpp" #include "rfl/Generic.hpp" +#include "rfl/Group.hpp" #include "rfl/Hex.hpp" #include "rfl/Hidden.hpp" #include "rfl/ImplicitValue.hpp" diff --git a/include/rfl/Group.hpp b/include/rfl/Group.hpp new file mode 100644 index 000000000..d4987b83f --- /dev/null +++ b/include/rfl/Group.hpp @@ -0,0 +1,136 @@ +#ifndef RFL_GROUP_HPP_ +#define RFL_GROUP_HPP_ + +#include +#include + +#include "default.hpp" +#include "internal/StringLiteral.hpp" + +namespace rfl { + +/// Assigns a CLI option to a named help section (e.g. "OUTPUT OPTIONS") in +/// `rfl::cli::usage` and `rfl::cli::read_app`. +/// For non-CLI formats (JSON, YAML, etc.), this is transparent. +template +struct Group { + /// The underlying type. + using Type = T; + + /// Every format reads and writes the underlying value directly. + using ReflectionType = Type; + + /// The section header name. + static constexpr auto group_name_ = _group; + + static_assert(_group.length > 0, "Group name must not be empty."); + + Group() + requires std::is_default_constructible_v + : value_(Type()) {} + + Group(const Type& _value) : value_(_value) {} + + Group(Type&& _value) noexcept(std::is_nothrow_move_constructible_v) + : value_(std::move(_value)) {} + + Group(Group<_group, T>&& _field) = default; + + Group(const Group<_group, T>& _field) = default; + + template + Group(const Group<_group, U>& _field) : value_(_field.get()) {} + + template + Group(Group<_group, U>&& _field) noexcept( + std::is_nothrow_constructible_v) + : value_(std::move(_field.value_)) {} + + template + requires std::is_convertible_v + Group(const U& _value) : value_(_value) {} + + template + requires std::is_convertible_v + Group(U&& _value) noexcept(std::is_nothrow_constructible_v) + : value_(std::forward(_value)) {} + + template + requires std::is_default_constructible_v + Group(const Default&) : value_(Type()) {} + + ~Group() = default; + + const Type& get() const noexcept { return value_; } + + Type& get() noexcept { return value_; } + + Type& operator*() noexcept { return value_; } + + const Type& operator*() const noexcept { return value_; } + + Type& operator()() noexcept { return value_; } + + const Type& operator()() const noexcept { return value_; } + + Type* operator->() noexcept { return &value_; } + + const Type* operator->() const noexcept { return &value_; } + + auto& operator=(const Type& _value) { + value_ = _value; + return *this; + } + + auto& operator=(Type&& _value) noexcept( + std::is_nothrow_move_assignable_v) { + value_ = std::move(_value); + return *this; + } + + template + requires std::is_convertible_v + auto& operator=(const U& _value) { + value_ = _value; + return *this; + } + + template + requires std::is_default_constructible_v + auto& operator=(const Default&) { + value_ = Type(); + return *this; + } + + Group<_group, T>& operator=(const Group<_group, T>& _field) = default; + + Group<_group, T>& operator=(Group<_group, T>&& _field) = default; + + template + auto& operator=(const Group<_group, U>& _field) { + value_ = _field.get(); + return *this; + } + + template + auto& operator=(Group<_group, U>&& _field) { + value_ = std::move(_field.value_); + return *this; + } + + void set(const Type& _value) { value_ = _value; } + + void set(Type&& _value) { value_ = std::move(_value); } + + Type& value() noexcept { return value_; } + + const Type& value() const noexcept { return value_; } + + const Type& reflection() const { return value_; } + + Type value_; +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index 3b9f81e74..c4d17a3b0 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -15,6 +15,7 @@ #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" +#include "../Group.hpp" #include "../Hidden.hpp" #include "../ImplicitValue.hpp" #include "../Positional.hpp" @@ -25,6 +26,7 @@ #include "../internal/has_reflection_type_v.hpp" #include "../internal/has_reflector.hpp" #include "../internal/is_extra_fields.hpp" +#include "../internal/is_group.hpp" #include "../internal/is_hidden.hpp" #include "../internal/is_named_tuple.hpp" #include "../internal/is_positional.hpp" @@ -112,6 +114,9 @@ struct Options { /// omitted from usage() and --help. std::set hidden_options; + /// Section header name for fields wrapped in rfl::Group, by path. + std::map option_groups; + /// Whether options that match no field are an error (rfl::NoExtraFields). bool reject_unknown = false; @@ -272,10 +277,12 @@ struct cli_annotations { static constexpr bool is_short = false; static constexpr bool is_positional = false; static constexpr bool is_hidden = false; + static constexpr bool has_group = false; static constexpr size_t num_implicit_value = 0; static constexpr rfl::internal::StringLiteral<1> short_name = ""; static constexpr int count = 0; static constexpr rfl::internal::StringLiteral<1> implicit_value = ""; + static constexpr rfl::internal::StringLiteral<1> group_name = ""; }; template @@ -325,6 +332,12 @@ struct cli_annotations> : cli_annotations_t { static constexpr bool is_hidden = true; }; +template +struct cli_annotations> : cli_annotations_t { + static constexpr bool has_group = true; + static constexpr auto group_name = _group; +}; + /// The CLI metadata of the _i-th field of a NamedTuple. InnerType is the /// declared type of the field, whichever wrappers it consists of. template @@ -394,6 +407,7 @@ auto unwrap_option_type() { || rfl::internal::is_positional_v || rfl::internal::is_implicit_value_v || rfl::internal::is_hidden_v + || rfl::internal::is_group_v || parsing::is_rename_v || parsing::is_default_val_v || parsing::is_skip_v) { @@ -562,6 +576,10 @@ void add_option(const std::string& _path, Options* _options) { if constexpr (cli_annotations_t::is_hidden) { _options->hidden_options.insert(_path); } + if constexpr (cli_annotations_t::has_group) { + _options->option_groups[_path] = + std::string(cli_annotations_t::group_name.string_view()); + } if constexpr (cli_annotations_t::num_implicit_value > 0) { _options->long_options[_path] = implicit_value_option(); diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 25352df9b..9c5c2d1ca 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -84,6 +84,8 @@ struct UsageArg { /// Rendered constraints, such as "Range: 1..65535.". std::vector constraints; std::optional default_value; + /// Optional help section header (from rfl::Group). + std::string group; }; template @@ -499,6 +501,10 @@ class UsageCollector { _arg.default_value = std::move(def); } } + if (const auto it = options_->option_groups.find(_arg.name); + it != options_->option_groups.end()) { + _arg.group = it->second; + } args_.emplace_back(std::move(_arg)); } @@ -678,12 +684,12 @@ inline std::string format_usage(const std::string& _program_name, constexpr size_t indent = 2; constexpr size_t gap = 2; const auto continuation = '\n' + std::string(indent + width + gap, ' '); - out += "\nArguments:\n"; - for (const auto& [left, right] : rows) { - out += std::string(indent, ' ') + left; - if (!right.empty()) { - out += std::string(width - left.size() + gap, ' '); - for (const char c : right) { + const auto emit_row = [&](const std::string& _left, + const std::string& _right) { + out += std::string(indent, ' ') + _left; + if (!_right.empty()) { + out += std::string(width - _left.size() + gap, ' '); + for (const char c : _right) { if (c == '\n') { out += continuation; } else { @@ -692,6 +698,40 @@ inline std::string format_usage(const std::string& _program_name, } } out += '\n'; + }; + + const bool has_groups = std::any_of( + _args.begin(), _args.end(), + [](const UsageArg& _arg) { return !_arg.group.empty(); }); + + if (!has_groups) { + out += "\nArguments:\n"; + for (const auto& [left, right] : rows) { + emit_row(left, right); + } + return out; + } + + // Emit sections in order of first appearance; ungrouped args (if any) go + // under "Arguments". + std::vector section_order; + for (const auto& arg : _args) { + const std::string section = + arg.group.empty() ? std::string("Arguments") : arg.group; + if (std::find(section_order.begin(), section_order.end(), section) + == section_order.end()) { + section_order.push_back(section); + } + } + for (const auto& section : section_order) { + out += "\n" + section + ":\n"; + for (size_t i = 0; i < _args.size(); ++i) { + const std::string arg_section = + _args[i].group.empty() ? std::string("Arguments") : _args[i].group; + if (arg_section == section) { + emit_row(rows[i].first, rows[i].second); + } + } } return out; } diff --git a/include/rfl/internal/is_default_val_v.hpp b/include/rfl/internal/is_default_val_v.hpp index b5106f5f8..cbccb3722 100644 --- a/include/rfl/internal/is_default_val_v.hpp +++ b/include/rfl/internal/is_default_val_v.hpp @@ -7,6 +7,7 @@ #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" +#include "../Group.hpp" #include "../Hidden.hpp" #include "../ImplicitValue.hpp" #include "../Positional.hpp" @@ -53,6 +54,9 @@ class is_default_val> : public is_default_val { template class is_default_val> : public is_default_val {}; +template +class is_default_val> : public is_default_val {}; + template constexpr bool is_default_val_v = is_default_val>>::value; @@ -88,6 +92,15 @@ template class is_unwrapped_default_val>> : public is_unwrapped_default_val {}; +template +class is_unwrapped_default_val> + : public is_unwrapped_default_val {}; + +template +class is_unwrapped_default_val>> + : public is_unwrapped_default_val {}; + template constexpr bool is_unwrapped_default_val_v = is_unwrapped_default_val< std::remove_cvref_t>>::value; diff --git a/include/rfl/internal/is_group.hpp b/include/rfl/internal/is_group.hpp new file mode 100644 index 000000000..2fc099fa2 --- /dev/null +++ b/include/rfl/internal/is_group.hpp @@ -0,0 +1,26 @@ +#ifndef RFL_INTERNAL_ISGROUP_HPP_ +#define RFL_INTERNAL_ISGROUP_HPP_ + +#include + +#include "../Group.hpp" +#include "StringLiteral.hpp" + +namespace rfl::internal { + +template +class is_group; + +template +class is_group : public std::false_type {}; + +template +class is_group> : public std::true_type {}; + +template +constexpr bool is_group_v = + is_group>>::value; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index a665b7cc2..bec8d823b 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -18,6 +18,7 @@ #include "../internal/is_basic_type.hpp" #include "../internal/is_deprecated.hpp" #include "../internal/is_description.hpp" +#include "../internal/is_group.hpp" #include "../internal/is_hidden.hpp" #include "../internal/is_implicit_value.hpp" #include "../internal/is_literal.hpp" @@ -555,7 +556,8 @@ struct Parser { ProcessorsType>::to_schema(_definitions); } else if constexpr (rfl::internal::is_implicit_value::value || - rfl::internal::is_hidden::value) { + rfl::internal::is_hidden::value || + rfl::internal::is_group::value) { // Read and written through its ReflectionType, but described as the // type itself rather than as a named reference, like rfl::Short. return Parser::to_schema( diff --git a/tests/cli/test_group.cpp b/tests/cli/test_group.cpp new file mode 100644 index 000000000..52f6a7c67 --- /dev/null +++ b/tests/cli/test_group.cpp @@ -0,0 +1,63 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_group { + +struct InputMixin { + rfl::Group<"INPUT OPTIONS", + rfl::Short<"F", rfl::Description<"Format of input file", + std::optional>>> + input_format; +}; + +struct OutputMixin { + rfl::Group<"OUTPUT OPTIONS", + rfl::Short<"o", rfl::Description<"Output file", + std::optional>>> + output; + rfl::Short<"O", rfl::Group<"OUTPUT OPTIONS", + rfl::Description<"Allow overwrite", + rfl::DefaultVal>>> + overwrite = false; +}; + +struct CatConfig { + rfl::Group<"COMMAND OPTIONS", + rfl::Description<"Buffer data in memory", rfl::DefaultVal>> + buffer_data = false; + rfl::Flatten input; + rfl::Flatten output; +}; + +TEST(cli, test_group_sections_and_flatten) { + const std::vector args = {"--buffer-data", "-F", "osm", "-o", + "out.pbf", "-O"}; + const auto res = + rfl::cli::read(args); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_TRUE(res->buffer_data.value().value().get()); + EXPECT_EQ(res->input().input_format.value().value().value(), "osm"); + EXPECT_EQ(res->output().output.value().value().value(), "out.pbf"); + EXPECT_TRUE(res->output().overwrite.value().value().value().get()); + + const auto detailed = rfl::cli::usage("osmium cat", true); + ASSERT_TRUE(detailed) << detailed.error().what(); + + const auto cmd_pos = detailed->find("\nCOMMAND OPTIONS:\n"); + const auto in_pos = detailed->find("\nINPUT OPTIONS:\n"); + const auto out_pos = detailed->find("\nOUTPUT OPTIONS:\n"); + ASSERT_NE(cmd_pos, std::string::npos) << *detailed; + ASSERT_NE(in_pos, std::string::npos) << *detailed; + ASSERT_NE(out_pos, std::string::npos) << *detailed; + EXPECT_LT(cmd_pos, in_pos); + EXPECT_LT(in_pos, out_pos); + EXPECT_EQ(detailed->find("\nArguments:\n"), std::string::npos); +} + +} // namespace test_group From f7ec684ec4360d2b3e559dcb703f7182889ff435 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Thu, 26 Nov 2026 07:06:17 +0100 Subject: [PATCH 3/8] Add rfl::cli::UsageOptions for runtime synopsis, description, footer, and help_group --- include/rfl/cli/read_app.hpp | 49 ++++++++---- include/rfl/cli/usage.hpp | 135 +++++++++++++++++++++++--------- tests/cli/test_usage_custom.cpp | 74 +++++++++++++++++ 3 files changed, 202 insertions(+), 56 deletions(-) create mode 100644 tests/cli/test_usage_custom.cpp diff --git a/include/rfl/cli/read_app.hpp b/include/rfl/cli/read_app.hpp index 230fc2d8f..4ab5cb336 100644 --- a/include/rfl/cli/read_app.hpp +++ b/include/rfl/cli/read_app.hpp @@ -50,7 +50,8 @@ inline rfl::Result take_builtin_flag( /// instead of reading the struct. template rfl::Result> parse_and_read_app( - const std::string& _program_name, const ParseFn& _parse) { + const std::string& _program_name, const ParseFn& _parse, + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { using ProcessorsType = Processors; using ResultType = std::variant; auto options = make_options(); @@ -78,7 +79,7 @@ rfl::Result> parse_and_read_app( } if (*help || *help_short) { - return usage(_program_name, true) + return usage(_program_name, _usage_opts) .transform([](std::string _text) { return ResultType( HelpOrVersion{HelpOrVersion::Kind::help, std::move(_text)}); @@ -135,36 +136,45 @@ inline std::string program_name(int argc, const wchar_t* const argv[]) { /// has no name. /// @return The struct, or the help or version text, or an error template -rfl::Result> read_app(int argc, - const char* const argv[]) { +rfl::Result> read_app( + int argc, const char* const argv[], + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { return internal::parse_and_read_app( internal::program_name(argc, argv), [&](const auto& _options) { return internal::parse_argv(argc, argv, _options); - }); + }, + _usage_opts); } template -rfl::Result> read_app(int argc, char* argv[]) { - return read_app(argc, static_cast(argv)); +rfl::Result> read_app( + int argc, char* argv[], + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { + return read_app(argc, static_cast(argv), + _usage_opts); } /// Like rfl::cli::read_app, for wide-character arguments, which are /// converted to UTF-8 first. template rfl::Result> read_app( - int argc, const wchar_t* const argv[]) { + int argc, const wchar_t* const argv[], + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { return internal::parse_and_read_app( internal::program_name(argc, argv), [&](const auto& _options) { return internal::parse_argv(argc, argv, _options); - }); + }, + _usage_opts); } template -rfl::Result> read_app(int argc, - wchar_t* argv[]) { - return read_app(argc, static_cast(argv)); +rfl::Result> read_app( + int argc, wchar_t* argv[], + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { + return read_app(argc, static_cast(argv), + _usage_opts); } /// Like rfl::cli::read_app, reading every element of a range of narrow or @@ -174,11 +184,14 @@ template > requires(internal::StringRange || internal::WideStringRange) rfl::Result> read_app( - std::string_view _program_name, R&& _args) { + std::string_view _program_name, R&& _args, + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { return internal::parse_and_read_app( - std::string(_program_name), [&](const auto& _options) { + std::string(_program_name), + [&](const auto& _options) { return internal::parse_argv(std::forward(_args), _options); - }); + }, + _usage_opts); } /// Like rfl::cli::read_app, reading every element of a range of narrow or @@ -186,10 +199,12 @@ rfl::Result> read_app( template > requires(internal::StringRange || internal::WideStringRange) -rfl::Result> read_app(R&& _args) { +rfl::Result> read_app( + R&& _args, + const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { using ProcessorsType = Processors; return read_app(internal::app_settings_t::name, - std::forward(_args)); + std::forward(_args), _usage_opts); } } // namespace rfl::cli diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 9c5c2d1ca..695efa5c4 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -41,6 +41,20 @@ namespace rfl::cli { +/// Runtime customization for `rfl::cli::usage` and `rfl::cli::read_app`. +struct UsageOptions { + bool detailed = true; + /// If non-empty, replaces the auto-generated synopsis after "Usage: ". + std::string synopsis = {}; + /// If non-empty, shown after the Usage line in detailed output. + std::string description = {}; + /// If non-empty, appended after a blank line at the end of detailed output. + std::string footer = {}; + /// If non-empty, places built-in `--help` and `--version` in this group + /// (at the start of the group if fields already use it). + std::string help_group = {}; +}; + namespace internal { /// Whether a top-level field is required, which the schema cannot tell the @@ -624,10 +638,11 @@ inline std::string usage_help_text(const UsageArg& _arg) { /// The rows of the built-in options of rfl::cli::App that no field takes. inline std::vector builtin_usage_args( - const BuiltinOptions& _builtin) { + const BuiltinOptions& _builtin, + const std::string& _help_group = std::string()) { auto args = std::vector(); - const auto make = [](std::string_view _name, std::string_view _short_name, - std::string _description) { + const auto make = [&](std::string_view _name, std::string_view _short_name, + std::string _description) { auto arg = UsageArg{}; arg.name = std::string(_name); arg.short_name = std::string(_short_name); @@ -635,6 +650,7 @@ inline std::vector builtin_usage_args( arg.bare = true; arg.required = false; arg.description = std::move(_description); + arg.group = _help_group; return arg; }; if (_builtin.help) { @@ -654,22 +670,36 @@ inline std::vector builtin_usage_args( /// argument (rfl::cli::OptionsFirst), so the synopsis lists them first. inline std::string format_usage(const std::string& _program_name, const std::vector& _args, - const bool _detailed, + const UsageOptions& _opts, const std::optional _delimiter, const bool _options_first, const std::string& _header) { - auto synopsis = _args; - if (_options_first) { - std::stable_partition(synopsis.begin(), synopsis.end(), - [](const UsageArg& _arg) { return !_arg.positional; }); + auto out = _opts.detailed ? _header : std::string(); + if (!_opts.synopsis.empty()) { + out += "Usage: " + _opts.synopsis + "\n"; + } else { + auto synopsis = _args; + if (_options_first) { + std::stable_partition(synopsis.begin(), synopsis.end(), + [](const UsageArg& _arg) { return !_arg.positional; }); + } + out += "Usage: " + _program_name; + for (const auto& arg : synopsis) { + const auto str = usage_arg_to_string(arg, "|", _delimiter); + out += arg.required ? " " + str : " [" + str + "]"; + } + out += '\n'; } - auto out = (_detailed ? _header : std::string()) + "Usage: " + _program_name; - for (const auto& arg : synopsis) { - const auto str = usage_arg_to_string(arg, "|", _delimiter); - out += arg.required ? " " + str : " [" + str + "]"; + if (!_opts.detailed) { + return out; } - out += '\n'; - if (!_detailed || _args.empty()) { + if (!_opts.description.empty()) { + out += "\n" + _opts.description + "\n"; + } + if (_args.empty()) { + if (!_opts.footer.empty()) { + out += "\n" + _opts.footer + "\n"; + } return out; } @@ -709,30 +739,32 @@ inline std::string format_usage(const std::string& _program_name, for (const auto& [left, right] : rows) { emit_row(left, right); } - return out; - } - - // Emit sections in order of first appearance; ungrouped args (if any) go - // under "Arguments". - std::vector section_order; - for (const auto& arg : _args) { - const std::string section = - arg.group.empty() ? std::string("Arguments") : arg.group; - if (std::find(section_order.begin(), section_order.end(), section) - == section_order.end()) { - section_order.push_back(section); + } else { + // Emit sections in order of first appearance; ungrouped args (if any) go + // under "Arguments". + std::vector section_order; + for (const auto& arg : _args) { + const std::string section = + arg.group.empty() ? std::string("Arguments") : arg.group; + if (std::find(section_order.begin(), section_order.end(), section) + == section_order.end()) { + section_order.push_back(section); + } } - } - for (const auto& section : section_order) { - out += "\n" + section + ":\n"; - for (size_t i = 0; i < _args.size(); ++i) { - const std::string arg_section = - _args[i].group.empty() ? std::string("Arguments") : _args[i].group; - if (arg_section == section) { - emit_row(rows[i].first, rows[i].second); + for (const auto& section : section_order) { + out += "\n" + section + ":\n"; + for (size_t i = 0; i < _args.size(); ++i) { + const std::string arg_section = + _args[i].group.empty() ? std::string("Arguments") : _args[i].group; + if (arg_section == section) { + emit_row(rows[i].first, rows[i].second); + } } } } + if (!_opts.footer.empty()) { + out += "\n" + _opts.footer + "\n"; + } return out; } @@ -781,7 +813,7 @@ std::optional usage_defaults() { /// rfl::DefaultVal and default-constructing it throws. template rfl::Result usage(const std::string& _program_name, - const bool _detailed = false) { + const UsageOptions& _opts) { using ProcessorsType = Processors; using NamedTupleType = rfl::internal::processed_t; constexpr auto delimiter = internal::list_delimiter_v; @@ -806,13 +838,32 @@ rfl::Result usage(const std::string& _program_name, auto collector = internal::UsageCollector( &definition, &meta, &options, rfl::internal::no_optionals_v, delimiter); - auto args = internal::builtin_usage_args(builtin); - const auto fields = collector.collect( + auto builtin_args = + internal::builtin_usage_args(builtin, _opts.help_group); + auto fields = collector.collect( rfl::internal::default_if_missing_v, internal::usage_defaults()); - args.insert(args.end(), fields.begin(), fields.end()); + auto args = std::vector(); + if (!_opts.help_group.empty() && !builtin_args.empty()) { + const auto pos = std::find_if( + fields.begin(), fields.end(), + [&](const internal::UsageArg& _a) { + return _a.group == _opts.help_group; + }); + if (pos != fields.end()) { + args.insert(args.end(), fields.begin(), pos); + args.insert(args.end(), builtin_args.begin(), builtin_args.end()); + args.insert(args.end(), pos, fields.end()); + } else { + args = std::move(builtin_args); + args.insert(args.end(), fields.begin(), fields.end()); + } + } else { + args = std::move(builtin_args); + args.insert(args.end(), fields.begin(), fields.end()); + } return internal::format_usage( - _program_name, args, _detailed, delimiter, options.options_first, + _program_name, args, _opts, delimiter, options.options_first, internal::app_header(_program_name)); } catch (std::exception& e) { return error(e.what()); @@ -820,6 +871,12 @@ rfl::Result usage(const std::string& _program_name, }); } +template +rfl::Result usage(const std::string& _program_name, + const bool _detailed = false) { + return usage(_program_name, UsageOptions{.detailed = _detailed}); +} + } // namespace rfl::cli #endif diff --git a/tests/cli/test_usage_custom.cpp b/tests/cli/test_usage_custom.cpp new file mode 100644 index 000000000..0a83917c0 --- /dev/null +++ b/tests/cli/test_usage_custom.cpp @@ -0,0 +1,74 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace test_usage_custom { + +struct CatOptions { + rfl::Group<"COMMAND OPTIONS", + rfl::Description<"Buffer data in memory", rfl::DefaultVal>> + buffer_data = false; + rfl::Group<"COMMON OPTIONS", + rfl::Short<"v", rfl::Description<"Set verbose mode", + rfl::DefaultVal>>> + verbose = false; + rfl::Group<"INPUT OPTIONS", + rfl::Short<"F", rfl::Description<"Format of input files", + std::optional>>> + input_format; + rfl::Hidden>>> + input_filenames; +}; + +using SubApp = + rfl::cli::App<"", "", "", rfl::cli::BuiltinHelp::short_and_long>; + +TEST(cli, test_usage_custom_synopsis_description_footer_and_help_group) { + const rfl::cli::UsageOptions opts{ + .detailed = true, + .synopsis = "osmium cat [OPTIONS] [OSM-FILE...]", + .description = "Concatenate OSM files and convert to different formats.", + .footer = "Use 'osmium help cat' to display the manual page.", + .help_group = "COMMON OPTIONS", + }; + const std::vector args = {"-h"}; + const auto res = + rfl::cli::read_app("osmium cat", args, opts); + ASSERT_TRUE(res) << res.error().what(); + ASSERT_TRUE(std::holds_alternative(*res)); + const auto& text = std::get(*res).text; + + EXPECT_TRUE(text.starts_with( + "Usage: osmium cat [OPTIONS] [OSM-FILE...]\n\n" + "Concatenate OSM files and convert to different formats.\n")); + const auto cmd_pos = text.find("\nCOMMAND OPTIONS:\n"); + const auto common_pos = text.find("\nCOMMON OPTIONS:\n"); + const auto help_pos = text.find(" -h, --help"); + const auto verbose_pos = text.find(" -v, --verbose"); + const auto input_pos = text.find("\nINPUT OPTIONS:\n"); + const auto footer_pos = + text.find("\nUse 'osmium help cat' to display the manual page.\n"); + + ASSERT_NE(cmd_pos, std::string::npos) << text; + ASSERT_NE(common_pos, std::string::npos) << text; + ASSERT_NE(help_pos, std::string::npos) << text; + ASSERT_NE(verbose_pos, std::string::npos) << text; + ASSERT_NE(input_pos, std::string::npos) << text; + ASSERT_NE(footer_pos, std::string::npos) << text; + + // Built-in -h/--help is placed at the start of COMMON OPTIONS without + // reordering COMMAND OPTIONS ahead of it. + EXPECT_LT(cmd_pos, common_pos); + EXPECT_LT(common_pos, help_pos); + EXPECT_LT(help_pos, verbose_pos); + EXPECT_LT(verbose_pos, input_pos); + EXPECT_LT(input_pos, footer_pos); + EXPECT_EQ(text.find("input-filenames"), std::string::npos); +} + +} // namespace test_usage_custom From 611ef38fb45586a2d06cd495bde7ba7f8fd4d49f Mon Sep 17 00:00:00 2001 From: clockblocker Date: Thu, 26 Nov 2026 07:07:44 +0100 Subject: [PATCH 4/8] Add rfl::unwrap helper for nested metadata wrappers --- include/rfl.hpp | 1 + include/rfl/unwrap.hpp | 49 +++++++++++++++++++++++++++++++++++++++ tests/cli/test_unwrap.cpp | 37 +++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+) create mode 100644 include/rfl/unwrap.hpp create mode 100644 tests/cli/test_unwrap.cpp diff --git a/include/rfl.hpp b/include/rfl.hpp index 825544c50..c7abcafc4 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -96,6 +96,7 @@ #include "rfl/to_view.hpp" #include "rfl/tuple_cat.hpp" #include "rfl/type_name_t.hpp" +#include "rfl/unwrap.hpp" #include "rfl/view_t.hpp" #include "rfl/visit.hpp" diff --git a/include/rfl/unwrap.hpp b/include/rfl/unwrap.hpp new file mode 100644 index 000000000..9dd123977 --- /dev/null +++ b/include/rfl/unwrap.hpp @@ -0,0 +1,49 @@ +#ifndef RFL_UNWRAP_HPP_ +#define RFL_UNWRAP_HPP_ + +#include +#include + +#include "internal/is_default_val_v.hpp" +#include "internal/is_deprecated.hpp" +#include "internal/is_description.hpp" +#include "internal/is_group.hpp" +#include "internal/is_hidden.hpp" +#include "internal/is_implicit_value.hpp" +#include "internal/is_positional.hpp" +#include "internal/is_rename.hpp" +#include "internal/is_short.hpp" + +namespace rfl { + +namespace internal { + +template +constexpr bool is_metadata_wrapper_v = + is_default_val_v || is_description_v || is_deprecated_v || + is_rename_v || is_short_v || is_positional_v || + is_implicit_value_v || is_hidden_v || is_group_v; + +} // namespace internal + +/// Recursively unwraps reflect-cpp metadata wrappers (DefaultVal, Description, +/// Deprecated, Rename, Short, Positional, ImplicitValue, Hidden, Group) and +/// returns a reference to the underlying value. Does not unwrap std::optional, +/// pointers, or Validator. +template +constexpr decltype(auto) unwrap(T&& _val) noexcept { + using U = std::remove_cvref_t; + if constexpr (internal::is_metadata_wrapper_v) { + if constexpr (std::is_lvalue_reference_v) { + return unwrap(_val.value()); + } else { + return unwrap(std::move(_val.value())); + } + } else { + return std::forward(_val); + } +} + +} // namespace rfl + +#endif diff --git a/tests/cli/test_unwrap.cpp b/tests/cli/test_unwrap.cpp new file mode 100644 index 000000000..fd7a81cc7 --- /dev/null +++ b/tests/cli/test_unwrap.cpp @@ -0,0 +1,37 @@ +#include + +#include +#include +#include +#include + +namespace test_unwrap { + +struct Config { + rfl::Group<"COMMON OPTIONS", + rfl::Short<"v", rfl::Description<"Verbose", rfl::DefaultVal>>> + verbose = false; + rfl::Group<"OUTPUT OPTIONS", + rfl::Short<"o", rfl::Description<"Output", + std::optional>>> + output; + rfl::Hidden>> input = "in.osm"; +}; + +TEST(cli, test_unwrap_nested_wrappers) { + const std::vector args = {"-v", "-o", "out.osm"}; + const auto res = + rfl::cli::read(args); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_TRUE(rfl::unwrap(res->verbose)); + ASSERT_TRUE(rfl::unwrap(res->output).has_value()); + EXPECT_EQ(*rfl::unwrap(res->output), "out.osm"); + EXPECT_EQ(rfl::unwrap(res->input), "in.osm"); + + // Mutable reference works too. + auto cfg = *res; + rfl::unwrap(cfg.verbose) = false; + EXPECT_FALSE(rfl::unwrap(cfg.verbose)); +} + +} // namespace test_unwrap From 848977b993e88c58e039814529637f8f71c534a4 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Thu, 26 Nov 2026 20:50:38 +0100 Subject: [PATCH 5/8] Flatten nested rfl::Processors bundles in cli and generic entry points --- include/rfl/Processors.hpp | 26 +++++++++ include/rfl/cli/read.hpp | 3 +- include/rfl/cli/read_app.hpp | 6 ++- include/rfl/cli/resolve_args.hpp | 3 +- include/rfl/cli/usage.hpp | 6 ++- include/rfl/generic/read.hpp | 2 +- include/rfl/generic/write.hpp | 3 +- tests/cli/test_processor_bundles.cpp | 79 ++++++++++++++++++++++++++++ 8 files changed, 120 insertions(+), 8 deletions(-) create mode 100644 tests/cli/test_processor_bundles.cpp diff --git a/include/rfl/Processors.hpp b/include/rfl/Processors.hpp index c693dba8d..fc53ac7ec 100644 --- a/include/rfl/Processors.hpp +++ b/include/rfl/Processors.hpp @@ -42,6 +42,32 @@ struct Processors { } }; +namespace internal { + +template +struct flatten_processors; + +template +struct flatten_processors> { + using type = Processors; +}; + +template +struct flatten_processors, Processors, Rest...> + : flatten_processors, Inner..., Rest...> {}; + +template +struct flatten_processors, Head, Rest...> + : flatten_processors, Rest...> {}; + +/// Flattens arbitrarily nested rfl::Processors<...> bundles into a single +/// flat rfl::Processors<...> list, preserving left-to-right order. +template +using flatten_processors_t = + typename flatten_processors, Ps...>::type; + +} // namespace internal + } // namespace rfl #endif diff --git a/include/rfl/cli/read.hpp b/include/rfl/cli/read.hpp index 6cb7ed252..a22fde487 100644 --- a/include/rfl/cli/read.hpp +++ b/include/rfl/cli/read.hpp @@ -47,7 +47,8 @@ rfl::Result read_parsed(ParsedArgs _parsed, const Options& _options) { /// (see make_options) and returns ParsedArgs, and turns them into a struct. template rfl::Result parse_and_read(const ParseFn& _parse) { - using ProcessorsType = Processors; + using ProcessorsType = + rfl::internal::flatten_processors_t; static_assert(!internal::has_app_v, "rfl::cli::App turns on --help and --version, which " "rfl::cli::read cannot report. Call rfl::cli::read_app " diff --git a/include/rfl/cli/read_app.hpp b/include/rfl/cli/read_app.hpp index 4ab5cb336..9dc4c56ef 100644 --- a/include/rfl/cli/read_app.hpp +++ b/include/rfl/cli/read_app.hpp @@ -52,7 +52,8 @@ template rfl::Result> parse_and_read_app( const std::string& _program_name, const ParseFn& _parse, const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { - using ProcessorsType = Processors; + using ProcessorsType = + rfl::internal::flatten_processors_t; using ResultType = std::variant; auto options = make_options(); const auto builtin = add_builtin_options(&options); @@ -202,7 +203,8 @@ template > read_app( R&& _args, const UsageOptions& _usage_opts = UsageOptions{.detailed = true}) { - using ProcessorsType = Processors; + using ProcessorsType = + rfl::internal::flatten_processors_t; return read_app(internal::app_settings_t::name, std::forward(_args), _usage_opts); } diff --git a/include/rfl/cli/resolve_args.hpp b/include/rfl/cli/resolve_args.hpp index f43ba2046..abc6ad90f 100644 --- a/include/rfl/cli/resolve_args.hpp +++ b/include/rfl/cli/resolve_args.hpp @@ -227,7 +227,8 @@ rfl::Result> resolve_args( return rfl::error("Duplicate argument: --" + _parsed.later_occurrences.begin()->first); } - const auto options = internal::make_options(); + using FlatProcessors = rfl::internal::flatten_processors_t; + const auto options = internal::make_options(); const auto short_names = internal::check_short_names(options); if (!short_names) { return rfl::error(short_names.error().what()); diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 695efa5c4..9d882423f 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -774,7 +774,8 @@ inline std::string format_usage(const std::string& _program_name, /// default-constructible, which read requires, too. template std::optional usage_defaults() { - using ProcessorsType = Processors; + using ProcessorsType = + rfl::internal::flatten_processors_t; if constexpr (rfl::internal::default_if_missing_v && std::is_default_constructible_v) { try { @@ -814,7 +815,8 @@ std::optional usage_defaults() { template rfl::Result usage(const std::string& _program_name, const UsageOptions& _opts) { - using ProcessorsType = Processors; + using ProcessorsType = + rfl::internal::flatten_processors_t; using NamedTupleType = rfl::internal::processed_t; constexpr auto delimiter = internal::list_delimiter_v; // The table that read() parses with, so the help shows what the parser diff --git a/include/rfl/generic/read.hpp b/include/rfl/generic/read.hpp index 6d1a4c36f..aa301875e 100644 --- a/include/rfl/generic/read.hpp +++ b/include/rfl/generic/read.hpp @@ -19,7 +19,7 @@ namespace generic { template auto read(const Generic& _g) { const auto r = Reader(); - return Parser>::read(r, _g); + return Parser>::read(r, _g); } } // namespace generic diff --git a/include/rfl/generic/write.hpp b/include/rfl/generic/write.hpp index f6668ce8a..b8824493f 100644 --- a/include/rfl/generic/write.hpp +++ b/include/rfl/generic/write.hpp @@ -19,7 +19,8 @@ Generic write(const auto& _t) { using T = std::remove_cvref_t; using ParentType = parsing::Parent; auto w = Writer(); - Parser>::write(w, _t, typename ParentType::Root{}); + Parser>::write( + w, _t, typename ParentType::Root{}); return w.root(); } diff --git a/tests/cli/test_processor_bundles.cpp b/tests/cli/test_processor_bundles.cpp new file mode 100644 index 000000000..0a2aeed7e --- /dev/null +++ b/tests/cli/test_processor_bundles.cpp @@ -0,0 +1,79 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace test_processor_bundles { + +using BaseCli = rfl::Processors>; +using FullCli = + rfl::Processors>; +using AppBundle = + rfl::Processors, FullCli>; + +static_assert( + std::is_same_v< + rfl::internal::flatten_processors_t, + rfl::Processors, rfl::cli::PureFlags>>); + +struct Config { + rfl::Short<"v", rfl::DefaultVal> verbose = false; + std::optional output; + std::optional> items; + rfl::Positional>> ids; +}; + +TEST(cli, test_processor_bundle_read) { + const std::vector args = { + "--output", "out.txt", "--items", "a,b", "-v", "1", "2"}; + const auto res = rfl::cli::read(args); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_TRUE(rfl::unwrap(res->verbose)); + EXPECT_EQ(res->output, "out.txt"); + EXPECT_EQ(*res->items, (std::vector{"a,b"})); + EXPECT_EQ(rfl::unwrap(res->ids), (std::vector{"1", "2"})); + + const std::vector bad_args = {"--unknown"}; + const auto err = rfl::cli::read(bad_args); + EXPECT_FALSE(err); +} + +TEST(cli, test_processor_bundle_read_app_and_usage) { + const std::vector help_args = {"--help"}; + const auto res = rfl::cli::read_app(help_args); + ASSERT_TRUE(res) << res.error().what(); + const auto* info = std::get_if(&*res); + ASSERT_NE(info, nullptr); + EXPECT_EQ(info->kind, rfl::cli::HelpOrVersion::Kind::help); + EXPECT_NE(info->text.find("demo 2.0"), std::string::npos); + // PureFlags inside the nested bundle takes effect in usage(). + EXPECT_EQ(info->text.find("[=]"), std::string::npos) << info->text; + EXPECT_EQ(info->text.find("Default: false."), std::string::npos) + << info->text; + + const auto direct = rfl::cli::usage("demo", true); + ASSERT_TRUE(direct) << direct.error().what(); + EXPECT_EQ(*direct, info->text); +} + +TEST(cli, test_processor_bundle_default_if_missing) { + struct Simple { + int count = 7; + bool flag = false; + }; + using Bundle = rfl::Processors; + const auto text = rfl::cli::usage("simple", true); + ASSERT_TRUE(text) << text.error().what(); + EXPECT_NE(text->find("Default: 7."), std::string::npos) << *text; + EXPECT_EQ(text->find("Default: false."), std::string::npos) << *text; +} + +} // namespace test_processor_bundles From 00278eae7726f5dc5a381872fb663c9398d1d07d Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 08:01:50 +0100 Subject: [PATCH 6/8] Add UsageOptions::header, max_option_width, and hidden_groups to rfl::cli::usage --- include/rfl/cli/usage.hpp | 48 ++++++++++++++++++++++++++++++--- tests/cli/test_usage_custom.cpp | 48 +++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 3 deletions(-) diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 9d882423f..252c80dee 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -44,6 +44,9 @@ namespace rfl::cli { /// Runtime customization for `rfl::cli::usage` and `rfl::cli::read_app`. struct UsageOptions { bool detailed = true; + /// If non-empty, shown before the Usage line in detailed output (overrides + /// any header from rfl::cli::App). + std::string header = {}; /// If non-empty, replaces the auto-generated synopsis after "Usage: ". std::string synopsis = {}; /// If non-empty, shown after the Usage line in detailed output. @@ -53,6 +56,13 @@ struct UsageOptions { /// If non-empty, places built-in `--help` and `--version` in this group /// (at the start of the group if fields already use it). std::string help_group = {}; + /// Maximum left-column width used to align option descriptions; options + /// wider than this place their description on the next line instead of + /// widening every other row. Set to 0 for no cap. + size_t max_option_width = 40; + /// Group names to omit from generated detailed help output (e.g. conditional + /// feature groups hidden at runtime). + std::vector hidden_groups = {}; }; namespace internal { @@ -674,7 +684,18 @@ inline std::string format_usage(const std::string& _program_name, const std::optional _delimiter, const bool _options_first, const std::string& _header) { - auto out = _opts.detailed ? _header : std::string(); + auto out = std::string(); + if (_opts.detailed) { + if (!_opts.header.empty()) { + out += _opts.header; + if (!out.ends_with('\n')) { + out += '\n'; + } + out += '\n'; + } else { + out += _header; + } + } if (!_opts.synopsis.empty()) { out += "Usage: " + _opts.synopsis + "\n"; } else { @@ -708,7 +729,12 @@ inline std::string format_usage(const std::string& _program_name, for (const auto& arg : _args) { rows.emplace_back(usage_arg_to_string(arg, ", ", _delimiter), usage_help_text(arg)); - width = std::max(width, rows.back().first.size()); + const size_t row_w = rows.back().first.size(); + if (_opts.max_option_width == 0 || row_w <= _opts.max_option_width) { + width = std::max(width, row_w); + } else { + width = std::max(width, _opts.max_option_width); + } } constexpr size_t indent = 2; @@ -718,7 +744,11 @@ inline std::string format_usage(const std::string& _program_name, const std::string& _right) { out += std::string(indent, ' ') + _left; if (!_right.empty()) { - out += std::string(width - _left.size() + gap, ' '); + if (_left.size() <= width) { + out += std::string(width - _left.size() + gap, ' '); + } else { + out += continuation; + } for (const char c : _right) { if (c == '\n') { out += continuation; @@ -864,6 +894,18 @@ rfl::Result usage(const std::string& _program_name, args = std::move(builtin_args); args.insert(args.end(), fields.begin(), fields.end()); } + if (!_opts.hidden_groups.empty()) { + args.erase( + std::remove_if( + args.begin(), args.end(), + [&](const internal::UsageArg& _a) { + return !_a.group.empty() && + std::find(_opts.hidden_groups.begin(), + _opts.hidden_groups.end(), + _a.group) != _opts.hidden_groups.end(); + }), + args.end()); + } return internal::format_usage( _program_name, args, _opts, delimiter, options.options_first, internal::app_header(_program_name)); diff --git a/tests/cli/test_usage_custom.cpp b/tests/cli/test_usage_custom.cpp index 0a83917c0..32f1be14a 100644 --- a/tests/cli/test_usage_custom.cpp +++ b/tests/cli/test_usage_custom.cpp @@ -71,4 +71,52 @@ TEST(cli, test_usage_custom_synopsis_description_footer_and_help_group) { EXPECT_EQ(text.find("input-filenames"), std::string::npos); } +TEST(cli, test_usage_custom_header_before_usage) { + const rfl::cli::UsageOptions opts{ + .detailed = true, + .header = "solc, the Solidity commandline compiler.\n\nNo warranty.", + .synopsis = "solc [options] [input_file...]", + }; + const auto text = rfl::cli::usage("solc", opts); + ASSERT_TRUE(text) << text.error().what(); + EXPECT_TRUE(text->starts_with( + "solc, the Solidity commandline compiler.\n\nNo warranty.\n\n" + "Usage: solc [options] [input_file...]\n")) + << *text; +} + +TEST(cli, test_usage_max_option_width_wraps_wide_options) { + struct WideOptions { + rfl::Description<"Short flag", rfl::DefaultVal> verbose = false; + rfl::Description<"Very wide option label", std::optional> + very_long_option_name_exceeding_forty_characters; + }; + const auto text = + rfl::cli::usage("tool", true); + ASSERT_TRUE(text) << text.error().what(); + // Short option should not be padded past the 40-char cap. + EXPECT_EQ(text->find("--verbose "), + std::string::npos) + << *text; + // Wide option wraps its description onto the next line. + EXPECT_NE( + text->find( + "--very-long-option-name-exceeding-forty-characters=\n"), + std::string::npos) + << *text; +} + +TEST(cli, test_usage_hidden_groups) { + const rfl::cli::UsageOptions opts{ + .detailed = true, + .hidden_groups = {"INPUT OPTIONS"}, + }; + const auto text = rfl::cli::usage("osmium cat", opts); + ASSERT_TRUE(text) << text.error().what(); + EXPECT_NE(text->find("COMMAND OPTIONS:"), std::string::npos) << *text; + EXPECT_NE(text->find("COMMON OPTIONS:"), std::string::npos) << *text; + EXPECT_EQ(text->find("INPUT OPTIONS:"), std::string::npos) << *text; + EXPECT_EQ(text->find("--input-format"), std::string::npos) << *text; +} + } // namespace test_usage_custom From 7b5c737145fe2b6d484620f4be9400c100f4ee02 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 08:03:22 +0100 Subject: [PATCH 7/8] Deduplicate transparent CLI metadata wrappers via rfl::internal::TransparentWrapper --- include/rfl/Group.hpp | 116 ++--------- include/rfl/Hidden.hpp | 114 ++--------- include/rfl/ImplicitValue.hpp | 214 ++------------------ include/rfl/cli/options.hpp | 7 +- include/rfl/internal/TransparentWrapper.hpp | 114 +++++++++++ include/rfl/internal/is_default_val_v.hpp | 49 ++--- include/rfl/internal/is_group.hpp | 26 --- include/rfl/internal/is_hidden.hpp | 25 --- include/rfl/internal/is_implicit_value.hpp | 27 --- include/rfl/parsing/Parser_default.hpp | 8 +- include/rfl/unwrap.hpp | 12 +- 11 files changed, 184 insertions(+), 528 deletions(-) create mode 100644 include/rfl/internal/TransparentWrapper.hpp delete mode 100644 include/rfl/internal/is_group.hpp delete mode 100644 include/rfl/internal/is_hidden.hpp delete mode 100644 include/rfl/internal/is_implicit_value.hpp diff --git a/include/rfl/Group.hpp b/include/rfl/Group.hpp index d4987b83f..045737733 100644 --- a/include/rfl/Group.hpp +++ b/include/rfl/Group.hpp @@ -1,11 +1,8 @@ #ifndef RFL_GROUP_HPP_ #define RFL_GROUP_HPP_ -#include -#include - -#include "default.hpp" #include "internal/StringLiteral.hpp" +#include "internal/TransparentWrapper.hpp" namespace rfl { @@ -13,122 +10,41 @@ namespace rfl { /// `rfl::cli::usage` and `rfl::cli::read_app`. /// For non-CLI formats (JSON, YAML, etc.), this is transparent. template -struct Group { - /// The underlying type. - using Type = T; - - /// Every format reads and writes the underlying value directly. - using ReflectionType = Type; +struct Group : internal::TransparentWrapper, T> { + using Base = internal::TransparentWrapper, T>; + using Base::Base; + using Base::operator=; - /// The section header name. static constexpr auto group_name_ = _group; - static_assert(_group.length > 0, "Group name must not be empty."); Group() - requires std::is_default_constructible_v - : value_(Type()) {} - - Group(const Type& _value) : value_(_value) {} - - Group(Type&& _value) noexcept(std::is_nothrow_move_constructible_v) - : value_(std::move(_value)) {} - - Group(Group<_group, T>&& _field) = default; - - Group(const Group<_group, T>& _field) = default; + requires std::is_default_constructible_v + = default; + Group(const Group&) = default; + Group(Group&&) = default; + Group& operator=(const Group&) = default; + Group& operator=(Group&&) = default; template - Group(const Group<_group, U>& _field) : value_(_field.get()) {} + Group(const Group<_group, U>& _field) : Base(_field.get()) {} template Group(Group<_group, U>&& _field) noexcept( - std::is_nothrow_constructible_v) - : value_(std::move(_field.value_)) {} - - template - requires std::is_convertible_v - Group(const U& _value) : value_(_value) {} - - template - requires std::is_convertible_v - Group(U&& _value) noexcept(std::is_nothrow_constructible_v) - : value_(std::forward(_value)) {} - - template - requires std::is_default_constructible_v - Group(const Default&) : value_(Type()) {} - - ~Group() = default; - - const Type& get() const noexcept { return value_; } - - Type& get() noexcept { return value_; } - - Type& operator*() noexcept { return value_; } - - const Type& operator*() const noexcept { return value_; } - - Type& operator()() noexcept { return value_; } - - const Type& operator()() const noexcept { return value_; } - - Type* operator->() noexcept { return &value_; } - - const Type* operator->() const noexcept { return &value_; } - - auto& operator=(const Type& _value) { - value_ = _value; - return *this; - } - - auto& operator=(Type&& _value) noexcept( - std::is_nothrow_move_assignable_v) { - value_ = std::move(_value); - return *this; - } - - template - requires std::is_convertible_v - auto& operator=(const U& _value) { - value_ = _value; - return *this; - } - - template - requires std::is_default_constructible_v - auto& operator=(const Default&) { - value_ = Type(); - return *this; - } - - Group<_group, T>& operator=(const Group<_group, T>& _field) = default; - - Group<_group, T>& operator=(Group<_group, T>&& _field) = default; + std::is_nothrow_constructible_v) + : Base(std::move(_field.value_)) {} template auto& operator=(const Group<_group, U>& _field) { - value_ = _field.get(); + this->value_ = _field.get(); return *this; } template auto& operator=(Group<_group, U>&& _field) { - value_ = std::move(_field.value_); + this->value_ = std::move(_field.value_); return *this; } - - void set(const Type& _value) { value_ = _value; } - - void set(Type&& _value) { value_ = std::move(_value); } - - Type& value() noexcept { return value_; } - - const Type& value() const noexcept { return value_; } - - const Type& reflection() const { return value_; } - - Type value_; }; } // namespace rfl diff --git a/include/rfl/Hidden.hpp b/include/rfl/Hidden.hpp index 92d4f681d..8fad4f40b 100644 --- a/include/rfl/Hidden.hpp +++ b/include/rfl/Hidden.hpp @@ -1,10 +1,7 @@ #ifndef RFL_HIDDEN_HPP_ #define RFL_HIDDEN_HPP_ -#include -#include - -#include "default.hpp" +#include "internal/TransparentWrapper.hpp" namespace rfl { @@ -13,116 +10,37 @@ namespace rfl { /// parsing it normally. /// For non-CLI formats (JSON, YAML, etc.), this is transparent. template -struct Hidden { - /// The underlying type. - using Type = T; - - /// Every format reads and writes the underlying value directly. - using ReflectionType = Type; +struct Hidden : internal::TransparentWrapper, T> { + using Base = internal::TransparentWrapper, T>; + using Base::Base; + using Base::operator=; Hidden() - requires std::is_default_constructible_v - : value_(Type()) {} - - Hidden(const Type& _value) : value_(_value) {} - - Hidden(Type&& _value) noexcept(std::is_nothrow_move_constructible_v) - : value_(std::move(_value)) {} - - Hidden(Hidden&& _field) = default; - - Hidden(const Hidden& _field) = default; + requires std::is_default_constructible_v + = default; + Hidden(const Hidden&) = default; + Hidden(Hidden&&) = default; + Hidden& operator=(const Hidden&) = default; + Hidden& operator=(Hidden&&) = default; template - Hidden(const Hidden& _field) : value_(_field.get()) {} + Hidden(const Hidden& _field) : Base(_field.get()) {} template - Hidden(Hidden&& _field) noexcept(std::is_nothrow_constructible_v) - : value_(std::move(_field.value_)) {} - - template - requires std::is_convertible_v - Hidden(const U& _value) : value_(_value) {} - - template - requires std::is_convertible_v - Hidden(U&& _value) noexcept(std::is_nothrow_constructible_v) - : value_(std::forward(_value)) {} - - template - requires std::is_default_constructible_v - Hidden(const Default&) : value_(Type()) {} - - ~Hidden() = default; - - const Type& get() const noexcept { return value_; } - - Type& get() noexcept { return value_; } - - Type& operator*() noexcept { return value_; } - - const Type& operator*() const noexcept { return value_; } - - Type& operator()() noexcept { return value_; } - - const Type& operator()() const noexcept { return value_; } - - Type* operator->() noexcept { return &value_; } - - const Type* operator->() const noexcept { return &value_; } - - auto& operator=(const Type& _value) { - value_ = _value; - return *this; - } - - auto& operator=(Type&& _value) noexcept( - std::is_nothrow_move_assignable_v) { - value_ = std::move(_value); - return *this; - } - - template - requires std::is_convertible_v - auto& operator=(const U& _value) { - value_ = _value; - return *this; - } - - template - requires std::is_default_constructible_v - auto& operator=(const Default&) { - value_ = Type(); - return *this; - } - - Hidden& operator=(const Hidden& _field) = default; - - Hidden& operator=(Hidden&& _field) = default; + Hidden(Hidden&& _field) noexcept(std::is_nothrow_constructible_v) + : Base(std::move(_field.value_)) {} template auto& operator=(const Hidden& _field) { - value_ = _field.get(); + this->value_ = _field.get(); return *this; } template auto& operator=(Hidden&& _field) { - value_ = std::move(_field.value_); + this->value_ = std::move(_field.value_); return *this; } - - void set(const Type& _value) { value_ = _value; } - - void set(Type&& _value) { value_ = std::move(_value); } - - Type& value() noexcept { return value_; } - - const Type& value() const noexcept { return value_; } - - const Type& reflection() const { return value_; } - - Type value_; }; } // namespace rfl diff --git a/include/rfl/ImplicitValue.hpp b/include/rfl/ImplicitValue.hpp index c8a82c783..dcc8b9635 100644 --- a/include/rfl/ImplicitValue.hpp +++ b/include/rfl/ImplicitValue.hpp @@ -1,11 +1,8 @@ #ifndef RFL_IMPLICITVALUE_HPP_ #define RFL_IMPLICITVALUE_HPP_ -#include -#include - -#include "default.hpp" #include "internal/StringLiteral.hpp" +#include "internal/TransparentWrapper.hpp" namespace rfl { @@ -15,220 +12,43 @@ namespace rfl { /// positional argument. If the option is absent, the field is read as usual /// (std::optional gives std::nullopt, rfl::DefaultVal gives its default). /// For non-CLI formats (JSON, YAML, etc.), this is transparent. -/// @tparam T The type of the field -/// @tparam _implicit The CLI text that a bare option stands for. It is parsed -/// like any other value, so `rfl::ImplicitValue` is 1. template -struct ImplicitValue { - /// The underlying type. - using Type = T; - - /// Every format but the command line reads and writes the underlying - /// value, as for rfl::Description. - using ReflectionType = Type; +struct ImplicitValue + : internal::TransparentWrapper, T> { + using Base = internal::TransparentWrapper, T>; + using Base::Base; + using Base::operator=; - /// The value that a bare option stands for. static constexpr auto implicit_value_ = _implicit; - /// @brief Default constructor. - /// @details Constructs the underlying value using its default constructor. - /// @requires Type must be default constructible. ImplicitValue() - requires std::is_default_constructible_v - : value_(Type()) {} - - /// @brief Constructs the ImplicitValue wrapper from a const reference to - /// the underlying value. - /// @param _value The value to assign to the underlying field. - ImplicitValue(const Type& _value) : value_(_value) {} - - /// @brief Constructs the ImplicitValue wrapper by moving the underlying - /// value. - /// @param _value The value to move into the underlying field. - ImplicitValue(Type&& _value) noexcept( - std::is_nothrow_move_constructible_v) - : value_(std::move(_value)) {} - - /// @brief Move constructor. - /// @param _field The ImplicitValue field to move from. - ImplicitValue(ImplicitValue&& _field) = default; - - /// @brief Copy constructor. - /// @param _field The ImplicitValue field to copy from. - ImplicitValue(const ImplicitValue& _field) = default; + requires std::is_default_constructible_v + = default; + ImplicitValue(const ImplicitValue&) = default; + ImplicitValue(ImplicitValue&&) = default; + ImplicitValue& operator=(const ImplicitValue&) = default; + ImplicitValue& operator=(ImplicitValue&&) = default; - /// @brief Constructs from another ImplicitValue with a convertible - /// underlying type. - /// @tparam U The type of the other ImplicitValue's underlying value. - /// @param _field The other ImplicitValue field to copy from. template ImplicitValue(const ImplicitValue& _field) - : value_(_field.get()) {} + : Base(_field.get()) {} - /// @brief Move constructs from another ImplicitValue with a convertible - /// underlying type. - /// @tparam U The type of the other ImplicitValue's underlying value. - /// @param _field The other ImplicitValue field to move from. template ImplicitValue(ImplicitValue&& _field) noexcept( - std::is_nothrow_constructible_v) - : value_(std::move(_field.value_)) {} + std::is_nothrow_constructible_v) + : Base(std::move(_field.value_)) {} - /// @brief Constructs from a value convertible to the underlying type. - /// @tparam U The type of the value. - /// @param _value The value to assign. - template - requires std::is_convertible_v - ImplicitValue(const U& _value) : value_(_value) {} - - /// @brief Move constructs from a value convertible to the underlying type. - /// @tparam U The type of the value. - /// @param _value The value to move. - template - requires std::is_convertible_v - ImplicitValue(U&& _value) noexcept( - std::is_nothrow_constructible_v) - : value_(std::forward(_value)) {} - - /// @brief Constructs the underlying object to its default value using - /// Default tag. - /// @tparam U The type to default construct (defaults to Type). - /// @param unused Default tag. - template - requires std::is_default_constructible_v - ImplicitValue(const Default&) : value_(Type()) {} - - /// @brief Destructor. - /// @details Defaulted destructor for ImplicitValue. - ~ImplicitValue() = default; - - /// @brief Returns a const reference to the underlying object. - /// @return Const reference to the underlying value. - const Type& get() const noexcept { return value_; } - - /// @brief Returns a reference to the underlying object. - /// @return Reference to the underlying value. - Type& get() noexcept { return value_; } - - /// @brief Dereference operator. - /// @return Reference to the underlying value. - Type& operator*() noexcept { return value_; } - - /// @brief Dereference operator (const). - /// @return Const reference to the underlying value. - const Type& operator*() const noexcept { return value_; } - - /// @brief Function call operator. - /// @return Reference to the underlying value. - Type& operator()() noexcept { return value_; } - - /// @brief Function call operator (const). - /// @return Const reference to the underlying value. - const Type& operator()() const noexcept { return value_; } - - /// @brief Pointer to the underlying value. - /// @return Pointer to the underlying value. - Type* operator->() noexcept { return &value_; } - - /// @brief Pointer to the underlying value (const). - /// @return Const pointer to the underlying value. - const Type* operator->() const noexcept { return &value_; } - - /// @brief Assigns a new value to the underlying object. - /// @param _value The value to assign. - /// @return Reference to this ImplicitValue. - auto& operator=(const Type& _value) { - value_ = _value; - return *this; - } - - /// @brief Move-assigns a new value to the underlying object. - /// @param _value The value to move. - /// @return Reference to this ImplicitValue. - auto& operator=(Type&& _value) noexcept( - std::is_nothrow_move_assignable_v) { - value_ = std::move(_value); - return *this; - } - - /// @brief Assigns a value convertible to the underlying type. - /// @tparam U The type of the value. - /// @param _value The value to assign. - /// @return Reference to this ImplicitValue. - template - requires std::is_convertible_v - auto& operator=(const U& _value) { - value_ = _value; - return *this; - } - - /// @brief Assigns the underlying object to its default value using Default - /// tag. - /// @tparam U The type to default construct (defaults to Type). - /// @param unused Default tag. - /// @return Reference to this ImplicitValue. - template - requires std::is_default_constructible_v - auto& operator=(const Default&) { - value_ = Type(); - return *this; - } - - /// @brief Copy assignment operator. - /// @param _field The ImplicitValue field to copy from. - /// @return Reference to this ImplicitValue. - ImplicitValue& operator=( - const ImplicitValue& _field) = default; - - /// @brief Move assignment operator. - /// @param _field The ImplicitValue field to move from. - /// @return Reference to this ImplicitValue. - ImplicitValue& operator=( - ImplicitValue&& _field) = default; - - /// @brief Assigns from another ImplicitValue with a convertible underlying - /// type. - /// @tparam U The type of the other ImplicitValue's underlying value. - /// @param _field The other ImplicitValue field to copy from. - /// @return Reference to this ImplicitValue. template auto& operator=(const ImplicitValue& _field) { - value_ = _field.get(); + this->value_ = _field.get(); return *this; } - /// @brief Move-assigns from another ImplicitValue with a convertible - /// underlying type. - /// @tparam U The type of the other ImplicitValue's underlying value. - /// @param _field The other ImplicitValue field to move from. - /// @return Reference to this ImplicitValue. template auto& operator=(ImplicitValue&& _field) { - value_ = std::move(_field.value_); + this->value_ = std::move(_field.value_); return *this; } - - /// @brief Sets the underlying object to a new value. - /// @param _value The value to assign. - void set(const Type& _value) { value_ = _value; } - - /// @brief Sets the underlying object to a new value by moving. - /// @param _value The value to move. - void set(Type&& _value) { value_ = std::move(_value); } - - /// @brief Returns a reference to the underlying value. - /// @return Reference to the underlying value. - Type& value() noexcept { return value_; } - - /// @brief Returns a const reference to the underlying value. - /// @return Const reference to the underlying value. - const Type& value() const noexcept { return value_; } - - /// Returns the underlying value for reflection (used by parsers). - const Type& reflection() const { return value_; } - - /// The underlying value. - Type value_; }; } // namespace rfl diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index c4d17a3b0..d4cd500ef 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -23,11 +23,10 @@ #include "../Short.hpp" #include "../Tuple.hpp" #include "../internal/StringLiteral.hpp" +#include "../internal/TransparentWrapper.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/has_reflector.hpp" #include "../internal/is_extra_fields.hpp" -#include "../internal/is_group.hpp" -#include "../internal/is_hidden.hpp" #include "../internal/is_named_tuple.hpp" #include "../internal/is_positional.hpp" #include "../internal/is_short.hpp" @@ -405,9 +404,7 @@ auto unwrap_option_type() { } else if constexpr (rfl::internal::is_short_v || rfl::internal::is_positional_v - || rfl::internal::is_implicit_value_v - || rfl::internal::is_hidden_v - || rfl::internal::is_group_v + || rfl::internal::is_transparent_wrapper_v || parsing::is_rename_v || parsing::is_default_val_v || parsing::is_skip_v) { diff --git a/include/rfl/internal/TransparentWrapper.hpp b/include/rfl/internal/TransparentWrapper.hpp new file mode 100644 index 000000000..1004cf6dc --- /dev/null +++ b/include/rfl/internal/TransparentWrapper.hpp @@ -0,0 +1,114 @@ +#ifndef RFL_INTERNAL_TRANSPARENT_WRAPPER_HPP_ +#define RFL_INTERNAL_TRANSPARENT_WRAPPER_HPP_ + +#include +#include + +#include "../default.hpp" + +namespace rfl::internal { + +/// CRTP base for transparent metadata wrappers (ImplicitValue, Hidden, Group, +/// ValueName, MultiToken, etc.) that hold a single `Type value_` and are +/// transparent to non-CLI serialization formats via `ReflectionType = Type`. +template +struct TransparentWrapper { + using Type = T; + using ReflectionType = Type; + static constexpr bool is_transparent_wrapper_ = true; + + TransparentWrapper() + requires std::is_default_constructible_v + : value_(Type()) {} + + TransparentWrapper(const Type& _value) : value_(_value) {} + + TransparentWrapper(Type&& _value) noexcept( + std::is_nothrow_move_constructible_v) + : value_(std::move(_value)) {} + + TransparentWrapper(const TransparentWrapper&) = default; + TransparentWrapper(TransparentWrapper&&) = default; + + template + requires std::is_convertible_v + TransparentWrapper(const U& _value) : value_(_value) {} + + template + requires std::is_convertible_v + TransparentWrapper(U&& _value) noexcept( + std::is_nothrow_constructible_v) + : value_(std::forward(_value)) {} + + template + requires std::is_default_constructible_v + TransparentWrapper(const Default&) : value_(Type()) {} + + ~TransparentWrapper() = default; + + TransparentWrapper& operator=(const TransparentWrapper&) = default; + TransparentWrapper& operator=(TransparentWrapper&&) = default; + + const Type& get() const noexcept { return value_; } + Type& get() noexcept { return value_; } + + Type& operator*() noexcept { return value_; } + const Type& operator*() const noexcept { return value_; } + + Type& operator()() noexcept { return value_; } + const Type& operator()() const noexcept { return value_; } + + Type* operator->() noexcept { return &value_; } + const Type* operator->() const noexcept { return &value_; } + + Derived& operator=(const Type& _value) { + value_ = _value; + return static_cast(*this); + } + + Derived& operator=(Type&& _value) noexcept( + std::is_nothrow_move_assignable_v) { + value_ = std::move(_value); + return static_cast(*this); + } + + template + requires std::is_convertible_v + Derived& operator=(const U& _value) { + value_ = _value; + return static_cast(*this); + } + + template + requires std::is_default_constructible_v + Derived& operator=(const Default&) { + value_ = Type(); + return static_cast(*this); + } + + void set(const Type& _value) { value_ = _value; } + void set(Type&& _value) { value_ = std::move(_value); } + + Type& value() noexcept { return value_; } + const Type& value() const noexcept { return value_; } + + const Type& reflection() const { return value_; } + + Type value_; +}; + +template +concept TransparentWrapperType = + !std::is_pointer_v> && + requires { + typename std::remove_cvref_t::Type; + requires std::remove_cvref_t::is_transparent_wrapper_ == true; + }; + +template +constexpr bool is_transparent_wrapper_v = + TransparentWrapperType>>; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/is_default_val_v.hpp b/include/rfl/internal/is_default_val_v.hpp index cbccb3722..942c86ed1 100644 --- a/include/rfl/internal/is_default_val_v.hpp +++ b/include/rfl/internal/is_default_val_v.hpp @@ -7,13 +7,11 @@ #include "../DefaultVal.hpp" #include "../Deprecated.hpp" #include "../Description.hpp" -#include "../Group.hpp" -#include "../Hidden.hpp" -#include "../ImplicitValue.hpp" #include "../Positional.hpp" #include "../Rename.hpp" #include "../Short.hpp" #include "StringLiteral.hpp" +#include "TransparentWrapper.hpp" namespace rfl::internal { @@ -47,22 +45,17 @@ template > : public is_default_val {}; -template -class is_default_val> : public is_default_val { -}; - template -class is_default_val> : public is_default_val {}; - -template -class is_default_val> : public is_default_val {}; + requires TransparentWrapperType +class is_default_val : public is_default_val {}; template constexpr bool is_default_val_v = is_default_val>>::value; -/// Whether T is an rfl::DefaultVal itself or inside rfl::Rename, but not -/// inside rfl::Short, rfl::Positional, rfl::Description or rfl::Deprecated. +/// Whether T is an rfl::DefaultVal itself or inside rfl::Rename / transparent +/// CLI wrappers, but not inside rfl::Short, rfl::Positional, rfl::Description +/// or rfl::Deprecated. template class is_unwrapped_default_val : public std::false_type {}; @@ -73,33 +66,15 @@ template class is_unwrapped_default_val>> : public std::true_type {}; -// rfl::ImplicitValue is transparent to every format but the command line, so -// a DefaultVal in it counts as unwrapped. -template -class is_unwrapped_default_val> - : public is_unwrapped_default_val {}; - -template -class is_unwrapped_default_val>> - : public is_unwrapped_default_val {}; - template -class is_unwrapped_default_val> - : public is_unwrapped_default_val {}; + requires TransparentWrapperType +class is_unwrapped_default_val + : public is_unwrapped_default_val {}; template -class is_unwrapped_default_val>> - : public is_unwrapped_default_val {}; - -template -class is_unwrapped_default_val> - : public is_unwrapped_default_val {}; - -template -class is_unwrapped_default_val>> - : public is_unwrapped_default_val {}; + requires TransparentWrapperType +class is_unwrapped_default_val> + : public is_unwrapped_default_val {}; template constexpr bool is_unwrapped_default_val_v = is_unwrapped_default_val< diff --git a/include/rfl/internal/is_group.hpp b/include/rfl/internal/is_group.hpp deleted file mode 100644 index 2fc099fa2..000000000 --- a/include/rfl/internal/is_group.hpp +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef RFL_INTERNAL_ISGROUP_HPP_ -#define RFL_INTERNAL_ISGROUP_HPP_ - -#include - -#include "../Group.hpp" -#include "StringLiteral.hpp" - -namespace rfl::internal { - -template -class is_group; - -template -class is_group : public std::false_type {}; - -template -class is_group> : public std::true_type {}; - -template -constexpr bool is_group_v = - is_group>>::value; - -} // namespace rfl::internal - -#endif diff --git a/include/rfl/internal/is_hidden.hpp b/include/rfl/internal/is_hidden.hpp deleted file mode 100644 index d2c197256..000000000 --- a/include/rfl/internal/is_hidden.hpp +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef RFL_INTERNAL_ISHIDDEN_HPP_ -#define RFL_INTERNAL_ISHIDDEN_HPP_ - -#include - -#include "../Hidden.hpp" - -namespace rfl::internal { - -template -class is_hidden; - -template -class is_hidden : public std::false_type {}; - -template -class is_hidden> : public std::true_type {}; - -template -constexpr bool is_hidden_v = - is_hidden>>::value; - -} // namespace rfl::internal - -#endif diff --git a/include/rfl/internal/is_implicit_value.hpp b/include/rfl/internal/is_implicit_value.hpp deleted file mode 100644 index efcb9b518..000000000 --- a/include/rfl/internal/is_implicit_value.hpp +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef RFL_INTERNAL_ISIMPLICITVALUE_HPP_ -#define RFL_INTERNAL_ISIMPLICITVALUE_HPP_ - -#include - -#include "../ImplicitValue.hpp" -#include "StringLiteral.hpp" - -namespace rfl::internal { - -template -class is_implicit_value; - -template -class is_implicit_value : public std::false_type {}; - -template -class is_implicit_value> - : public std::true_type {}; - -template -constexpr bool is_implicit_value_v = - is_implicit_value>>::value; - -} // namespace rfl::internal - -#endif diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index bec8d823b..17a9a75d6 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -15,12 +15,10 @@ #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/has_reflector.hpp" +#include "../internal/TransparentWrapper.hpp" #include "../internal/is_basic_type.hpp" #include "../internal/is_deprecated.hpp" #include "../internal/is_description.hpp" -#include "../internal/is_group.hpp" -#include "../internal/is_hidden.hpp" -#include "../internal/is_implicit_value.hpp" #include "../internal/is_literal.hpp" #include "../internal/is_validator.hpp" #include "../internal/processed_t.hpp" @@ -555,9 +553,7 @@ struct Parser { return ParserPositional::to_schema(_definitions); - } else if constexpr (rfl::internal::is_implicit_value::value || - rfl::internal::is_hidden::value || - rfl::internal::is_group::value) { + } else if constexpr (rfl::internal::is_transparent_wrapper_v) { // Read and written through its ReflectionType, but described as the // type itself rather than as a named reference, like rfl::Short. return Parser::to_schema( diff --git a/include/rfl/unwrap.hpp b/include/rfl/unwrap.hpp index 9dd123977..9a1dd4acf 100644 --- a/include/rfl/unwrap.hpp +++ b/include/rfl/unwrap.hpp @@ -4,12 +4,10 @@ #include #include +#include "internal/TransparentWrapper.hpp" #include "internal/is_default_val_v.hpp" #include "internal/is_deprecated.hpp" #include "internal/is_description.hpp" -#include "internal/is_group.hpp" -#include "internal/is_hidden.hpp" -#include "internal/is_implicit_value.hpp" #include "internal/is_positional.hpp" #include "internal/is_rename.hpp" #include "internal/is_short.hpp" @@ -22,14 +20,14 @@ template constexpr bool is_metadata_wrapper_v = is_default_val_v || is_description_v || is_deprecated_v || is_rename_v || is_short_v || is_positional_v || - is_implicit_value_v || is_hidden_v || is_group_v; + is_transparent_wrapper_v; } // namespace internal /// Recursively unwraps reflect-cpp metadata wrappers (DefaultVal, Description, -/// Deprecated, Rename, Short, Positional, ImplicitValue, Hidden, Group) and -/// returns a reference to the underlying value. Does not unwrap std::optional, -/// pointers, or Validator. +/// Deprecated, Rename, Short, Positional, and all transparent CLI wrappers) +/// and returns a reference to the underlying value. Does not unwrap +/// std::optional, pointers, or Validator. template constexpr decltype(auto) unwrap(T&& _val) noexcept { using U = std::remove_cvref_t; From 86f4632ad458e5cdf52bb42e716186b94c98ee73 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 08:05:19 +0100 Subject: [PATCH 8/8] Add rfl::ValueName and rfl::MultiToken wrappers for rfl::cli --- include/rfl.hpp | 2 ++ include/rfl/MultiToken.hpp | 51 +++++++++++++++++++++++++++++++ include/rfl/ValueName.hpp | 52 ++++++++++++++++++++++++++++++++ include/rfl/cli/options.hpp | 37 +++++++++++++++++++++-- include/rfl/cli/parse_argv.hpp | 21 +++++++++++-- include/rfl/cli/usage.hpp | 16 ++++++++-- tests/cli/test_multi_token.cpp | 55 ++++++++++++++++++++++++++++++++++ tests/cli/test_value_name.cpp | 41 +++++++++++++++++++++++++ 8 files changed, 268 insertions(+), 7 deletions(-) create mode 100644 include/rfl/MultiToken.hpp create mode 100644 include/rfl/ValueName.hpp create mode 100644 tests/cli/test_multi_token.cpp create mode 100644 tests/cli/test_value_name.cpp diff --git a/include/rfl.hpp b/include/rfl.hpp index c7abcafc4..5017f09ca 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -34,6 +34,7 @@ #include "rfl/Hidden.hpp" #include "rfl/ImplicitValue.hpp" #include "rfl/Literal.hpp" +#include "rfl/MultiToken.hpp" #include "rfl/NamedTuple.hpp" #include "rfl/NoExtraFields.hpp" #include "rfl/NoFieldNames.hpp" @@ -59,6 +60,7 @@ #include "rfl/ToAllCaps.hpp" #include "rfl/UnderlyingEnums.hpp" #include "rfl/Validator.hpp" +#include "rfl/ValueName.hpp" #include "rfl/Variant.hpp" #include "rfl/Vectorstring.hpp" #include "rfl/always_false.hpp" diff --git a/include/rfl/MultiToken.hpp b/include/rfl/MultiToken.hpp new file mode 100644 index 000000000..8354dd241 --- /dev/null +++ b/include/rfl/MultiToken.hpp @@ -0,0 +1,51 @@ +#ifndef RFL_MULTITOKEN_HPP_ +#define RFL_MULTITOKEN_HPP_ + +#include "internal/TransparentWrapper.hpp" + +namespace rfl { + +/// Marks a CLI list option (such as `std::vector`) as accepting +/// multiple space-separated tokens after a single option occurrence (like +/// Boost.Program_options's `multitoken()` or argparse's `nargs='+'`), e.g.: +/// `--population a b c --rounds 5` +/// Consumes subsequent tokens until the next option or `--`. +/// For non-CLI formats (JSON, YAML, etc.), this is transparent. +template +struct MultiToken : internal::TransparentWrapper, T> { + using Base = internal::TransparentWrapper, T>; + using Base::Base; + using Base::operator=; + + MultiToken() + requires std::is_default_constructible_v + = default; + MultiToken(const MultiToken&) = default; + MultiToken(MultiToken&&) = default; + MultiToken& operator=(const MultiToken&) = default; + MultiToken& operator=(MultiToken&&) = default; + + template + MultiToken(const MultiToken& _field) : Base(_field.get()) {} + + template + MultiToken(MultiToken&& _field) noexcept( + std::is_nothrow_constructible_v) + : Base(std::move(_field.value_)) {} + + template + auto& operator=(const MultiToken& _field) { + this->value_ = _field.get(); + return *this; + } + + template + auto& operator=(MultiToken&& _field) { + this->value_ = std::move(_field.value_); + return *this; + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/ValueName.hpp b/include/rfl/ValueName.hpp new file mode 100644 index 000000000..b1ee28693 --- /dev/null +++ b/include/rfl/ValueName.hpp @@ -0,0 +1,52 @@ +#ifndef RFL_VALUENAME_HPP_ +#define RFL_VALUENAME_HPP_ + +#include "internal/StringLiteral.hpp" +#include "internal/TransparentWrapper.hpp" + +namespace rfl { + +/// Sets a custom value placeholder name (metavar, e.g. `"path"` or `""`) +/// for a CLI option in `rfl::cli::usage` and `rfl::cli::read_app`. +/// For non-CLI formats (JSON, YAML, etc.), this is transparent. +template +struct ValueName : internal::TransparentWrapper, T> { + using Base = internal::TransparentWrapper, T>; + using Base::Base; + using Base::operator=; + + static constexpr auto value_name_ = _value_name; + static_assert(_value_name.length > 0, "ValueName must not be empty."); + + ValueName() + requires std::is_default_constructible_v + = default; + ValueName(const ValueName&) = default; + ValueName(ValueName&&) = default; + ValueName& operator=(const ValueName&) = default; + ValueName& operator=(ValueName&&) = default; + + template + ValueName(const ValueName<_value_name, U>& _field) : Base(_field.get()) {} + + template + ValueName(ValueName<_value_name, U>&& _field) noexcept( + std::is_nothrow_constructible_v) + : Base(std::move(_field.value_)) {} + + template + auto& operator=(const ValueName<_value_name, U>& _field) { + this->value_ = _field.get(); + return *this; + } + + template + auto& operator=(ValueName<_value_name, U>&& _field) { + this->value_ = std::move(_field.value_); + return *this; + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index d4cd500ef..b42cb60a1 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -18,10 +18,12 @@ #include "../Group.hpp" #include "../Hidden.hpp" #include "../ImplicitValue.hpp" +#include "../MultiToken.hpp" #include "../Positional.hpp" #include "../Rename.hpp" #include "../Short.hpp" #include "../Tuple.hpp" +#include "../ValueName.hpp" #include "../internal/StringLiteral.hpp" #include "../internal/TransparentWrapper.hpp" #include "../internal/has_reflection_type_v.hpp" @@ -76,6 +78,10 @@ struct Option { /// when it is given without one. It views the rfl::ImplicitValue's /// template argument, which lives as long as the program. std::string_view implicit_value = {}; + + /// Whether a list option consumes multiple space-separated tokens after one + /// occurrence (rfl::MultiToken). + bool multi_token = false; }; /// The options that a target struct accepts, built from its fields by @@ -116,6 +122,9 @@ struct Options { /// Section header name for fields wrapped in rfl::Group, by path. std::map option_groups; + /// Custom value placeholder name for fields wrapped in rfl::ValueName, by path. + std::map option_value_names; + /// Whether options that match no field are an error (rfl::NoExtraFields). bool reject_unknown = false; @@ -277,11 +286,14 @@ struct cli_annotations { static constexpr bool is_positional = false; static constexpr bool is_hidden = false; static constexpr bool has_group = false; + static constexpr bool has_value_name = false; + static constexpr bool is_multi_token = false; static constexpr size_t num_implicit_value = 0; static constexpr rfl::internal::StringLiteral<1> short_name = ""; static constexpr int count = 0; static constexpr rfl::internal::StringLiteral<1> implicit_value = ""; static constexpr rfl::internal::StringLiteral<1> group_name = ""; + static constexpr rfl::internal::StringLiteral<1> value_name = ""; }; template @@ -337,6 +349,17 @@ struct cli_annotations> : cli_annotations_t { static constexpr auto group_name = _group; }; +template +struct cli_annotations> : cli_annotations_t { + static constexpr bool has_value_name = true; + static constexpr auto value_name = _value_name; +}; + +template +struct cli_annotations> : cli_annotations_t { + static constexpr bool is_multi_token = true; +}; + /// The CLI metadata of the _i-th field of a NamedTuple. InnerType is the /// declared type of the field, whichever wrappers it consists of. template @@ -512,6 +535,8 @@ Option implicit_value_option() { template Option option_for() { using U = unwrapped_option_t; + static_assert(!cli_annotations_t::is_multi_token || is_option_list_v, + "rfl::MultiToken can only wrap a list type (such as std::vector)."); if constexpr (cli_annotations_t::num_implicit_value > 0) { return implicit_value_option(); } @@ -523,7 +548,8 @@ Option option_for() { return Option{OptionKind::other}; } else { - return Option{OptionKind::value, is_option_list_v}; + return Option{OptionKind::value, is_option_list_v, {}, + cli_annotations_t::is_multi_token}; } } @@ -577,6 +603,10 @@ void add_option(const std::string& _path, Options* _options) { _options->option_groups[_path] = std::string(cli_annotations_t::group_name.string_view()); } + if constexpr (cli_annotations_t::has_value_name) { + _options->option_value_names[_path] = + std::string(cli_annotations_t::value_name.string_view()); + } if constexpr (cli_annotations_t::num_implicit_value > 0) { _options->long_options[_path] = implicit_value_option(); @@ -603,8 +633,11 @@ void add_option(const std::string& _path, Options* _options) { } } else { + static_assert(!cli_annotations_t::is_multi_token || is_option_list_v, + "rfl::MultiToken can only wrap a list type (such as std::vector)."); _options->long_options[_path] = - Option{OptionKind::value, is_option_list_v}; + Option{OptionKind::value, is_option_list_v, {}, + cli_annotations_t::is_multi_token}; } } diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index c793518f2..f8581864d 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -222,6 +222,7 @@ inline rfl::Result parse_string_views( if (option.kind == OptionKind::unknown && _options.reject_unknown) { return error("Unknown option '--" + key + "'."); } + bool consume_multi = false; if (eq == std::string_view::npos && option.kind == OptionKind::value && _options.separate_values) { // --key value (rfl::cli::SeparateOptionValues). A flag never takes @@ -230,6 +231,7 @@ inline rfl::Result parse_string_views( auto v = take_value(option, "--" + key, &i); if (!v) { return error(v.error().what()); } val = std::move(*v); + consume_multi = option.multi_token; } else if (eq == std::string_view::npos && option.kind == OptionKind::implicit_value) { @@ -237,8 +239,14 @@ inline rfl::Result parse_string_views( // implicit value. val = std::string(option.implicit_value); } - const auto r = add_long(std::move(key), std::move(val), option, arg_raw); + const auto r = add_long(key, std::move(val), option, arg_raw); if (!r) { return error(r.error().what()); } + while (consume_multi && i + 1 < _args.size() && _args[i + 1] != "--" + && !looks_like_option(_args[i + 1])) { + const auto r2 = + add_long(key, std::string(_args[++i]), option, arg_raw); + if (!r2) { return error(r2.error().what()); } + } continue; } @@ -274,6 +282,7 @@ inline rfl::Result parse_string_views( const bool alone = j == 0 && rest.empty(); auto val = std::string(); + bool consume_multi = false; if (j == 0 && rest.starts_with('=')) { // -x=value, whatever -x is. Unlike getopt, where -f=csv gives // "=csv", the '=' is not part of the value. @@ -314,11 +323,17 @@ inline rfl::Result parse_string_views( auto v = take_value(option, name, &i); if (!v) { return error(v.error().what()); } val = std::move(*v); + consume_multi = option.multi_token; } - const auto r = - add_short(std::move(key), std::move(val), option, arg_raw); + const auto r = add_short(key, std::move(val), option, arg_raw); if (!r) { return error(r.error().what()); } + while (consume_multi && i + 1 < _args.size() && _args[i + 1] != "--" + && !looks_like_option(_args[i + 1])) { + const auto r2 = + add_short(key, std::string(_args[++i]), option, arg_raw); + if (!r2) { return error(r2.error().what()); } + } break; } continue; diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 252c80dee..e771c0e0a 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -88,6 +88,8 @@ struct UsageArg { std::string implicit_value; /// Whether the field is a list, which can be repeated. bool is_list = false; + /// Whether the field accepts multiple space-separated tokens (rfl::MultiToken). + bool multi_token = false; /// Whether the field is the last positional one and a list, so that it /// takes the remaining positional arguments. bool takes_rest = false; @@ -101,6 +103,8 @@ struct UsageArg { /// The placeholder for one value: "", "" or "". Lists /// are rendered from it with the list delimiter. std::string value = ""; + /// Whether `value` was explicitly set via rfl::ValueName. + bool has_custom_value_name = false; /// The allowed values of enums and literals. std::vector choices; std::string description; @@ -514,6 +518,7 @@ class UsageCollector { _arg.kind = option.kind; _arg.implicit_value = std::string(option.implicit_value); _arg.is_list = option.is_list; + _arg.multi_token = option.multi_token; const bool pure_flag = options_->pure_flags && _arg.kind == OptionKind::flag && !_arg.positional; if (pure_flag) { @@ -529,6 +534,13 @@ class UsageCollector { it != options_->option_groups.end()) { _arg.group = it->second; } + if (const auto it = options_->option_value_names.find(_arg.name); + it != options_->option_value_names.end()) { + const auto& vn = it->second; + _arg.value = + (!vn.empty() && vn.front() == '<' && vn.back() == '>') ? vn : "<" + vn + ">"; + _arg.has_custom_value_name = true; + } args_.emplace_back(std::move(_arg)); } @@ -561,7 +573,7 @@ class UsageCollector { /// (ListDelimiter<"">), every occurrence is one item: "". inline std::string usage_value_to_string(const UsageArg& _arg, const std::optional _delimiter) { - if (!_arg.is_list || !_delimiter) { + if (_arg.has_custom_value_name || !_arg.is_list || !_delimiter) { return _arg.value; } const auto d = std::string(1, *_delimiter); @@ -592,7 +604,7 @@ inline std::string usage_arg_to_string(const UsageArg& _arg, str += "[=" + value + "]"; break; default: - str += "=" + value; + str += "=" + value + (_arg.multi_token ? "..." : ""); break; } return str; diff --git a/tests/cli/test_multi_token.cpp b/tests/cli/test_multi_token.cpp new file mode 100644 index 000000000..df10ce131 --- /dev/null +++ b/tests/cli/test_multi_token.cpp @@ -0,0 +1,55 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_multi_token { + +struct PhaserLike { + rfl::MultiToken", std::optional>>> + population; + rfl::Short<"p", rfl::MultiToken>>> + files; + std::optional rounds; + rfl::Positional>> input_files; +}; + +using Cli = rfl::Processors, rfl::cli::PureFlags>; + +TEST(cli, test_multi_token_long_and_stop_at_next_option_or_double_dash) { + const std::vector args = { + "--population", "a", "afc", "xadd", "--rounds", "10", "--", "prog.yul"}; + const auto res = rfl::cli::read(args); + ASSERT_TRUE(res) << res.error().what(); + ASSERT_TRUE(rfl::unwrap(res->population).has_value()); + EXPECT_EQ(*rfl::unwrap(res->population), + (std::vector{"a", "afc", "xadd"})); + EXPECT_EQ(res->rounds, 10); + ASSERT_TRUE(rfl::unwrap(res->input_files).has_value()); + EXPECT_EQ(*rfl::unwrap(res->input_files), + (std::vector{"prog.yul"})); +} + +TEST(cli, test_multi_token_repeated_and_short) { + const std::vector args = { + "--population", "a", "b", "--population=c", "-p", "f1", "f2"}; + const auto res = rfl::cli::read(args); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(*rfl::unwrap(res->population), + (std::vector{"a", "b", "c"})); + EXPECT_EQ(*rfl::unwrap(res->files), (std::vector{"f1", "f2"})); +} + +TEST(cli, test_multi_token_usage) { + const auto help = rfl::cli::usage("yul-phaser", true); + ASSERT_TRUE(help) << help.error().what(); + EXPECT_NE(help->find("--population=..."), std::string::npos) + << *help; + EXPECT_NE(help->find("-p, --files=..."), std::string::npos) << *help; +} + +} // namespace test_multi_token diff --git a/tests/cli/test_value_name.cpp b/tests/cli/test_value_name.cpp new file mode 100644 index 000000000..75c9a7631 --- /dev/null +++ b/tests/cli/test_value_name.cpp @@ -0,0 +1,41 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_value_name { + +struct SolcLike { + rfl::Short<"o", rfl::ValueName<"path", rfl::Description<"Output directory", + std::optional>>> + output_dir; + rfl::ValueName<"n", rfl::Description<"Optimizer runs", rfl::DefaultVal>> + optimize_runs = 200; + rfl::ValueName<"", std::optional>> include_path; +}; + +TEST(cli, test_value_name_parsing_and_usage) { + const std::vector args = {"-o", "/tmp/out", "--optimize-runs", + "500", "--include-path", "/a"}; + const auto res = + rfl::cli::read(args); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(rfl::unwrap(res->output_dir), "/tmp/out"); + EXPECT_EQ(rfl::unwrap(res->optimize_runs), 500); + ASSERT_TRUE(rfl::unwrap(res->include_path).has_value()); + EXPECT_EQ(*rfl::unwrap(res->include_path), (std::vector{"/a"})); + + const auto help = rfl::cli::usage("solc", true); + ASSERT_TRUE(help) << help.error().what(); + EXPECT_NE(help->find("-o, --output-dir="), std::string::npos) << *help; + EXPECT_NE(help->find("--optimize-runs="), std::string::npos) << *help; + EXPECT_NE(help->find("Default: 200."), std::string::npos) << *help; + // Already bracketed value names are not double-wrapped. + EXPECT_NE(help->find("--include-path="), std::string::npos) << *help; + EXPECT_EQ(help->find("<>"), std::string::npos) << *help; +} + +} // namespace test_value_name