From 2704765cb4a60c5dec73e1ebf6afa45d2b911184 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Sat, 14 Nov 2026 11:30:11 +0100 Subject: [PATCH 1/4] 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 | 75 +++++ include/rfl/cli.hpp | 1 + include/rfl/cli/usage.hpp | 444 ++++++++++++++++++++++++++ tests/cli/test_usage.cpp | 317 ++++++++++++++++++ tests/cli/test_usage_options.cpp | 79 +++++ 6 files changed, 925 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 9cfdfa223..426489281 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 00b4002cc..433cecb03 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -195,6 +195,80 @@ struct Config { // ./app data.csv -o /tmp/out -v --count=10 ``` +## 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` 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 +a struct with `rfl::DefaultVal` cannot be default-constructed (for instance +because a validator rejects another field's default value), it cannot be read, +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 | @@ -239,6 +313,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 85881e7b9..a35b9e025 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 000000000..02d9bc545 --- /dev/null +++ b/include/rfl/cli/usage.hpp @@ -0,0 +1,444 @@ +#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. + // The schema cannot tell on its own, 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 = ""; + _arg.kind = OptionKind::flag; + 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. Keep + // the schema-derived kind (such as OptionKind::flag for nested booleans) + // when the option table only tracks top-level paths. + const auto option = options_->find_long(_arg.name); + if (option.kind != OptionKind::unknown) { + _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. + 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 000000000..19310ca3c --- /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::DefaultVal> per_host = 4; + int total; +}; + +/// rfl::DefaultVal combined with other wrappers. +struct WrappedDefaultVal { + rfl::DefaultVal< + rfl::Short<"l", rfl::Description<"Minimum level to log", LogLevel>>> + log_level = LogLevel::info; + rfl::DefaultVal> timeout = 30; + rfl::DefaultVal> 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.get().value(), "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 000000000..2c358699e --- /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 From c898597c7920193b5a8d62b43ddd690e03c3b173 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 22:27:55 +0100 Subject: [PATCH 2/4] Address Judge blockers: unwrap root via unwrapped_option_t/option_fields_t, recurse into StringMap value_type_, remove runtime T{} probe, and expand tests --- README.md | 2 + include/rfl/cli/usage.hpp | 107 ++++++++++++++++++++------------------ tests/cli/test_usage.cpp | 92 ++++++++++++++++++++++++++++++++ 3 files changed, 149 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 426489281..e39f622ed 100644 --- a/README.md +++ b/README.md @@ -379,6 +379,8 @@ struct Config { 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= + // + // Arguments: ... } ``` diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 02d9bc545..199d90c43 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -62,19 +62,35 @@ struct UsageArg { std::string description; }; -template -void add_usage_field_meta(const bool _default_vals_are_optional, - std::map* _meta) { +/// Whether a missing field of type `ValueType` inside root type `U` is filled +/// in by the parser's default-value path. Mirrors +/// `NamedTupleParser::handle_one_missing_field` without invoking `T{}` at +/// runtime (for structs, `schema::make` already constructs `T{}` once if and +/// only if `has_default_val_v` is true). +template +constexpr bool usage_default_val_is_optional() { + if constexpr (!rfl::internal::is_default_val_v) { + return false; + } else if constexpr (rfl::internal::is_named_tuple_v) { + using Inner = typename rfl::internal::default_val_t::Type; + return !std::is_const_v && + std::is_default_constructible_v && + std::is_default_constructible_v; + } else { + return std::is_default_constructible_v; + } +} + +template +void add_usage_field_meta(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. // The schema cannot tell on its own, because it marks a DefaultVal field as - // optional even where the parser requires it (see - // usage_default_vals_are_optional). + // optional even where the parser requires it. meta.required = - !(rfl::internal::is_default_val_v - && _default_vals_are_optional) + !usage_default_val_is_optional() && !rfl::internal::is_extra_fields_v && (rfl::internal::no_optionals_v || parsing::is_required()); @@ -84,40 +100,14 @@ void add_usage_field_meta(const bool _default_vals_are_optional, /// 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 +template std::map collect_usage_field_meta( - const bool _default_vals_are_optional, std::index_sequence<_is...>) { + std::index_sequence<_is...>) { std::map meta; - (add_usage_field_meta( - _default_vals_are_optional, &meta), - ...); + (add_usage_field_meta(&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 { @@ -152,9 +142,8 @@ class UsageCollector { 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. + // Description and Deprecated wrap the inner schema node without changing + // how the field is read. Short, Positional and Rename leave no node. if constexpr (std::is_same_v || std::is_same_v) { if (_arg.description.empty()) { @@ -169,10 +158,8 @@ class UsageCollector { 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. + // The schema populates `default_value_` only when the parser recognizes + // the DefaultVal field and default-constructed its enclosing struct. if (!_arg.required_is_known && _outermost && _t.default_value_) { _arg.required = false; } @@ -198,7 +185,9 @@ class UsageCollector { } else if constexpr (std::is_same_v) { _arg.name += path_separator; _arg.name += ""; - add_leaf(std::move(_arg)); + _arg.short_name.clear(); + _arg.positional = false; + add(*_t.value_type_, std::move(_arg), false); } else if constexpr (std::is_same_v) { _arg.value = ""; @@ -338,6 +327,11 @@ inline std::string usage_help_text(const UsageArg& _arg) { sentences.push_back("Required"); } auto text = _arg.description; + while (!text.empty() + && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r' + || text.back() == '\n')) { + text.pop_back(); + } for (const auto& s : sentences) { if (!text.empty()) { text += usage_ends_sentence(text) ? " " : ". "; @@ -378,9 +372,14 @@ inline std::string format_usage(const std::string& _program_name, out += std::string(indent, ' ') + left; if (!right.empty()) { out += std::string(width - left.size() + gap, ' '); - for (const char c : right) { + for (size_t i = 0; i < right.size(); ++i) { + const char c = right[i]; if (c == '\n') { - out += continuation; + if (i + 1 < right.size() && right[i + 1] != '\n') { + out += continuation; + } else { + out += '\n'; + } } else { out += c; } @@ -411,17 +410,21 @@ template rfl::Result usage(const std::string& _program_name, const bool _detailed = false) { using ProcessorsType = Processors; - using NamedTupleType = rfl::internal::processed_t; + using U = internal::unwrapped_option_t; // The table that read() parses with, so the help shows what the parser // accepts. 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{}); + std::map meta; + if constexpr (internal::is_option_struct_v) { + using NamedTupleType = + internal::option_fields_t; + meta = internal::collect_usage_field_meta( + std::make_index_sequence{}); + } // The schema takes the default values from a default-constructed // T, which can throw. const auto definition = @@ -433,7 +436,7 @@ rfl::Result usage(const std::string& _program_name, const auto args = collector.collect( rfl::internal::default_if_missing_v); return internal::format_usage(_program_name, args, _detailed); - } catch (std::exception& e) { + } catch (const std::exception& e) { return error(e.what()); } }); diff --git a/tests/cli/test_usage.cpp b/tests/cli/test_usage.cpp index 19310ca3c..d31422a5d 100644 --- a/tests/cli/test_usage.cpp +++ b/tests/cli/test_usage.cpp @@ -1,10 +1,13 @@ #include +#include #include +#include #include #include #include #include +#include #include namespace test_usage { @@ -314,4 +317,93 @@ TEST(cli, test_usage_empty) { EXPECT_EQ(rfl::cli::usage("app", true).value(), "Usage: app\n"); } +struct CountingDefault { + static inline int ctor_count = 0; + static std::string make_host() { + ++ctor_count; + return "localhost"; + } + std::string host = make_host(); +}; + +TEST(cli, test_usage_does_not_default_construct_without_default_val) { + CountingDefault::ctor_count = 0; + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --host=\n"); + EXPECT_EQ(CountingDefault::ctor_count, 0); +} + +TEST(cli, test_usage_named_tuple_and_reflection_type) { + using NT = rfl::NamedTuple>, + rfl::Field<"my_req", std::string>, + rfl::Field<"my_flag", bool>>; + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app [--my_opt=] --my_req= " + "--my_flag[=]\n"); + const char* nt_args[] = {"app", "--my_req=hi", "--my_flag"}; + const auto nt_res = rfl::cli::read(3, const_cast(nt_args)); + ASSERT_TRUE(nt_res) << nt_res.error().what(); + EXPECT_EQ(nt_res.value().get<"my_opt">().get(), 0); + + class WrappedRoot { + public: + struct Impl { + std::string host_name; + std::optional port; + }; + using ReflectionType = Impl; + WrappedRoot(Impl _impl) : impl_(std::move(_impl)) {} + const Impl& reflection() const { return impl_; } + + private: + Impl impl_; + }; + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --host-name= [--port=]\n"); +} + +struct RichMapsAndTypes { + std::map dbs; + std::map flags; + std::map levels; + rfl::Short<"l", std::map> labels; + rfl::Literal<"fast", "slow"> mode; + std::array coords; + std::tuple pair; +}; + +struct RecursiveNode { + std::string name; + std::unique_ptr next; +}; + +struct TrailingNewlineDesc { + rfl::Description<"Line 1\n\nLine 2\n", std::string> note; +}; + +TEST(cli, test_usage_maps_recursive_literals_and_formatting) { + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --dbs..host= --dbs..port= " + "--flags.[=] --levels.= " + "--labels.= --mode= " + "--coords= --pair=\n"); + + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --name= [--next=]\n"); + + EXPECT_EQ( + (rfl::cli::usage("app").value()), + "Usage: app --host-name= --verbose[=] " + "--tags= -p|--port= --database.host= " + "--database.port= [--log-level=]\n"); + + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app --note=\n" + "\n" + "Arguments:\n" + " --note= Line 1\n" + "\n" + " Line 2. Required.\n"); +} + } // namespace test_usage From c68e285e516e4f96c6dc72f3d68615d0f25cf2b4 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Tue, 17 Nov 2026 05:31:20 +0100 Subject: [PATCH 3/4] Add `--help` and `--version` to rfl::cli through rfl::cli::App rfl::cli::App<"name", "version", "description"> is a setting that turns on -h/--help and --version. rfl::cli::read_app, in the new header rfl/cli/read_app.hpp, reads the struct, or returns an rfl::cli::HelpOrVersion with the text to print, so callers tell help and version apart from errors without looking at the message. The help is returned before the struct is read, so required fields can be missing. The options are flags in the parser's option table, so grouped short options (-vh) and `--` treat them like any other flag. A field that takes their names does not compile: rfl::Short<"h", ...> wherever it sits among the field's wrappers, a field named help, or one named version when there is a version. The fourth parameter, rfl::cli::BuiltinHelp::long_only or ::none, leaves -h or the help out, and an empty version leaves out --version. usage shows the rows of the options that read_app handles, and the detailed form starts with the header. Without the setting, nothing changes, and read rejects it at compile time, because Result has no room for a help request. rfl/cli/read.hpp does not include usage.hpp. --- README.md | 13 ++ docs/content/supported_formats/cli.md | 87 ++++++- include/rfl/cli.hpp | 2 + include/rfl/cli/App.hpp | 260 +++++++++++++++++++++ include/rfl/cli/read.hpp | 5 + include/rfl/cli/read_app.hpp | 171 ++++++++++++++ include/rfl/cli/usage.hpp | 58 ++++- tests/cli/test_help_version.cpp | 315 ++++++++++++++++++++++++++ 8 files changed, 899 insertions(+), 12 deletions(-) create mode 100644 include/rfl/cli/App.hpp create mode 100644 include/rfl/cli/read_app.hpp create mode 100644 tests/cli/test_help_version.cpp diff --git a/README.md b/README.md index e39f622ed..3ca925ff3 100644 --- a/README.md +++ b/README.md @@ -384,6 +384,19 @@ if (argc > 1 && std::string_view(argv[1]) == "--help") { } ``` +Or let `rfl::cli::read_app` handle `-h`, `--help` and `--version`, turned on by the setting `rfl::cli::App`: + +```cpp +using MyApp = rfl::cli::App<"app", "1.0", "Processes data files.">; + +const auto result = rfl::cli::read_app(argc, argv).value(); +if (const auto* info = std::get_if(&result)) { + std::cout << info->text; // the help or "app 1.0" + return 0; +} +const auto& config = std::get(result); +``` + 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 433cecb03..f2579e1cf 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -256,19 +256,92 @@ 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: +## Help and version + +`--help` and `--version` are off by default: `rfl::cli::read` treats them +as it treats any option that matches no field. To turn them on, pass the +setting `rfl::cli::App<"name", "version", "description">` (each part is +optional) and call `rfl::cli::read_app` instead of `read`. It returns either +the struct or an `rfl::cli::HelpOrVersion` with the text to print: ```cpp +using CopyApp = rfl::cli::App<"copy", "1.2.0", "Copies a file.">; + +struct Copy { + rfl::Positional> source; + rfl::Short<"o", rfl::Description<"Where to copy it", std::string>> output; + rfl::Short<"v", std::optional> verbose; + rfl::Short<"j", rfl::DefaultVal> jobs = 1; +}; + int main(int argc, char* argv[]) { - if (argc > 1 && std::string_view(argv[1]) == "--help") { - std::cout << rfl::cli::usage(argv[0], true).value(); + const auto result = rfl::cli::read_app(argc, argv); + if (!result) { + std::cerr << result.error().what() << "\n\n" + << rfl::cli::usage(argv[0]); + return 2; + } + if (const auto* info = std::get_if(&*result)) { + std::cout << info->text; // info->kind is help or version return 0; } - const auto config = rfl::cli::read(argc, argv).value(); + const Copy& copy = std::get(*result); + // ... } ``` +`./copy --help` prints the detailed usage, with a header from the setting +and rows for the two options: + +``` +copy 1.2.0 +Copies a file. + +Usage: ./copy [-h|--help] [--version] -o|--output= [-v|--verbose[=]] [-j|--jobs=] + +Arguments: + -h, --help Show this help + --version Show the version + File to copy. Required. + -o, --output= Where to copy it. Required. + -v, --verbose[=] + -j, --jobs= +``` + +and `./copy --version` prints `copy 1.2.0`. + +- The help is returned before the struct is read, so it works when required + fields are missing or other values are invalid. A token before it that + cannot be split into options at all, such as `-o` without its value, is + still an error. If both are given, the help wins. +- `-h`, `--help` and `--version` are flags in the same option table as the + fields, so `-vh` works, `--` ends them, and `--help=false` does not ask for + the help. +- **A field that takes their names is a compile-time error**, as in + argparse (`conflicting option string: -h`): a field with + `rfl::Short<"h", ...>`, wherever `rfl::Short` sits among its wrappers, a + field named `help`, and, if there is a version, a field named `version`. + To use those names, opt out of the built-in option with the fourth + parameter, `rfl::cli::BuiltinHelp`: + + ```cpp + // -h is the field's, the help is --help only. + using Client = rfl::cli::App<"client", "1.0", "", rfl::cli::BuiltinHelp::long_only>; + // No help at all, like argparse's add_help=False: a field can be `help`. + using Tool = rfl::cli::App<"tool", "1.0", "", rfl::cli::BuiltinHelp::none>; + ``` + +- An empty version leaves out `--version`, so a field can be `version`. An + empty name is replaced by the program name (`argv[0]`). +- Pass the same settings to `usage` as to `read_app`: `usage` shows the + header (in the detailed form only) and the rows of the options that + `read_app` handles. +- `read_app` is in `rfl/cli/read_app.hpp`, which `rfl/cli.hpp` includes. + It takes `argc` and `argv` (narrow or wide, const or not), since + the help and the version show the program name. `rfl::cli::read>` does not compile, in any of its forms: its result has + no room for a help request. Other formats ignore the setting. + ## Supported types | Type | CLI format | Notes | @@ -307,7 +380,9 @@ Parsing proceeds in three stages: ## Files -- `include/rfl/cli/read.hpp` — public API +- `include/rfl/cli/read.hpp` — public API: `read` +- `include/rfl/cli/read_app.hpp` — public API: `read_app`, with `--help` and `--version` +- `include/rfl/cli/App.hpp` — `App<"name", "version", "description", BuiltinHelp>` setting for `--help` and `--version` - `include/rfl/cli/Reader.hpp` — Reader + `parse_value` overloads - `include/rfl/cli/Parser.hpp` — Parser type alias - `include/rfl/cli/parse_argv.hpp` — `argv` -> `ParsedArgs` diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index a35b9e025..ceb020655 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -2,11 +2,13 @@ #define RFL_CLI_HPP_ #include "../rfl.hpp" +#include "cli/App.hpp" #include "cli/Parser.hpp" #include "cli/Reader.hpp" #include "cli/options.hpp" #include "cli/parse_argv.hpp" #include "cli/read.hpp" +#include "cli/read_app.hpp" #include "cli/resolve_args.hpp" #include "cli/usage.hpp" diff --git a/include/rfl/cli/App.hpp b/include/rfl/cli/App.hpp new file mode 100644 index 000000000..dd705c4ef --- /dev/null +++ b/include/rfl/cli/App.hpp @@ -0,0 +1,260 @@ +#ifndef RFL_CLI_APP_HPP_ +#define RFL_CLI_APP_HPP_ + +#include +#include +#include +#include +#include + +#include "../Processors.hpp" +#include "../internal/StringLiteral.hpp" +#include "options.hpp" + +namespace rfl::cli { + +/// Which built-in help options rfl::cli::App adds. +enum class BuiltinHelp { + /// `-h` and `--help` + short_and_long, + /// `--help` only, so that a field can have rfl::Short<"h", ...> + long_only, + /// None, so that a field can be called `help` + none +}; + +/// A setting that turns on `--help` and `--version` in rfl::cli::read_app, +/// and adds a header and their rows to rfl::cli::usage. Without it, `--help` +/// and `--version` are ordinary options, as they always were. +/// using MyApp = rfl::cli::App<"copy", "1.2.0", "Copies files.">; +/// rfl::cli::read_app(argc, argv); +/// rfl::cli::usage(argv[0], true); +/// - `-h` and `--help` ask for the help, `--version` for the version. They +/// are flags in the option table, so they can be grouped (`-vh`) like any +/// other, and `--` ends them. +/// - A field that takes one of their names is a compile-time error, as in +/// argparse ("conflicting option string: -h"): rfl::Short<"h", ...> +/// wherever it sits among the field's wrappers, a field named `help` or, +/// with a version, `version` (after processors). Opt out of them instead: +/// BuiltinHelp::long_only leaves `-h` to a field, BuiltinHelp::none leaves +/// out the help, like argparse's add_help=False, and an empty version +/// leaves out `--version`. +/// This is a marker type (doesn't modify data) that only rfl::cli::read_app +/// and rfl::cli::usage look at. Other formats ignore it. rfl::cli::read +/// rejects it at compile time, because its result has no room for a help +/// request. +/// @tparam _name The name shown in the header and before the version. If it +/// is empty, the program name (argv[0]) is used. +/// @tparam _version The version shown by `--version` and in the header +/// @tparam _about A one-line description, shown in the header +/// @tparam _help Which built-in help options to add +template +struct App { + static constexpr std::string_view name = _name.string_view(); + static constexpr std::string_view version = _version.string_view(); + static constexpr std::string_view about = _about.string_view(); + static constexpr BuiltinHelp help = _help; + + /// Identity process function - returns the named tuple unchanged. + /// @tparam StructType The struct type being processed + /// @param _named_tuple The named tuple representation of the struct + /// @return The same named tuple (unchanged) + template + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +/// What rfl::cli::read_app returns instead of the struct when the command +/// line asks for the help or the version. The caller prints `text` (to +/// stdout, usually) and exits successfully. +struct HelpOrVersion { + enum class Kind { help, version }; + + Kind kind; + + /// The help (rfl::cli::usage with the details) or the version line, ending + /// with a newline. + std::string text; +}; + +namespace internal { + +template +struct app_settings { + static constexpr size_t count = 0; + static constexpr std::string_view name = ""; + static constexpr std::string_view version = ""; + static constexpr std::string_view about = ""; + static constexpr BuiltinHelp help = BuiltinHelp::none; +}; + +template +struct app_settings> { + using AppType = App<_name, _version, _about, _help>; + static constexpr size_t count = 1; + static constexpr std::string_view name = AppType::name; + static constexpr std::string_view version = AppType::version; + static constexpr std::string_view about = AppType::about; + static constexpr BuiltinHelp help = AppType::help; +}; + +/// The first of Ps that is an rfl::cli::App, or void. +template +struct find_app { + using type = void; +}; + +template +struct find_app { + using type = std::conditional_t<(app_settings

::count > 0), P, + typename find_app::type>; +}; + +template +struct app_settings> + : app_settings::type> { + static constexpr size_t count = (app_settings::count + ... + 0); + static_assert(count <= 1, "Pass at most one rfl::cli::App."); +}; + +/// The rfl::cli::App in the processors, if any. +template +using app_settings_t = + app_settings>>; + +/// Whether the processors contain rfl::cli::App. +template +constexpr bool has_app_v = app_settings_t::count > 0; + +/// The built-in options that rfl::cli::App adds. +struct BuiltinOptions { + /// `--help` + bool help = false; + /// `-h`, for `--help` + bool help_short = false; + /// `--version` + bool version = false; +}; + +/// The long name of the built-in help. +inline constexpr std::string_view help_option = "help"; + +/// The short name of the built-in help. +inline constexpr std::string_view help_short_option = "h"; + +/// The long name of the built-in version. +inline constexpr std::string_view version_option = "version"; + +/// Whether a top-level field of the NamedTuple NT is called `_name`. +template +consteval bool has_field_named(const std::string_view _name, + std::index_sequence<_is...>) { + return ((field_info::name() == _name) || ...); +} + +/// Whether a top-level field of the NamedTuple NT has the short name +/// `_name`, wherever rfl::Short sits among its wrappers. +template +consteval bool has_short_named(const std::string_view _name, + std::index_sequence<_is...>) { + return ((field_info::is_short + && get_short_name().string_view() == _name) + || ...); +} + +/// Adds the built-in options of the rfl::cli::App in ProcessorsType to +/// _options. They are flags, so the parser handles them as it does any +/// flag. A field of T that takes one of their names does not compile. +/// @return Which of them were added +template +BuiltinOptions add_builtin_options(Options* _options) { + using Settings = app_settings_t; + auto builtin = BuiltinOptions{}; + if constexpr (Settings::count > 0) { + builtin.help = Settings::help != BuiltinHelp::none; + builtin.help_short = Settings::help == BuiltinHelp::short_and_long; + builtin.version = !Settings::version.empty(); + using U = unwrapped_option_t; + if constexpr (is_option_struct_v) { + using NT = option_fields_t; + constexpr auto fields = std::make_index_sequence(); + static_assert(Settings::help == BuiltinHelp::none + || !has_field_named(help_option, fields), + "A field named 'help' clashes with the built-in --help " + "of rfl::cli::App. Rename the field, or pass " + "rfl::cli::BuiltinHelp::none to rfl::cli::App."); + static_assert(Settings::help != BuiltinHelp::short_and_long + || !has_short_named(help_short_option, fields), + "A field with rfl::Short<\"h\", ...> clashes with the " + "built-in -h of rfl::cli::App. Use another short name, " + "or pass rfl::cli::BuiltinHelp::long_only to " + "rfl::cli::App to keep only --help."); + static_assert(Settings::version.empty() + || !has_field_named(version_option, fields), + "A field named 'version' clashes with the built-in " + "--version of rfl::cli::App. Rename the field, or give " + "rfl::cli::App no version."); + } + if (builtin.help) { + _options->long_options[std::string(help_option)] = + Option{OptionKind::flag}; + } + if (builtin.help_short) { + _options->short_options[std::string(help_short_option)] = + std::string(help_option); + } + if (builtin.version) { + _options->long_options[std::string(version_option)] = + Option{OptionKind::flag}; + } + } + return builtin; +} + +/// The header of the help: "name version" and the description, each on a +/// line of its own if it is given, and a blank line. Empty if the +/// processors contain no rfl::cli::App or it has none of them. +template +std::string app_header(const std::string& _program_name) { + using Settings = app_settings_t; + auto header = std::string(); + if constexpr (Settings::count > 0) { + if (!Settings::name.empty() || !Settings::version.empty()) { + header += Settings::name.empty() ? _program_name + : std::string(Settings::name); + if (!Settings::version.empty()) { + header += " " + std::string(Settings::version); + } + header += '\n'; + } + if (!Settings::about.empty()) { + header += std::string(Settings::about) + '\n'; + } + if (!header.empty()) { + header += '\n'; + } + } + return header; +} + +/// What `--version` prints: "name version", or "program version" if the +/// name is empty. +template +std::string app_version_text(const std::string& _program_name) { + using Settings = app_settings_t; + return (Settings::name.empty() ? _program_name + : std::string(Settings::name)) + + " " + std::string(Settings::version) + '\n'; +} + +} // namespace internal + +} // namespace rfl::cli + +#endif diff --git a/include/rfl/cli/read.hpp b/include/rfl/cli/read.hpp index abcbc4ceb..bccf5e4d7 100644 --- a/include/rfl/cli/read.hpp +++ b/include/rfl/cli/read.hpp @@ -7,6 +7,7 @@ #include "../Processors.hpp" #include "../SnakeCaseToKebabCase.hpp" +#include "App.hpp" #include "Parser.hpp" #include "Reader.hpp" #include "options.hpp" @@ -33,6 +34,10 @@ rfl::Result read_parsed(ParsedArgs _parsed, const Options& _options) { template rfl::Result parse_and_read(const ParseFn& _parse) { using ProcessorsType = Processors; + static_assert(!internal::has_app_v, + "rfl::cli::App turns on --help and --version, which " + "rfl::cli::read cannot report. Call rfl::cli::read_app " + "instead."); const auto options = make_options(); return check_short_names(options) .and_then([&](bool) { return _parse(options); }) diff --git a/include/rfl/cli/read_app.hpp b/include/rfl/cli/read_app.hpp new file mode 100644 index 000000000..07784603e --- /dev/null +++ b/include/rfl/cli/read_app.hpp @@ -0,0 +1,171 @@ +#ifndef RFL_CLI_READ_APP_HPP_ +#define RFL_CLI_READ_APP_HPP_ + +#include +#include +#include +#include +#include + +#include "../Processors.hpp" +#include "../Result.hpp" +#include "../SnakeCaseToKebabCase.hpp" +#include "../internal/strings/utf8_conversions.hpp" +#include "App.hpp" +#include "Reader.hpp" +#include "options.hpp" +#include "parse_argv.hpp" +#include "read.hpp" +#include "resolve_args.hpp" +#include "usage.hpp" + +namespace rfl::cli { + +namespace internal { + +/// Takes the built-in option `_key` out of `_args`, if it is enabled and +/// was given, and reads its value as the reader reads a bool. +/// @return Whether it was given and set +inline rfl::Result take_builtin_flag( + const bool _enabled, std::map* _args, + const std::string_view _key) { + if (!_enabled) { + return false; + } + const auto it = _args->find(std::string(_key)); + if (it == _args->end()) { + return false; + } + const auto value = std::move(it->second); + _args->erase(it); + // -h is held under "h", but named after the option it stands for. + return parse_value( + value, _key == help_short_option ? std::string(help_option) + : std::string(_key)); +} + +/// Like parse_and_read, with the built-in options of the rfl::cli::App in +/// Ps. If the arguments ask for the help or the version, returns its text +/// instead of reading the struct. +template +rfl::Result> parse_and_read_app( + const std::string& _program_name, const ParseFn& _parse) { + using ProcessorsType = Processors; + using ResultType = std::variant; + auto options = make_options(); + const auto builtin = add_builtin_options(&options); + const auto short_names = check_short_names(options); + if (!short_names) { + return error(short_names.error().what()); + } + auto parsed = _parse(options); + if (!parsed) { + return error(parsed.error().what()); + } + + // Take the built-in options out, so that the struct never sees them. + const auto help = + take_builtin_flag(builtin.help, &parsed->named, help_option); + const auto help_short = take_builtin_flag( + builtin.help_short, &parsed->short_args, help_short_option); + const auto version = + take_builtin_flag(builtin.version, &parsed->named, version_option); + for (const auto* r : {&help, &help_short, &version}) { + if (!*r) { + return error(r->error().what()); + } + } + + if (*help || *help_short) { + return usage(_program_name, true) + .transform([](std::string _text) { + return ResultType( + HelpOrVersion{HelpOrVersion::Kind::help, std::move(_text)}); + }); + } + if (*version) { + return ResultType( + HelpOrVersion{HelpOrVersion::Kind::version, + app_version_text(_program_name)}); + } + return read_parsed(std::move(*parsed), options) + .transform([](T&& _t) { return ResultType(std::move(_t)); }); +} + +/// argv[0], or an empty string if there is none. +inline std::string program_name(int argc, const char* const argv[]) { + return argc > 0 && argv && argv[0] ? std::string(argv[0]) : std::string(); +} + +/// argv[0] converted to UTF-8, or an empty string if there is none or it +/// cannot be converted. +inline std::string program_name(int argc, const wchar_t* const argv[]) { + if (argc <= 0 || !argv || !argv[0]) { + return std::string(); + } + return rfl::internal::strings::wstring_to_utf8(std::wstring(argv[0])) + .value_or(std::string()); +} + +} // namespace internal + +/// Like rfl::cli::read, but with `--help` and `--version` turned on by an +/// rfl::cli::App in Ps (see App.hpp). If the command line asks for one of +/// them, the result holds an rfl::cli::HelpOrVersion with the text to print, +/// and the struct is not read, so missing or invalid fields don't matter. +/// The help wins if both are given. Otherwise, it holds the struct, read +/// exactly as rfl::cli::read would. Errors are errors either way. +/// const auto result = rfl::cli::read_app(argc, argv); +/// if (!result) { ... result.error().what() ... return 2; } +/// if (const auto* info = std::get_if(&*result)) { +/// std::cout << info->text; +/// return 0; +/// } +/// const auto& config = std::get(*result); +/// `--help` and `--version` are found once argv is split into options, so +/// an earlier token that fails to parse (such as an option that is missing +/// its value) is still an error. +/// @tparam T The struct type to parse into +/// @tparam Ps Optional processors and settings, as for rfl::cli::read, and +/// at most one rfl::cli::App +/// @param argc Number of command-line arguments +/// @param argv Array of command-line argument strings. argv[0] is the +/// program name, which the help and the version show if the rfl::cli::App +/// has no name. +/// @return The struct, or the help or version text, or an error +template +rfl::Result> read_app(int argc, + const char* const argv[]) { + return internal::parse_and_read_app( + internal::program_name(argc, argv), + [&](const auto& _options) { + return internal::parse_argv(argc, argv, _options); + }); +} + +template +rfl::Result> read_app(int argc, char* argv[]) { + return read_app(argc, static_cast(argv)); +} + +/// Like rfl::cli::read_app, for wide-character arguments, which are +/// converted to UTF-8 first. +template +rfl::Result> read_app( + int argc, const wchar_t* const argv[]) { + return internal::parse_and_read_app( + internal::program_name(argc, argv), + [&](const auto& _options) { + return internal::parse_argv(argc, argv, _options); + }); +} + +template +rfl::Result> read_app(int argc, + wchar_t* argv[]) { + return read_app(argc, static_cast(argv)); +} + +} // namespace rfl::cli + +#endif diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index 199d90c43..a519d2f94 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -25,6 +25,7 @@ #include "../parsing/schema/Definition.hpp" #include "../parsing/schema/Type.hpp" #include "../parsing/schema/make.hpp" +#include "App.hpp" #include "Reader.hpp" #include "options.hpp" #include "resolve_args.hpp" @@ -54,6 +55,9 @@ struct UsageArg { /// Whether `required` was taken from the parser's compile-time traits, so /// that the schema must not override it. bool required_is_known = false; + /// Whether the option is shown without a value, as the built-in `--help` + /// and `--version` are. + bool bare = false; /// The placeholder for one value: "", "" or "". Lists /// are rendered from it with the list delimiter. std::string value = ""; @@ -295,6 +299,9 @@ inline std::string usage_arg_to_string(const UsageArg& _arg, auto str = _arg.short_name.empty() ? std::string() : "-" + _arg.short_name + _short_sep; str += "--" + _arg.name; + if (_arg.bare) { + return str; + } const auto value = usage_value_to_string(_arg); switch (_arg.kind) { case OptionKind::flag: @@ -344,10 +351,39 @@ inline std::string usage_help_text(const UsageArg& _arg) { return text; } +/// The rows of the built-in options of rfl::cli::App that no field takes. +inline std::vector builtin_usage_args( + const BuiltinOptions& _builtin) { + auto args = std::vector(); + const auto make = [](std::string_view _name, std::string_view _short_name, + std::string _description) { + auto arg = UsageArg{}; + arg.name = std::string(_name); + arg.short_name = std::string(_short_name); + arg.kind = OptionKind::flag; + arg.bare = true; + arg.required = false; + arg.description = std::move(_description); + return arg; + }; + if (_builtin.help) { + args.push_back(make(help_option, + _builtin.help_short ? help_short_option : "", + "Show this help")); + } + if (_builtin.version) { + args.push_back(make(version_option, "", "Show the version")); + } + return args; +} + +/// @param _header Shown before the usage line in the detailed form +/// (rfl::cli::App). inline std::string format_usage(const std::string& _program_name, const std::vector& _args, - const bool _detailed) { - auto out = "Usage: " + _program_name; + const bool _detailed, + const std::string& _header) { + auto out = (_detailed ? _header : std::string()) + "Usage: " + _program_name; for (const auto& arg : _args) { const auto str = usage_arg_to_string(arg, "|"); out += arg.required ? " " + str : " [" + str + "]"; @@ -399,6 +435,11 @@ inline std::string format_usage(const std::string& _program_name, /// /// The help text lists the description (rfl::Description), the allowed /// values of enums and literals and whether the argument is required. +/// +/// With an rfl::cli::App in Ps, the detailed form starts with its header +/// (name, version and description), and both forms list the built-in +/// `-h, --help` and `--version` that rfl::cli::read_app handles, unless a +/// field takes their names. /// @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] @@ -412,8 +453,9 @@ rfl::Result usage(const std::string& _program_name, using ProcessorsType = Processors; using U = internal::unwrapped_option_t; // The table that read() parses with, so the help shows what the parser - // accepts. - const auto options = internal::make_options(); + // accepts, plus the built-in options of rfl::cli::App that read_app handles. + auto options = internal::make_options(); + const auto builtin = internal::add_builtin_options(&options); return internal::check_short_names(options).and_then( [&](auto) -> rfl::Result { try { @@ -433,9 +475,13 @@ rfl::Result usage(const std::string& _program_name, auto collector = internal::UsageCollector( &definition, &meta, &options, rfl::internal::no_optionals_v); - const auto args = collector.collect( + auto args = internal::builtin_usage_args(builtin); + const auto fields = collector.collect( rfl::internal::default_if_missing_v); - return internal::format_usage(_program_name, args, _detailed); + args.insert(args.end(), fields.begin(), fields.end()); + return internal::format_usage( + _program_name, args, _detailed, + internal::app_header(_program_name)); } catch (const std::exception& e) { return error(e.what()); } diff --git a/tests/cli/test_help_version.cpp b/tests/cli/test_help_version.cpp new file mode 100644 index 000000000..147e40b14 --- /dev/null +++ b/tests/cli/test_help_version.cpp @@ -0,0 +1,315 @@ +#include + +#include +#include +#include +#include +#include +#include + +// `--help` and `--version` in rfl::cli::read_app, turned on by +// rfl::cli::App, and their rows in rfl::cli::usage. +namespace test_help_version { + +template +rfl::Result> read_app( + std::vector _args) { + _args.insert(_args.begin(), "app"); + return rfl::cli::read_app(static_cast(_args.size()), + const_cast(_args.data())); +} + +template +rfl::Result read(std::vector _args) { + _args.insert(_args.begin(), "app"); + return rfl::cli::read(static_cast(_args.size()), + const_cast(_args.data())); +} + +/// The help or version text, or "(struct)" or the error. +template +std::string text_of( + const rfl::Result>& _result) { + if (!_result) { + return std::string("error: ") + _result.error().what(); + } + const auto* info = std::get_if(&*_result); + return info ? info->text : std::string("(struct)"); +} + +template +std::optional kind_of( + const rfl::Result>& _result) { + if (!_result) { + return std::nullopt; + } + const auto* info = std::get_if(&*_result); + return info ? std::optional(info->kind) : std::nullopt; +} + +using Kind = rfl::cli::HelpOrVersion::Kind; + +struct Copy { + rfl::Positional> source; + rfl::Short<"o", rfl::Description<"Where to copy it", std::string>> output; + rfl::Short<"v", std::optional> verbose; + rfl::Short<"j", std::optional> jobs; +}; + +using CopyApp = rfl::cli::App<"copy", "1.2.0", "Copies a file.">; + +constexpr const char* copy_help = + "copy 1.2.0\n" + "Copies a file.\n" + "\n" + "Usage: app [-h|--help] [--version] -o|--output= " + "[-v|--verbose[=]] [-j|--jobs=]\n" + "\n" + "Arguments:\n" + " -h, --help Show this help\n" + " --version Show the version\n" + " File to copy. Required.\n" + " -o, --output= Where to copy it. Required.\n" + " -v, --verbose[=]\n" + " -j, --jobs=\n"; + +TEST(cli, test_help_version_usage) { + EXPECT_EQ((rfl::cli::usage("app", true).value()), copy_help); + + // The usage line has no header. + EXPECT_EQ((rfl::cli::usage("app").value()), + "Usage: app [-h|--help] [--version] -o|--output= " + "[-v|--verbose[=]] [-j|--jobs=]\n"); + + // Without rfl::cli::App, there are no such rows. + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app -o|--output= " + "[-v|--verbose[=]] [-j|--jobs=]\n"); +} + +TEST(cli, test_help_version_help) { + // The required fields are missing, but the help is shown. + for (const auto& args : std::vector>{ + {"--help"}, {"-h"}, {"-vh"}, {"in.txt", "-h"}, + {"--version", "--help"}, {"--help=true"}, {"-h", "--jobs=x"}}) { + const auto result = read_app(args); + EXPECT_EQ(kind_of(result), Kind::help) << args.front(); + EXPECT_EQ(text_of(result), copy_help) << args.front(); + } +} + +TEST(cli, test_help_version_version) { + for (const auto& args : std::vector>{ + {"--version"}, {"in.txt", "--version", "-v"}}) { + const auto result = read_app(args); + EXPECT_EQ(kind_of(result), Kind::version) << args.front(); + EXPECT_EQ(text_of(result), "copy 1.2.0\n") << args.front(); + } +} + +TEST(cli, test_help_version_reads_the_struct) { + const auto result = + read_app({"in.txt", "-o", "out.txt", "-j", "4"}); + ASSERT_TRUE(result) << result.error().what(); + const auto* copy = std::get_if(&*result); + ASSERT_TRUE(copy); + EXPECT_EQ(copy->source.value().value(), "in.txt"); + EXPECT_EQ(copy->output.value().value(), "out.txt"); + EXPECT_EQ(copy->jobs.value(), 4); + + // `--help=false` does not ask for the help. + const auto not_help = + read_app({"in.txt", "-o", "out.txt", "--help=false"}); + ASSERT_TRUE(not_help) << not_help.error().what(); + EXPECT_TRUE(std::holds_alternative(*not_help)); +} + +TEST(cli, test_help_version_errors) { + // Errors are errors, not help. + EXPECT_EQ(text_of(read_app({"in.txt"})), + "error: Field named 'output' not found."); + EXPECT_EQ(text_of(read_app({"--help=yes"})), + "error: Could not cast 'yes' to boolean for key 'help'."); + // An earlier token that fails to parse is an error. + EXPECT_EQ(text_of(read_app({"-o", "--help"})), + "error: Missing value for option '-o'."); + // After `--`, everything is positional. + EXPECT_EQ(text_of(read_app({"-o", "x", "--", "--help"})), + "(struct)"); +} + +TEST(cli, test_help_version_off_by_default) { + // Without rfl::cli::App, `--help` is an option like any other: ignored + // unless rfl::NoExtraFields is passed. + const auto ignored = read({"in.txt", "-o", "out.txt", "--help"}); + ASSERT_TRUE(ignored) << ignored.error().what(); + const auto rejected = + read({"in.txt", "-o", "out.txt", "--help"}); + ASSERT_FALSE(rejected); + EXPECT_NE(rejected.error().what().find("help"), std::string::npos) + << rejected.error().what(); + EXPECT_FALSE(read({"-h"})); + + // read_app without rfl::cli::App is read. + EXPECT_EQ(text_of(read_app({"in.txt", "-o", "out.txt", "--help"})), + "(struct)"); +} + +// A field that takes the name of a built-in option does not compile: a +// field with rfl::Short<"h", ...> (wherever it sits among the field's +// wrappers), a field named `help`, or, with a version, a field named +// `version`. rfl::cli::App opts out of them instead. + +// rfl::cli::BuiltinHelp::long_only leaves `-h` to a field: the help is +// `--help` only. +struct WithHostShort { + rfl::Short<"h", rfl::Description<"Host to connect to", std::string>> host; +}; + +using LongHelpApp = + rfl::cli::App<"client", "", "", rfl::cli::BuiltinHelp::long_only>; + +TEST(cli, test_help_version_long_only) { + EXPECT_EQ((rfl::cli::usage("client", true) + .value()), + "client\n" + "\n" + "Usage: client [--help] -h|--host=\n" + "\n" + "Arguments:\n" + " --help Show this help\n" + " -h, --host= Host to connect to. Required.\n"); + + const auto host = read_app({"-h", "example.com"}); + ASSERT_TRUE(host) << host.error().what(); + EXPECT_EQ(std::get(*host).host.value().value(), + "example.com"); + EXPECT_EQ(kind_of(read_app({"--help"})), + Kind::help); + + // No version: `--version` is an unknown option. + const auto ver_rejected = + read_app({"--version"}); + ASSERT_FALSE(ver_rejected); + EXPECT_NE(ver_rejected.error().what().find("version"), std::string::npos) + << ver_rejected.error().what(); +} + +// The same with rfl::Short inside other wrappers. +struct WithWrappedHostShort { + rfl::Description<"Host to connect to", rfl::Short<"h", std::string>> host; +}; + +TEST(cli, test_help_version_long_only_wrapped_short_h) { + EXPECT_EQ((rfl::cli::usage("client") + .value()), + "Usage: client [--help] -h|--host=\n"); + const auto host = + read_app({"-h", "example.com"}); + ASSERT_TRUE(host) << host.error().what(); + EXPECT_EQ(std::get(*host).host.value().value(), + "example.com"); +} + +// rfl::cli::BuiltinHelp::none leaves out the help, like argparse's +// add_help=False, so a field can be called `help`. Here it is +// `--help=`. +struct WithHelpField { + rfl::Description<"Show help on a topic", std::optional> help; + rfl::Short<"n", std::optional> count; +}; + +TEST(cli, test_help_version_without_help) { + using MyApp = rfl::cli::App<"tool", "0.1", "", rfl::cli::BuiltinHelp::none>; + EXPECT_EQ((rfl::cli::usage("tool", true).value()), + "tool 0.1\n" + "\n" + "Usage: tool [--version] [--help=] [-n|--count=]\n" + "\n" + "Arguments:\n" + " --version Show the version\n" + " --help= Show help on a topic\n" + " -n, --count=\n"); + + const auto topic = read_app({"--help=lists"}); + ASSERT_TRUE(topic) << topic.error().what(); + EXPECT_EQ(std::get(*topic).help.value().value(), "lists"); + // `-h` is not the help either. + EXPECT_FALSE((read_app({"-h"}))); + EXPECT_EQ(text_of(read_app({"--version"})), + "tool 0.1\n"); +} + +// Without a version, there is no `--version`, so a field can be called +// `version`. +struct WithVersionField { + std::optional version; +}; + +TEST(cli, test_help_version_without_version) { + using MyApp = rfl::cli::App<"tool">; + const auto result = read_app({"--version=3"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(std::get(*result).version, 3); + EXPECT_EQ((rfl::cli::usage("tool").value()), + "Usage: tool [-h|--help] [--version=]\n"); +} + +TEST(cli, test_help_version_without_name) { + // Without a name, the program name is used. + using MyApp = rfl::cli::App<"", "2.0", "", rfl::cli::BuiltinHelp::long_only>; + EXPECT_EQ(text_of(read_app({"--version"})), + "app 2.0\n"); + EXPECT_EQ((rfl::cli::usage("app", true).value()), + "app 2.0\n" + "\n" + "Usage: app [--help] [--version] -h|--host=\n" + "\n" + "Arguments:\n" + " --help Show this help\n" + " --version Show the version\n" + " -h, --host= Host to connect to. Required.\n"); + + // Without anything, there is no header and no `--version`. + EXPECT_EQ((rfl::cli::usage>("app", true).value()), + "Usage: app [-h|--help] [--version=]\n" + "\n" + "Arguments:\n" + " -h, --help Show this help\n" + " --version=\n"); +} + +TEST(cli, test_help_version_no_extra_fields) { + // The built-in options are known options, so rfl::NoExtraFields accepts + // them. + EXPECT_EQ( + (kind_of(read_app({"--help"}))), + Kind::help); + const auto result = read_app( + {"in.txt", "-o", "out.txt", "--help=0"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(std::holds_alternative(*result)); +} + +TEST(cli, test_help_version_spellings) { + // `-h` and `--help` together are the help. + EXPECT_EQ(kind_of(read_app({"-h", "--help"})), Kind::help); + // A negative number is still a positional argument. + const auto negative = read_app({"-5", "-o", "out.txt"}); + ASSERT_TRUE(negative) << negative.error().what(); + EXPECT_EQ(std::get(*negative).source.value().value(), "-5"); + // const argv, as for rfl::cli::read. + const char* const args[] = {"app", "-vh"}; + EXPECT_EQ(kind_of(rfl::cli::read_app(2, args)), Kind::help); +} + +TEST(cli, test_help_version_wide) { + const wchar_t* args[] = {L"app", L"--version"}; + const auto result = + rfl::cli::read_app(2, const_cast(args)); + EXPECT_EQ(text_of(result), "copy 1.2.0\n"); +} + +using Strings = std::vector; + +} // namespace test_help_version From 9b633264a90d6e1914898485adbec827660c947e Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 22:39:25 +0100 Subject: [PATCH 4/4] Address Judge blockers: fix cli.md usage() unwrap and DefaultVal wrapper order, update usage.hpp clash doc comments, polish App header/version and tests --- docs/content/supported_formats/cli.md | 4 +-- include/rfl/cli/App.hpp | 23 +++++++++------ include/rfl/cli/usage.hpp | 7 +++-- tests/cli/test_help_version.cpp | 40 ++++++++++++++++++++++++--- 4 files changed, 57 insertions(+), 17 deletions(-) diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index f2579e1cf..101e84c69 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -271,14 +271,14 @@ struct Copy { rfl::Positional> source; rfl::Short<"o", rfl::Description<"Where to copy it", std::string>> output; rfl::Short<"v", std::optional> verbose; - rfl::Short<"j", rfl::DefaultVal> jobs = 1; + rfl::DefaultVal> jobs = 1; }; int main(int argc, char* argv[]) { const auto result = rfl::cli::read_app(argc, argv); if (!result) { std::cerr << result.error().what() << "\n\n" - << rfl::cli::usage(argv[0]); + << rfl::cli::usage(argv[0]).value_or(""); return 2; } if (const auto* info = std::get_if(&*result)) { diff --git a/include/rfl/cli/App.hpp b/include/rfl/cli/App.hpp index dd705c4ef..46e7e7b6c 100644 --- a/include/rfl/cli/App.hpp +++ b/include/rfl/cli/App.hpp @@ -104,7 +104,7 @@ struct app_settings> { static constexpr BuiltinHelp help = AppType::help; }; -/// The first of Ps that is an rfl::cli::App, or void. +/// The first of Ps that is or contains an rfl::cli::App, or void. template struct find_app { using type = void; @@ -226,10 +226,14 @@ std::string app_header(const std::string& _program_name) { auto header = std::string(); if constexpr (Settings::count > 0) { if (!Settings::name.empty() || !Settings::version.empty()) { - header += Settings::name.empty() ? _program_name - : std::string(Settings::name); + const auto title = Settings::name.empty() ? _program_name + : std::string(Settings::name); + header += title; if (!Settings::version.empty()) { - header += " " + std::string(Settings::version); + if (!title.empty()) { + header += ' '; + } + header += std::string(Settings::version); } header += '\n'; } @@ -244,13 +248,16 @@ std::string app_header(const std::string& _program_name) { } /// What `--version` prints: "name version", or "program version" if the -/// name is empty. +/// name is empty (or just "version" if both are empty). template std::string app_version_text(const std::string& _program_name) { using Settings = app_settings_t; - return (Settings::name.empty() ? _program_name - : std::string(Settings::name)) - + " " + std::string(Settings::version) + '\n'; + const auto title = Settings::name.empty() ? _program_name + : std::string(Settings::name); + if (title.empty()) { + return std::string(Settings::version) + '\n'; + } + return title + " " + std::string(Settings::version) + '\n'; } } // namespace internal diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index a519d2f94..9a0811a3d 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -351,7 +352,7 @@ inline std::string usage_help_text(const UsageArg& _arg) { return text; } -/// The rows of the built-in options of rfl::cli::App that no field takes. +/// The rows of the built-in options enabled by rfl::cli::App. inline std::vector builtin_usage_args( const BuiltinOptions& _builtin) { auto args = std::vector(); @@ -438,8 +439,8 @@ inline std::string format_usage(const std::string& _program_name, /// /// With an rfl::cli::App in Ps, the detailed form starts with its header /// (name, version and description), and both forms list the built-in -/// `-h, --help` and `--version` that rfl::cli::read_app handles, unless a -/// field takes their names. +/// `-h, --help` and `--version` options that rfl::cli::App enables (unless +/// opted out via rfl::cli::BuiltinHelp or an empty version). /// @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_help_version.cpp b/tests/cli/test_help_version.cpp index 147e40b14..710a7e5f7 100644 --- a/tests/cli/test_help_version.cpp +++ b/tests/cli/test_help_version.cpp @@ -304,12 +304,44 @@ TEST(cli, test_help_version_spellings) { } TEST(cli, test_help_version_wide) { - const wchar_t* args[] = {L"app", L"--version"}; - const auto result = - rfl::cli::read_app(2, const_cast(args)); + const wchar_t* const args[] = {L"app", L"--version"}; + const auto result = rfl::cli::read_app(2, args); EXPECT_EQ(text_of(result), "copy 1.2.0\n"); } -using Strings = std::vector; +TEST(cli, test_help_version_edge_cases) { + // Nested Processors. + EXPECT_EQ( + (text_of(read_app>({"--version"}))), + "copy 1.2.0\n"); + + // Description-only header (empty name and version). + using AboutOnlyApp = rfl::cli::App<"", "", "Standalone description.">; + const auto about_usage = + rfl::cli::usage("./copy", true).value(); + EXPECT_TRUE(about_usage.starts_with("Standalone description.\n\nUsage: ./copy")) + << about_usage; + + // Empty App::name and empty program_name must not emit a leading space. + using VerOnlyApp = rfl::cli::App<"", "2.0">; + const char* const empty_prog[] = {"", "--version"}; + EXPECT_EQ(text_of(rfl::cli::read_app(2, empty_prog)), + "2.0\n"); + const auto ver_header = rfl::cli::usage("", true).value(); + EXPECT_TRUE(ver_header.starts_with("2.0\n\nUsage: ")) << ver_header; + + // Both --help and --version: help wins in either order. + EXPECT_EQ(kind_of(read_app({"--help", "--version"})), + Kind::help); + EXPECT_EQ(kind_of(read_app({"--version", "--help"})), + Kind::help); + + // Explicit false flags do not trigger help/version. + EXPECT_EQ(kind_of(read_app({"--help=false", "--version"})), + Kind::version); + EXPECT_EQ(text_of(read_app( + {"in.txt", "-o", "out.txt", "-h=false", "--version=false"})), + "(struct)"); +} } // namespace test_help_version