diff --git a/README.md b/README.md index 33f883ef..1715ef5d 100644 --- a/README.md +++ b/README.md @@ -382,6 +382,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); +``` + `rfl::ImplicitValue` lets an option be given without a value, which then stands for the text: ```cpp diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index b375c781..3bcc7d8a 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -586,19 +586,95 @@ 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= Default: 1. +``` + +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 with `rfl::cli::OptionsFirst` + they are passed through after the first positional argument. With + `rfl::cli::AllowAbbreviations`, `--hel` works too, and `--ver` is + ambiguous if there is also a `--verbose`. `--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 | @@ -638,7 +714,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 + empty `DefaultVal` and `std::wstring` items - `include/rfl/cli/KeepEmptyItems.hpp` — `KeepEmptyItems` processor diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index 9a86a5d4..c37792ee 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -3,6 +3,7 @@ #include "../rfl.hpp" #include "cli/AllowAbbreviations.hpp" +#include "cli/App.hpp" #include "cli/KeepEmptyItems.hpp" #include "cli/ListDelimiter.hpp" #include "cli/OptionsFirst.hpp" @@ -12,6 +13,7 @@ #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 00000000..356d61a4 --- /dev/null +++ b/include/rfl/cli/App.hpp @@ -0,0 +1,261 @@ +#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`) and, +/// with rfl::cli::AllowAbbreviations, abbreviated (`--hel`) 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 714c50e4..6cb7ed25 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 "KeepEmptyItems.hpp" #include "ListDelimiter.hpp" #include "Parser.hpp" @@ -47,6 +48,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 00000000..07784603 --- /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 23d108c0..a2878da2 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -32,6 +32,7 @@ #include "../parsing/schema/ValidationType.hpp" #include "../parsing/schema/make.hpp" #include "../to_generic.hpp" +#include "App.hpp" #include "ListDelimiter.hpp" #include "OptionsFirst.hpp" #include "Reader.hpp" @@ -70,6 +71,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 = ""; @@ -536,6 +540,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, _delimiter); switch (_arg.kind) { case OptionKind::flag: @@ -598,19 +605,48 @@ 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). /// @param _options_first Whether the options end at the first positional /// argument (rfl::cli::OptionsFirst), so the synopsis lists them first. inline std::string format_usage(const std::string& _program_name, const std::vector& _args, const bool _detailed, const std::optional _delimiter, - const bool _options_first) { + const bool _options_first, + const std::string& _header) { auto synopsis = _args; if (_options_first) { std::stable_partition(synopsis.begin(), synopsis.end(), [](const UsageArg& _arg) { return !_arg.positional; }); } - auto out = "Usage: " + _program_name; + auto out = (_detailed ? _header : std::string()) + "Usage: " + _program_name; for (const auto& arg : synopsis) { const auto str = usage_arg_to_string(arg, "|", _delimiter); out += arg.required ? " " + str : " [" + str + "]"; @@ -680,6 +716,11 @@ std::optional usage_defaults() { /// allowed values of enums and literals, the constraints of validators, the /// default value (rfl::DefaultVal, or all fields with rfl::DefaultIfMissing) /// and whether the argument is required. +/// +/// 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] @@ -694,9 +735,11 @@ rfl::Result usage(const std::string& _program_name, using NamedTupleType = rfl::internal::processed_t; constexpr auto delimiter = internal::list_delimiter_v; // The table that read() parses with, so the help shows what the parser - // accepts, including the options inside nested structs and maps. - const auto options = + // accepts, including the options inside nested structs and maps, and 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 { @@ -712,11 +755,14 @@ rfl::Result usage(const std::string& _program_name, auto collector = internal::UsageCollector( &definition, &meta, &options, rfl::internal::no_optionals_v, delimiter); - const auto args = collector.collect( + auto args = internal::builtin_usage_args(builtin); + const auto fields = collector.collect( rfl::internal::default_if_missing_v, internal::usage_defaults()); - return internal::format_usage(_program_name, args, _detailed, - delimiter, options.options_first); + args.insert(args.end(), fields.begin(), fields.end()); + return internal::format_usage( + _program_name, args, _detailed, delimiter, options.options_first, + internal::app_header(_program_name)); } catch (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 00000000..7a34c315 --- /dev/null +++ b/tests/cli/test_help_version.cpp @@ -0,0 +1,374 @@ +#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", rfl::DefaultVal> jobs = 1; +}; + +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= Default: 1.\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_abbreviated) { + // With rfl::cli::AllowAbbreviations, `--help` and `--version` can be + // abbreviated like the fields. + using Abbreviated = rfl::cli::AllowAbbreviations; + const auto help = read_app({"--hel"}); + EXPECT_EQ(kind_of(help), Kind::help); + EXPECT_EQ(text_of(help), copy_help); + const auto version = read_app({"--vers"}); + EXPECT_EQ(kind_of(version), Kind::version); + // `--verbose` shares a prefix with `--version`. + EXPECT_EQ(text_of(read_app({"--ver"})), + "error: Option '--ver' is ambiguous; possibilities: '--verbose', " + "'--version'."); + + // Without it, `--hel` is an unknown option, which is ignored. + EXPECT_EQ(text_of(read_app({"--hel", "in.txt", "-o", "x"})), + "(struct)"); +} + +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().get(), 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_EQ(std::string(rejected.error().what()), "Unknown option '--help'."); + 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. + EXPECT_EQ(text_of(read_app( + {"--version"})), + "error: Unknown option '--version'."); +} + +// 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; + +// recipe [options] , as in test_options_first.cpp. +struct Recipe { + rfl::Short<"v", std::optional> verbose; + rfl::Positional name; + rfl::Positional> args; +}; + +TEST(cli, test_help_version_options_first) { + using Settings = rfl::cli::App<"recipe">; + // `--help` before the first positional argument is the help. After it, + // it is passed through, as every later token is. + EXPECT_EQ((kind_of(read_app>({"-v", "--help"}))), + Kind::help); + const auto passed = read_app>({"build", "--help"}); + ASSERT_TRUE(passed) << passed.error().what(); + EXPECT_EQ(std::get(*passed).args.value().value(), + (Strings{"--help"})); +} + +struct Report { + rfl::ImplicitValue, "all"> details; + std::optional>> tags; +}; + +TEST(cli, test_help_version_implicit_value_and_keep_empty_items) { + using Settings = rfl::cli::App<"report">; + // The settings below rfl::cli::App apply to the struct as in read. + const auto result = + read_app>({"--details", "--tags=a;;b"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& report = std::get(*result); + EXPECT_EQ(report.details(), "all"); + EXPECT_EQ(report.tags, (std::vector>{ + "a", std::nullopt, "b"})); + + // A bare `--details` never takes the next token, so `--help` is the help. + EXPECT_EQ(kind_of(read_app({"--details", "--help"})), + Kind::help); +} + +} // namespace test_help_version