diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index b5e89b68..d6e8d664 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -216,6 +216,35 @@ option in a token treats the next token as it would alone (`-qv false` sets - Grouping needs the struct: the public `rfl::cli::parse_argv` reads `-abc` as the one short option `abc`. +## Lists and repeated options + +A field that is read as a list (`std::vector`, `std::set`, `std::deque` and +the like, `std::array`, `rfl::Array`, tuples and pairs, inside any of the +wrappers above) takes comma-separated items. Its option can also be +repeated: every occurrence is split at the commas, and the items are added +in argv order. + +```cpp +struct Config { + rfl::Short<"r", std::vector> report; +}; + +// ./app --report=a,b --report=c -> report = {"a", "b", "c"} +// ./app -r a --report=b -r c -> report = {"a", "b", "c"} +``` + +- Long and short spellings of a field all add to it. +- Repeating is the same as joining with a comma, so the size of a + `std::array` and validators such as `rfl::Size` see all items. An empty + occurrence (`--report=`) adds none. +- Nested lists (`--database.replicas=a --database.replicas=b`) and map + entries whose values are lists (`--groups.x=a --groups.x=b`) work the + same way. + +Any other option can be given only once. That includes nested +fields and map entries: `Duplicate argument: --output`, +`Duplicate short argument: -o`, `Conflict: '-o' and '--output' both provided.` + ## Combining wrappers `Short` and `Positional` can be nested with `DefaultVal`, `std::optional`, @@ -330,8 +359,10 @@ Arguments: 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=`). +struct, is a flag whose value can be left out (`--verbose[=]`), a list +takes comma-separated items and can be repeated (`--tags=`, with +`Can be repeated.` in its row), 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 @@ -361,7 +392,7 @@ int main(int argc, char* argv[]) { | `bool` | `--flag` or `--flag=true` | No `=` implies `true` | | `enum` | `--key=value_name` | Via `rfl::string_to_enum` | | `std::optional` | omit for `nullopt` | | -| `std::vector` | `--key=a,b,c` | Comma-separated; empty elements skipped | +| `std::vector` | `--key=a,b,c` or `--key=a --key=b,c` | Comma-separated; empty elements skipped; [repeatable](#lists-and-repeated-options) | | Nested struct | `--parent.child=val` | Dot-separated path | | `rfl::Flatten` | fields inlined | No prefix needed | | `rfl::Rename<"x", T>` | `--x=val` | Bypasses kebab conversion | diff --git a/include/rfl/cli/Reader.hpp b/include/rfl/cli/Reader.hpp index 58c16d37..ccee2207 100644 --- a/include/rfl/cli/Reader.hpp +++ b/include/rfl/cli/Reader.hpp @@ -26,6 +26,17 @@ static constexpr char path_separator = '.'; /// Example: `--ports=8080,8081,8082` for an array of ports. static constexpr char array_delimiter = ','; +namespace internal { + +/// The occurrences after the first of the list options given more than +/// once, by path, in argv order. The argument map holds the first one: +/// `--ports 80 --ports 81,82` is held as "80" in the argument map and +/// {"81,82"} here. Each occurrence is split at array_delimiter. +using CliLaterOccurrencesType = + std::map>; + +} // namespace internal + /// Represents a CLI variable that can be a direct value or a path in the argument map. /// The `path` represents the hierarchical key (e.g., "database.host"). /// The `direct_value` is used when parsing array elements directly. @@ -33,6 +44,8 @@ struct CliVarType { const std::map* const args = nullptr; const std::string path; const std::optional direct_value; + /// The later occurrences of repeated list options, if any. + const internal::CliLaterOccurrencesType* const later_occurrences = nullptr; }; /// Represents a CLI object with a prefix path for accessing nested fields. @@ -40,6 +53,8 @@ struct CliVarType { struct CliObjectType { const std::map* const args = nullptr; const std::string prefix; + /// The later occurrences of repeated list options, if any. + const internal::CliLaterOccurrencesType* const later_occurrences = nullptr; }; /// Represents a CLI array containing multiple string values. @@ -167,7 +182,8 @@ struct Reader { const auto child_path = _obj.prefix.empty() ? _name : _obj.prefix + _name; - return InputVarType{_obj.args, child_path, std::nullopt}; + return InputVarType{_obj.args, child_path, std::nullopt, + _obj.later_occurrences}; } /// Checks if a CLI variable is empty (has no value). @@ -240,7 +256,8 @@ struct Reader { const auto child_path = _obj.prefix + child; _object_reader.read( std::string_view(child), - InputVarType{_obj.args, child_path, std::nullopt}); + InputVarType{_obj.args, child_path, std::nullopt, + _obj.later_occurrences}); } ++it; } @@ -261,6 +278,8 @@ struct Reader { } /// Converts a CLI variable to an array by splitting the value on commas. + /// The items of every occurrence of a repeated list option are added in + /// order (see internal::CliLaterOccurrencesType). /// @param _var The CLI variable containing a comma-delimited string /// @return A Result containing a CliArrayType with the split values rfl::Result to_array( @@ -269,7 +288,7 @@ struct Reader { if (!str) { return InputArrayType{{}}; } - return InputArrayType{split(*str, array_delimiter)}; + return InputArrayType{split_items(*str, _var)}; } /// Converts a CLI variable to an object for reading nested fields. @@ -287,7 +306,7 @@ struct Reader { const auto prefix = _var.path.empty() ? std::string("") : _var.path + path_separator; - return InputObjectType{_var.args, prefix}; + return InputObjectType{_var.args, prefix, _var.later_occurrences}; } /// Custom constructors are not supported for CLI parsing. @@ -318,6 +337,33 @@ struct Reader { return it->second; } + /// Splits a list into its items: those of _first, the occurrence that + /// get_value returns for _var, then those of its later occurrences. + static std::vector split_items(const std::string& _first, + const InputVarType& _var) { + std::vector items; + add_items(_first, &items); + if (_var.direct_value || !_var.later_occurrences) { + return items; + } + const auto it = _var.later_occurrences->find(_var.path); + if (it != _var.later_occurrences->end()) { + for (const auto& occurrence : it->second) { + add_items(occurrence, &items); + } + } + return items; + } + + /// Adds the items of one occurrence of a list, split at array_delimiter, + /// to _items. + static void add_items(const std::string& _occurrence, + std::vector* _items) { + for (auto& item : split(_occurrence, array_delimiter)) { + _items->emplace_back(std::move(item)); + } + } + static std::vector split( const std::string& _str, char _delim ) { diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index 91468e34..8e89f4f7 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -55,6 +55,11 @@ enum class OptionKind { /// How an option is given on the command line. struct Option { OptionKind kind = OptionKind::unknown; + + /// Whether the field is a list (see is_option_list_v). Every + /// occurrence of a list option adds to it, however the option is spelled, + /// so it may be repeated. Any other option may be given only once. + bool is_list = false; }; /// The options that a target struct accepts, built from its fields by @@ -99,6 +104,12 @@ struct Options { /// when it is given without '=' (rfl::cli::SeparateOptionValues). bool separate_values = false; + /// Builds the table with every long option through nested structs and + /// maps, if this one lists only the top-level fields (see make_options). + /// parse_argv looks up nested options in it, for instance to tell whether + /// a repeated nested option is a list. + Options (*make_all_paths)() = nullptr; + /// 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 @@ -349,6 +360,20 @@ struct type_list { using add = type_list; }; +/// Whether the reader reads T as a list, through Reader::to_array: vectors, +/// sets, deques and the like, std::array, rfl::Array, C arrays, tuples and +/// pairs. Maps are not lists, even those whose keys are not strings. The +/// value of a list option is split into items at the list delimiter, and +/// repeating the option adds the items of every occurrence, so +/// `--x=a --x=b` is `--x=a,b`. +template +constexpr bool is_option_list_v = + (parsing::is_vector_like_v && !parsing::is_map_like_v + && !parsing::is_bytestring_v && !parsing::is_vectorstring_v) + || parsing::is_array_v || parsing::is_rfl_array_v + || parsing::is_c_array_v || parsing::is_tuple_v + || parsing::is_rfl_tuple_v || parsing::is_pair_v; + /// The option for a field, or a key of a map or of rfl::ExtraFields, with /// values of type T. template @@ -362,7 +387,7 @@ Option option_for() { return Option{OptionKind::other}; } else { - return Option{OptionKind::value}; + return Option{OptionKind::value, is_option_list_v}; } } @@ -430,7 +455,8 @@ void add_option(const std::string& _path, Options* _options) { } } else { - _options->long_options[_path] = Option{OptionKind::value}; + _options->long_options[_path] = + Option{OptionKind::value, is_option_list_v}; } } @@ -529,6 +555,9 @@ Options make_options() { options.group_short_options = true; options.reject_unknown = rfl::internal::no_extra_fields_v; options.separate_values = separate_option_values_v; + if constexpr (!_all_paths) { + options.make_all_paths = &make_options; + } using U = unwrapped_option_t; if constexpr (_all_paths) { collect_value_options>(&options); diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index 59cc4949..26a1872d 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -61,6 +62,10 @@ namespace internal { /// 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. +/// Every occurrence of a list option (Option::is_list) adds to it, however +/// it is spelled. Its first occurrence is kept in `named` under its long +/// name, and the later ones in `later_occurrences`, in argv order. Any other +/// option given twice is an error. /// @param _args The command-line arguments to parse /// @param _options The options of the target struct (see make_options) /// @return A Result containing ParsedArgs with categorized arguments or an error @@ -74,8 +79,48 @@ inline rfl::Result parse_string_views( const bool negative_numbers_are_options = _options.negative_numbers_are_options; + // Without rfl::NoExtraFields, `_options` lists only the top-level fields + // (see make_options), so a nested option such as `--database.replicas` is + // looked up in the table of all paths, built the first time one is given. + std::optional all_paths; + const auto find_long = [&](const std::string& _key) { + if (!_options.make_all_paths + || _key.find(path_separator) == std::string::npos) { + return _options.find_long(_key); + } + if (!all_paths) { + all_paths = _options.make_all_paths(); + } + return all_paths->find_long(_key); + }; + + // Every occurrence of a list option adds to it. Any other option can be + // given only once. + const auto add_long = [&](std::string _key, std::string _val, + const Option& _option, + std::string_view _raw) -> rfl::Result { + const auto it = result.named.find(_key); + if (it == result.named.end()) { + result.named.emplace(std::move(_key), std::move(_val)); + } + else if (_option.is_list) { + result.later_occurrences[it->first].emplace_back(std::move(_val)); + } + else { + return error("Duplicate argument: " + std::string(_raw)); + } + return true; + }; + const auto add_short = [&](std::string _key, std::string _val, + const Option& _option, std::string_view _raw) -> rfl::Result { + if (_option.is_list) { + // Under its long name, so that `-r a --report b` keeps argv order. A + // short option is only a list if it is in `_options`. + return add_long(_options.short_options.find(_key)->second, + std::move(_val), _option, _raw); + } result.short_order.emplace_back(_key); if (!result.short_args.emplace(std::move(_key), std::move(_val)).second) { return error("Duplicate short argument: " + std::string(_raw)); @@ -144,7 +189,7 @@ inline rfl::Result parse_string_views( if (key.empty()) { return error("Empty key in argument: " + std::string(arg_raw)); } - const auto option = _options.find_long(key); + const auto option = find_long(key); if (option.kind == OptionKind::unknown && _options.reject_unknown) { return error("Unknown option '--" + key + "'."); } @@ -156,9 +201,8 @@ inline rfl::Result parse_string_views( if (!v) { return error(v.error().what()); } val = std::move(*v); } - if (!result.named.emplace(std::move(key), std::move(val)).second) { - return error("Duplicate argument: " + std::string(arg_raw)); - } + const auto r = add_long(std::move(key), std::move(val), option, arg_raw); + if (!r) { return error(r.error().what()); } continue; } @@ -218,7 +262,7 @@ inline rfl::Result parse_string_views( + std::string(arg_raw) + "'. Write '" + name + std::string(rest) + "' on its own."); } - const auto r = add_short(std::move(key), "", arg_raw); + const auto r = add_short(std::move(key), "", option, arg_raw); if (!r) { return error(r.error().what()); } continue; } @@ -235,7 +279,8 @@ inline rfl::Result parse_string_views( val = std::move(*v); } - const auto r = add_short(std::move(key), std::move(val), arg_raw); + const auto r = + add_short(std::move(key), std::move(val), option, arg_raw); if (!r) { return error(r.error().what()); } break; } diff --git a/include/rfl/cli/read.hpp b/include/rfl/cli/read.hpp index abcbc4ce..c5fcbcf8 100644 --- a/include/rfl/cli/read.hpp +++ b/include/rfl/cli/read.hpp @@ -23,7 +23,8 @@ 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(); - const auto var = CliVarType{&_args, "", std::nullopt}; + const auto var = CliVarType{&_args.values, "", std::nullopt, + &_args.later_occurrences}; return Parser::read(r, var); }); } diff --git a/include/rfl/cli/resolve_args.hpp b/include/rfl/cli/resolve_args.hpp index 1bd79d9e..53a206e2 100644 --- a/include/rfl/cli/resolve_args.hpp +++ b/include/rfl/cli/resolve_args.hpp @@ -15,15 +15,31 @@ namespace rfl::cli { /// Holds the parsed command-line arguments categorized by type. /// Used as an intermediate structure before resolving to a flat key-value map. struct ParsedArgs { + /// The long options, by name. A list option is held here under its long + /// name however it is spelled, also as a short option. If it is given + /// more than once, this holds its first occurrence, and + /// `later_occurrences` the others. std::map named; std::map short_args; std::vector positional; /// Insertion order of short arg keys (for stable reclaim ordering). std::vector short_order; + /// The occurrences after the first of each list option given more than + /// once, by long name, in argv order. + internal::CliLaterOccurrencesType later_occurrences; }; namespace internal { +/// The arguments resolved to the paths of their fields, which Reader reads. +struct ResolvedArgs { + /// The value of each field. For a list given more than once, its first + /// occurrence. + std::map values; + /// The occurrences after the first of each list given more than once. + CliLaterOccurrencesType later_occurrences; +}; + /// Applies what parse_argv could not know without the option table. /// Without it, every short option takes the next token, so `-v somefile` /// makes "somefile" the value of -v. If -v is a bool flag (by its type once @@ -82,9 +98,9 @@ inline rfl::Unexpected too_many_positionals(const size_t _expected, /// The caller checks the short names first (check_short_names). /// @param _parsed The arguments, parsed by parse_argv with the same options /// @param _options The options of the target struct (see make_options) -/// @return A Result containing a flat map of field names to values or an +/// @return A Result containing the values of the fields, by path, or an /// error -inline rfl::Result> resolve_args( +inline rfl::Result resolve_args( ParsedArgs _parsed, const Options& _options ) { auto& result = _parsed.named; @@ -120,7 +136,8 @@ inline rfl::Result> resolve_args( result.emplace(long_name, std::move(value)); } - return std::move(result); + return ResolvedArgs{std::move(result), + std::move(_parsed.later_occurrences)}; } } // namespace internal @@ -129,7 +146,8 @@ inline rfl::Result> resolve_args( /// metadata from the target struct T. Like the overload taking the options /// of T, but for arguments parsed by parse_argv without them: values that /// boolean short options took from the next token are returned to the -/// positional arguments. +/// positional arguments. A flat map cannot hold the occurrences of a +/// repeated list option, which parse_argv without the options rejects. /// @tparam T The target struct type /// @tparam ProcessorsType The processors applied to the struct /// @param _parsed The parsed command-line arguments @@ -138,13 +156,20 @@ template rfl::Result> resolve_args( ParsedArgs _parsed ) { + if (!_parsed.later_occurrences.empty()) { + return rfl::error("Duplicate argument: --" + + _parsed.later_occurrences.begin()->first); + } const auto options = internal::make_options(); const auto short_names = internal::check_short_names(options); if (!short_names) { return rfl::error(short_names.error().what()); } internal::apply_option_kinds(options, &_parsed); - return internal::resolve_args(std::move(_parsed), options); + return internal::resolve_args(std::move(_parsed), options) + .transform([](internal::ResolvedArgs _args) { + return std::move(_args.values); + }); } } // namespace rfl::cli diff --git a/include/rfl/cli/usage.hpp b/include/rfl/cli/usage.hpp index adadb6dd..4b8bee2d 100644 --- a/include/rfl/cli/usage.hpp +++ b/include/rfl/cli/usage.hpp @@ -55,7 +55,7 @@ struct UsageArg { /// 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. + /// Whether the field is a list, which can be repeated. bool is_list = false; bool required = true; /// Whether `required` was taken from the parser's compile-time traits, so @@ -94,8 +94,8 @@ void add_usage_field_meta(const bool _default_vals_are_optional, /// 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). +/// parser accepts. Positional, Short, flags 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...>) { @@ -403,13 +403,9 @@ class UsageCollector { } add_choices(values, std::move(_arg), _default); - } else if constexpr (std::is_same_v - || std::is_same_v - || std::is_same_v) { - _arg.is_list = true; - add_leaf(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); } }); @@ -469,6 +465,7 @@ class UsageCollector { // key ("labels.") is found through its open prefix. const auto option = options_->find_long(_arg.name); _arg.kind = option.kind; + _arg.is_list = option.is_list; if (_default) { _arg.default_value = usage_default_to_string(*_default); } @@ -543,6 +540,9 @@ inline std::string usage_help_text(const UsageArg& _arg) { 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"); } diff --git a/tests/cli/test_repeated_options.cpp b/tests/cli/test_repeated_options.cpp new file mode 100644 index 00000000..9fb42926 --- /dev/null +++ b/tests/cli/test_repeated_options.cpp @@ -0,0 +1,177 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_repeated_options { + +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()); +} + +using Strings = std::vector; + +struct Database { + std::optional host; + std::optional replicas; +}; + +struct Opts { + rfl::Short<"r", std::optional> report; + std::optional> ports; + std::optional> tags; + std::optional> queue; + std::optional> rgb; + std::optional> range; + rfl::Short<"o", std::optional> output; + std::optional level; + rfl::Short<"q", std::optional> quiet; + std::optional database; + std::optional> labels; + std::optional> groups; + rfl::Positional> input; +}; + +TEST(cli, test_repeated_long_option_appends) { + for (const auto& args : std::vector>{ + {"--report=a", "--report=b", "--report=c"}, + {"--report=a,b", "--report=c"}}) { + const auto result = read(args); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().report(), (Strings{"a", "b", "c"})); + } + + // With rfl::cli::SeparateOptionValues, also as `--report a`. + const auto separate = read( + {"--report", "a", "--report=b", "--report", "c"}); + ASSERT_TRUE(separate) << separate.error().what(); + EXPECT_EQ(separate.value().report(), (Strings{"a", "b", "c"})); +} + +TEST(cli, test_repeated_short_and_long_merge_in_argv_order) { + const auto result = + read({"-r", "a", "--report=b", "-r=c", "-rd", "--report=e"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().report(), (Strings{"a", "b", "c", "d", "e"})); +} + +TEST(cli, test_repeated_short_list_in_a_cluster) { + // -q is a flag, so -qra is -q -r a. + const auto result = read({"-qra", "-r", "b", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().quiet(), true); + EXPECT_EQ(result.value().report(), (Strings{"a", "b"})); + EXPECT_EQ(result.value().input(), "in.txt"); + + // The flag is still given only once. + EXPECT_FALSE(read({"-qra", "-qrb"})); +} + +TEST(cli, test_repeated_other_list_types) { + const auto result = read( + {"--ports=80", "--ports=81,82", "--tags=b", "--tags=a,b", + "--queue=x", "--queue=y", "--rgb=1", "--rgb=2,3", + "--range=5", "--range=five"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& o = result.value(); + EXPECT_EQ(o.ports, (std::vector{80, 81, 82})); + EXPECT_EQ(o.tags, (std::set{"a", "b"})); + EXPECT_EQ(o.queue, (std::deque{"x", "y"})); + EXPECT_EQ(o.rgb, (std::array{1, 2, 3})); + EXPECT_EQ(o.range, (std::pair{5, "five"})); +} + +TEST(cli, test_repeated_fixed_size_checked_on_all_items) { + // Repeating is the same as joining with ',': the size is checked once. + EXPECT_EQ(error_of(read({"--rgb=1", "--rgb=2"})), + error_of(read({"--rgb=1,2"}))); + EXPECT_NE(error_of(read({"--rgb=1,2"})), "(no error)"); +} + +TEST(cli, test_repeated_empty_occurrence_adds_nothing) { + const auto some = read({"--report=a", "--report=", "--report=b"}); + ASSERT_TRUE(some) << some.error().what(); + EXPECT_EQ(some.value().report(), (Strings{"a", "b"})); + + const auto none = read({"--report=", "--report="}); + ASSERT_TRUE(none) << none.error().what(); + EXPECT_EQ(none.value().report(), Strings{}); +} + +TEST(cli, test_repeated_nested_list) { + const auto result = read({"--database.replicas=a", + "--database.replicas=b,c", + "--database.host=db"}); + ASSERT_TRUE(result) << result.error().what(); + ASSERT_TRUE(result.value().database); + EXPECT_EQ(result.value().database->replicas, (Strings{"a", "b", "c"})); + EXPECT_EQ(result.value().database->host, "db"); +} + +TEST(cli, test_repeated_map_entry_list) { + const auto result = read( + {"--groups.x=a", "--groups.y=c", "--groups.x=b"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().groups, + (std::map{{"x", {"a", "b"}}, {"y", {"c"}}})); +} + +TEST(cli, test_repeated_scalar_errors) { + EXPECT_FALSE(read({"--output=a", "--output=b"})); + EXPECT_FALSE(read({"--level=1", "--level=2"})); + EXPECT_FALSE(read({"-o", "a", "-o", "b"})); + EXPECT_FALSE(read({"-o", "a", "--output=b"})); + EXPECT_FALSE(read({"--quiet", "--quiet"})); + EXPECT_FALSE(read({"x", "--input=y"})); +} + +TEST(cli, test_repeated_nested_scalar_and_map_key_error) { + EXPECT_FALSE(read({"--database.host=a", "--database.host=b"})); + EXPECT_FALSE(read({"--labels.env=a", "--labels.env=b"})); + + const auto two_keys = read({"--labels.env=a", "--labels.os=b"}); + ASSERT_TRUE(two_keys) << two_keys.error().what(); + EXPECT_EQ(two_keys.value().labels, + (std::map{{"env", "a"}, {"os", "b"}})); +} + +struct Wrapped { + rfl::Description<"Files to include", + rfl::DefaultVal>> + include; + rfl::Rename<"L", std::optional>> lib_dirs; + rfl::Validator, rfl::Size>> pair; +}; + +TEST(cli, test_repeated_through_wrappers) { + const auto result = read( + {"--include=a.h", "--include=b.h", "--L=/x", "--L=/y", + "--pair=1", "--pair=2"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().include().value(), (Strings{"a.h", "b.h"})); + EXPECT_EQ(result.value().lib_dirs(), (Strings{"/x", "/y"})); + EXPECT_EQ(result.value().pair.value(), (std::vector{1, 2})); + + // The validator sees every item. + EXPECT_NE(error_of(read({"--pair=1", "--pair=2,3"})), + "(no error)"); +} + +} // namespace test_repeated_options diff --git a/tests/cli/test_usage.cpp b/tests/cli/test_usage.cpp index 11c9ce35..f5807e4e 100644 --- a/tests/cli/test_usage.cpp +++ b/tests/cli/test_usage.cpp @@ -111,8 +111,8 @@ TEST(cli, test_usage_validators) { " --outside= Range: <= 0 or >= 10. Required.\n" " --one-or-two= Range: 1 or 2. Required.\n" " --nonzero= Range: != 0. Required.\n" - " --tags= Size: >= 1. Required.\n" - " --ids= Size: 1..3. 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"); @@ -143,7 +143,7 @@ TEST(cli, test_usage_default_val) { "Arguments:\n" " --port= Default: 8080.\n" " --host= Default: localhost.\n" - " --tags= Default: a,b.\n" + " --tags= Default: a,b. Can be repeated.\n" " --level= Default: info.\n" " --rate= Default: 0.25.\n" " --dry-run[=] Default: false.\n" diff --git a/tests/cli/test_usage_options.cpp b/tests/cli/test_usage_options.cpp index d990717a..77ef51ae 100644 --- a/tests/cli/test_usage_options.cpp +++ b/tests/cli/test_usage_options.cpp @@ -6,9 +6,9 @@ #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. +// rfl::cli::usage for the parser's option features: wrappers in any order, +// repeated list options and positional order. Each test also reads the +// arguments as the help spells them. namespace test_usage_options { template @@ -18,6 +18,8 @@ rfl::Result read(std::vector _args) { const_cast(_args.data())); } +using Strings = std::vector; + struct WrapperOrder { rfl::Description<"Where to write", rfl::Short<"o", std::string>> output; rfl::DefaultVal> input = "in.txt"; @@ -39,6 +41,31 @@ TEST(cli, test_usage_wrapper_order) { EXPECT_EQ(defaulted.value().input.value().value(), "in.txt"); } +struct Lists { + rfl::Short<"r", rfl::Description<"Reports to write", Strings>> report; + rfl::DefaultVal tags = Strings{"a", "b"}; + rfl::Positional command; +}; + +TEST(cli, test_usage_lists) { + EXPECT_EQ(rfl::cli::usage("app", true).value(), + "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"); + + const auto result = + read({"-r", "a", "run", "--report=b,c", "--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"); +} + /// The parser fills the rfl::Positional fields in declaration order, wherever /// rfl::Positional sits among their wrappers. struct PositionalOrder {