From dcb5ff46ee80f6f5e30dc4678b77d2a0e2f54890 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Sat, 14 Nov 2026 11:30:11 +0100 Subject: [PATCH] Add rfl::cli::usage to generate usage and help text rfl::cli::usage(program_name, detailed = false) returns the one-line usage form for the struct that rfl::cli::read parses into, and with detailed = true one row per argument: description, enum choices of positional arguments, and "Required.". It returns an rfl::Result, with an error where no read of T can succeed. It walks the format-agnostic schema (rfl::parsing::schema::make) and takes positionals, short aliases and flags from the parser's option table, and requiredness from the same traits as the parser, so the help matches what read accepts. Implements https://github.com/munich-data-engineering/reflect-cpp/issues/692. Co-Authored-By: Claude Opus 5.5 --- README.md | 9 + docs/content/supported_formats/cli.md | 78 +++++ include/rfl/cli.hpp | 1 + include/rfl/cli/usage.hpp | 442 ++++++++++++++++++++++++++ tests/cli/test_usage.cpp | 317 ++++++++++++++++++ tests/cli/test_usage_options.cpp | 79 +++++ 6 files changed, 926 insertions(+) create mode 100644 include/rfl/cli/usage.hpp create mode 100644 tests/cli/test_usage.cpp create mode 100644 tests/cli/test_usage_options.cpp diff --git a/README.md b/README.md index 9cfdfa22..42648928 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,15 @@ struct Config { // ./app data.csv -o /tmp/out -v --count=10 ``` +`rfl::cli::usage` generates the help text from the same struct, for instance for `--help`: + +```cpp +if (argc > 1 && std::string_view(argv[1]) == "--help") { + std::cout << rfl::cli::usage(argv[0], true).value(); + // Usage: ./app -o|--output-dir= -v|--verbose[=] --count= +} +``` + Nested structs, `std::optional`, `std::vector`, enums, `rfl::Flatten` and `rfl::Rename` are all supported. Refer to the [documentation](https://munich-data-engineering.github.io/reflect-cpp/cli) for details. ### Error messages diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 6ef51f64..47a514dc 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -177,6 +177,83 @@ 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. +It returns an `rfl::Result`. + +```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", int>> port; + rfl::Description<"Minimum level to log", std::optional> log_level; + rfl::Description<"Tags to attach", std::vector> 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 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= + +Arguments: + Path to the input file. Required. + -p, --port= Port to listen on. Required. + --log-level= Minimum level to log + --tags= Tags to attach. Required. + --database.host= Required. + --database.port= Required. +``` + +Fields wrapped in `rfl::DefaultVal`, also inside `rfl::Short`, +`rfl::Positional`, `rfl::Description` or `rfl::Deprecated`, are optional, and +so are all fields if you pass `rfl::DefaultIfMissing` (to both `read` and +`usage`). 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 if they are all inside another wrapper, and the help +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. + +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 +every other option takes a value (`--port=`). + +`rfl::Positional` and `rfl::Short` are found through the other wrappers, as +the parser does (see [Combining wrappers](#combining-wrappers)), so +`rfl::Description<"...", rfl::Positional>` is listed as a +positional argument. + +`read` does not handle `--help`: check `argv` for it and print `usage` +yourself: + +```cpp +int main(int argc, char* argv[]) { + if (argc > 1 && std::string_view(argv[1]) == "--help") { + std::cout << rfl::cli::usage(argv[0], true).value(); + return 0; + } + const auto config = rfl::cli::read(argc, argv).value(); +} +``` + ## Supported types | Type | CLI format | Notes | @@ -221,6 +298,7 @@ Parsing proceeds in three stages: - `include/rfl/cli/parse_argv.hpp` — `argv` -> `ParsedArgs` - `include/rfl/cli/options.hpp` — the internal option table: the long, short and positional options of a struct - `include/rfl/cli/resolve_args.hpp` — `ParsedArgs` -> `map` +- `include/rfl/cli/usage.hpp` — `usage()` help text, built on `rfl::parsing::schema` and the internal option table - `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 85881e7b..a35b9e02 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -8,5 +8,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 00000000..e9695ed9 --- /dev/null +++ b/include/rfl/cli/usage.hpp @@ -0,0 +1,442 @@ +#ifndef RFL_CLI_USAGE_HPP_ +#define RFL_CLI_USAGE_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Processors.hpp" +#include "../Result.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/make.hpp" +#include "Reader.hpp" +#include "options.hpp" +#include "resolve_args.hpp" + +namespace rfl::cli { + +namespace internal { + +/// Whether a top-level field is required, which the schema cannot tell the +/// way the parser sees it. +struct UsageFieldMeta { + 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; + /// What the option does with a value, from the parser's option table: + /// flags (`--verbose`) can be given without one. + OptionKind kind = OptionKind::value; + /// Whether the field is a list. + bool is_list = 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 one value: "", "" or "". Lists + /// are rendered from it with the list delimiter. + std::string value = ""; + /// The allowed values of enums and literals. + std::vector choices; + std::string description; +}; + +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())]; + // The same condition as in NamedTupleParser::handle_one_missing_field. + // 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) + && !rfl::internal::is_extra_fields_v + && (rfl::internal::no_optionals_v + || parsing::is_required()); +} + +/// Collects whether each top-level field is required from the same +/// compile-time traits that the parser uses, so the help matches what the +/// parser accepts. Positional, Short and flags come from the parser's option +/// table (make_options). +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 (only possible if all of them are wrapped in +/// another type), 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 { + static_cast(T{}); + return true; + } catch (const std::exception&) { + return false; + } + } else { + return false; + } +} + +/// 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 Options* _options, + const bool _optionals_are_required) + : definition_(_definition), + meta_(_meta), + options_(_options), + optionals_are_required_(_optionals_are_required) { + for (const auto& [short_name, path] : _options->short_options) { + short_names_[path] = short_name; + } + } + + /// Collects the arguments. + /// @param _all_optional Whether no argument is required + /// (rfl::DefaultIfMissing). + std::vector collect(const bool _all_optional) { + auto root = UsageArg{}; + root.required = !_all_optional; + add(definition_->root_, std::move(root), 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) { + _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 + || std::is_same_v) { + if (_arg.description.empty()) { + _arg.description = _t.description_; + } + add(*_t.type_, std::move(_arg), _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); + + } else if constexpr (std::is_same_v) { + // 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_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + add(*_t.type_, std::move(_arg), 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)); + return; + } + add(it->second, std::move(_arg), _outermost); + visiting_.erase(_t.name_); + + } else if constexpr (std::is_same_v) { + add_object(_t, _arg); + + } else if constexpr (std::is_same_v) { + _arg.name += path_separator; + _arg.name += ""; + add_leaf(std::move(_arg)); + + } else if constexpr (std::is_same_v) { + _arg.value = ""; + add_leaf(std::move(_arg)); + + } else if constexpr (std::is_same_v) { + add_choices(_t.values_, std::move(_arg)); + + } 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)); + + } else if constexpr (std::is_same_v + || std::is_same_v + || std::is_same_v) { + _arg.is_list = true; + add_leaf(std::move(_arg)); + + } else { + add_leaf(std::move(_arg)); + } + }); + } + + void add_object(const Type::Object& _object, const UsageArg& _parent) { + 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& positionals = options_->positionals; + arg.positional = std::find(positionals.begin(), positionals.end(), + name) != positionals.end(); + const auto short_name = short_names_.find(name); + if (short_name != short_names_.end()) { + arg.short_name = short_name->second; + } + const auto it = meta_->find(name); + if (it != meta_->end()) { + arg.required = arg.required && it->second.required; + arg.required_is_known = true; + } + } + add(type, std::move(arg), true); + } + } + + void add_choices(const std::vector& _values, UsageArg _arg) { + _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)); + } + + void add_leaf(UsageArg _arg) { + if (_arg.name.empty()) { + return; + } + // How the parser treats the option, from the table that it uses. A map + // key ("labels.") is found through its open prefix. + const auto option = options_->find_long(_arg.name); + _arg.kind = option.kind; + args_.emplace_back(std::move(_arg)); + } + + private: + const parsing::schema::Definition* definition_; + const std::map* meta_; + const Options* options_; + const bool optionals_are_required_; + /// The rfl::Short aliases, by the path of their field. + std::map short_names_; + std::set visiting_; + std::vector args_; +}; + +/// The placeholder for the value of _arg: "", "", or for a list +/// "" with the list delimiter. +inline std::string usage_value_to_string(const UsageArg& _arg) { + if (!_arg.is_list) { + return _arg.value; + } + const auto d = std::string(1, array_delimiter); + return ""; +} + +/// "", "-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; + const auto value = usage_value_to_string(_arg); + switch (_arg.kind) { + case OptionKind::flag: + // `--verbose`: the value can be left out. + str += "[=" + value + "]"; + break; + default: + str += "=" + value; + break; + } + return str; +} + +inline bool usage_ends_sentence(const std::string& _str) { + return !_str.empty() + && (_str.back() == '.' || _str.back() == '!' || _str.back() == '?'); +} + +/// "Port to connect on. Required." +inline std::string usage_help_text(const UsageArg& _arg) { + auto sentences = std::vector(); + 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)); + } + 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; +} + +} // 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 the description (rfl::Description), the allowed +/// values of enums and literals 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] +/// @param _detailed Whether to add a line for every argument +/// @return The usage text, ending with a newline, or an error if no read of +/// T can succeed: two fields have the same short name, or T has a bare +/// rfl::DefaultVal and default-constructing it throws. +template +rfl::Result usage(const std::string& _program_name, + const bool _detailed = false) { + using ProcessorsType = Processors; + using NamedTupleType = rfl::internal::processed_t; + // The table that read() parses with, so the help shows what the parser + // accepts, including the options inside nested structs and maps. + const auto options = + internal::make_options(); + return internal::check_short_names(options).and_then( + [&](auto) -> rfl::Result { + try { + const auto meta = internal::collect_usage_field_meta< + NamedTupleType, ProcessorsType>( + internal::usage_default_vals_are_optional(), + std::make_index_sequence{}); + // The schema takes the default values from a default-constructed + // T, which can throw. + const auto definition = + parsing::schema::make(); + auto collector = internal::UsageCollector( + &definition, &meta, &options, + rfl::internal::no_optionals_v); + const auto args = collector.collect( + rfl::internal::default_if_missing_v); + return internal::format_usage(_program_name, args, _detailed); + } catch (std::exception& e) { + return error(e.what()); + } + }); +} + +} // namespace rfl::cli + +#endif diff --git a/tests/cli/test_usage.cpp b/tests/cli/test_usage.cpp new file mode 100644 index 00000000..c6cb4d39 --- /dev/null +++ b/tests/cli/test_usage.cpp @@ -0,0 +1,317 @@ +#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 + // https://github.com/munich-data-engineering/reflect-cpp/issues/692. + EXPECT_EQ(rfl::cli::usage("my_binary").value(), + "Usage: my_binary --host-name= " + "--verbose[=] --tags= -p|--port= " + "--database.host= --database.port= " + "[--log-level=]\n"); +} + +// The issue's second example: rfl::Positional and rfl::Short inside +// rfl::Description, which the parser finds, and so does the help. +struct Described { + rfl::Description<"Path to the input file", rfl::Positional> + input_file; + rfl::Description<"Host to connect to", std::string> host_name; + bool verbose; + rfl::Description<"Port to connect on", rfl::Short<"p", 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).value(), + "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().value(), "in.txt"); + EXPECT_EQ(result.value().port().value(), 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 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::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).value(), + "Usage: app [-l|--log-level=] " + "[--timeout=] [] " + "-n|--runs= [--limits.per-host=] " + "--limits.total=\n" + "\n" + "Arguments:\n" + " -l, --log-level= Minimum level to log\n" + " --timeout= Seconds to wait\n" + " \n" + " -n, --runs= Number of runs. Required.\n" + " --limits.per-host= Connections per host\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().output.value().get(), "out.txt"); + + // 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; + 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; +}; + +/// 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; +}; + +/// A bare DefaultVal here would not compile: the struct has no default +/// constructor. A wrapped one is required. +struct WithPortAndDefaultVal { + Port port; + rfl::Description<"Retries", rfl::DefaultVal> retries = 3; +}; + +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. + 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. + const auto invalid = rfl::cli::usage("app", true); + ASSERT_FALSE(invalid); + EXPECT_EQ(std::string(invalid.error().what()), + "Value expected to be greater than or equal to 1, but got 0."); + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --port= -t|--threads=\n"); + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --server.port= --server.threads=\n"); + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --port= --retries=\n"); + + // A bare DefaultVal makes every read fail; a wrapped one is required. + const char* both[] = {"app", "--port=1", "--threads=2"}; + EXPECT_FALSE(rfl::cli::read(3, const_cast(both))); + 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* port_only[] = {"app", "--port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(port_only))); + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(port_only))); + const char* nested[] = {"app", "--server.port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(nested))); + + // With rfl::DefaultIfMissing nothing is required, even without T{}. + static_assert(!std::is_default_constructible_v); + EXPECT_EQ((rfl::cli::usage("app", true).value()), + "Usage: app [--port=] [--retries=]\n" + "\n" + "Arguments:\n" + " --port=\n" + " --retries=\n"); +} + +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_without_default_if_missing) { + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --count= --name= --verbose[=] " + "[--limit=] --database.host= " + "--database.port=\n"); + + const char* args[] = {"app"}; + EXPECT_FALSE(rfl::cli::read(1, const_cast(args))); +} + +struct Tls { + bool verify; +}; + +struct WithNestedFlag { + Tls tls; +}; + +TEST(cli, test_usage_nested_flag) { + // A nested bool is a flag, as for the parser. + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --tls.verify[=]\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).value(), + "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).value(), + "Usage: app [] [-v|--verbose[=]] " + "[--old-port=] --notes=\n" + "\n" + "Arguments:\n" + " Choices: debug|info|warn.\n" + " -v, --verbose[=]\n" + " --old-port= Old port\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").value()), + "Usage: app -v|--verbose[=] --old-port= " + "--notes=\n"); +} + +struct Empty {}; + +TEST(cli, test_usage_empty) { + EXPECT_EQ(rfl::cli::usage("app").value(), "Usage: app\n"); + EXPECT_EQ(rfl::cli::usage("app", true).value(), "Usage: app\n"); +} + +} // namespace test_usage diff --git a/tests/cli/test_usage_options.cpp b/tests/cli/test_usage_options.cpp new file mode 100644 index 00000000..2c358699 --- /dev/null +++ b/tests/cli/test_usage_options.cpp @@ -0,0 +1,79 @@ +#include + +#include +#include +#include +#include +#include + +// rfl::cli::usage for the parser's option features: wrappers in any order +// and positional order. Each test also reads the arguments as the help +// spells them. +namespace test_usage_options { + +template +rfl::Result read(std::vector _args) { + _args.insert(_args.begin(), "app"); + return rfl::cli::read(static_cast(_args.size()), + const_cast(_args.data())); +} + +struct WrapperOrder { + rfl::Description<"Where to write", rfl::Short<"o", std::string>> output; + rfl::DefaultVal> input = "in.txt"; + rfl::Description<"Be verbose", rfl::Short<"v", std::optional>> + verbose; +}; + +TEST(cli, test_usage_wrapper_order) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app -o|--output= [] [-v|--verbose[=]]\n" + "\n" + "Arguments:\n" + " -o, --output= Where to write. Required.\n" + " \n" + " -v, --verbose[=] Be verbose\n"); + + const auto defaulted = read({"-o", "out"}); + ASSERT_TRUE(defaulted) << defaulted.error().what(); + EXPECT_EQ(defaulted.value().input.value().value(), "in.txt"); +} + +/// The parser fills the rfl::Positional fields in declaration order, wherever +/// rfl::Positional sits among their wrappers. +struct PositionalOrder { + rfl::Description<"Files to process", rfl::Positional> files; + rfl::Positional pair; + rfl::Positional command; +}; + +TEST(cli, test_usage_positional_order) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app \n" + "\n" + "Arguments:\n" + " Files to process. Required.\n" + " Required.\n" + " Required.\n"); + + const auto result = read({"x", "a", "run"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().pair.value(), "a"); + EXPECT_EQ(result.value().command.value(), "run"); + EXPECT_EQ(result.value().files.value().value(), "x"); +} + +/// Two fields with the same short name fail every read, and usage too. +struct ShortNameTaken { + rfl::Short<"o", std::string> output; + rfl::Description<"Where to log", rfl::Short<"o", std::string>> log; +}; + +TEST(cli, test_usage_short_name_taken) { + const auto usage = rfl::cli::usage("app", true); + ASSERT_FALSE(usage); + EXPECT_EQ(std::string(usage.error().what()), + "Duplicate short name '-o' in struct definition."); +} + +} // namespace test_usage_options