From 0711c46dae428abcd253c0b8f26745ee9d7a21da Mon Sep 17 00:00:00 2001 From: clockblocker Date: Sat, 14 Nov 2026 11:30:11 +0100 Subject: [PATCH] Show defaults in rfl::cli::usage The detailed help of rfl::cli::usage now also lists the default of each argument: of rfl::DefaultVal fields, or of every field with rfl::DefaultIfMissing, when T{} can be built. The usage line does not change. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 22 +++- include/rfl/cli/usage.hpp | 150 +++++++++++++++++++++----- tests/cli/test_usage.cpp | 85 +++++++++++++-- tests/cli/test_usage_options.cpp | 2 +- 4 files changed, 225 insertions(+), 34 deletions(-) diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 1e3b4095..b4e86157 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -276,8 +276,8 @@ struct Config { `rfl::cli::usage("app", true).value()` is the usage line, where optional arguments are in brackets, and one line per argument, with its -description and whether it is required. `rfl::cli::usage("app")` -gives only the usage line. +description, its default and whether it is required. +`rfl::cli::usage("app")` gives only the usage line. ``` Usage: app -p|--port= [--log-level=] --tags= --database.host= --database.port= @@ -302,6 +302,24 @@ says so. With a bare `rfl::DefaultVal`, such a struct cannot be read at all, and `usage` returns the error, as it does for two fields with the same short name. +Defaults are shown for these fields, 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. +``` + Each argument is shown as the option table that `read` parses with (see [Architecture](#architecture)) reads it: a `bool`, also inside a nested struct, is a flag whose value can be left out (`--verbose[=]`), and diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index e9695ed9..f0ae4984 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -4,13 +4,18 @@ #include #include #include +#include #include +#include #include +#include #include #include #include +#include #include +#include "../Generic.hpp" #include "../Processors.hpp" #include "../Result.hpp" #include "../SnakeCaseToKebabCase.hpp" @@ -25,6 +30,7 @@ #include "../parsing/schema/Definition.hpp" #include "../parsing/schema/Type.hpp" #include "../parsing/schema/make.hpp" +#include "../to_generic.hpp" #include "Reader.hpp" #include "options.hpp" #include "resolve_args.hpp" @@ -60,6 +66,7 @@ struct UsageArg { /// The allowed values of enums and literals. std::vector choices; std::string description; + std::optional default_value; }; template @@ -119,6 +126,55 @@ bool usage_default_vals_are_optional() { } } +/// 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(); +} + +/// 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). +/// Lists are joined with the list delimiter. +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()); +} + /// Walks the format-agnostic schema of the struct and collects one UsageArg /// per command-line argument, in declaration order. class UsageCollector { @@ -141,16 +197,19 @@ class UsageCollector { /// Collects the arguments. /// @param _all_optional Whether no argument is required /// (rfl::DefaultIfMissing). - std::vector collect(const bool _all_optional) { + /// @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), false); + 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 bool _outermost) { + 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; // Description and Deprecated do not change how a field is read, so a @@ -161,13 +220,13 @@ class UsageCollector { if (_arg.description.empty()) { _arg.description = _t.description_; } - add(*_t.type_, std::move(_arg), _outermost); + add(*_t.type_, std::move(_arg), _default, _outermost); } else if constexpr (std::is_same_v) { if (!_arg.required_is_known && !optionals_are_required_) { _arg.required = false; } - add(*_t.type_, std::move(_arg), false); + add(*_t.type_, std::move(_arg), _default, false); } else if constexpr (std::is_same_v) { // Like the parser (is_default_val_v), only count a DefaultVal that @@ -177,57 +236,59 @@ class UsageCollector { if (!_arg.required_is_known && _outermost && _t.default_value_) { _arg.required = false; } - add(*_t.type_, std::move(_arg), false); + add(*_t.type_, std::move(_arg), + _t.default_value_ ? _t.default_value_ : _default, false); } else if constexpr (std::is_same_v) { - add(*_t.type_, std::move(_arg), false); + 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)); + add_leaf(std::move(_arg), _default); return; } - add(it->second, std::move(_arg), _outermost); + add(it->second, std::move(_arg), _default, _outermost); visiting_.erase(_t.name_); } else if constexpr (std::is_same_v) { - add_object(_t, _arg); + add_object(_t, _arg, _default); } else if constexpr (std::is_same_v) { _arg.name += path_separator; _arg.name += ""; - add_leaf(std::move(_arg)); + add_leaf(std::move(_arg), std::nullopt); } else if constexpr (std::is_same_v) { _arg.value = ""; - add_leaf(std::move(_arg)); + add_leaf(std::move(_arg), _default); } else if constexpr (std::is_same_v) { - add_choices(_t.values_, std::move(_arg)); + 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)); + add_choices(values, std::move(_arg), _default); } else if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) { _arg.is_list = true; - add_leaf(std::move(_arg)); + add_leaf(std::move(_arg), _default); } else { - add_leaf(std::move(_arg)); + add_leaf(std::move(_arg), _default); } }); } - void add_object(const Type::Object& _object, const UsageArg& _parent) { + 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{}; @@ -248,21 +309,31 @@ class UsageCollector { arg.required_is_known = true; } } - add(type, std::move(arg), 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) { + 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)); + add_leaf(std::move(_arg), _default); } - void add_leaf(UsageArg _arg) { + void add_leaf(UsageArg _arg, const std::optional& _default) { if (_arg.name.empty()) { return; } @@ -270,6 +341,9 @@ class UsageCollector { // key ("labels.") is found through its open prefix. const auto option = options_->find_long(_arg.name); _arg.kind = option.kind; + if (_default) { + _arg.default_value = usage_default_to_string(*_default); + } args_.emplace_back(std::move(_arg)); } @@ -321,7 +395,7 @@ inline bool usage_ends_sentence(const std::string& _str) { && (_str.back() == '.' || _str.back() == '!' || _str.back() == '?'); } -/// "Port to connect on. Required." +/// "Port to connect on. Default: 8080. Required." inline std::string usage_help_text(const UsageArg& _arg) { auto sentences = std::vector(); if (_arg.positional && !_arg.choices.empty()) { @@ -331,6 +405,9 @@ inline std::string usage_help_text(const UsageArg& _arg) { } sentences.push_back(std::move(choices)); } + if (_arg.default_value) { + sentences.push_back("Default: " + *_arg.default_value); + } if (_arg.required) { sentences.push_back("Required"); } @@ -388,6 +465,26 @@ inline std::string format_usage(const std::string& _program_name, 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 (const std::exception&) { + // 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 @@ -395,8 +492,10 @@ inline std::string format_usage(const std::string& _program_name, /// 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 the description (rfl::Description), the allowed -/// values of enums and literals and whether the argument is required. +/// The help text lists, where known, the description (rfl::Description), the +/// allowed values of enums and literals, the default value (rfl::DefaultVal, +/// or all fields with rfl::DefaultIfMissing) and whether the argument is +/// required. /// @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] @@ -429,7 +528,8 @@ rfl::Result usage(const std::string& _program_name, &definition, &meta, &options, rfl::internal::no_optionals_v); const auto args = collector.collect( - rfl::internal::default_if_missing_v); + rfl::internal::default_if_missing_v, + internal::usage_defaults()); return internal::format_usage(_program_name, args, _detailed); } catch (std::exception& e) { return error(e.what()); diff --git a/tests/cli/test_usage.cpp b/tests/cli/test_usage.cpp index c6cb4d39..638a9c47 100644 --- a/tests/cli/test_usage.cpp +++ b/tests/cli/test_usage.cpp @@ -77,6 +77,53 @@ TEST(cli, test_usage_detailed) { EXPECT_FALSE(rfl::cli::read(5, const_cast(no_verbose))); } +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).value(), + "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); +} + struct Limits { rfl::Description<"Connections per host", rfl::DefaultVal> per_host = 4; int total; @@ -101,11 +148,14 @@ TEST(cli, test_usage_wrapped_default_val) { "--limits.total=\n" "\n" "Arguments:\n" - " -l, --log-level= Minimum level to log\n" - " --timeout= Seconds to wait\n" - " \n" + " -l, --log-level= Minimum level to log. " + "Default: info.\n" + " --timeout= Seconds to wait. " + "Default: 30.\n" + " Default: out.txt.\n" " -n, --runs= Number of runs. Required.\n" - " --limits.per-host= Connections per host\n" + " --limits.per-host= Connections per host. " + "Default: 4.\n" " --limits.total= Required.\n"); // Everything the help leaves optional can be left out. @@ -167,7 +217,7 @@ TEST(cli, test_usage_defaults_without_default_construction) { // The parser fills in a missing DefaultVal field only after it // default-constructed the struct. If that throws (`port`'s zero value // fails its validator) or the struct has no default constructor, the - // field is required, and the help says so. + // field is required, and the help shows it without a default. static_assert(!std::is_default_constructible_v); // With a bare DefaultVal, every read fails, and so does usage: the schema // takes the defaults from a default-constructed struct. @@ -198,7 +248,8 @@ TEST(cli, test_usage_defaults_without_default_construction) { EXPECT_FALSE(rfl::cli::read( 2, const_cast(nested))); - // With rfl::DefaultIfMissing nothing is required, even without T{}. + // With rfl::DefaultIfMissing nothing is required, but the defaults are + // unknown without T{}, so usage() leaves them out. static_assert(!std::is_default_constructible_v); EXPECT_EQ((rfl::cli::usage("app", true).value()), "Usage: app [--port=] [--retries=]\n" @@ -221,6 +272,28 @@ struct WithInitializers { Inner database; }; +TEST(cli, test_usage_default_if_missing) { + EXPECT_EQ( + (rfl::cli::usage("app", true).value()), + "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").value(), "Usage: app --count= --name= --verbose[=] " diff --git a/tests/cli/test_usage_options.cpp b/tests/cli/test_usage_options.cpp index 2c358699..d990717a 100644 --- a/tests/cli/test_usage_options.cpp +++ b/tests/cli/test_usage_options.cpp @@ -31,7 +31,7 @@ TEST(cli, test_usage_wrapper_order) { "\n" "Arguments:\n" " -o, --output= Where to write. Required.\n" - " \n" + " Default: in.txt.\n" " -v, --verbose[=] Be verbose\n"); const auto defaulted = read({"-o", "out"});