From c68e285e516e4f96c6dc72f3d68615d0f25cf2b4 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Tue, 17 Nov 2026 05:31:20 +0100 Subject: [PATCH 1/2] 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 2/2] 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