diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index b4e86157..b5e89b68 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -267,16 +267,24 @@ struct Database { struct Config { rfl::Positional> input_file; - rfl::Short<"p", rfl::Description<"Port to listen on", int>> port; + 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", std::vector> tags; + rfl::Description<"Tags to attach", + rfl::Validator, + rfl::Size>>> + tags; Database database; }; ``` `rfl::cli::usage("app", true).value()` is the usage line, where optional arguments are in brackets, and one line per argument, with its -description, its default and whether it is required. +description, the constraints of its validators (`Range: 1..65535.`, +`Size: >= 1.`, `Pattern: ^[a-z]+$.`), `Deprecated: .` for +`rfl::Deprecated`, its default and whether it is required. `rfl::cli::usage("app")` gives only the usage line. ``` @@ -284,9 +292,9 @@ Usage: app -p|--port= [--log-level=] --tags Arguments: Path to the input file. Required. - -p, --port= Port to listen on. Required. + -p, --port= Port to listen on. Range: 1..65535. Required. --log-level= Minimum level to log - --tags= Tags to attach. Required. + --tags= Tags to attach. Size: >= 1. Required. --database.host= Required. --database.port= Required. ``` diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index f0ae4984..adadb6dd 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -29,6 +29,7 @@ #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" @@ -66,6 +67,9 @@ struct UsageArg { /// 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; }; @@ -135,6 +139,17 @@ inline std::string usage_number_to_string(const double _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). @@ -175,6 +190,110 @@ inline std::optional usage_default_to_string( _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 { @@ -215,11 +334,17 @@ class UsageCollector { // 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 - || std::is_same_v) { + if constexpr (std::is_same_v) { + if (_arg.description.empty()) { + _arg.description = _t.description_; + } + 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, _outermost); } else if constexpr (std::is_same_v) { @@ -240,6 +365,9 @@ class UsageCollector { _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) { @@ -395,9 +523,14 @@ inline bool usage_ends_sentence(const std::string& _str) { && (_str.back() == '.' || _str.back() == '!' || _str.back() == '?'); } -/// "Port to connect on. Default: 8080. Required." +/// "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) { @@ -405,6 +538,8 @@ inline std::string usage_help_text(const UsageArg& _arg) { } 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); } @@ -493,9 +628,9 @@ std::optional usage_defaults() { /// 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 default value (rfl::DefaultVal, -/// or all fields with rfl::DefaultIfMissing) and whether the argument is -/// required. +/// 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. /// @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] diff --git a/tests/cli/test_usage.cpp b/tests/cli/test_usage.cpp index 638a9c47..11c9ce35 100644 --- a/tests/cli/test_usage.cpp +++ b/tests/cli/test_usage.cpp @@ -77,6 +77,47 @@ TEST(cli, test_usage_detailed) { EXPECT_FALSE(rfl::cli::read(5, const_cast(no_verbose))); } +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).value(), + "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"; @@ -367,7 +408,8 @@ TEST(cli, test_usage_optionals) { "Arguments:\n" " Choices: debug|info|warn.\n" " -v, --verbose[=]\n" - " --old-port= Old port\n" + " --old-port= Old port. Deprecated: Use --port " + "instead.\n" " --notes= First line\n" " Second line. Required.\n"); }