diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 6a79c102..99b2efe5 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -506,6 +506,221 @@ a `std::optional` or an `rfl::DefaultVal`, so the argument may be omitted: with `rfl::Short<"o", rfl::DefaultVal> output_dir = "out";`, leaving out `-o` gives `"out"`. +## Usage / help + +`rfl::cli::usage(program_name, detailed = false)` generates the +help text from the same struct, and with the same processors, as +`rfl::cli::read()`. So the names always match what the parser +accepts, including kebab-case, `rfl::Rename`, `rfl::Flatten` and nested paths. + +```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", + rfl::Validator, + rfl::Maximum<65535>>>> + port; + rfl::Description<"Minimum level to log", std::optional> log_level; + rfl::Description<"Tags to attach", + rfl::Validator, + rfl::Size>>> + tags; + Database database; +}; +``` + +`rfl::cli::usage("app")` returns the usage line, where optional +arguments are in brackets: + +``` +Usage: app -p|--port= [--log-level=] --tags= --database.host= --database.port= +``` + +`rfl::cli::usage("app", true)` adds one line per argument, with its +description, the constraints of its validators, its default and whether it is +required: + +``` +Usage: app -p|--port= [--log-level=] --tags= --database.host= --database.port= + +Arguments: + Path to the input file. Required. + -p, --port= Port to listen on. Range: 1..65535. Required. + --log-level= Minimum level to log + --tags= Tags to attach. Size: >= 1. Required. + --database.host= Required. + --database.port= Required. +``` + +Defaults are shown for fields wrapped in `rfl::DefaultVal`, and for all fields +if you pass `rfl::DefaultIfMissing` (to both `read` and `usage`), as long as +the struct can be default-constructed: + +```cpp +struct Server { + rfl::DefaultVal host = "localhost"; + rfl::DefaultVal threads = 4; + rfl::DefaultVal dry_run = false; +}; +``` + +``` +Arguments: + --host= Default: localhost. + --threads= Default: 4. + --dry-run[=] Default: false. +``` + +The parser takes the defaults of `rfl::DefaultVal` fields from a +default-constructed struct. If the struct cannot be default-constructed, for +instance because a validator rejects another field's default value, those +fields are required, and the help says so. + +An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description` +or `rfl::Deprecated`, in any order, makes the field optional for the parser, +and the help shows it in brackets with its default: + +```cpp +struct Logging { + rfl::Short<"l", rfl::Description<"Minimum level to log", + rfl::DefaultVal>> + log_level = LogLevel::info; +}; +``` + +``` +Usage: app [-l|--log-level=] + +Arguments: + -l, --log-level= Minimum level to log. Default: info. +``` + +The help is built from the same internal option table that `read` parses +with (see [Architecture](#architecture)), so it shows how each argument can +be given: + +| Field | Synopsis | Detail | +|---|---|---| +| `bool` | `--verbose[=]` | | +| `rfl::ImplicitValue, "always">` | `--color[=]` | `Without a value: always.` | +| list (vector, set, array, ...) | `--tags=` | `Can be repeated.` | +| list, with `rfl::cli::ListDelimiter<";">` | `--tags=` | defaults joined with `;` | +| list, with `rfl::cli::ListDelimiter<"">` | `--tags=` | `Can be repeated.` | +| list as the last `rfl::Positional` | `...` | | + +`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. The usage line lists the positional arguments in the +order in which the parser fills them, and leaves out a short alias that the +parser does not give a field because another field has it. + +With `rfl::cli::OptionsFirst`, the options end at the first positional +argument, so the usage line lists every option before the positional +arguments. The rows of the detailed form keep the declaration order: + +```cpp +struct Recipe { + rfl::Short<"v", std::optional> verbose; + rfl::Positional name; + rfl::Positional>> args; + rfl::Short<"j", std::optional> jobs; +}; + +rfl::cli::usage("recipe"); +// Usage: recipe [-v|--verbose[=]] [-j|--jobs=] [...] +``` + +## 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[]) { + 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 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 `--hel` and `-vh` work, `--ver` is ambiguous if there is also a + `--verbose`, `--` ends them, and with `rfl::cli::OptionsFirst` they are + passed through after the first positional argument. `--help=false` does + not ask for the help. +- **A field takes precedence.** If a field has `rfl::Short<"h", ...>`, `-h` + is that field's and the help is `--help` only. That includes an + `rfl::Short` inside other wrappers, unless another field has the same + short name, in which case the parser gives `-h` to neither field (see + [Combining wrappers](#combining-wrappers)) and it stays the help. A field named `help` turns + the built-in help off and is read like any other field, so you can define + your own, for instance `--help[=]` with + `rfl::ImplicitValue, "all"> help;`. A field + named `version` turns `--version` off. +- An empty version leaves out `--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` 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 | @@ -549,7 +764,8 @@ Parsing proceeds in three stages: ## Files -- `include/rfl/cli/read.hpp` — public API +- `include/rfl/cli/read.hpp` — public API: `read` and `read_app` +- `include/rfl/cli/App.hpp` — `App<"name", "version", "description">` setting for `--help` and `--version` - `include/rfl/cli/BlankItemsAsMissing.hpp` — setting for blank list items - `include/rfl/cli/Reader.hpp` — Reader + `parse_value` overloads - `include/rfl/cli/Parser.hpp` — Parser type alias + blank `DefaultVal` and `std::wstring` items @@ -559,6 +775,7 @@ Parsing proceeds in three stages: - `include/rfl/cli/ListDelimiter.hpp` — `ListDelimiter<"x">` processor - `include/rfl/cli/OptionsFirst.hpp` — `OptionsFirst` processor - `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 72091bdf..6d1c7658 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -2,6 +2,7 @@ #define RFL_CLI_HPP_ #include "../rfl.hpp" +#include "cli/App.hpp" #include "cli/BlankItemsAsMissing.hpp" #include "cli/ListDelimiter.hpp" #include "cli/NoAbbreviations.hpp" @@ -12,5 +13,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/App.hpp b/include/rfl/cli/App.hpp new file mode 100644 index 00000000..b4de04f9 --- /dev/null +++ b/include/rfl/cli/App.hpp @@ -0,0 +1,239 @@ +#ifndef RFL_CLI_APP_HPP_ +#define RFL_CLI_APP_HPP_ + +#include +#include +#include +#include + +#include "../Processors.hpp" +#include "../Result.hpp" +#include "../internal/StringLiteral.hpp" +#include "options.hpp" + +namespace rfl::cli { + +/// 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 abbreviated (`--hel`) and +/// grouped (`-vh`) like any other, and `--` ends them. +/// - A field takes precedence over them: if a field has rfl::Short<"h", ...>, +/// `-h` is that field's and the help is `--help` only. A field named +/// `help` (after processors) turns the built-in help off, and a field named +/// `version` turns `--version` off. Such a field is read like any other. +/// - 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 +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(); + + /// 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 = ""; +}; + +template +struct app_settings> { + static constexpr size_t count = 1; + static constexpr std::string_view name = App<_name, _version, _about>::name; + static constexpr std::string_view version = + App<_name, _version, _about>::version; + static constexpr std::string_view about = + App<_name, _version, _about>::about; +}; + +/// 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: those that no field takes. +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 field of the struct is called `--_name`, or has it as the path +/// of a nested struct or map. Keys of rfl::ExtraFields do not count: they are +/// not known in advance. +inline bool is_field_name(const Options& _options, const std::string& _name) { + if (_options.long_options.count(_name)) { + return true; + } + const auto prefix = _name + path_separator; + const auto starts_with_prefix = [&](const auto& _map) { + const auto it = _map.lower_bound(prefix); + return it != _map.end() && it->first.starts_with(prefix); + }; + return starts_with_prefix(_options.long_options) + || starts_with_prefix(_options.open_prefixes); +} + +/// Adds the built-in options of the rfl::cli::App in ProcessorsType to +/// _options, unless a field takes their names. They are flags, so the parser +/// handles them as it does any flag. +/// @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) { + const auto help = std::string(help_option); + const auto help_short = std::string(help_short_option); + const auto version = std::string(version_option); + builtin.help = !is_field_name(*_options, help); + builtin.help_short = + builtin.help && !_options->short_options.count(help_short); + builtin.version = + !Settings::version.empty() && !is_field_name(*_options, version); + if (builtin.help) { + _options->long_options[help] = Option{OptionKind::flag}; + } + if (builtin.help_short) { + _options->short_options[help_short] = help; + } + if (builtin.version) { + _options->long_options[version] = Option{OptionKind::flag}; + } + } + return builtin; +} + +/// Reads the value of a built-in flag the way the reader reads a bool: +/// empty (given without a value), "true" or "1" turn it on, "false" or "0" +/// leave it off. +inline rfl::Result builtin_flag_is_set(const std::string& _value, + const std::string& _option) { + if (_value.empty() || _value == "true" || _value == "1") { + return true; + } + if (_value == "false" || _value == "0") { + return false; + } + return error("Could not cast '" + _value + "' to boolean for '" + _option + + "'."); +} + +/// 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 b9504076..fec8dab6 100644 --- a/include/rfl/cli/read.hpp +++ b/include/rfl/cli/read.hpp @@ -2,11 +2,16 @@ #define RFL_CLI_READ_HPP_ #include +#include +#include #include #include +#include #include "../Processors.hpp" #include "../SnakeCaseToKebabCase.hpp" +#include "../internal/strings/utf8_conversions.hpp" +#include "App.hpp" #include "BlankItemsAsMissing.hpp" #include "ListDelimiter.hpp" #include "Parser.hpp" @@ -14,6 +19,7 @@ #include "options.hpp" #include "parse_argv.hpp" #include "resolve_args.hpp" +#include "usage.hpp" namespace rfl::cli { @@ -21,27 +27,116 @@ namespace internal { static_assert(list_delimiter_v> == array_delimiter); +/// Resolves the parsed arguments and reads them into T. +template +rfl::Result read_parsed(ParsedArgs _parsed, const Options& _options) { + return resolve_args(std::move(_parsed), _options) + .and_then([](auto _args) -> rfl::Result { + const auto r = + Reader(internal::list_delimiter_v, + internal::blank_items_as_missing_v); + const auto var = CliVarType{&_args.values, "", std::nullopt, + &_args.later_occurrences}; + return Parser::read(r, var); + }); +} + /// Categorizes the arguments with `_parse`, which takes the options of T /// (see make_options) and returns ParsedArgs, and turns them into a struct. 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); }) .and_then([&](ParsedArgs _parsed) { - return resolve_args(std::move(_parsed), options); - }) - .and_then([](auto _args) -> rfl::Result { - const auto r = - Reader(internal::list_delimiter_v, - internal::blank_items_as_missing_v); - const auto var = CliVarType{&_args.values, "", std::nullopt, - &_args.later_occurrences}; - return Parser::read(r, var); + return read_parsed(std::move(_parsed), options); }); } +/// Takes the built-in option `_key` out of `_args`, if it is enabled and +/// was given. +/// @return Whether it was given and set +inline rfl::Result take_builtin_flag( + const bool _enabled, std::map* _args, + const std::string_view _key, const std::string& _option) { + 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); + return builtin_flag_is_set(value, _option); +} + +/// 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, "--help"); + const auto help_short = + take_builtin_flag(builtin.help_short, &parsed->short_args, + help_short_option, "-h"); + const auto version = take_builtin_flag(builtin.version, &parsed->named, + version_option, "--version"); + for (const auto* r : {&help, &help_short, &version}) { + if (!*r) { + return error(r->error().what()); + } + } + + if (*help || *help_short) { + return ResultType(HelpOrVersion{HelpOrVersion::Kind::help, + usage(_program_name, true)}); + } + 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 /// Parses a sequence of command-line arguments into a struct using reflection. @@ -124,6 +219,63 @@ rfl::Result read(int argc, wchar_t* argv[]) { return read(argc, static_cast(argv)); } +/// 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 new file mode 100644 index 00000000..28123336 --- /dev/null +++ b/include/rfl/cli/usage.hpp @@ -0,0 +1,772 @@ +#ifndef RFL_CLI_USAGE_HPP_ +#define RFL_CLI_USAGE_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Generic.hpp" +#include "../Processors.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/ValidationType.hpp" +#include "../parsing/schema/make.hpp" +#include "../to_generic.hpp" +#include "App.hpp" +#include "ListDelimiter.hpp" +#include "OptionsFirst.hpp" +#include "Reader.hpp" +#include "options.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`) and rfl::ImplicitValue (`--help`) can be given + /// without one. + OptionKind kind = OptionKind::value; + /// For OptionKind::implicit_value: what the option stands for without a + /// value. + std::string implicit_value; + /// Whether the field is a list, which can be repeated. + bool is_list = false; + /// Whether the field is the last positional one and a list, so that it + /// takes the remaining positional arguments. + bool takes_rest = false; + /// Whether the option is shown without a value, as the built-in `--help` + /// and `--version` are. + bool bare = 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; + std::optional deprecation; + /// Rendered constraints, such as "Range: 1..65535.". + std::vector constraints; + std::optional default_value; +}; + +template +void add_usage_field_meta(const bool _default_vals_are_optional, + std::map* _meta) { + using Info = field_info; + using ValueType = std::remove_cvref_t; + auto& meta = (*_meta)[std::string(Info::name())]; + // The same condition as in NamedTupleParser::handle_one_missing_field. + // is_default_val_v sees a DefaultVal through Short, Positional, Rename, + // Description and Deprecated, in any order, as the parser does. The schema + // cannot tell, because it marks a DefaultVal field as optional even where + // the parser requires it (see usage_default_vals_are_optional). + meta.required = + !(rfl::internal::is_default_val_v + && _default_vals_are_optional) + && !rfl::internal::is_extra_fields_v + && (rfl::internal::no_optionals_v + || parsing::is_required()); +} + +/// Collects whether each top-level field is required from the same +/// compile-time traits that the parser uses, so the help matches what the +/// parser accepts. Positional, Short, flags, implicit values and lists 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, 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 { + [[maybe_unused]] const auto t = T{}; + return true; + } catch (...) { + return false; + } + } else { + return false; + } +} + +/// Renders a number without locale-dependent separators. +inline std::string usage_number_to_string(const double _value) { + std::ostringstream stream; + stream.imbue(std::locale::classic()); + stream.precision(15); + stream << _value; + return stream.str(); +} + +inline std::string usage_number_to_string( + const rfl::Variant& _value) { + return _value.visit([](const auto _v) -> std::string { + if constexpr (std::is_same_v, int>) { + return std::to_string(_v); + } else { + return usage_number_to_string(_v); + } + }); +} + +/// Renders a default value the way it would be passed on the command line. +/// Returns nullopt for values that cannot be rendered sensibly (null, +/// objects, empty arrays). +/// Lists are joined with the list delimiter, or with ", " if lists are not +/// split (ListDelimiter<"">). +inline std::optional usage_default_to_string( + const Generic& _value, const std::optional _delimiter) { + return std::visit( + [&](const auto& _v) -> std::optional { + using V = std::remove_cvref_t; + if constexpr (std::is_same_v) { + return _v ? "true" : "false"; + } else if constexpr (std::is_same_v) { + return std::to_string(_v); + } else if constexpr (std::is_same_v) { + return usage_number_to_string(_v); + } else if constexpr (std::is_same_v) { + return _v.empty() ? std::string("\"\"") : _v; + } else if constexpr (std::is_same_v) { + if (_v.empty()) { + return std::nullopt; + } + std::string joined; + for (const auto& element : _v) { + const auto str = usage_default_to_string(element, _delimiter); + if (!str) { + return std::nullopt; + } + if (!joined.empty()) { + joined += _delimiter ? std::string(1, *_delimiter) + : std::string(", "); + } + joined += *str; + } + return joined; + } else { + return std::nullopt; + } + }, + _value.variant()); +} + +/// Renders a numeric bound such as ">= 1", "1..10" or "< 0 or > 10". +/// Returns nullopt if the validation is not purely numeric. +inline std::optional usage_bounds_to_string( + const parsing::schema::ValidationType& _validation) { + using ValidationType = parsing::schema::ValidationType; + const auto join = [](const std::vector& _types, + const std::string& _sep) -> std::optional { + std::string joined; + for (const auto& t : _types) { + const auto str = usage_bounds_to_string(t); + if (!str) { + return std::nullopt; + } + joined += (joined.empty() ? "" : _sep) + *str; + } + return joined; + }; + return _validation.variant_.visit( + [&](const auto& _v) -> std::optional { + using V = std::remove_cvref_t; + if constexpr (std::is_same_v) { + if (_v.types_.size() == 2) { + using Min = ValidationType::Minimum; + using Max = ValidationType::Maximum; + const auto& first = _v.types_[0].variant_; + const auto& second = _v.types_[1].variant_; + const auto* min = rfl::get_if(&first); + const auto* max = rfl::get_if(&second); + if (!min && !max) { + min = rfl::get_if(&second); + max = rfl::get_if(&first); + } + if (min && max) { + return usage_number_to_string(min->value_) + ".." + + usage_number_to_string(max->value_); + } + } + return join(_v.types_, " and "); + } else if constexpr (std::is_same_v + || std::is_same_v) { + return join(_v.types_, " or "); + } else if constexpr (std::is_same_v) { + return usage_number_to_string(_v.value_); + } else if constexpr (std::is_same_v) { + return "!= " + usage_number_to_string(_v.value_); + } else if constexpr (std::is_same_v) { + return ">= " + usage_number_to_string(_v.value_); + } else if constexpr (std::is_same_v) { + return "<= " + usage_number_to_string(_v.value_); + } else if constexpr (std::is_same_v) { + return "> " + usage_number_to_string(_v.value_); + } else if constexpr (std::is_same_v) { + return "< " + usage_number_to_string(_v.value_); + } else { + return std::nullopt; + } + }); +} + +/// Renders a validation as one or more phrases, such as "Range: 1..10", +/// "Size: >= 1" or "Pattern: ^[a-z]+$". +inline std::vector usage_constraints( + const parsing::schema::ValidationType& _validation) { + using ValidationType = parsing::schema::ValidationType; + if (const auto bounds = usage_bounds_to_string(_validation)) { + return {"Range: " + *bounds}; + } + return _validation.variant_.visit( + [](const auto& _v) -> std::vector { + using V = std::remove_cvref_t; + if constexpr (std::is_same_v) { + std::vector all; + for (const auto& t : _v.types_) { + const auto phrases = usage_constraints(t); + all.insert(all.end(), phrases.begin(), phrases.end()); + } + return all; + } else if constexpr (std::is_same_v + || std::is_same_v) { + std::string joined; + for (const auto& t : _v.types_) { + std::string alternative; + for (const auto& phrase : usage_constraints(t)) { + alternative += (alternative.empty() ? "" : ", ") + phrase; + } + joined += (joined.empty() ? "" : " or ") + alternative; + } + return {joined}; + } else if constexpr (std::is_same_v) { + const auto bounds = usage_bounds_to_string(*_v.size_limit_); + if (!bounds) { + return {}; + } + return {"Size: " + *bounds}; + } else if constexpr (std::is_same_v) { + return {"Pattern: " + _v.pattern_}; + } else { + return {}; + } + }); +} + +/// Walks the format-agnostic schema of the struct and collects one UsageArg +/// per command-line argument, in declaration order. +class UsageCollector { + public: + using Type = parsing::schema::Type; + + UsageCollector(const parsing::schema::Definition* _definition, + const std::map* _meta, + const Options* _options, + const bool _optionals_are_required, + const std::optional _delimiter) + : definition_(_definition), + meta_(_meta), + options_(_options), + optionals_are_required_(_optionals_are_required), + delimiter_(_delimiter) { + 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). + /// @param _defaults The default values of all fields, if known. + std::vector collect(const bool _all_optional, + const std::optional& _defaults) { + auto root = UsageArg{}; + root.required = !_all_optional; + add(definition_->root_, std::move(root), _defaults, false); + order_positionals(); + return std::move(args_); + } + + private: + /// @param _outermost Whether _type is the outermost type of a field. + void add(const Type& _type, UsageArg _arg, + const std::optional& _default, 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) { + if (_arg.description.empty()) { + _arg.description = _t.description_; + } + add(*_t.type_, std::move(_arg), _default, _outermost); + + } else if constexpr (std::is_same_v) { + if (_arg.description.empty()) { + _arg.description = _t.description_; + } + _arg.deprecation = _t.deprecation_message_; + add(*_t.type_, std::move(_arg), _default, _outermost); + + } else if constexpr (std::is_same_v) { + if (!_arg.required_is_known && !optionals_are_required_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), _default, 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), + _t.default_value_ ? _t.default_value_ : _default, false); + + } else if constexpr (std::is_same_v) { + const auto constraints = usage_constraints(_t.validation_); + _arg.constraints.insert(_arg.constraints.end(), constraints.begin(), + constraints.end()); + add(*_t.type_, std::move(_arg), _default, false); + + } else if constexpr (std::is_same_v) { + 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), _default); + return; + } + add(it->second, std::move(_arg), _default, _outermost); + visiting_.erase(_t.name_); + + } else if constexpr (std::is_same_v) { + add_object(_t, _arg, _default); + + } else if constexpr (std::is_same_v) { + _arg.name += path_separator; + _arg.name += ""; + add_leaf(std::move(_arg), std::nullopt); + + } else if constexpr (std::is_same_v) { + _arg.value = ""; + add_leaf(std::move(_arg), _default); + + } else if constexpr (std::is_same_v) { + add_choices(_t.values_, std::move(_arg), _default); + + } 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), _default); + + } else { + // Lists, too: whether a field is a list comes from the option table + // (add_leaf), which is what the parser uses. + add_leaf(std::move(_arg), _default); + } + }); + } + + void add_object(const Type::Object& _object, const UsageArg& _parent, + const std::optional& _defaults) { + 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; + } + } + auto child_default = std::optional(); + const auto* obj = _defaults + ? std::get_if(&_defaults->variant()) + : nullptr; + if (obj) { + if (auto res = obj->get(name)) { + child_default = std::move(*res); + } + } + add(type, std::move(arg), child_default, true); + } + } + + void add_choices(const std::vector& _values, UsageArg _arg, + const std::optional& _default) { + _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), _default); + } + + void add_leaf(UsageArg _arg, const std::optional& _default) { + if (_arg.name.empty()) { + return; + } + // How the parser treats the option, from the table that it uses. A map + // key ("labels.") is found through its open prefix. + const auto option = options_->find_long(_arg.name); + _arg.kind = option.kind; + _arg.implicit_value = option.implicit_value; + _arg.is_list = option.is_list; + if (_default) { + _arg.default_value = usage_default_to_string(*_default, delimiter_); + } + args_.emplace_back(std::move(_arg)); + } + + /// Puts the positional arguments in the order in which the parser fills + /// them (Options::positionals: outermost rfl::Positional fields first), + /// in the places where positional arguments are, and marks the one that + /// takes the remaining arguments. + void order_positionals() { + const auto& order = options_->positionals; + auto slots = std::vector(); + auto positionals = std::vector(); + for (size_t i = 0; i < args_.size(); ++i) { + if (args_[i].positional) { + slots.push_back(i); + positionals.push_back(std::move(args_[i])); + } + } + const auto rank = [&](const UsageArg& _arg) { + return std::find(order.begin(), order.end(), _arg.name) - order.begin(); + }; + std::stable_sort(positionals.begin(), positionals.end(), + [&](const UsageArg& _a, const UsageArg& _b) { + return rank(_a) < rank(_b); + }); + for (size_t i = 0; i < slots.size(); ++i) { + positionals[i].takes_rest = options_->last_positional_is_list() + && positionals[i].name == order.back(); + args_[slots[i]] = std::move(positionals[i]); + } + } + + private: + const parsing::schema::Definition* definition_; + const std::map* meta_; + const Options* options_; + const bool optionals_are_required_; + const std::optional delimiter_; + /// 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. If lists are not split +/// (ListDelimiter<"">), every occurrence is one item: "". +inline std::string usage_value_to_string(const UsageArg& _arg, + const std::optional _delimiter) { + if (!_arg.is_list || !_delimiter) { + return _arg.value; + } + const auto d = std::string(1, *_delimiter); + return ""; +} + +/// "", "...", "-p|--port=", "--verbose[=]", +/// "--help[=]" +inline std::string usage_arg_to_string(const UsageArg& _arg, + const std::string& _short_sep, + const std::optional _delimiter) { + if (_arg.positional) { + // A list as the last positional field takes the remaining arguments. + // Any other positional field takes one. + return "<" + _arg.name + ">" + (_arg.takes_rest ? "..." : ""); + } + 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: + case OptionKind::implicit_value: + // `--verbose`, `--help`: 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. Range: 1..65535. Default: 8080. Required." +inline std::string usage_help_text(const UsageArg& _arg) { + auto sentences = std::vector(); + if (_arg.deprecation) { + sentences.push_back(_arg.deprecation->empty() + ? std::string("Deprecated") + : "Deprecated: " + *_arg.deprecation); + } + if (_arg.positional && !_arg.choices.empty()) { + auto choices = std::string("Choices: "); + for (size_t i = 0; i < _arg.choices.size(); ++i) { + choices += (i == 0 ? "" : "|") + _arg.choices[i]; + } + sentences.push_back(std::move(choices)); + } + sentences.insert(sentences.end(), _arg.constraints.begin(), + _arg.constraints.end()); + if (_arg.kind == OptionKind::implicit_value && !_arg.positional + && !_arg.implicit_value.empty()) { + sentences.push_back("Without a value: " + _arg.implicit_value); + } + if (_arg.default_value) { + sentences.push_back("Default: " + *_arg.default_value); + } + if (_arg.is_list && !_arg.positional) { + sentences.push_back("Can be repeated"); + } + 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; +} + +/// 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 std::string& _header) { + auto synopsis = _args; + if (_options_first) { + std::stable_partition(synopsis.begin(), synopsis.end(), + [](const UsageArg& _arg) { return !_arg.positional; }); + } + 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 + "]"; + } + 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, ", ", _delimiter), + 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; +} + +/// The default values of all fields, if they are known: only with +/// rfl::DefaultIfMissing (otherwise, plain fields are required and their +/// default member initializers are never used) and only if T is +/// default-constructible, which read requires, too. +template +std::optional usage_defaults() { + using ProcessorsType = Processors; + if constexpr (rfl::internal::default_if_missing_v + && std::is_default_constructible_v) { + try { + return rfl::to_generic(T{}); + } catch (...) { + // For instance, a default value that does not satisfy its validator. + return std::nullopt; + } + } else { + return std::nullopt; + } +} + +} // 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, where known, the description (rfl::Description), the +/// 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] +/// @param _detailed Whether to add a line for every argument +/// @return The usage text, ending with a newline +template +std::string usage(const std::string& _program_name, + const bool _detailed = false) { + using ProcessorsType = Processors; + using NamedTupleType = rfl::internal::processed_t; + constexpr auto delimiter = internal::list_delimiter_v; + const auto meta = + internal::collect_usage_field_meta( + internal::usage_default_vals_are_optional(), + std::make_index_sequence{}); + // The table that read() parses with, so the help shows what the parser + // accepts. + auto options = internal::make_options(); + const auto builtin = internal::add_builtin_options(&options); + const auto definition = + parsing::schema::make(); + auto collector = internal::UsageCollector( + &definition, &meta, &options, + rfl::internal::no_optionals_v, delimiter); + auto args = internal::builtin_usage_args(builtin); + const auto fields = collector.collect( + rfl::internal::default_if_missing_v, + internal::usage_defaults()); + 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)); +} + +} // namespace rfl::cli + +#endif diff --git a/tests/cli/test_help_version.cpp b/tests/cli/test_help_version.cpp new file mode 100644 index 00000000..ef50f0d9 --- /dev/null +++ b/tests/cli/test_help_version.cpp @@ -0,0 +1,342 @@ +#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 { + +using Strings = std::vector; + +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)), copy_help); + + // The usage line has no header. + EXPECT_EQ((rfl::cli::usage("app")), + "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"), + "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"}, {"--hel"}, {"-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"}, {"--vers"}, {"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().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 '--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'."); + // `--help` and `--verbose` share a prefix with `--version`. + EXPECT_EQ(text_of(read_app({"--ver"})), + "error: Option '--ver' is ambiguous; possibilities: '--verbose', " + "'--version'."); + // 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, as before. + 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 with rfl::Short<"h", ...> keeps `-h`: the help is `--help` only. +struct WithHostShort { + rfl::Short<"h", rfl::Description<"Host to connect to", std::string>> host; +}; + +TEST(cli, test_help_version_short_h_is_taken) { + using MyApp = rfl::cli::App<"client">; + EXPECT_EQ((rfl::cli::usage("client", true)), + "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'."); +} + +// An rfl::Short found through other wrappers keeps `-h` too, if the parser +// gives it to the field: when no other field has that name. +struct WithWrappedHostShort { + rfl::Description<"Host to connect to", rfl::Short<"h", std::string>> host; +}; + +// Two of them: the parser gives `-h` to neither, so it is the help's. +struct WithTwoWrappedHShorts { + rfl::Description<"Host", rfl::Short<"h", std::optional>> host; + rfl::Description<"Hash", rfl::Short<"h", std::optional>> hash; +}; + +TEST(cli, test_help_version_wrapped_short_h) { + using MyApp = rfl::cli::App<"client">; + EXPECT_EQ((rfl::cli::usage("client")), + "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"); + + EXPECT_EQ((rfl::cli::usage("client")), + "Usage: client [-h|--help] [--host=] [--hash=]\n"); + EXPECT_EQ(kind_of(read_app({"-h"})), + Kind::help); +} + +// A field named `help` turns the built-in help off: the field is read like +// any other. Here it is `--help[=]`. +struct WithHelpField { + rfl::Description<"Show help on a topic", + rfl::ImplicitValue, "all">> + help; + rfl::Short<"n", std::optional> count; +}; + +TEST(cli, test_help_version_help_field_is_taken) { + using MyApp = rfl::cli::App<"tool", "0.1">; + EXPECT_EQ((rfl::cli::usage("tool", true)), + "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. Without a value: " + "all.\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"); + const auto bare = read_app({"--help"}); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(std::get(*bare).help.value().value(), "all"); + // `-h` is not the help either. + EXPECT_FALSE((read_app({"-h"}))); + EXPECT_EQ(text_of(read_app({"--version"})), + "tool 0.1\n"); +} + +// A field named `version` turns `--version` off. +struct WithVersionField { + std::optional version; +}; + +TEST(cli, test_help_version_version_field_is_taken) { + using MyApp = rfl::cli::App<"tool", "0.1">; + 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")), + "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">; + EXPECT_EQ(text_of(read_app({"--version"})), + "app 2.0\n"); + EXPECT_EQ((rfl::cli::usage("app", true)), + "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)), + "Usage: app [-h|--help] [--version=]\n" + "\n" + "Arguments:\n" + " -h, --help Show this help\n" + " --version=\n"); +} + +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"})); +} + +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"); +} + +} // namespace test_help_version diff --git a/tests/cli/test_usage.cpp b/tests/cli/test_usage.cpp new file mode 100644 index 00000000..37f25fed --- /dev/null +++ b/tests/cli/test_usage.cpp @@ -0,0 +1,481 @@ +#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 #692. + EXPECT_EQ(rfl::cli::usage("my_binary"), + "Usage: my_binary --host-name= " + "--verbose[=] --tags= -p|--port= " + "--database.host= --database.port= " + "[--log-level=]\n"); +} + +struct Described { + rfl::Positional> + input_file; + rfl::Description<"Host to connect to", std::string> host_name; + bool verbose; + rfl::Short<"p", rfl::Description<"Port to connect on", 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), + "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().get(), "in.txt"); + EXPECT_EQ(result.value().port().get(), 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 DescriptionOutside { + rfl::Description<"Path to the input file", rfl::Positional> + input_file; +}; + +TEST(cli, test_usage_description_outside_positional) { + // The parser finds rfl::Positional inside rfl::Description, and so does + // the help. + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app \n" + "\n" + "Arguments:\n" + " Path to the input file. Required.\n"); + + const char* positional[] = {"app", "in.txt"}; + const auto result = + rfl::cli::read(2, const_cast(positional)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().input_file.value().value(), "in.txt"); +} + +struct Validated { + rfl::Description<"Port to listen on", + rfl::Validator, rfl::Maximum<65535>>> + port; + rfl::Validator, rfl::Maximum<1>> ratio; + rfl::Validator> percent; + rfl::Validator, rfl::Minimum<10>>> outside; + rfl::Validator, rfl::EqualTo<2>>> one_or_two; + rfl::Validator> nonzero; + rfl::Validator, rfl::Size>> tags; + rfl::Validator, + rfl::Size, rfl::Maximum<3>>>> + ids; + rfl::Validator>, + rfl::PatternValidator<"^[a-z]+$", "Lowercase">> + user; + rfl::Literal<"fast", "slow"> mode; +}; + +TEST(cli, test_usage_validators) { + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app --port= --ratio= --percent= " + "--outside= --one-or-two= --nonzero= " + "--tags= --ids= --user= " + "--mode=\n" + "\n" + "Arguments:\n" + " --port= Port to listen on. Range: 1..65535. " + "Required.\n" + " --ratio= Range: > 0 and <= 1. Required.\n" + " --percent= Range: < 100. Required.\n" + " --outside= Range: <= 0 or >= 10. Required.\n" + " --one-or-two= Range: 1 or 2. Required.\n" + " --nonzero= Range: != 0. Required.\n" + " --tags= Size: >= 1. Can be repeated. Required.\n" + " --ids= Size: 1..3. Can be repeated. Required.\n" + " --user= Size: >= 1. Pattern: ^[a-z]+$. " + "Required.\n" + " --mode= Required.\n"); +} + +struct WithDefaultVal { + rfl::DefaultVal port = 8080; + rfl::DefaultVal host = "localhost"; + rfl::DefaultVal> tags = + std::vector{"a", "b"}; + rfl::DefaultVal level = LogLevel::info; + rfl::DefaultVal rate = 0.25; + rfl::DefaultVal dry_run = false; + int count = 3; + rfl::Short<"r", rfl::DefaultVal> retries = 5; +}; + +TEST(cli, test_usage_default_val) { + // Without rfl::DefaultIfMissing, `count` is required, so its member + // initializer is never used and not shown. A DefaultVal inside rfl::Short + // makes `retries` optional, as for the parser. + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app [--port=] [--host=] " + "[--tags=] [--level=] " + "[--rate=] [--dry-run[=]] --count= " + "[-r|--retries=]\n" + "\n" + "Arguments:\n" + " --port= Default: 8080.\n" + " --host= Default: localhost.\n" + " --tags= Default: a,b. Can be repeated.\n" + " --level= Default: info.\n" + " --rate= Default: 0.25.\n" + " --dry-run[=] Default: false.\n" + " --count= Required.\n" + " -r, --retries= Default: 5.\n"); + + const char* args[] = {"app", "--count=1", "-r", "2"}; + const auto result = + rfl::cli::read(4, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().port.get(), 8080); + EXPECT_EQ(result.value().host.get(), "localhost"); + EXPECT_EQ(result.value().retries.value().get(), 2); + + const char* no_retries[] = {"app", "--count=1"}; + const auto defaulted = + rfl::cli::read(2, const_cast(no_retries)); + ASSERT_TRUE(defaulted) << defaulted.error().what(); + EXPECT_EQ(defaulted.value().retries.value().get(), 5); +} + +struct Limits { + rfl::Description<"Connections per host", rfl::DefaultVal> per_host = 4; + int total; +}; + +/// rfl::DefaultVal inside other wrappers, in different orders. +struct WrappedDefaultVal { + rfl::Short<"l", rfl::Description<"Minimum level to log", + rfl::DefaultVal>> + log_level = LogLevel::info; + rfl::Description<"Seconds to wait", rfl::DefaultVal> timeout = 30; + rfl::Deprecated<"Use --timeout", "Old timeout", rfl::DefaultVal> wait = + 10; + rfl::Positional> output = "out.txt"; + rfl::Short<"n", rfl::Description<"Number of runs", int>> runs; + Limits limits; +}; + +TEST(cli, test_usage_wrapped_default_val) { + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app [-l|--log-level=] " + "[--timeout=] [--wait=] [] " + "-n|--runs= [--limits.per-host=] " + "--limits.total=\n" + "\n" + "Arguments:\n" + " -l, --log-level= Minimum level to log. " + "Default: info.\n" + " --timeout= Seconds to wait. " + "Default: 30.\n" + " --wait= Old timeout. Deprecated: " + "Use --timeout. Default: 10.\n" + " Default: out.txt.\n" + " -n, --runs= Number of runs. Required.\n" + " --limits.per-host= Connections per host. " + "Default: 4.\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().log_level.value().value().get(), + LogLevel::info); + EXPECT_EQ(defaulted.value().timeout.value().get(), 30); + EXPECT_EQ(defaulted.value().wait.value().get(), 10); + EXPECT_EQ(defaulted.value().output.value().get(), "out.txt"); + EXPECT_EQ(defaulted.value().runs.value().value(), 3); + EXPECT_EQ(defaulted.value().limits.per_host.value().get(), 4); + EXPECT_EQ(defaulted.value().limits.total, 8); + + // The arguments are spelled as the help shows them. + const char* all[] = {"app", "-l", "warn", + "--timeout=5", "--wait=1", "result.txt", + "--runs=2", "--limits.per-host=2", + "--limits.total=4"}; + const auto given = + rfl::cli::read(9, const_cast(all)); + ASSERT_TRUE(given) << given.error().what(); + EXPECT_EQ(given.value().log_level.value().value().get(), LogLevel::warn); + EXPECT_EQ(given.value().timeout.value().get(), 5); + EXPECT_EQ(given.value().wait.value().get(), 1); + EXPECT_EQ(given.value().output.value().get(), "result.txt"); + EXPECT_EQ(given.value().limits.per_host.value().get(), 2); + + // 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; +}; + +TEST(cli, test_usage_default_val_struct_not_default_constructible) { + // The defaults are read from a default-constructed struct, which throws + // here. The help leaves them out instead of aborting. The parser fills in + // a missing DefaultVal field only after it default-constructed the + // struct, so `threads` is required. + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app --port= --threads=\n" + "\n" + "Arguments:\n" + " --port= Range: >= 1. Required.\n" + " --threads= Required.\n"); + + // A bare DefaultVal makes every read fail, since the struct must be + // default-constructed for it. + const char* both[] = {"app", "--port=1", "--threads=2"}; + EXPECT_FALSE(rfl::cli::read(3, const_cast(both))); + + // One that is wrapped in rfl::Short is read without the defaults, and is + // required. + EXPECT_EQ(rfl::cli::usage("app"), + "Usage: app --port= -t|--threads=\n"); + 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* no_threads[] = {"app", "--port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(no_threads))); + + // The same in a nested struct. + EXPECT_EQ(rfl::cli::usage("app"), + "Usage: app --server.port= --server.threads=\n"); + const char* nested_no_threads[] = {"app", "--server.port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(nested_no_threads))); + const char* nested_both[] = {"app", "--server.port=1", "--server.threads=2"}; + EXPECT_TRUE(rfl::cli::read( + 3, const_cast(nested_both))); +} + +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_default_if_missing) { + EXPECT_EQ( + (rfl::cli::usage("app", true)), + "Usage: app [--count=] [--name=] [--verbose[=]] " + "[--limit=] [--database.host=] [--database.port=]\n" + "\n" + "Arguments:\n" + " --count= Default: 3.\n" + " --name= Default: \"\".\n" + " --verbose[=] Default: false.\n" + " --limit=\n" + " --database.host= Default: db.\n" + " --database.port= Default: 5432.\n"); + + const char* args[] = {"app"}; + const auto result = rfl::cli::read( + 1, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().count, 3); + EXPECT_EQ(result.value().database.port, 5432); +} + +TEST(cli, test_usage_without_default_if_missing) { + EXPECT_EQ(rfl::cli::usage("app"), + "Usage: app --count= --name= --verbose[=] " + "[--limit=] --database.host= " + "--database.port=\n"); + + const char* args[] = {"app"}; + EXPECT_FALSE(rfl::cli::read(1, const_cast(args))); +} + +/// 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; +}; + +struct WithPortAndDefaultVal { + Port port; + rfl::DefaultVal retries = 3; +}; + +TEST(cli, test_usage_default_val_without_default_constructor) { + static_assert(!std::is_default_constructible_v); + // The struct cannot be default-constructed, so the parser cannot fill in + // `retries`, and it is required. + EXPECT_EQ(rfl::cli::usage("app"), + "Usage: app --port= --retries=\n"); + const char* no_retries[] = {"app", "--port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(no_retries))); + const char* both[] = {"app", "--port=1", "--retries=2"}; + const auto result = + rfl::cli::read(3, const_cast(both)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().retries.get(), 2); +} + +TEST(cli, test_usage_default_if_missing_not_default_constructible) { + static_assert(!std::is_default_constructible_v); + // Nothing is required, but the defaults cannot be known without T{}, so + // usage() still compiles and leaves them out. + EXPECT_EQ((rfl::cli::usage("app", true)), + "Usage: app [--port=] [--retries=]\n" + "\n" + "Arguments:\n" + " --port=\n" + " --retries=\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), + "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), + "Usage: app [] [-v|--verbose[=]] " + "[--old-port=] --notes=\n" + "\n" + "Arguments:\n" + " Choices: debug|info|warn.\n" + " -v, --verbose[=]\n" + " --old-port= Old port. Deprecated: Use --port " + "instead.\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")), + "Usage: app -v|--verbose[=] --old-port= " + "--notes=\n"); +} + +struct Empty {}; + +TEST(cli, test_usage_empty) { + EXPECT_EQ(rfl::cli::usage("app"), "Usage: app\n"); + EXPECT_EQ(rfl::cli::usage("app", true), "Usage: app\n"); +} + +} // namespace test_usage diff --git a/tests/cli/test_usage_options.cpp b/tests/cli/test_usage_options.cpp new file mode 100644 index 00000000..aa047279 --- /dev/null +++ b/tests/cli/test_usage_options.cpp @@ -0,0 +1,244 @@ +#include + +#include +#include +#include +#include +#include + +// rfl::cli::usage for the parser's option features: rfl::ImplicitValue, +// wrappers in any order, repeated list options, a list as the last +// positional field, rfl::cli::ListDelimiter and rfl::cli::OptionsFirst. 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())); +} + +using Strings = std::vector; + +enum class Color { never, always, automatic }; + +struct WithImplicitValues { + rfl::Description<"When to color the output", + rfl::ImplicitValue, "always">> + color; + rfl::Short<"j", rfl::ImplicitValue, "4">> jobs = 1; + rfl::ImplicitValue> tag; + rfl::Short<"q", bool> quiet; +}; + +TEST(cli, test_usage_implicit_value) { + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app [--color[=]] " + "[-j|--jobs[=]] [--tag[=]] -q|--quiet[=]\n" + "\n" + "Arguments:\n" + " --color[=] When to color the output. " + "Without a value: always.\n" + " -j, --jobs[=] Without a value: 4. " + "Default: 1.\n" + " --tag[=]\n" + " -q, --quiet[=] Required.\n"); + + // Bare, the options stand for their implicit values. + const auto bare = read({"--color", "-j", "--tag", "-q"}); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(bare.value().color.value().value(), Color::always); + EXPECT_EQ(bare.value().jobs.value().value().get(), 4); + EXPECT_EQ(bare.value().tag.value(), std::string()); + EXPECT_TRUE(bare.value().quiet.value()); + + // With a value after '=', and left out. + const auto given = read({"--color=never", "-q"}); + ASSERT_TRUE(given) << given.error().what(); + EXPECT_EQ(given.value().color.value().value(), Color::never); + EXPECT_EQ(given.value().jobs.value().value().get(), 1); + EXPECT_FALSE(given.value().tag.value()); +} + +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), + "Usage: app -o|--output= [] [-v|--verbose[=]]\n" + "\n" + "Arguments:\n" + " -o, --output= Where to write. Required.\n" + " Default: in.txt.\n" + " -v, --verbose[=] Be verbose\n"); + + const auto result = read({"-v", "-o", "out", "data.csv"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().output.value().value(), "out"); + EXPECT_EQ(result.value().input.value().value(), "data.csv"); + EXPECT_EQ(result.value().verbose.value().value(), true); + + const auto defaulted = read({"-o", "out"}); + ASSERT_TRUE(defaulted) << defaulted.error().what(); + EXPECT_EQ(defaulted.value().input.value().value(), "in.txt"); + EXPECT_FALSE(read({"data.csv"})); +} + +struct Lists { + rfl::Short<"r", rfl::Description<"Reports to write", Strings>> report; + rfl::DefaultVal tags = Strings{"a", "b"}; + rfl::Positional command; + rfl::Description<"Files to process", rfl::Positional> files; +}; + +TEST(cli, test_usage_lists) { + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app -r|--report= [--tags=] " + " ...\n" + "\n" + "Arguments:\n" + " -r, --report= Reports to write. Can be repeated. " + "Required.\n" + " --tags= Default: a,b. Can be repeated.\n" + " Required.\n" + " ... Files to process. Required.\n"); + + const auto result = read( + {"-r", "a", "run", "--report=b,c", "x,y", "z", "--tags", "t"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().report.value().value(), (Strings{"a", "b", "c"})); + EXPECT_EQ(result.value().tags.value(), (Strings{"t"})); + EXPECT_EQ(result.value().command.value(), "run"); + EXPECT_EQ(result.value().files.value().value(), (Strings{"x", "y", "z"})); +} + +/// The parser fills the outermost rfl::Positional fields first, then those +/// found through other wrappers, and a list takes the remaining arguments +/// only as the last of them. +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), + "Usage: app ...\n" + "\n" + "Arguments:\n" + " Required.\n" + " Required.\n" + " ... Files to process. Required.\n"); + + const auto result = read({"a,b", "run", "x", "y"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().pair.value(), (Strings{"a", "b"})); + EXPECT_EQ(result.value().command.value(), "run"); + EXPECT_EQ(result.value().files.value().value(), (Strings{"x", "y"})); +} + +/// An rfl::Short found through other wrappers counts only if no other field +/// has its name. +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) { + EXPECT_EQ(rfl::cli::usage("app", true), + "Usage: app -o|--output= --log=\n" + "\n" + "Arguments:\n" + " -o, --output= Required.\n" + " --log= Where to log. Required.\n"); + + const auto result = read({"-o", "out", "--log", "l"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().output.value(), "out"); + EXPECT_EQ(result.value().log.value().value(), "l"); +} + +TEST(cli, test_usage_list_delimiter) { + using Semicolon = rfl::cli::ListDelimiter<";">; + EXPECT_EQ((rfl::cli::usage("app", true)), + "Usage: app -r|--report= [--tags=] " + " ...\n" + "\n" + "Arguments:\n" + " -r, --report= Reports to write. Can be repeated. " + "Required.\n" + " --tags= Default: a;b. Can be repeated.\n" + " Required.\n" + " ... Files to process. Required.\n"); + const auto semicolon = + read({"-r", "a;b,c", "run", "x;y", "--tags=t;u"}); + ASSERT_TRUE(semicolon) << semicolon.error().what(); + EXPECT_EQ(semicolon.value().report.value().value(), + (Strings{"a", "b,c"})); + EXPECT_EQ(semicolon.value().tags.value(), (Strings{"t", "u"})); + EXPECT_EQ(semicolon.value().files.value().value(), (Strings{"x", "y"})); + + // Not split: every occurrence is one item, so a list takes one value per + // occurrence. + using NoSplit = rfl::cli::ListDelimiter<"">; + EXPECT_EQ((rfl::cli::usage("app", true)), + "Usage: app -r|--report= [--tags=] " + " ...\n" + "\n" + "Arguments:\n" + " -r, --report= Reports to write. Can be repeated. " + "Required.\n" + " --tags= Default: a, b. Can be repeated.\n" + " Required.\n" + " ... Files to process. Required.\n"); + const auto no_split = + read({"-r", "a,b", "-r", "c", "run", "x,y", "z"}); + ASSERT_TRUE(no_split) << no_split.error().what(); + EXPECT_EQ(no_split.value().report.value().value(), (Strings{"a,b", "c"})); + EXPECT_EQ(no_split.value().files.value().value(), (Strings{"x,y", "z"})); +} + +// recipe [options] , as in test_options_first.cpp. +struct Recipe { + rfl::Short<"v", std::optional> verbose; + rfl::Positional name; + rfl::Positional> args; + rfl::Short<"j", std::optional> jobs; +}; + +TEST(cli, test_usage_options_first) { + // Without OptionsFirst, options and positional arguments can be mixed, so + // the synopsis keeps the declaration order. + EXPECT_EQ(rfl::cli::usage("recipe"), + "Usage: recipe [-v|--verbose[=]] [...] " + "[-j|--jobs=]\n"); + + // With OptionsFirst, the options end at the first positional argument, so + // the synopsis lists them first. The rows keep the declaration order. + EXPECT_EQ( + (rfl::cli::usage>("recipe", true)), + "Usage: recipe [-v|--verbose[=]] [-j|--jobs=] " + "[...]\n" + "\n" + "Arguments:\n" + " -v, --verbose[=]\n" + " Required.\n" + " ...\n" + " -j, --jobs=\n"); + + const auto result = + read>( + {"-v", "-j", "4", "build", "--jobs", "8"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().jobs.value(), 4); + EXPECT_EQ(result.value().name.value(), "build"); + EXPECT_EQ(result.value().args.value().value(), (Strings{"--jobs", "8"})); +} + +} // namespace test_usage_options