diff --git a/README.md b/README.md index 9cfdfa223..e39f622ed 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,17 @@ struct Config { // ./app data.csv -o /tmp/out -v --count=10 ``` +`rfl::cli::usage` generates the help text from the same struct, for instance for `--help`: + +```cpp +if (argc > 1 && std::string_view(argv[1]) == "--help") { + std::cout << rfl::cli::usage(argv[0], true).value(); + // Usage: ./app -o|--output-dir= -v|--verbose[=] --count= + // + // Arguments: ... +} +``` + Nested structs, `std::optional`, `std::vector`, enums, `rfl::Flatten` and `rfl::Rename` are all supported. Refer to the [documentation](https://munich-data-engineering.github.io/reflect-cpp/cli) for details. ### Error messages diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 7c4443f71..433cecb03 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -133,6 +133,41 @@ looks like an option (`-` followed by anything except a digit or `.`): `Missing value for option '-o'.` Use `=` to pass an empty value or one that starts with `-`: `-o=`, `-o=-x`. +### Grouped short options + +As in getopt, short options can share one token, and a value can be +attached to its option: + +```cpp +struct Config { + rfl::Short<"q", std::optional> quiet; + rfl::Short<"v", std::optional> verbose; + rfl::Short<"f", std::optional> format; +}; + +// ./app -qv -fcsv -> quiet, verbose, format = "csv" +// ./app -qvfcsv -> the same +// ./app -qf csv -> quiet, format = "csv" +``` + +Flags are set up to the first option that takes a value. That option takes +the rest of the token, or the next token if nothing is left. The last +option in a token treats the next token as it would alone (`-qv false` sets +`verbose` to `false`). + +- `-f=csv` and `-qf=csv` give `csv`: the `=` is not part of the value. +- A flag inside a group takes no value: `-vq=false` is an error. +- A letter that is not a short option is an error: + `Unknown short argument: -x (in '-qxf').` +- A token like `-42`, `-1.5` or `-.5` is a negative number, so `-p -42`, + `-p-42` and a positional `-42` work. If a short option's name is a digit + (see [Positional arguments](#positional-arguments)), such a token is a + group of short options instead: `-15` is `-1 -5`, and `-10` and `-1.5` + fail with `Unknown short argument: -0 (in '-10').` and + `-. (in '-1.5')`. +- Grouping needs the struct: the public `rfl::cli::parse_argv` reads `-abc` + as the one short option `abc`. + ## Combining wrappers `Short` and `Positional` can be nested with `DefaultVal`, `std::optional`, @@ -160,6 +195,80 @@ struct Config { // ./app data.csv -o /tmp/out -v --count=10 ``` +## Usage / help + +`rfl::cli::usage(program_name, detailed = false)` generates the +help text from the same struct, and with the same processors, as +`rfl::cli::read()`. So the names always match what the parser +accepts, including kebab-case, `rfl::Rename`, `rfl::Flatten` and nested paths. +It returns an `rfl::Result`. + +```cpp +enum class LogLevel { debug, info, warn }; + +struct Database { + std::string host; + int port; +}; + +struct Config { + rfl::Positional> + input_file; + rfl::Short<"p", rfl::Description<"Port to listen on", int>> port; + rfl::Description<"Minimum level to log", std::optional> log_level; + rfl::Description<"Tags to attach", std::vector> tags; + Database database; +}; +``` + +`rfl::cli::usage("app", true).value()` is the usage line, where +optional arguments are in brackets, and one line per argument, with its +description and whether it is required. `rfl::cli::usage("app")` +gives only the usage line. + +``` +Usage: app -p|--port= [--log-level=] --tags= --database.host= --database.port= + +Arguments: + Path to the input file. Required. + -p, --port= Port to listen on. Required. + --log-level= Minimum level to log + --tags= Tags to attach. Required. + --database.host= Required. + --database.port= Required. +``` + +Fields wrapped in `rfl::DefaultVal` are optional, and so are all fields if you +pass `rfl::DefaultIfMissing` (to both `read` and `usage`). The parser takes +the defaults of `rfl::DefaultVal` fields from a default-constructed struct. If +a struct with `rfl::DefaultVal` cannot be default-constructed (for instance +because a validator rejects another field's default value), it cannot be read, +and `usage` returns the error, as it does for two fields with the same short +name. + +Each argument is shown as the option table that `read` parses with (see +[Architecture](#architecture)) reads it: a `bool`, also inside a nested +struct, is a flag whose value can be left out (`--verbose[=]`), and +every other option takes a value (`--port=`). + +`rfl::Positional` and `rfl::Short` are found through the other wrappers, as +the parser does (see [Combining wrappers](#combining-wrappers)), so +`rfl::Description<"...", rfl::Positional>` is listed as a +positional argument. + +`read` does not handle `--help`: check `argv` for it and print `usage` +yourself: + +```cpp +int main(int argc, char* argv[]) { + if (argc > 1 && std::string_view(argv[1]) == "--help") { + std::cout << rfl::cli::usage(argv[0], true).value(); + return 0; + } + const auto config = rfl::cli::read(argc, argv).value(); +} +``` + ## Supported types | Type | CLI format | Notes | @@ -175,7 +284,7 @@ struct Config { | `rfl::Flatten` | fields inlined | No prefix needed | | `rfl::Rename<"x", T>` | `--x=val` | Bypasses kebab conversion | | `rfl::Positional` | bare token | Matched in declaration order | -| `rfl::Short<"x", T>` | `-x value` or `-x=value` | Single-character alias | +| `rfl::Short<"x", T>` | `-x value`, `-x=value` or `-xvalue` | Single-character alias, can be grouped (`-qv`) | ## Architecture @@ -204,6 +313,7 @@ Parsing proceeds in three stages: - `include/rfl/cli/parse_argv.hpp` — `argv` -> `ParsedArgs` - `include/rfl/cli/options.hpp` — the internal option table: the long, short and positional options of a struct - `include/rfl/cli/resolve_args.hpp` — `ParsedArgs` -> `map` +- `include/rfl/cli/usage.hpp` — `usage()` help text, built on `rfl::parsing::schema` and the internal option table - `include/rfl/cli.hpp` — aggregator header - `include/rfl/SnakeCaseToKebabCase.hpp` — processor - `include/rfl/Positional.hpp` — `Positional` wrapper diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index 85881e7b9..a35b9e025 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -8,5 +8,6 @@ #include "cli/parse_argv.hpp" #include "cli/read.hpp" #include "cli/resolve_args.hpp" +#include "cli/usage.hpp" #endif diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index 3fa061105..bfa62c928 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -70,6 +70,11 @@ struct Options { /// argument. std::vector positionals; + /// Whether short options can be grouped (`-qv`, `-fcsv`). make_options + /// sets it. Without a table (the table-less parse_argv), `-abc` is the + /// one short option `abc`. + bool group_short_options = false; + /// Whether tokens such as `-5` and `-.5` are short options rather than /// negative numbers. They are when parse_argv is called without the /// struct. make_options clears it unless, as in argparse, a short option's @@ -334,6 +339,7 @@ void collect_short_and_positional(Options* _options) { template Options make_options() { Options options; + options.group_short_options = true; using U = unwrapped_option_t; if constexpr (is_option_struct_v) { collect_options(&options); diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index 76fce4491..03af64a83 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -51,6 +51,11 @@ namespace internal { /// argument unless `_options.negative_numbers_are_options` is set, as it is /// without `_options` and when the struct has a short option whose name /// looks like a number (rfl::Short<"1", ...>), as in argparse. +/// Short options known to `_options` can be grouped as in getopt: in `-qvf` +/// every flag is set until the first option that takes a value, which +/// takes the rest of the token (`-qfcsv`) or, if nothing is left, the next +/// token (`-qf csv`). Without `_options` from make_options, short options +/// are not grouped: `-abc` is the short option `abc`. /// Every element of `_args` is parsed; nothing is skipped as the program name. /// @param _args The command-line arguments to parse /// @param _options The options of the target struct (see make_options) @@ -141,46 +146,95 @@ inline rfl::Result parse_string_views( continue; } - // Short argument: -x value, -x=value, or -x (bool). + // Short options: -x, -x value, -x=value, and groups of them in one + // token, as in getopt: -qv, -fvalue, -qfvalue, -qf value. if (arg_raw.size() >= 2 && arg_raw[0] == '-') { + const auto group = arg_raw.substr(1); + // A negative number such as -42 or -.5 is a positional argument, // unless, as in argparse, a short option's name looks like a number - // (-1). Without a table, it is the short option "42". + // (-1). Then -42 is a group of short options. Without a table, it is + // the short option "42". if (!looks_like_option(arg_raw) && !negative_numbers_are_options) { result.positional.emplace_back(arg_raw); continue; } - const auto arg = arg_raw.substr(1); - const auto eq = arg.find('='); - - // -x=value - if (eq != std::string_view::npos) { - const auto r = add_short( - std::string(arg.substr(0, eq)), - std::string(arg.substr(eq + 1)), arg_raw); - if (!r) { return error(r.error().what()); } - continue; + if (group.starts_with('=')) { + return error("Invalid short option '" + std::string(arg_raw) + "'."); } - auto key = std::string(arg); - const auto option = _options.find_short(key); - auto val = std::string(); - if (option.kind == OptionKind::unknown) { - // Not in `_options`: consume the next token as the value if it - // doesn't look like an option. resolve_args reports unknown short - // options. - if (i + 1 < _args.size() && !looks_like_option(_args[i + 1])) { - val = std::string(_args[++i]); + // Without a table, the short options are not known, so -abc is the one + // short option "abc": -abc value, -abc=value or -abc. + for (size_t j = 0; j < group.size(); ++j) { + // Short names are single ASCII characters. An unknown character may + // take several bytes in UTF-8, so take them all for the message. + const auto c = static_cast(group[j]); + size_t len = 1; + if (_options.group_short_options && c >= 0xC0) { + const size_t expected = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : 2; + while (len < expected && j + len < group.size() + && (static_cast(group[j + len]) & 0xC0) + == 0x80) { + ++len; + } } + auto key = std::string( + _options.group_short_options + ? group.substr(j, len) + : group.substr(0, group.find('='))); + const auto option = _options.find_short(key); + const auto rest = group.substr(j + key.size()); + const auto name = "-" + key; + const bool alone = j == 0 && rest.empty(); + auto val = std::string(); + + if (j == 0 && rest.starts_with('=')) { + // -x=value, whatever -x is. Unlike getopt, where -f=csv gives + // "=csv", the '=' is not part of the value. + val = std::string(rest.substr(1)); + } + else if (option.kind == OptionKind::unknown) { + if (!alone) { + return error("Unknown short argument: " + name + " (in '" + + std::string(arg_raw) + "')."); + } + // Not in `_options`: consume the next token as the value if it + // doesn't look like an option. resolve_args reports unknown short + // options. + if (i + 1 < _args.size() && !looks_like_option(_args[i + 1])) { + val = std::string(_args[++i]); + } + } + else if (option.kind == OptionKind::flag && !rest.empty()) { + // -qv: a flag followed by more options. Like getopt, a flag in a + // group takes no value: -vq=false is an error, -q=false is not. + if (rest.starts_with('=')) { + return error("Option '" + name + "' does not take a value in '" + + std::string(arg_raw) + "'. Write '" + name + + std::string(rest) + "' on its own."); + } + const auto r = add_short(std::move(key), "", arg_raw); + if (!r) { return error(r.error().what()); } + continue; + } + else if (!rest.empty()) { + // -fvalue, -qfvalue: the rest of the token is the value. -qf=value + // is the same as -qfvalue, as -f=value is. + val = std::string(rest.starts_with('=') ? rest.substr(1) : rest); + } + else { + // The last option of the token handles the next one as it would + // alone: -qf csv takes "csv", -vq false takes "false". + auto v = take_value(option, name, &i); + if (!v) { return error(v.error().what()); } + val = std::move(*v); + } + + const auto r = add_short(std::move(key), std::move(val), arg_raw); + if (!r) { return error(r.error().what()); } + break; } - else { - auto v = take_value(option, arg_raw, &i); - if (!v) { return error(v.error().what()); } - val = std::move(*v); - } - const auto r = add_short(std::move(key), std::move(val), arg_raw); - if (!r) { return error(r.error().what()); } continue; } diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp new file mode 100644 index 000000000..199d90c43 --- /dev/null +++ b/include/rfl/cli/usage.hpp @@ -0,0 +1,447 @@ +#ifndef RFL_CLI_USAGE_HPP_ +#define RFL_CLI_USAGE_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Processors.hpp" +#include "../Result.hpp" +#include "../SnakeCaseToKebabCase.hpp" +#include "../generic/Writer.hpp" +#include "../internal/default_if_missing_v.hpp" +#include "../internal/is_default_val_v.hpp" +#include "../internal/is_extra_fields.hpp" +#include "../internal/is_named_tuple.hpp" +#include "../internal/no_optionals_v.hpp" +#include "../internal/processed_t.hpp" +#include "../parsing/is_required.hpp" +#include "../parsing/schema/Definition.hpp" +#include "../parsing/schema/Type.hpp" +#include "../parsing/schema/make.hpp" +#include "Reader.hpp" +#include "options.hpp" +#include "resolve_args.hpp" + +namespace rfl::cli { + +namespace internal { + +/// Whether a top-level field is required, which the schema cannot tell the +/// way the parser sees it. +struct UsageFieldMeta { + bool required = true; +}; + +/// Everything usage() renders about one argument. +struct UsageArg { + /// The long name, including the path of nested objects ("database.host"). + std::string name; + std::string short_name; + bool positional = false; + /// What the option does with a value, from the parser's option table: + /// flags (`--verbose`) can be given without one. + OptionKind kind = OptionKind::value; + /// Whether the field is a list. + bool is_list = false; + bool required = true; + /// Whether `required` was taken from the parser's compile-time traits, so + /// that the schema must not override it. + bool required_is_known = false; + /// The placeholder for one value: "", "" or "". Lists + /// are rendered from it with the list delimiter. + std::string value = ""; + /// The allowed values of enums and literals. + std::vector choices; + std::string description; +}; + +/// Whether a missing field of type `ValueType` inside root type `U` is filled +/// in by the parser's default-value path. Mirrors +/// `NamedTupleParser::handle_one_missing_field` without invoking `T{}` at +/// runtime (for structs, `schema::make` already constructs `T{}` once if and +/// only if `has_default_val_v` is true). +template +constexpr bool usage_default_val_is_optional() { + if constexpr (!rfl::internal::is_default_val_v) { + return false; + } else if constexpr (rfl::internal::is_named_tuple_v) { + using Inner = typename rfl::internal::default_val_t::Type; + return !std::is_const_v && + std::is_default_constructible_v && + std::is_default_constructible_v; + } else { + return std::is_default_constructible_v; + } +} + +template +void add_usage_field_meta(std::map* _meta) { + using Info = field_info; + using ValueType = std::remove_cvref_t; + auto& meta = (*_meta)[std::string(Info::name())]; + // The same condition as in NamedTupleParser::handle_one_missing_field. + // The schema cannot tell on its own, because it marks a DefaultVal field as + // optional even where the parser requires it. + meta.required = + !usage_default_val_is_optional() + && !rfl::internal::is_extra_fields_v + && (rfl::internal::no_optionals_v + || parsing::is_required()); +} + +/// Collects whether each top-level field is required from the same +/// compile-time traits that the parser uses, so the help matches what the +/// parser accepts. Positional, Short and flags come from the parser's option +/// table (make_options). +template +std::map collect_usage_field_meta( + std::index_sequence<_is...>) { + std::map meta; + (add_usage_field_meta(&meta), ...); + return meta; +} + +/// Walks the format-agnostic schema of the struct and collects one UsageArg +/// per command-line argument, in declaration order. +class UsageCollector { + public: + using Type = parsing::schema::Type; + + UsageCollector(const parsing::schema::Definition* _definition, + const std::map* _meta, + const Options* _options, + const bool _optionals_are_required) + : definition_(_definition), + meta_(_meta), + options_(_options), + optionals_are_required_(_optionals_are_required) { + for (const auto& [short_name, path] : _options->short_options) { + short_names_[path] = short_name; + } + } + + /// Collects the arguments. + /// @param _all_optional Whether no argument is required + /// (rfl::DefaultIfMissing). + std::vector collect(const bool _all_optional) { + auto root = UsageArg{}; + root.required = !_all_optional; + add(definition_->root_, std::move(root), false); + return std::move(args_); + } + + private: + /// @param _outermost Whether _type is the outermost type of a field. + void add(const Type& _type, UsageArg _arg, const bool _outermost) { + _type.variant_.visit([&](const auto& _t) { + using T = std::remove_cvref_t; + // Description and Deprecated wrap the inner schema node without changing + // how the field is read. Short, Positional and Rename leave no node. + if constexpr (std::is_same_v + || std::is_same_v) { + if (_arg.description.empty()) { + _arg.description = _t.description_; + } + add(*_t.type_, std::move(_arg), _outermost); + + } else if constexpr (std::is_same_v) { + if (!_arg.required_is_known && !optionals_are_required_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + // The schema populates `default_value_` only when the parser recognizes + // the DefaultVal field and default-constructed its enclosing struct. + if (!_arg.required_is_known && _outermost && _t.default_value_) { + _arg.required = false; + } + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + add(*_t.type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + const auto it = definition_->definitions_.find(_t.name_); + if (it == definition_->definitions_.end() + || !visiting_.insert(_t.name_).second) { + // Unknown or recursive: there is no finite set of paths to list. + add_leaf(std::move(_arg)); + return; + } + add(it->second, std::move(_arg), _outermost); + visiting_.erase(_t.name_); + + } else if constexpr (std::is_same_v) { + add_object(_t, _arg); + + } else if constexpr (std::is_same_v) { + _arg.name += path_separator; + _arg.name += ""; + _arg.short_name.clear(); + _arg.positional = false; + add(*_t.value_type_, std::move(_arg), false); + + } else if constexpr (std::is_same_v) { + _arg.value = ""; + _arg.kind = OptionKind::flag; + add_leaf(std::move(_arg)); + + } else if constexpr (std::is_same_v) { + add_choices(_t.values_, std::move(_arg)); + + } else if constexpr (std::is_same_v) { + auto values = std::vector(); + for (const auto& v : _t.values_) { + values.push_back(v.value_); + } + add_choices(values, std::move(_arg)); + + } else if constexpr (std::is_same_v + || std::is_same_v + || std::is_same_v) { + _arg.is_list = true; + add_leaf(std::move(_arg)); + + } else { + add_leaf(std::move(_arg)); + } + }); + } + + void add_object(const Type::Object& _object, const UsageArg& _parent) { + const bool is_root = _parent.name.empty(); + for (const auto& [name, type] : _object.types_) { + auto arg = UsageArg{}; + arg.name = is_root ? name : _parent.name + path_separator + name; + // Children of an optional object are only needed if it is given. + arg.required = _parent.required; + if (is_root) { + const auto& positionals = options_->positionals; + arg.positional = std::find(positionals.begin(), positionals.end(), + name) != positionals.end(); + const auto short_name = short_names_.find(name); + if (short_name != short_names_.end()) { + arg.short_name = short_name->second; + } + const auto it = meta_->find(name); + if (it != meta_->end()) { + arg.required = arg.required && it->second.required; + arg.required_is_known = true; + } + } + add(type, std::move(arg), true); + } + } + + void add_choices(const std::vector& _values, UsageArg _arg) { + _arg.choices = _values; + _arg.value = "<"; + for (size_t i = 0; i < _values.size(); ++i) { + _arg.value += (i == 0 ? "" : "|") + _values[i]; + } + _arg.value += ">"; + add_leaf(std::move(_arg)); + } + + void add_leaf(UsageArg _arg) { + if (_arg.name.empty()) { + return; + } + // How the parser treats the option, from the table that it uses. Keep + // the schema-derived kind (such as OptionKind::flag for nested booleans) + // when the option table only tracks top-level paths. + const auto option = options_->find_long(_arg.name); + if (option.kind != OptionKind::unknown) { + _arg.kind = option.kind; + } + args_.emplace_back(std::move(_arg)); + } + + private: + const parsing::schema::Definition* definition_; + const std::map* meta_; + const Options* options_; + const bool optionals_are_required_; + /// The rfl::Short aliases, by the path of their field. + std::map short_names_; + std::set visiting_; + std::vector args_; +}; + +/// The placeholder for the value of _arg: "", "", or for a list +/// "" with the list delimiter. +inline std::string usage_value_to_string(const UsageArg& _arg) { + if (!_arg.is_list) { + return _arg.value; + } + const auto d = std::string(1, array_delimiter); + return ""; +} + +/// "", "-p|--port=", "--verbose[=]" +inline std::string usage_arg_to_string(const UsageArg& _arg, + const std::string& _short_sep) { + if (_arg.positional) { + return "<" + _arg.name + ">"; + } + auto str = _arg.short_name.empty() ? std::string() + : "-" + _arg.short_name + _short_sep; + str += "--" + _arg.name; + const auto value = usage_value_to_string(_arg); + switch (_arg.kind) { + case OptionKind::flag: + // `--verbose`: the value can be left out. + str += "[=" + value + "]"; + break; + default: + str += "=" + value; + break; + } + return str; +} + +inline bool usage_ends_sentence(const std::string& _str) { + return !_str.empty() + && (_str.back() == '.' || _str.back() == '!' || _str.back() == '?'); +} + +/// "Port to connect on. Required." +inline std::string usage_help_text(const UsageArg& _arg) { + auto sentences = std::vector(); + if (_arg.positional && !_arg.choices.empty()) { + auto choices = std::string("Choices: "); + for (size_t i = 0; i < _arg.choices.size(); ++i) { + choices += (i == 0 ? "" : "|") + _arg.choices[i]; + } + sentences.push_back(std::move(choices)); + } + if (_arg.required) { + sentences.push_back("Required"); + } + auto text = _arg.description; + while (!text.empty() + && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r' + || text.back() == '\n')) { + text.pop_back(); + } + for (const auto& s : sentences) { + if (!text.empty()) { + text += usage_ends_sentence(text) ? " " : ". "; + } + text += s; + } + if (!sentences.empty() && !usage_ends_sentence(text)) { + text += "."; + } + return text; +} + +inline std::string format_usage(const std::string& _program_name, + const std::vector& _args, + const bool _detailed) { + auto out = "Usage: " + _program_name; + for (const auto& arg : _args) { + const auto str = usage_arg_to_string(arg, "|"); + out += arg.required ? " " + str : " [" + str + "]"; + } + out += '\n'; + if (!_detailed || _args.empty()) { + return out; + } + + auto rows = std::vector>(); + size_t width = 0; + for (const auto& arg : _args) { + rows.emplace_back(usage_arg_to_string(arg, ", "), usage_help_text(arg)); + width = std::max(width, rows.back().first.size()); + } + + constexpr size_t indent = 2; + constexpr size_t gap = 2; + const auto continuation = '\n' + std::string(indent + width + gap, ' '); + out += "\nArguments:\n"; + for (const auto& [left, right] : rows) { + out += std::string(indent, ' ') + left; + if (!right.empty()) { + out += std::string(width - left.size() + gap, ' '); + for (size_t i = 0; i < right.size(); ++i) { + const char c = right[i]; + if (c == '\n') { + if (i + 1 < right.size() && right[i + 1] != '\n') { + out += continuation; + } else { + out += '\n'; + } + } else { + out += c; + } + } + } + out += '\n'; + } + return out; +} + +} // namespace internal + +/// Generates the usage line, and optionally a help text with one row per +/// argument, for the struct that `rfl::cli::read()` parses into. +/// It applies the same processors as `read`, so the names always match what +/// the parser accepts (kebab-case, rfl::Rename, rfl::Flatten, nested paths). +/// +/// The help text lists the description (rfl::Description), the allowed +/// values of enums and literals and whether the argument is required. +/// @tparam T The struct type that the arguments are parsed into +/// @tparam Ps The processors passed to `rfl::cli::read` +/// @param _program_name The name shown after "Usage:", usually argv[0] +/// @param _detailed Whether to add a line for every argument +/// @return The usage text, ending with a newline, or an error if no read of +/// T can succeed: two fields have the same short name, or T has a bare +/// rfl::DefaultVal and default-constructing it throws. +template +rfl::Result usage(const std::string& _program_name, + const bool _detailed = false) { + using ProcessorsType = Processors; + using U = internal::unwrapped_option_t; + // The table that read() parses with, so the help shows what the parser + // accepts. + const auto options = internal::make_options(); + return internal::check_short_names(options).and_then( + [&](auto) -> rfl::Result { + try { + std::map meta; + if constexpr (internal::is_option_struct_v) { + using NamedTupleType = + internal::option_fields_t; + meta = internal::collect_usage_field_meta( + std::make_index_sequence{}); + } + // The schema takes the default values from a default-constructed + // T, which can throw. + const auto definition = + parsing::schema::make(); + auto collector = internal::UsageCollector( + &definition, &meta, &options, + rfl::internal::no_optionals_v); + const auto args = collector.collect( + rfl::internal::default_if_missing_v); + return internal::format_usage(_program_name, args, _detailed); + } catch (const std::exception& e) { + return error(e.what()); + } + }); +} + +} // namespace rfl::cli + +#endif diff --git a/include/rfl/internal/no_duplicate_field_names.hpp b/include/rfl/internal/no_duplicate_field_names.hpp index 4e3f90dc2..86bf5f671 100644 --- a/include/rfl/internal/no_duplicate_field_names.hpp +++ b/include/rfl/internal/no_duplicate_field_names.hpp @@ -1,51 +1,48 @@ #ifndef RFL_INTERNAL_NO_DUPLICATE_FIELD_NAMES_HPP_ #define RFL_INTERNAL_NO_DUPLICATE_FIELD_NAMES_HPP_ +#include +#include +#include +#include +#include + #include "../Tuple.hpp" namespace rfl { namespace internal { -namespace no_duplicate_field_names_helpers { - -template -constexpr inline void compare_two_fields() { - if constexpr (_j < _i) { - using FieldType1 = std::remove_cvref_t>; - using FieldType2 = std::remove_cvref_t>; - - constexpr auto field_name_i = FieldType1::name_; - constexpr auto field_name_j = FieldType2::name_; - - constexpr bool no_duplicate = (field_name_i != field_name_j); - - static_assert(no_duplicate, - "Duplicate field names are not allowed in either named " - "tuples or Literals."); - } -} - -template -constexpr inline void iterate_over_j(std::integer_sequence) { - (compare_two_fields(), ...); -} - -template -constexpr inline void iterate_over_i(std::integer_sequence) { - (iterate_over_j(std::make_integer_sequence()), ...); -} -} // namespace no_duplicate_field_names_helpers - template constexpr inline bool no_duplicate_field_names() { - constexpr auto num_fields = rfl::tuple_size_v; + constexpr std::size_t num_fields = rfl::tuple_size_v; if constexpr (num_fields <= 1) { return true; } else { - no_duplicate_field_names_helpers::iterate_over_i( - std::make_integer_sequence()); - return true; + constexpr bool result = + [](std::index_sequence<_is...>) { + std::array arr{ + std::remove_cvref_t>::name_ + .string_view()...}; + for (std::size_t gap = arr.size() / 2; gap > 0; gap /= 2) { + for (std::size_t i = gap; i < arr.size(); ++i) { + const auto key = arr[i]; + std::size_t j = i; + while (j >= gap && key < arr[j - gap]) { + arr[j] = arr[j - gap]; + j -= gap; + } + arr[j] = key; + } + } + for (std::size_t i = 1; i < arr.size(); ++i) { + if (arr[i] == arr[i - 1]) { + return false; + } + } + return true; + }(std::make_index_sequence()); + return result; } } diff --git a/tests/cli/test_short_clusters.cpp b/tests/cli/test_short_clusters.cpp new file mode 100644 index 000000000..49f32d794 --- /dev/null +++ b/tests/cli/test_short_clusters.cpp @@ -0,0 +1,310 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_short_clusters { + +template +rfl::Result read(std::vector _args) { + _args.insert(_args.begin(), "program"); + return rfl::cli::read(static_cast(_args.size()), + const_cast(_args.data())); +} + +template +std::string error_of(const rfl::Result& _result) { + return _result ? std::string("(no error)") + : std::string(_result.error().what()); +} + +struct Opts { + rfl::Short<"a", bool> all; + rfl::DefaultVal> brief = false; + rfl::Short<"c", std::optional> color; + rfl::DefaultVal> quiet = false; + rfl::Short<"f", std::optional> format; + rfl::Short<"p", std::optional> port; + rfl::Positional> input; + rfl::Positional> output; +}; + +TEST(cli, test_short_cluster_flags) { + const auto result = read({"-abc"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& o = result.value(); + EXPECT_TRUE(o.all()); + EXPECT_TRUE(o.brief().value()); + EXPECT_EQ(o.color(), true); + EXPECT_FALSE(o.quiet().value()); + EXPECT_FALSE(o.format()); +} + +TEST(cli, test_short_cluster_flags_any_order) { + const auto result = read({"-cba", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().all()); + EXPECT_TRUE(result.value().brief().value()); + EXPECT_EQ(result.value().color(), true); + EXPECT_EQ(result.value().input(), "in.txt"); +} + +TEST(cli, test_short_attached_value) { + const auto result = read({"-a", "-fcsv"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().format(), "csv"); +} + +TEST(cli, test_short_cluster_then_attached_value) { + const auto result = read({"-a", "-qfcsv", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().quiet().value()); + EXPECT_EQ(result.value().format(), "csv"); + EXPECT_EQ(result.value().input(), "in.txt"); +} + +TEST(cli, test_short_cluster_value_takes_next_token) { + const auto result = read({"-a", "-qf", "csv", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().quiet().value()); + EXPECT_EQ(result.value().format(), "csv"); + EXPECT_EQ(result.value().input(), "in.txt"); +} + +TEST(cli, test_short_cluster_value_takes_rest_verbatim) { + // Everything after the first option that takes a value is its value, even + // letters that are short options themselves. + const auto result = read({"-afabc"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().all()); + EXPECT_FALSE(result.value().brief().value()); + EXPECT_EQ(result.value().format(), "abc"); +} + +TEST(cli, test_short_cluster_value_missing) { + for (const auto& args : std::vector>{ + {"-a", "-qf"}, {"-aqf", "-b"}, {"-aqf", "--format=x"}}) { + const auto result = read(args); + EXPECT_EQ(error_of(result), "Missing value for option '-f'."); + } +} + +TEST(cli, test_short_equals_value) { + // rfl keeps `-f=csv` meaning "csv", also in a group. getopt would give + // "=csv". + for (const auto& args : std::vector>{ + {"-a", "-f=csv"}, {"-aqf=csv"}}) { + const auto result = read(args); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().format(), "csv"); + } + const auto empty = read({"-af="}); + ASSERT_TRUE(empty) << empty.error().what(); + EXPECT_EQ(empty.value().format(), ""); + const auto twice = read({"-af==x"}); + ASSERT_TRUE(twice) << twice.error().what(); + EXPECT_EQ(twice.value().format(), "=x"); +} + +TEST(cli, test_short_flag_equals_value_alone) { + const auto result = read({"-a=false", "-q=true"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_FALSE(result.value().all()); + EXPECT_TRUE(result.value().quiet().value()); +} + +TEST(cli, test_short_cluster_flag_takes_no_attached_value) { + const auto result = read({"-aq=false"}); + EXPECT_EQ(error_of(result), + "Option '-q' does not take a value in '-aq=false'. Write " + "'-q=false' on its own."); + const auto second = read({"-a", "-bq=false"}); + EXPECT_EQ(error_of(second), + "Option '-q' does not take a value in '-bq=false'. Write " + "'-q=false' on its own."); +} + +TEST(cli, test_short_cluster_last_flag_takes_bool_literal) { + // The last option of a group treats the next token as it would alone. + const auto result = read({"-qa", "false", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().quiet().value()); + EXPECT_FALSE(result.value().all()); + EXPECT_EQ(result.value().input(), "in.txt"); + EXPECT_FALSE(result.value().output()); +} + +TEST(cli, test_short_cluster_flag_does_not_take_other_tokens) { + const auto result = read({"-ab", "in.txt", "out.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().all()); + EXPECT_TRUE(result.value().brief().value()); + EXPECT_EQ(result.value().input(), "in.txt"); + EXPECT_EQ(result.value().output(), "out.txt"); +} + +TEST(cli, test_short_cluster_unknown_letter) { + const auto middle = read({"-axf", "csv"}); + EXPECT_EQ(error_of(middle), "Unknown short argument: -x (in '-axf')."); + const auto first = read({"-xa"}); + EXPECT_EQ(error_of(first), "Unknown short argument: -x (in '-xa')."); + const auto last = read({"-abz"}); + EXPECT_EQ(error_of(last), "Unknown short argument: -z (in '-abz')."); + // A character that takes several bytes in UTF-8 is named whole. + const auto utf8 = read({"-a\xC3\xA9", "-\xE2\x82\xAC"}); + EXPECT_EQ(error_of(utf8), + "Unknown short argument: -\xC3\xA9 (in '-a\xC3\xA9')."); + const auto utf8_alone = read({"-a", "-\xE2\x82\xAC"}); + EXPECT_EQ(error_of(utf8_alone), "Unknown short argument: -\xE2\x82\xAC"); +} + +TEST(cli, test_short_unknown_alone) { + EXPECT_FALSE(read({"-a", "-x"})); + EXPECT_FALSE(read({"-a", "-x=1"})); +} + +TEST(cli, test_short_cluster_duplicate) { + EXPECT_FALSE(read({"-aa"})); + EXPECT_FALSE(read({"-ab", "-ba"})); +} + +TEST(cli, test_short_cluster_conflicts_with_long) { + EXPECT_FALSE(read({"-afcsv", "--format=json"})); +} + +TEST(cli, test_short_negative_number_value) { + for (const auto& args : std::vector>{ + {"-a", "-p", "-42"}, {"-a", "-p-42"}, {"-ap", "-42"}, + {"-ap-42"}, {"-a", "-p=-42"}}) { + const auto result = read(args); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().port(), -42); + } +} + +struct Numbers { + rfl::Short<"v", bool> verbose; + rfl::Short<"n", std::optional> number; + rfl::Positional x; + rfl::Positional> y; +}; + +TEST(cli, test_short_negative_number_positional) { + const auto result = read({"-v", "-42", "-.5"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().verbose()); + EXPECT_DOUBLE_EQ(result.value().x(), -42.0); + EXPECT_DOUBLE_EQ(result.value().y().value(), -0.5); + + const auto value = read({"-vn", "-1.5", "-3"}); + ASSERT_TRUE(value) << value.error().what(); + EXPECT_DOUBLE_EQ(value.value().number().value(), -1.5); + EXPECT_DOUBLE_EQ(value.value().x(), -3.0); +} + +struct DigitShort { + rfl::Short<"1", bool> one_per_line; + rfl::Short<"n", std::optional> count; + rfl::Positional> x; +}; + +struct DigitShortNumbers { + rfl::Short<"1", bool> one_per_line; + rfl::Positional> x; + rfl::Positional> y; + rfl::Positional> z; +}; + +TEST(cli, test_short_digit_option_negative_numbers_are_groups) { + // Once a short option's name is a digit, a token that looks like a + // negative number is a group of short options. + const auto grouped = read({"-1n2"}); + ASSERT_TRUE(grouped) << grouped.error().what(); + EXPECT_TRUE(grouped.value().one_per_line()); + EXPECT_EQ(grouped.value().count(), 2); + + EXPECT_EQ(error_of(read({"-1", "-5"})), + "Unknown short argument: -5"); + EXPECT_EQ(error_of(read({"-2"})), "Unknown short argument: -2"); + EXPECT_EQ(error_of(read({"-.5"})), + "Unknown short argument: -. (in '-.5')."); + EXPECT_EQ(error_of(read({"-1.5"})), + "Unknown short argument: -. (in '-1.5')."); + EXPECT_EQ(error_of(read({"-10"})), + "Unknown short argument: -0 (in '-10')."); + EXPECT_EQ(error_of(read({"-15"})), + "Unknown short argument: -5 (in '-15')."); + + const auto separated = + read({"-1", "--", "-1.5", "-10", "-15"}); + ASSERT_TRUE(separated) << separated.error().what(); + EXPECT_TRUE(separated.value().one_per_line()); + EXPECT_DOUBLE_EQ(separated.value().x().value(), -1.5); + EXPECT_DOUBLE_EQ(separated.value().y().value(), -10.0); + EXPECT_DOUBLE_EQ(separated.value().z().value(), -15.0); +} + +TEST(cli, test_short_cluster_after_separator) { + const auto result = read({"-ab", "--", "-qfcsv", "-x"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().all()); + EXPECT_FALSE(result.value().quiet().value()); + EXPECT_FALSE(result.value().format()); + EXPECT_EQ(result.value().input(), "-qfcsv"); + EXPECT_EQ(result.value().output(), "-x"); +} + +TEST(cli, test_short_cluster_value_after_separator_token) { + // `--` after an option that needs a value is not its value. + const auto result = read({"-af", "--", "x"}); + EXPECT_EQ(error_of(result), "Missing value for option '-f'."); +} + +struct Nested { + rfl::Description<"Be quiet", rfl::Short<"q", bool>> quiet; + rfl::DefaultVal> output; + std::optional> verbose; +}; + +TEST(cli, test_short_cluster_nested_wrappers) { + const auto result = read({"-vqoout.csv"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().quiet().value()); + EXPECT_EQ(result.value().output().value(), "out.csv"); + ASSERT_TRUE(result.value().verbose.has_value()); + EXPECT_TRUE(result.value().verbose.value().value()); +} + +TEST(cli, test_short_cluster_invalid_utf8_lead_byte) { + // Invalid/truncated UTF-8 lead byte must not swallow a following '=' or ASCII + // character. + const auto res = read({"-\xC3=1"}); + ASSERT_FALSE(res); + EXPECT_EQ(std::string(res.error().what()), "Unknown short argument: -\xC3"); + + const auto res2 = read({"-q\xE9v"}); + ASSERT_FALSE(res2); + EXPECT_EQ(std::string(res2.error().what()), + "Unknown short argument: -\xE9 (in '-q\xE9v')."); +} + +TEST(cli, test_short_leading_equals_rejected) { + // `-=` and `-=foo` must be rejected cleanly (never produce an empty short key + // or consume the following token). + EXPECT_FALSE(read({"-="})); + EXPECT_FALSE(read({"-=foo"})); + EXPECT_FALSE(read({"-=", "value"})); + + const rfl::cli::internal::Options no_group{}; + const auto raw = rfl::cli::internal::parse_string_views( + std::vector{"-="}, no_group); + EXPECT_FALSE(raw); + const auto raw_val = rfl::cli::internal::parse_string_views( + std::vector{"-=foo"}, no_group); + EXPECT_FALSE(raw_val); +} + +} // namespace test_short_clusters diff --git a/tests/cli/test_usage.cpp b/tests/cli/test_usage.cpp new file mode 100644 index 000000000..d31422a5d --- /dev/null +++ b/tests/cli/test_usage.cpp @@ -0,0 +1,409 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_usage { + +enum class LogLevel { debug, info, warn }; + +struct Database { + std::string host; + int port; +}; + +struct Config { + rfl::Positional input_file; + std::string host_name; + bool verbose; + std::vector tags; + rfl::Short<"p", int> port; + Database database; + std::optional log_level; +}; + +TEST(cli, test_usage_synopsis) { + // The exact string proposed in + // https://github.com/munich-data-engineering/reflect-cpp/issues/692. + EXPECT_EQ(rfl::cli::usage("my_binary").value(), + "Usage: my_binary --host-name= " + "--verbose[=] --tags= -p|--port= " + "--database.host= --database.port= " + "[--log-level=]\n"); +} + +// The issue's second example: rfl::Positional and rfl::Short inside +// rfl::Description, which the parser finds, and so does the help. +struct Described { + rfl::Description<"Path to the input file", rfl::Positional> + input_file; + rfl::Description<"Host to connect to", std::string> host_name; + bool verbose; + rfl::Description<"Port to connect on", rfl::Short<"p", int>> port; + rfl::Description<"Minimum level to log", std::optional> log_level; +}; + +TEST(cli, test_usage_detailed) { + EXPECT_EQ( + rfl::cli::usage("my_binary", true).value(), + "Usage: my_binary --host-name= --verbose[=] " + "-p|--port= [--log-level=]\n" + "\n" + "Arguments:\n" + " Path to the input file. Required.\n" + " --host-name= Host to connect to. Required.\n" + " --verbose[=] Required.\n" + " -p, --port= Port to connect on. Required.\n" + " --log-level= Minimum level to log\n"); + + // What the help advertises is what the parser accepts. + const char* args[] = {"my_binary", "in.txt", "--host-name=localhost", + "--verbose", "-p", "8080", + "--log-level=warn"}; + const auto result = + rfl::cli::read(7, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().input_file().value(), "in.txt"); + EXPECT_EQ(result.value().port().value(), 8080); + EXPECT_EQ(result.value().log_level.get(), LogLevel::warn); + + // A plain bool is required, as the help says. + const char* no_verbose[] = {"my_binary", "in.txt", "--host-name=localhost", + "-p", "8080"}; + EXPECT_FALSE(rfl::cli::read(5, const_cast(no_verbose))); +} + +struct Limits { + rfl::DefaultVal> per_host = 4; + int total; +}; + +/// rfl::DefaultVal combined with other wrappers. +struct WrappedDefaultVal { + rfl::DefaultVal< + rfl::Short<"l", rfl::Description<"Minimum level to log", LogLevel>>> + log_level = LogLevel::info; + rfl::DefaultVal> timeout = 30; + rfl::DefaultVal> output = "out.txt"; + rfl::Short<"n", rfl::Description<"Number of runs", int>> runs; + Limits limits; +}; + +TEST(cli, test_usage_wrapped_default_val) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app [-l|--log-level=] " + "[--timeout=] [] " + "-n|--runs= [--limits.per-host=] " + "--limits.total=\n" + "\n" + "Arguments:\n" + " -l, --log-level= Minimum level to log\n" + " --timeout= Seconds to wait\n" + " \n" + " -n, --runs= Number of runs. Required.\n" + " --limits.per-host= Connections per host\n" + " --limits.total= Required.\n"); + + // Everything the help leaves optional can be left out. + const char* minimal[] = {"app", "-n", "3", "--limits.total=8"}; + const auto defaulted = + rfl::cli::read(4, const_cast(minimal)); + ASSERT_TRUE(defaulted) << defaulted.error().what(); + EXPECT_EQ(defaulted.value().output.get().value(), "out.txt"); + + // What the help calls required is required. + const char* no_runs[] = {"app", "--limits.total=8"}; + EXPECT_FALSE( + rfl::cli::read(2, const_cast(no_runs))); + const char* no_total[] = {"app", "-n", "3"}; + EXPECT_FALSE( + rfl::cli::read(3, const_cast(no_total))); +} + +/// The default-constructed `port` does not satisfy its validator. +struct WithInvalidDefault { + rfl::Validator> port; + rfl::DefaultVal threads = 4; +}; + +/// The same with the DefaultVal inside rfl::Short. +struct WithInvalidWrappedDefault { + rfl::Validator> port; + rfl::Short<"t", rfl::DefaultVal> threads = 4; +}; + +struct WithInvalidWrappedDefaultInside { + WithInvalidWrappedDefault server; +}; + +/// Has no default constructor, so neither has a struct that contains it. +class Port { + public: + using ReflectionType = int; + Port(int _value) : value_(_value) {} + int reflection() const { return value_; } + + private: + int value_; +}; + +struct WithPort { + Port port; + int retries = 3; +}; + +/// A bare DefaultVal here would not compile: the struct has no default +/// constructor. A wrapped one is required. +struct WithPortAndDefaultVal { + Port port; + rfl::Description<"Retries", rfl::DefaultVal> retries = 3; +}; + +TEST(cli, test_usage_defaults_without_default_construction) { + // The parser fills in a missing DefaultVal field only after it + // default-constructed the struct. If that throws (`port`'s zero value + // fails its validator) or the struct has no default constructor, the + // field is required, and the help says so. + static_assert(!std::is_default_constructible_v); + // With a bare DefaultVal, every read fails, and so does usage: the schema + // takes the defaults from a default-constructed struct. + const auto invalid = rfl::cli::usage("app", true); + ASSERT_FALSE(invalid); + EXPECT_EQ(std::string(invalid.error().what()), + "Value expected to be greater than or equal to 1, but got 0."); + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --port= -t|--threads=\n"); + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --server.port= --server.threads=\n"); + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --port= --retries=\n"); + + // A bare DefaultVal makes every read fail; a wrapped one is required. + const char* both[] = {"app", "--port=1", "--threads=2"}; + EXPECT_FALSE(rfl::cli::read(3, const_cast(both))); + const auto wrapped = rfl::cli::read( + 3, const_cast(both)); + ASSERT_TRUE(wrapped) << wrapped.error().what(); + EXPECT_EQ(wrapped.value().threads.value().get(), 2); + const char* port_only[] = {"app", "--port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(port_only))); + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(port_only))); + const char* nested[] = {"app", "--server.port=1"}; + EXPECT_FALSE(rfl::cli::read( + 2, const_cast(nested))); + + // With rfl::DefaultIfMissing nothing is required, even without T{}. + static_assert(!std::is_default_constructible_v); + EXPECT_EQ((rfl::cli::usage("app", true).value()), + "Usage: app [--port=] [--retries=]\n" + "\n" + "Arguments:\n" + " --port=\n" + " --retries=\n"); +} + +struct Inner { + std::string host = "db"; + int port = 5432; +}; + +struct WithInitializers { + int count = 3; + std::string name; + bool verbose = false; + std::optional limit; + Inner database; +}; + +TEST(cli, test_usage_without_default_if_missing) { + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --count= --name= --verbose[=] " + "[--limit=] --database.host= " + "--database.port=\n"); + + const char* args[] = {"app"}; + EXPECT_FALSE(rfl::cli::read(1, const_cast(args))); +} + +struct Tls { + bool verify; +}; + +struct WithNestedFlag { + Tls tls; +}; + +TEST(cli, test_usage_nested_flag) { + // A nested bool is a flag, as for the parser. + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --tls.verify[=]\n"); +} + +struct Address { + std::string city; + int zip; +}; + +struct Names { + rfl::Rename<"output_dir", std::string> output_dir; + rfl::Flatten
address; + std::optional backup; + std::map labels; +}; + +TEST(cli, test_usage_names) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app --output_dir= --city= --zip= " + "[--backup.host=] [--backup.port=] " + "--labels.=\n" + "\n" + "Arguments:\n" + " --output_dir= Required.\n" + " --city= Required.\n" + " --zip= Required.\n" + " --backup.host=\n" + " --backup.port=\n" + " --labels.= Required.\n"); + + const char* args[] = {"app", "--output_dir=/tmp", "--city=Springfield", + "--zip=12345", "--labels.env=prod"}; + const auto result = rfl::cli::read(5, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().labels.at("env"), "prod"); +} + +struct Optionals { + rfl::Positional> level; + rfl::Short<"v", std::optional> verbose; + rfl::Deprecated<"Use --port instead", "Old port", std::optional> + old_port; + rfl::Description<"First line\nSecond line", std::string> notes; +}; + +TEST(cli, test_usage_optionals) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app [] [-v|--verbose[=]] " + "[--old-port=] --notes=\n" + "\n" + "Arguments:\n" + " Choices: debug|info|warn.\n" + " -v, --verbose[=]\n" + " --old-port= Old port\n" + " --notes= First line\n" + " Second line. Required.\n"); +} + +TEST(cli, test_usage_no_optionals) { + // Processors are applied exactly as in read: with rfl::NoOptionals, + // optional fields are required. + EXPECT_EQ((rfl::cli::usage("app").value()), + "Usage: app -v|--verbose[=] --old-port= " + "--notes=\n"); +} + +struct Empty {}; + +TEST(cli, test_usage_empty) { + EXPECT_EQ(rfl::cli::usage("app").value(), "Usage: app\n"); + EXPECT_EQ(rfl::cli::usage("app", true).value(), "Usage: app\n"); +} + +struct CountingDefault { + static inline int ctor_count = 0; + static std::string make_host() { + ++ctor_count; + return "localhost"; + } + std::string host = make_host(); +}; + +TEST(cli, test_usage_does_not_default_construct_without_default_val) { + CountingDefault::ctor_count = 0; + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --host=\n"); + EXPECT_EQ(CountingDefault::ctor_count, 0); +} + +TEST(cli, test_usage_named_tuple_and_reflection_type) { + using NT = rfl::NamedTuple>, + rfl::Field<"my_req", std::string>, + rfl::Field<"my_flag", bool>>; + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app [--my_opt=] --my_req= " + "--my_flag[=]\n"); + const char* nt_args[] = {"app", "--my_req=hi", "--my_flag"}; + const auto nt_res = rfl::cli::read(3, const_cast(nt_args)); + ASSERT_TRUE(nt_res) << nt_res.error().what(); + EXPECT_EQ(nt_res.value().get<"my_opt">().get(), 0); + + class WrappedRoot { + public: + struct Impl { + std::string host_name; + std::optional port; + }; + using ReflectionType = Impl; + WrappedRoot(Impl _impl) : impl_(std::move(_impl)) {} + const Impl& reflection() const { return impl_; } + + private: + Impl impl_; + }; + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --host-name= [--port=]\n"); +} + +struct RichMapsAndTypes { + std::map dbs; + std::map flags; + std::map levels; + rfl::Short<"l", std::map> labels; + rfl::Literal<"fast", "slow"> mode; + std::array coords; + std::tuple pair; +}; + +struct RecursiveNode { + std::string name; + std::unique_ptr next; +}; + +struct TrailingNewlineDesc { + rfl::Description<"Line 1\n\nLine 2\n", std::string> note; +}; + +TEST(cli, test_usage_maps_recursive_literals_and_formatting) { + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --dbs..host= --dbs..port= " + "--flags.[=] --levels.= " + "--labels.= --mode= " + "--coords= --pair=\n"); + + EXPECT_EQ(rfl::cli::usage("app").value(), + "Usage: app --name= [--next=]\n"); + + EXPECT_EQ( + (rfl::cli::usage("app").value()), + "Usage: app --host-name= --verbose[=] " + "--tags= -p|--port= --database.host= " + "--database.port= [--log-level=]\n"); + + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app --note=\n" + "\n" + "Arguments:\n" + " --note= Line 1\n" + "\n" + " Line 2. Required.\n"); +} + +} // namespace test_usage diff --git a/tests/cli/test_usage_options.cpp b/tests/cli/test_usage_options.cpp new file mode 100644 index 000000000..2c358699e --- /dev/null +++ b/tests/cli/test_usage_options.cpp @@ -0,0 +1,79 @@ +#include + +#include +#include +#include +#include +#include + +// rfl::cli::usage for the parser's option features: wrappers in any order +// and positional order. Each test also reads the arguments as the help +// spells them. +namespace test_usage_options { + +template +rfl::Result read(std::vector _args) { + _args.insert(_args.begin(), "app"); + return rfl::cli::read(static_cast(_args.size()), + const_cast(_args.data())); +} + +struct WrapperOrder { + rfl::Description<"Where to write", rfl::Short<"o", std::string>> output; + rfl::DefaultVal> input = "in.txt"; + rfl::Description<"Be verbose", rfl::Short<"v", std::optional>> + verbose; +}; + +TEST(cli, test_usage_wrapper_order) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app -o|--output= [] [-v|--verbose[=]]\n" + "\n" + "Arguments:\n" + " -o, --output= Where to write. Required.\n" + " \n" + " -v, --verbose[=] Be verbose\n"); + + const auto defaulted = read({"-o", "out"}); + ASSERT_TRUE(defaulted) << defaulted.error().what(); + EXPECT_EQ(defaulted.value().input.value().value(), "in.txt"); +} + +/// The parser fills the rfl::Positional fields in declaration order, wherever +/// rfl::Positional sits among their wrappers. +struct PositionalOrder { + rfl::Description<"Files to process", rfl::Positional> files; + rfl::Positional pair; + rfl::Positional command; +}; + +TEST(cli, test_usage_positional_order) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "Usage: app \n" + "\n" + "Arguments:\n" + " Files to process. Required.\n" + " Required.\n" + " Required.\n"); + + const auto result = read({"x", "a", "run"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().pair.value(), "a"); + EXPECT_EQ(result.value().command.value(), "run"); + EXPECT_EQ(result.value().files.value().value(), "x"); +} + +/// Two fields with the same short name fail every read, and usage too. +struct ShortNameTaken { + rfl::Short<"o", std::string> output; + rfl::Description<"Where to log", rfl::Short<"o", std::string>> log; +}; + +TEST(cli, test_usage_short_name_taken) { + const auto usage = rfl::cli::usage("app", true); + ASSERT_FALSE(usage); + EXPECT_EQ(std::string(usage.error().what()), + "Duplicate short name '-o' in struct definition."); +} + +} // namespace test_usage_options diff --git a/tests/json/test_literal.cpp b/tests/json/test_literal.cpp index d4c28b6de..877a7b8d7 100644 --- a/tests/json/test_literal.cpp +++ b/tests/json/test_literal.cpp @@ -38,4 +38,38 @@ TEST(json, test_literal_reports_unsupported_string) { "string 'Ned'. The following strings are supported: 'Homer', " "'Marge', 'Bart', 'Lisa', 'Maggie'."); } + +TEST(json, test_literal_has_duplicates) { + static_assert(!FirstName::has_duplicates()); + static_assert(!LastName::has_duplicates()); + static_assert(rfl::Literal<"a", "a">::has_duplicates()); + static_assert(rfl::Literal<"a", "b", "c", "a">::has_duplicates()); + static_assert(rfl::Literal<"z", "m", "a", "m", "b">::has_duplicates()); + + using UniqueLarge = rfl::Literal< + "f15", "f03", "f28", "f00", "f19", "f07", "f24", "f11", "f31", "f02", + "f16", "f21", "f08", "f26", "f13", "f05", "f29", "f01", "f18", "f10", + "f25", "f06", "f22", "f14", "f30", "f04", "f17", "f20", "f09", "f27", + "f12", "f23">; + using DuplicateLarge = rfl::Literal< + "f15", "f03", "f28", "f00", "f19", "f07", "f24", "f11", "f31", "f02", + "f16", "f21", "f08", "f26", "f13", "f05", "f29", "f01", "f18", "f10", + "f25", "f06", "f22", "f14", "f30", "f04", "f17", "f20", "f09", "f27", + "f12", "f19">; + static_assert(!UniqueLarge::has_duplicates()); + static_assert(DuplicateLarge::has_duplicates()); + + static_assert(rfl::internal::no_duplicate_field_names>()); + static_assert(rfl::internal::no_duplicate_field_names< + rfl::Tuple>>()); + static_assert( + rfl::internal::no_duplicate_field_names< + rfl::Tuple, rfl::Field<"a", int>, + rfl::Field<"c", int>>>()); + static_assert( + !rfl::internal::no_duplicate_field_names< + rfl::Tuple, rfl::Field<"a", int>, + rfl::Field<"b", double>>>()); + SUCCEED(); +} } // namespace test_literal