From a8e9707496357f0ec815404736327408b73a65da Mon Sep 17 00:00:00 2001 From: clockblocker Date: Tue, 10 Nov 2026 09:58:03 +0100 Subject: [PATCH 1/2] Add rfl::cli::usage to generate usage and help text rfl::cli::read prints nothing for --help, so every program that parses its options with it has to write and maintain its help text by hand, and the text drifts from what the parser accepts. usage(program_name, detailed) generates the usage line proposed in #692, and with detailed = true one aligned row per argument. It walks the format-agnostic schema (rfl::parsing::schema), which already resolves processors, Rename, Flatten, nested structs, descriptions, validators, enums, literals, optionals and DefaultVal defaults, so rfl::cli does not depend on the JSON backend. Positional, Short and whether a top-level field is required come from the same compile-time traits as resolve_args and the parser. The schema cannot tell them: Short and Positional are invisible in it, and it marks a DefaultVal field as optional even where the parser requires it, because the struct cannot be default-constructed to take the default from. In nested structs, a DefaultVal field is shown as optional only if the schema has its default, which it has only if the struct could be default-constructed. Defaults are shown for DefaultVal fields, and for all fields when rfl::DefaultIfMissing is passed and T is default-constructible. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 108 +++++ include/rfl/cli.hpp | 1 + include/rfl/cli/usage.hpp | 616 ++++++++++++++++++++++++++ tests/cli/test_usage.cpp | 406 +++++++++++++++++ 4 files changed, 1131 insertions(+) create mode 100644 include/rfl/cli/usage.hpp create mode 100644 tests/cli/test_usage.cpp diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 93a1084b8..c65cf11c3 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -154,6 +154,113 @@ a `std::optional` or an `rfl::DefaultVal`, so the argument may be omitted: with `rfl::Short<"o", rfl::DefaultVal> output_dir = "out";`, leaving out `-o` gives `"out"`. +## Usage / help + +`rfl::cli::usage(program_name, detailed = false)` generates the +help text from the same struct, and with the same processors, as +`rfl::cli::read()`. So the names always match what the parser +accepts, including kebab-case, `rfl::Rename`, `rfl::Flatten` and nested paths. + +```cpp +enum class LogLevel { debug, info, warn }; + +struct Database { + std::string host; + int port; +}; + +struct Config { + rfl::Positional> + input_file; + rfl::Short<"p", rfl::Description<"Port to listen on", + rfl::Validator, + rfl::Maximum<65535>>>> + port; + rfl::Description<"Minimum level to log", std::optional> log_level; + rfl::Description<"Tags to attach", + rfl::Validator, + rfl::Size>>> + tags; + Database database; +}; +``` + +`rfl::cli::usage("app")` returns the usage line, where optional +arguments are in brackets: + +``` +Usage: app -p|--port= [--log-level=] --tags= --database.host= --database.port= +``` + +`rfl::cli::usage("app", true)` adds one line per argument, with its +description, the constraints of its validators, its default and whether it is +required: + +``` +Usage: app -p|--port= [--log-level=] --tags= --database.host= --database.port= + +Arguments: + Path to the input file. Required. + -p, --port= Port to listen on. Range: 1..65535. Required. + --log-level= Minimum level to log + --tags= Tags to attach. Size: >= 1. Required. + --database.host= Required. + --database.port= Required. +``` + +Defaults are shown for fields wrapped in `rfl::DefaultVal`, and for all fields +if you pass `rfl::DefaultIfMissing` (to both `read` and `usage`), as long as +the struct can be default-constructed: + +```cpp +struct Server { + rfl::DefaultVal host = "localhost"; + rfl::DefaultVal threads = 4; + rfl::DefaultVal dry_run = false; +}; +``` + +``` +Arguments: + --host= Default: localhost. + --threads= Default: 4. + --dry-run[=] Default: false. +``` + +The parser takes the defaults of `rfl::DefaultVal` fields from a +default-constructed struct. If the struct cannot be default-constructed, for +instance because a validator rejects another field's default value, those +fields are required, and the help says so. + +`rfl::Positional`, `rfl::Short` and `rfl::DefaultVal` only take effect as the +outermost wrapper of a field, so put `rfl::Description` and validators inside +them. The help shows what the parser does: a field declared as +`rfl::Description<"...", rfl::Positional>` is listed as a named +argument, because that is how it is parsed. + +`read` does not handle `--help`. Check for it before calling `read`, and +print the usage line when parsing fails: + +```cpp +int main(int argc, char* argv[]) { + if (std::any_of(argv + 1, argv + argc, [](std::string_view _arg) { + return _arg == "--help" || _arg == "-h"; + })) { + std::cout << rfl::cli::usage(argv[0], true); + return 0; + } + const auto config = rfl::cli::read(argc, argv); + if (!config) { + std::cerr << config.error().what() << "\n\n" + << rfl::cli::usage(argv[0]); + return 1; + } + // ... +} +``` + +(Leave out `-h` if one of your fields uses `rfl::Short<"h", ...>`.) + ## Supported types | Type | CLI format | Notes | @@ -193,6 +300,7 @@ Parsing proceeds in three stages: - `include/rfl/cli/Parser.hpp` — Parser type alias - `include/rfl/cli/parse_argv.hpp` — `argv` -> `ParsedArgs` - `include/rfl/cli/resolve_args.hpp` — `ParsedArgs` -> `map` +- `include/rfl/cli/usage.hpp` — `usage()` help text, built on `rfl::parsing::schema` - `include/rfl/cli.hpp` — aggregator header - `include/rfl/SnakeCaseToKebabCase.hpp` — processor - `include/rfl/Positional.hpp` — `Positional` wrapper diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index 763f335b0..79a9fe420 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -7,5 +7,6 @@ #include "cli/parse_argv.hpp" #include "cli/read.hpp" #include "cli/resolve_args.hpp" +#include "cli/usage.hpp" #endif diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp new file mode 100644 index 000000000..1019175f3 --- /dev/null +++ b/include/rfl/cli/usage.hpp @@ -0,0 +1,616 @@ +#ifndef RFL_CLI_USAGE_HPP_ +#define RFL_CLI_USAGE_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Generic.hpp" +#include "../Processors.hpp" +#include "../SnakeCaseToKebabCase.hpp" +#include "../generic/Writer.hpp" +#include "../internal/default_if_missing_v.hpp" +#include "../internal/is_default_val_v.hpp" +#include "../internal/is_extra_fields.hpp" +#include "../internal/is_named_tuple.hpp" +#include "../internal/no_optionals_v.hpp" +#include "../internal/processed_t.hpp" +#include "../parsing/is_required.hpp" +#include "../parsing/schema/Definition.hpp" +#include "../parsing/schema/Type.hpp" +#include "../parsing/schema/ValidationType.hpp" +#include "../parsing/schema/make.hpp" +#include "../to_generic.hpp" +#include "Reader.hpp" +#include "resolve_args.hpp" + +namespace rfl::cli { + +namespace internal { + +/// Metadata of a top-level field that the schema does not carry, or does not +/// carry the way the parser sees it. +struct UsageFieldMeta { + bool positional = false; + std::string short_name; + bool required = true; +}; + +/// Everything usage() renders about one argument. +struct UsageArg { + /// The long name, including the path of nested objects ("database.host"). + std::string name; + std::string short_name; + bool positional = false; + /// Booleans can be passed without a value (`--verbose`). + bool flag = false; + bool required = true; + /// Whether `required` was taken from the parser's compile-time traits, so + /// that the schema must not override it. + bool required_is_known = false; + /// The placeholder for the value: "", "" or "". + std::string value = ""; + /// The allowed values of enums and literals. + std::vector choices; + std::string description; + std::optional deprecation; + /// Rendered constraints, such as "Range: 1..65535.". + std::vector constraints; + std::optional default_value; +}; + +template +void add_usage_field_meta(const bool _default_vals_are_optional, + std::map* _meta) { + using Info = field_info; + using ValueType = std::remove_cvref_t; + auto& meta = (*_meta)[std::string(Info::name())]; + meta.positional = Info::is_positional; + if constexpr (Info::is_short) { + meta.short_name = + std::string(get_short_name().string_view()); + } + // The same condition as in NamedTupleParser::handle_one_missing_field. + // The schema cannot tell, because it marks a DefaultVal field as optional + // even where the parser requires it (see usage_default_vals_are_optional). + meta.required = + !(rfl::internal::is_default_val_v + && _default_vals_are_optional) + && !rfl::internal::is_extra_fields_v + && (rfl::internal::no_optionals_v + || parsing::is_required()); +} + +/// Collects Positional, Short and whether a field is required from the same +/// compile-time traits that resolve_args and the parser use, so the help +/// matches what the parser accepts. +template +std::map collect_usage_field_meta( + const bool _default_vals_are_optional, std::index_sequence<_is...>) { + std::map meta; + (add_usage_field_meta( + _default_vals_are_optional, &meta), + ...); + return meta; +} + +/// Whether the parser fills in the rfl::DefaultVal fields of T that are +/// missing. It does so by default-constructing T before reading it. If T is +/// not default-constructible, or T{} throws (for instance because a +/// validator rejects another field's default value), they are required, or +/// the read fails if one of them is not wrapped in another type. An +/// rfl::NamedTuple has no in-class initializers, so it is never +/// default-constructed for its defaults. +template +bool usage_default_vals_are_optional() { + if constexpr (rfl::internal::is_named_tuple_v) { + return true; + } else if constexpr (std::is_default_constructible_v) { + try { + [[maybe_unused]] const auto t = T{}; + return true; + } catch (...) { + return false; + } + } else { + return false; + } +} + +/// Renders a number without locale-dependent separators. +inline std::string usage_number_to_string(const double _value) { + std::ostringstream stream; + stream.imbue(std::locale::classic()); + stream.precision(15); + stream << _value; + return stream.str(); +} + +inline std::string usage_number_to_string( + const rfl::Variant& _value) { + return _value.visit([](const auto _v) -> std::string { + if constexpr (std::is_same_v, int>) { + return std::to_string(_v); + } else { + return usage_number_to_string(_v); + } + }); +} + +/// Renders a default value the way it would be passed on the command line. +/// Returns nullopt for values that cannot be rendered sensibly (null, +/// objects, empty arrays). +inline std::optional usage_default_to_string( + const Generic& _value) { + return std::visit( + [](const auto& _v) -> std::optional { + using V = std::remove_cvref_t; + if constexpr (std::is_same_v) { + return _v ? "true" : "false"; + } else if constexpr (std::is_same_v) { + return std::to_string(_v); + } else if constexpr (std::is_same_v) { + return usage_number_to_string(_v); + } else if constexpr (std::is_same_v) { + return _v.empty() ? std::string("\"\"") : _v; + } else if constexpr (std::is_same_v) { + if (_v.empty()) { + return std::nullopt; + } + std::string joined; + for (const auto& element : _v) { + const auto str = usage_default_to_string(element); + if (!str) { + return std::nullopt; + } + if (!joined.empty()) { + joined += array_delimiter; + } + joined += *str; + } + return joined; + } else { + return std::nullopt; + } + }, + _value.variant()); +} + +/// Renders a numeric bound such as ">= 1", "1..10" or "< 0 or > 10". +/// Returns nullopt if the validation is not purely numeric. +inline std::optional usage_bounds_to_string( + const parsing::schema::ValidationType& _validation) { + using ValidationType = parsing::schema::ValidationType; + const auto join = [](const std::vector& _types, + const std::string& _sep) -> std::optional { + std::string joined; + for (const auto& t : _types) { + const auto str = usage_bounds_to_string(t); + if (!str) { + return std::nullopt; + } + joined += (joined.empty() ? "" : _sep) + *str; + } + return joined; + }; + return _validation.variant_.visit( + [&](const auto& _v) -> std::optional { + using V = std::remove_cvref_t; + if constexpr (std::is_same_v) { + if (_v.types_.size() == 2) { + using Min = ValidationType::Minimum; + using Max = ValidationType::Maximum; + const auto& first = _v.types_[0].variant_; + const auto& second = _v.types_[1].variant_; + const auto* min = rfl::get_if(&first); + const auto* max = rfl::get_if(&second); + if (!min && !max) { + min = rfl::get_if(&second); + max = rfl::get_if(&first); + } + if (min && max) { + return usage_number_to_string(min->value_) + ".." + + usage_number_to_string(max->value_); + } + } + return join(_v.types_, " and "); + } else if constexpr (std::is_same_v + || std::is_same_v) { + return join(_v.types_, " or "); + } else if constexpr (std::is_same_v) { + return usage_number_to_string(_v.value_); + } else if constexpr (std::is_same_v) { + return "!= " + usage_number_to_string(_v.value_); + } else if constexpr (std::is_same_v) { + return ">= " + usage_number_to_string(_v.value_); + } else if constexpr (std::is_same_v) { + return "<= " + usage_number_to_string(_v.value_); + } else if constexpr (std::is_same_v) { + return "> " + usage_number_to_string(_v.value_); + } else if constexpr (std::is_same_v) { + return "< " + usage_number_to_string(_v.value_); + } else { + return std::nullopt; + } + }); +} + +/// Renders a validation as one or more phrases, such as "Range: 1..10", +/// "Size: >= 1" or "Pattern: ^[a-z]+$". +inline std::vector usage_constraints( + const parsing::schema::ValidationType& _validation) { + using ValidationType = parsing::schema::ValidationType; + if (const auto bounds = usage_bounds_to_string(_validation)) { + return {"Range: " + *bounds}; + } + return _validation.variant_.visit( + [](const auto& _v) -> std::vector { + using V = std::remove_cvref_t; + if constexpr (std::is_same_v) { + std::vector all; + for (const auto& t : _v.types_) { + const auto phrases = usage_constraints(t); + all.insert(all.end(), phrases.begin(), phrases.end()); + } + return all; + } else if constexpr (std::is_same_v + || std::is_same_v) { + std::string joined; + for (const auto& t : _v.types_) { + std::string alternative; + for (const auto& phrase : usage_constraints(t)) { + alternative += (alternative.empty() ? "" : ", ") + phrase; + } + joined += (joined.empty() ? "" : " or ") + alternative; + } + return {joined}; + } else if constexpr (std::is_same_v) { + const auto bounds = usage_bounds_to_string(*_v.size_limit_); + if (!bounds) { + return {}; + } + return {"Size: " + *bounds}; + } else if constexpr (std::is_same_v) { + return {"Pattern: " + _v.pattern_}; + } else { + return {}; + } + }); +} + +/// Walks the format-agnostic schema of the struct and collects one UsageArg +/// per command-line argument, in declaration order. +class UsageCollector { + public: + using Type = parsing::schema::Type; + + UsageCollector(const parsing::schema::Definition* _definition, + const std::map* _meta, + const bool _optionals_are_required) + : definition_(_definition), + meta_(_meta), + optionals_are_required_(_optionals_are_required) {} + + /// Collects the arguments. + /// @param _all_optional Whether no argument is required + /// (rfl::DefaultIfMissing). + /// @param _defaults The default values of all fields, if known. + std::vector collect(const bool _all_optional, + const std::optional& _defaults) { + auto root = UsageArg{}; + root.required = !_all_optional; + add(definition_->root_, std::move(root), _defaults, false); + return std::move(args_); + } + + private: + /// @param _outermost Whether _type is the outermost type of a field. + void add(const Type& _type, UsageArg _arg, + const std::optional& _default, const bool _outermost) { + _type.variant_.visit([&](const auto& _t) { + using T = std::remove_cvref_t; + if constexpr (std::is_same_v) { + if (_arg.description.empty()) { + _arg.description = _t.description_; + } + add(*_t.type_, std::move(_arg), _default, false); + + } else if constexpr (std::is_same_v) { + if (_arg.description.empty()) { + _arg.description = _t.description_; + } + _arg.deprecation = _t.deprecation_message_; + add(*_t.type_, std::move(_arg), _default, false); + + } else if constexpr (std::is_same_v) { + if (!_arg.required_is_known && !optionals_are_required_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), _default, false); + + } else if constexpr (std::is_same_v) { + // Like the parser, only count a DefaultVal that wraps the field. The + // schema has its default value only if the struct around it could be + // default-constructed, which is when the parser fills it in. + if (!_arg.required_is_known && _outermost && _t.default_value_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), + _t.default_value_ ? _t.default_value_ : _default, false); + + } else if constexpr (std::is_same_v) { + const auto constraints = usage_constraints(_t.validation_); + _arg.constraints.insert(_arg.constraints.end(), constraints.begin(), + constraints.end()); + add(*_t.type_, std::move(_arg), _default, false); + + } else if constexpr (std::is_same_v) { + const auto it = definition_->definitions_.find(_t.name_); + if (it == definition_->definitions_.end() + || !visiting_.insert(_t.name_).second) { + // Unknown or recursive: there is no finite set of paths to list. + add_leaf(std::move(_arg), _default); + return; + } + add(it->second, std::move(_arg), _default, _outermost); + visiting_.erase(_t.name_); + + } else if constexpr (std::is_same_v) { + add_object(_t, _arg, _default); + + } else if constexpr (std::is_same_v) { + _arg.name += path_separator; + _arg.name += ""; + add_leaf(std::move(_arg), std::nullopt); + + } else if constexpr (std::is_same_v) { + _arg.flag = true; + add_leaf(std::move(_arg), _default); + + } else if constexpr (std::is_same_v) { + add_choices(_t.values_, std::move(_arg), _default); + + } else if constexpr (std::is_same_v) { + auto values = std::vector(); + for (const auto& v : _t.values_) { + values.push_back(v.value_); + } + add_choices(values, std::move(_arg), _default); + + } else if constexpr (std::is_same_v + || std::is_same_v + || std::is_same_v) { + _arg.value = ""; + add_leaf(std::move(_arg), _default); + + } else { + add_leaf(std::move(_arg), _default); + } + }); + } + + void add_object(const Type::Object& _object, const UsageArg& _parent, + const std::optional& _defaults) { + const bool is_root = _parent.name.empty(); + for (const auto& [name, type] : _object.types_) { + auto arg = UsageArg{}; + arg.name = is_root ? name : _parent.name + path_separator + name; + // Children of an optional object are only needed if it is given. + arg.required = _parent.required; + if (is_root) { + const auto it = meta_->find(name); + if (it != meta_->end()) { + arg.positional = it->second.positional; + arg.short_name = it->second.short_name; + arg.required = arg.required && it->second.required; + arg.required_is_known = true; + } + } + auto child_default = std::optional(); + const auto* obj = _defaults + ? std::get_if(&_defaults->variant()) + : nullptr; + if (obj) { + if (auto res = obj->get(name)) { + child_default = std::move(*res); + } + } + add(type, std::move(arg), child_default, true); + } + } + + void add_choices(const std::vector& _values, UsageArg _arg, + const std::optional& _default) { + _arg.choices = _values; + _arg.value = "<"; + for (size_t i = 0; i < _values.size(); ++i) { + _arg.value += (i == 0 ? "" : "|") + _values[i]; + } + _arg.value += ">"; + add_leaf(std::move(_arg), _default); + } + + void add_leaf(UsageArg _arg, const std::optional& _default) { + if (_arg.name.empty()) { + return; + } + if (_default) { + _arg.default_value = usage_default_to_string(*_default); + } + args_.emplace_back(std::move(_arg)); + } + + private: + const parsing::schema::Definition* definition_; + const std::map* meta_; + const bool optionals_are_required_; + std::set visiting_; + std::vector args_; +}; + +/// "", "-p|--port=", "--verbose[=]" +inline std::string usage_arg_to_string(const UsageArg& _arg, + const std::string& _short_sep) { + if (_arg.positional) { + return "<" + _arg.name + ">"; + } + auto str = _arg.short_name.empty() ? std::string() + : "-" + _arg.short_name + _short_sep; + str += "--" + _arg.name; + str += _arg.flag ? "[=]" : "=" + _arg.value; + return str; +} + +inline bool usage_ends_sentence(const std::string& _str) { + return !_str.empty() + && (_str.back() == '.' || _str.back() == '!' || _str.back() == '?'); +} + +/// "Port to connect on. Range: 1..65535. Default: 8080. Required." +inline std::string usage_help_text(const UsageArg& _arg) { + auto sentences = std::vector(); + if (_arg.deprecation) { + sentences.push_back(_arg.deprecation->empty() + ? std::string("Deprecated") + : "Deprecated: " + *_arg.deprecation); + } + if (_arg.positional && !_arg.choices.empty()) { + auto choices = std::string("Choices: "); + for (size_t i = 0; i < _arg.choices.size(); ++i) { + choices += (i == 0 ? "" : "|") + _arg.choices[i]; + } + sentences.push_back(std::move(choices)); + } + sentences.insert(sentences.end(), _arg.constraints.begin(), + _arg.constraints.end()); + if (_arg.default_value) { + sentences.push_back("Default: " + *_arg.default_value); + } + if (_arg.required) { + sentences.push_back("Required"); + } + auto text = _arg.description; + for (const auto& s : sentences) { + if (!text.empty()) { + text += usage_ends_sentence(text) ? " " : ". "; + } + text += s; + } + if (!sentences.empty() && !usage_ends_sentence(text)) { + text += "."; + } + return text; +} + +inline std::string format_usage(const std::string& _program_name, + const std::vector& _args, + const bool _detailed) { + auto out = "Usage: " + _program_name; + for (const auto& arg : _args) { + const auto str = usage_arg_to_string(arg, "|"); + out += arg.required ? " " + str : " [" + str + "]"; + } + out += '\n'; + if (!_detailed || _args.empty()) { + return out; + } + + auto rows = std::vector>(); + size_t width = 0; + for (const auto& arg : _args) { + rows.emplace_back(usage_arg_to_string(arg, ", "), usage_help_text(arg)); + width = std::max(width, rows.back().first.size()); + } + + 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) { + if (c == '\n') { + out += continuation; + } else { + out += c; + } + } + } + out += '\n'; + } + return out; +} + +/// The default values of all fields, if they are known: only with +/// rfl::DefaultIfMissing (otherwise, plain fields are required and their +/// default member initializers are never used) and only if T is +/// default-constructible, which read requires, too. +template +std::optional usage_defaults() { + using ProcessorsType = Processors; + if constexpr (rfl::internal::default_if_missing_v + && std::is_default_constructible_v) { + try { + return rfl::to_generic(T{}); + } catch (...) { + // For instance, a default value that does not satisfy its validator. + return std::nullopt; + } + } else { + return std::nullopt; + } +} + +} // namespace internal + +/// Generates the usage line, and optionally a help text with one row per +/// argument, for the struct that `rfl::cli::read()` parses into. +/// It applies the same processors as `read`, so the names always match what +/// the parser accepts (kebab-case, rfl::Rename, rfl::Flatten, nested paths). +/// +/// The help text lists, where known, the description (rfl::Description), the +/// allowed values of enums and literals, the constraints of validators, the +/// default value (rfl::DefaultVal, or all fields with rfl::DefaultIfMissing) +/// and whether the argument is required. +/// +/// `read` does not handle `--help`; check for it before calling `read`. +/// @tparam T The struct type that the arguments are parsed into +/// @tparam Ps The processors passed to `rfl::cli::read` +/// @param _program_name The name shown after "Usage:", usually argv[0] +/// @param _detailed Whether to add a line for every argument +/// @return The usage text, ending with a newline +template +std::string usage(const std::string& _program_name, + const bool _detailed = false) { + using ProcessorsType = Processors; + using NamedTupleType = rfl::internal::processed_t; + const auto meta = + internal::collect_usage_field_meta( + internal::usage_default_vals_are_optional(), + std::make_index_sequence{}); + const auto definition = + parsing::schema::make(); + auto collector = internal::UsageCollector( + &definition, &meta, rfl::internal::no_optionals_v); + const auto args = collector.collect( + rfl::internal::default_if_missing_v, + internal::usage_defaults()); + return internal::format_usage(_program_name, args, _detailed); +} + +} // namespace rfl::cli + +#endif diff --git a/tests/cli/test_usage.cpp b/tests/cli/test_usage.cpp new file mode 100644 index 000000000..12e4d73bb --- /dev/null +++ b/tests/cli/test_usage.cpp @@ -0,0 +1,406 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace test_usage { + +enum class LogLevel { debug, info, warn }; + +struct Database { + std::string host; + int port; +}; + +struct Config { + rfl::Positional input_file; + std::string host_name; + bool verbose; + std::vector tags; + rfl::Short<"p", int> port; + Database database; + std::optional log_level; +}; + +TEST(cli, test_usage_synopsis) { + // The exact string proposed in #692. + EXPECT_EQ(rfl::cli::usage("my_binary"), + "Usage: my_binary --host-name= " + "--verbose[=] --tags= -p|--port= " + "--database.host= --database.port= " + "[--log-level=]\n"); +} + +struct Described { + rfl::Positional> + input_file; + rfl::Description<"Host to connect to", std::string> host_name; + bool verbose; + rfl::Short<"p", rfl::Description<"Port to connect on", int>> port; + rfl::Description<"Minimum level to log", std::optional> log_level; +}; + +TEST(cli, test_usage_detailed) { + EXPECT_EQ( + rfl::cli::usage("my_binary", true), + "Usage: my_binary --host-name= --verbose[=] " + "-p|--port= [--log-level=]\n" + "\n" + "Arguments:\n" + " Path to the input file. Required.\n" + " --host-name= Host to connect to. Required.\n" + " --verbose[=] Required.\n" + " -p, --port= Port to connect on. Required.\n" + " --log-level= Minimum level to log\n"); + + // What the help advertises is what the parser accepts. + const char* args[] = {"my_binary", "in.txt", "--host-name=localhost", + "--verbose", "-p", "8080", + "--log-level=warn"}; + const auto result = + rfl::cli::read(7, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().input_file().get(), "in.txt"); + EXPECT_EQ(result.value().port().get(), 8080); + EXPECT_EQ(result.value().log_level.get(), LogLevel::warn); + + // A plain bool is required, as the help says. + const char* no_verbose[] = {"my_binary", "in.txt", "--host-name=localhost", + "-p", "8080"}; + EXPECT_FALSE(rfl::cli::read(5, const_cast(no_verbose))); +} + +struct DescriptionOutside { + rfl::Description<"Path to the input file", rfl::Positional> + input_file; +}; + +TEST(cli, test_usage_description_outside_positional) { + // The parser only treats a field as positional if rfl::Positional is the + // outermost wrapper, so the help shows a named argument. + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app --input-file=\n" + "\n" + "Arguments:\n" + " --input-file= Path to the input file. Required.\n"); + + const char* positional[] = {"app", "in.txt"}; + EXPECT_FALSE( + rfl::cli::read(2, const_cast(positional))); + const char* named[] = {"app", "--input-file=in.txt"}; + EXPECT_TRUE(rfl::cli::read(2, const_cast(named))); +} + +struct Validated { + rfl::Description<"Port to listen on", + rfl::Validator, rfl::Maximum<65535>>> + port; + rfl::Validator, rfl::Maximum<1>> ratio; + rfl::Validator> percent; + rfl::Validator, rfl::Minimum<10>>> outside; + rfl::Validator, rfl::EqualTo<2>>> one_or_two; + rfl::Validator> nonzero; + rfl::Validator, rfl::Size>> tags; + rfl::Validator, + rfl::Size, rfl::Maximum<3>>>> + ids; + rfl::Validator>, + rfl::PatternValidator<"^[a-z]+$", "Lowercase">> + user; + rfl::Literal<"fast", "slow"> mode; +}; + +TEST(cli, test_usage_validators) { + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app --port= --ratio= --percent= " + "--outside= --one-or-two= --nonzero= " + "--tags= --ids= --user= " + "--mode=\n" + "\n" + "Arguments:\n" + " --port= Port to listen on. Range: 1..65535. " + "Required.\n" + " --ratio= Range: > 0 and <= 1. Required.\n" + " --percent= Range: < 100. Required.\n" + " --outside= Range: <= 0 or >= 10. Required.\n" + " --one-or-two= Range: 1 or 2. Required.\n" + " --nonzero= Range: != 0. Required.\n" + " --tags= Size: >= 1. Required.\n" + " --ids= Size: 1..3. Required.\n" + " --user= Size: >= 1. Pattern: ^[a-z]+$. " + "Required.\n" + " --mode= Required.\n"); +} + +struct WithDefaultVal { + rfl::DefaultVal port = 8080; + rfl::DefaultVal host = "localhost"; + rfl::DefaultVal> tags = + std::vector{"a", "b"}; + rfl::DefaultVal level = LogLevel::info; + rfl::DefaultVal rate = 0.25; + rfl::DefaultVal dry_run = false; + int count = 3; + rfl::Short<"r", rfl::DefaultVal> retries = 5; +}; + +TEST(cli, test_usage_default_val) { + // Without rfl::DefaultIfMissing, `count` is required, so its member + // initializer is never used and not shown. A DefaultVal inside rfl::Short + // makes `retries` optional, as for the parser. + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app [--port=] [--host=] " + "[--tags=] [--level=] " + "[--rate=] [--dry-run[=]] --count= " + "[-r|--retries=]\n" + "\n" + "Arguments:\n" + " --port= Default: 8080.\n" + " --host= Default: localhost.\n" + " --tags= Default: a,b.\n" + " --level= Default: info.\n" + " --rate= Default: 0.25.\n" + " --dry-run[=] Default: false.\n" + " --count= Required.\n" + " -r, --retries= Default: 5.\n"); + + const char* args[] = {"app", "--count=1", "-r", "2"}; + const auto result = + rfl::cli::read(4, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().port.get(), 8080); + EXPECT_EQ(result.value().host.get(), "localhost"); + EXPECT_EQ(result.value().retries.value().get(), 2); + + const char* no_retries[] = {"app", "--count=1"}; + const auto defaulted = + rfl::cli::read(2, const_cast(no_retries)); + ASSERT_TRUE(defaulted) << defaulted.error().what(); + EXPECT_EQ(defaulted.value().retries.value().get(), 5); +} + +/// The default-constructed `port` does not satisfy its validator. +struct WithInvalidDefault { + rfl::Validator> port; + rfl::DefaultVal threads = 4; +}; + +/// The same with the DefaultVal inside rfl::Short. +struct WithInvalidWrappedDefault { + rfl::Validator> port; + rfl::Short<"t", rfl::DefaultVal> threads = 4; +}; + +struct WithInvalidWrappedDefaultInside { + WithInvalidWrappedDefault server; +}; + +TEST(cli, test_usage_default_val_struct_not_default_constructible) { + // The defaults are read from a default-constructed struct, which throws + // here. The help leaves them out instead of aborting. The parser fills in + // a missing DefaultVal field only after it default-constructed the + // struct, so `threads` is required. + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app --port= --threads=\n" + "\n" + "Arguments:\n" + " --port= Range: >= 1. Required.\n" + " --threads= Required.\n"); + + // A bare DefaultVal makes every read fail, since the struct must be + // default-constructed for it. + const char* both[] = {"app", "--port=1", "--threads=2"}; + EXPECT_FALSE(rfl::cli::read(3, const_cast(both))); + + // One that is wrapped in rfl::Short is read without the defaults, and is + // required. + EXPECT_EQ(rfl::cli::usage("app"), + "Usage: app --port= -t|--threads=\n"); + const auto wrapped = rfl::cli::read( + 3, const_cast(both)); + ASSERT_TRUE(wrapped) << wrapped.error().what(); + EXPECT_EQ(wrapped.value().threads.value().get(), 2); + const char* no_threads[] = {"app", "--port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(no_threads))); + + // The same in a nested struct. + EXPECT_EQ(rfl::cli::usage("app"), + "Usage: app --server.port= --server.threads=\n"); + const char* nested_no_threads[] = {"app", "--server.port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(nested_no_threads))); + const char* nested_both[] = {"app", "--server.port=1", "--server.threads=2"}; + EXPECT_TRUE(rfl::cli::read( + 3, const_cast(nested_both))); +} + +struct Inner { + std::string host = "db"; + int port = 5432; +}; + +struct WithInitializers { + int count = 3; + std::string name; + bool verbose = false; + std::optional limit; + Inner database; +}; + +TEST(cli, test_usage_default_if_missing) { + EXPECT_EQ( + (rfl::cli::usage("app", true)), + "Usage: app [--count=] [--name=] [--verbose[=]] " + "[--limit=] [--database.host=] [--database.port=]\n" + "\n" + "Arguments:\n" + " --count= Default: 3.\n" + " --name= Default: \"\".\n" + " --verbose[=] Default: false.\n" + " --limit=\n" + " --database.host= Default: db.\n" + " --database.port= Default: 5432.\n"); + + const char* args[] = {"app"}; + const auto result = rfl::cli::read( + 1, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().count, 3); + EXPECT_EQ(result.value().database.port, 5432); +} + +TEST(cli, test_usage_without_default_if_missing) { + EXPECT_EQ(rfl::cli::usage("app"), + "Usage: app --count= --name= --verbose[=] " + "[--limit=] --database.host= " + "--database.port=\n"); + + const char* args[] = {"app"}; + EXPECT_FALSE(rfl::cli::read(1, const_cast(args))); +} + +/// Has no default constructor, so neither has a struct that contains it. +class Port { + public: + using ReflectionType = int; + Port(int _value) : value_(_value) {} + int reflection() const { return value_; } + + private: + int value_; +}; + +struct WithPort { + Port port; + int retries = 3; +}; + +struct WithPortAndDefaultVal { + Port port; + rfl::DefaultVal retries = 3; +}; + +TEST(cli, test_usage_default_val_without_default_constructor) { + static_assert(!std::is_default_constructible_v); + // The struct cannot be default-constructed, so the parser cannot fill in + // `retries`, and it is required. + EXPECT_EQ(rfl::cli::usage("app"), + "Usage: app --port= --retries=\n"); + const char* no_retries[] = {"app", "--port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(no_retries))); + const char* both[] = {"app", "--port=1", "--retries=2"}; + const auto result = + rfl::cli::read(3, const_cast(both)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().retries.get(), 2); +} + +TEST(cli, test_usage_default_if_missing_not_default_constructible) { + static_assert(!std::is_default_constructible_v); + // Nothing is required, but the defaults cannot be known without T{}, so + // usage() still compiles and leaves them out. + EXPECT_EQ((rfl::cli::usage("app", true)), + "Usage: app [--port=] [--retries=]\n" + "\n" + "Arguments:\n" + " --port=\n" + " --retries=\n"); +} + +struct Address { + std::string city; + int zip; +}; + +struct Names { + rfl::Rename<"output_dir", std::string> output_dir; + rfl::Flatten
address; + std::optional backup; + std::map labels; +}; + +TEST(cli, test_usage_names) { + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app --output_dir= --city= --zip= " + "[--backup.host=] [--backup.port=] " + "--labels.=\n" + "\n" + "Arguments:\n" + " --output_dir= Required.\n" + " --city= Required.\n" + " --zip= Required.\n" + " --backup.host=\n" + " --backup.port=\n" + " --labels.= Required.\n"); + + const char* args[] = {"app", "--output_dir=/tmp", "--city=Springfield", + "--zip=12345", "--labels.env=prod"}; + const auto result = rfl::cli::read(5, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().labels.at("env"), "prod"); +} + +struct Optionals { + rfl::Positional> level; + rfl::Short<"v", std::optional> verbose; + rfl::Deprecated<"Use --port instead", "Old port", std::optional> + old_port; + rfl::Description<"First line\nSecond line", std::string> notes; +}; + +TEST(cli, test_usage_optionals) { + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app [] [-v|--verbose[=]] " + "[--old-port=] --notes=\n" + "\n" + "Arguments:\n" + " Choices: debug|info|warn.\n" + " -v, --verbose[=]\n" + " --old-port= Old port. Deprecated: Use --port " + "instead.\n" + " --notes= First line\n" + " Second line. Required.\n"); +} + +TEST(cli, test_usage_no_optionals) { + // Processors are applied exactly as in read: with rfl::NoOptionals, + // optional fields are required. + EXPECT_EQ((rfl::cli::usage("app")), + "Usage: app -v|--verbose[=] --old-port= " + "--notes=\n"); +} + +struct Empty {}; + +TEST(cli, test_usage_empty) { + EXPECT_EQ(rfl::cli::usage("app"), "Usage: app\n"); + EXPECT_EQ(rfl::cli::usage("app", true), "Usage: app\n"); +} + +} // namespace test_usage From 1d3c9d2ce4561a363205f0df8ce2ada250002867 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 13 Nov 2026 04:07:06 +0100 Subject: [PATCH 2/2] Show DefaultVal inside Short, Positional or Description as optional in usage With wrapper-composition, the parser reads a DefaultVal inside Short, Positional, Description or Deprecated as optional. Top-level fields already followed, since usage takes requiredness from is_default_val_v. Fields of nested structs come from the schema walk, which only counted a DefaultVal node at the top of a field; it now also looks through Description and Deprecated nodes. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 25 +++++++-- include/rfl/cli/usage.hpp | 16 ++++-- tests/cli/test_usage.cpp | 75 +++++++++++++++++++++++++++ 3 files changed, 108 insertions(+), 8 deletions(-) diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index c65cf11c3..4c2760e12 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -232,9 +232,28 @@ default-constructed struct. If the struct cannot be default-constructed, for instance because a validator rejects another field's default value, those fields are required, and the help says so. -`rfl::Positional`, `rfl::Short` and `rfl::DefaultVal` only take effect as the -outermost wrapper of a field, so put `rfl::Description` and validators inside -them. The help shows what the parser does: a field declared as +An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description` +or `rfl::Deprecated`, in any order, makes the field optional for the parser, +and the help shows it in brackets with its default: + +```cpp +struct Logging { + rfl::Short<"l", rfl::Description<"Minimum level to log", + rfl::DefaultVal>> + log_level = LogLevel::info; +}; +``` + +``` +Usage: app [-l|--log-level=] + +Arguments: + -l, --log-level= Minimum level to log. Default: info. +``` + +`rfl::Positional` and `rfl::Short` only take effect as the outermost wrapper +of a field, so put `rfl::Description` and validators inside them. The help +shows what the parser does: a field declared as `rfl::Description<"...", rfl::Positional>` is listed as a named argument, because that is how it is parsed. diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 1019175f3..413fd141b 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -80,8 +80,10 @@ void add_usage_field_meta(const bool _default_vals_are_optional, std::string(get_short_name().string_view()); } // The same condition as in NamedTupleParser::handle_one_missing_field. - // The schema cannot tell, because it marks a DefaultVal field as optional - // even where the parser requires it (see usage_default_vals_are_optional). + // is_default_val_v sees a DefaultVal through Short, Positional, Rename, + // Description and Deprecated, in any order, as the parser does. The schema + // cannot tell, because it marks a DefaultVal field as optional even where + // the parser requires it (see usage_default_vals_are_optional). meta.required = !(rfl::internal::is_default_val_v && _default_vals_are_optional) @@ -320,18 +322,21 @@ class UsageCollector { const std::optional& _default, const bool _outermost) { _type.variant_.visit([&](const auto& _t) { using T = std::remove_cvref_t; + // Description and Deprecated do not change how a field is read, so a + // DefaultVal inside them still makes the field optional + // (is_default_val_v). Short, Positional and Rename leave no node. if constexpr (std::is_same_v) { if (_arg.description.empty()) { _arg.description = _t.description_; } - add(*_t.type_, std::move(_arg), _default, false); + add(*_t.type_, std::move(_arg), _default, _outermost); } else if constexpr (std::is_same_v) { if (_arg.description.empty()) { _arg.description = _t.description_; } _arg.deprecation = _t.deprecation_message_; - add(*_t.type_, std::move(_arg), _default, false); + add(*_t.type_, std::move(_arg), _default, _outermost); } else if constexpr (std::is_same_v) { if (!_arg.required_is_known && !optionals_are_required_) { @@ -340,7 +345,8 @@ class UsageCollector { add(*_t.type_, std::move(_arg), _default, false); } else if constexpr (std::is_same_v) { - // Like the parser, only count a DefaultVal that wraps the field. The + // Like the parser (is_default_val_v), only count a DefaultVal that + // wraps the field, possibly inside Description or Deprecated. The // schema has its default value only if the struct around it could be // default-constructed, which is when the parser fills it in. if (!_arg.required_is_known && _outermost && _t.default_value_) { diff --git a/tests/cli/test_usage.cpp b/tests/cli/test_usage.cpp index 12e4d73bb..b9adcf557 100644 --- a/tests/cli/test_usage.cpp +++ b/tests/cli/test_usage.cpp @@ -183,6 +183,81 @@ TEST(cli, test_usage_default_val) { EXPECT_EQ(defaulted.value().retries.value().get(), 5); } +struct Limits { + rfl::Description<"Connections per host", rfl::DefaultVal> per_host = 4; + int total; +}; + +/// rfl::DefaultVal inside other wrappers, in different orders. +struct WrappedDefaultVal { + rfl::Short<"l", rfl::Description<"Minimum level to log", + rfl::DefaultVal>> + log_level = LogLevel::info; + rfl::Description<"Seconds to wait", rfl::DefaultVal> timeout = 30; + rfl::Deprecated<"Use --timeout", "Old timeout", rfl::DefaultVal> wait = + 10; + rfl::Positional> output = "out.txt"; + rfl::Short<"n", rfl::Description<"Number of runs", int>> runs; + Limits limits; +}; + +TEST(cli, test_usage_wrapped_default_val) { + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app [-l|--log-level=] " + "[--timeout=] [--wait=] [] " + "-n|--runs= [--limits.per-host=] " + "--limits.total=\n" + "\n" + "Arguments:\n" + " -l, --log-level= Minimum level to log. " + "Default: info.\n" + " --timeout= Seconds to wait. " + "Default: 30.\n" + " --wait= Old timeout. Deprecated: " + "Use --timeout. Default: 10.\n" + " Default: out.txt.\n" + " -n, --runs= Number of runs. Required.\n" + " --limits.per-host= Connections per host. " + "Default: 4.\n" + " --limits.total= Required.\n"); + + // Everything the help leaves optional can be left out. + const char* minimal[] = {"app", "-n", "3", "--limits.total=8"}; + const auto defaulted = + rfl::cli::read(4, const_cast(minimal)); + ASSERT_TRUE(defaulted) << defaulted.error().what(); + EXPECT_EQ(defaulted.value().log_level.value().value().get(), + LogLevel::info); + EXPECT_EQ(defaulted.value().timeout.value().get(), 30); + EXPECT_EQ(defaulted.value().wait.value().get(), 10); + EXPECT_EQ(defaulted.value().output.value().get(), "out.txt"); + EXPECT_EQ(defaulted.value().runs.value().value(), 3); + EXPECT_EQ(defaulted.value().limits.per_host.value().get(), 4); + EXPECT_EQ(defaulted.value().limits.total, 8); + + // The arguments are spelled as the help shows them. + const char* all[] = {"app", "-l", "warn", + "--timeout=5", "--wait=1", "result.txt", + "--runs=2", "--limits.per-host=2", + "--limits.total=4"}; + const auto given = + rfl::cli::read(9, const_cast(all)); + ASSERT_TRUE(given) << given.error().what(); + EXPECT_EQ(given.value().log_level.value().value().get(), LogLevel::warn); + EXPECT_EQ(given.value().timeout.value().get(), 5); + EXPECT_EQ(given.value().wait.value().get(), 1); + EXPECT_EQ(given.value().output.value().get(), "result.txt"); + EXPECT_EQ(given.value().limits.per_host.value().get(), 2); + + // What the help calls required is required. + const char* no_runs[] = {"app", "--limits.total=8"}; + EXPECT_FALSE( + rfl::cli::read(2, const_cast(no_runs))); + const char* no_total[] = {"app", "-n", "3"}; + EXPECT_FALSE( + rfl::cli::read(3, const_cast(no_total))); +} + /// The default-constructed `port` does not satisfy its validator. struct WithInvalidDefault { rfl::Validator> port;