From 2dbb7e5ff5aa123836ce54da043f0820bd40a96d Mon Sep 17 00:00:00 2001 From: clockblocker Date: Tue, 10 Nov 2026 11:54:38 +0100 Subject: [PATCH 1/2] Add rfl::cli::BlankItemsAsMissing to keep blank list items rfl::cli skips blank items in comma-separated lists, so `--tags=a,,b` is read as [a, b] and `--format=,csv` as [csv]. A CLI that gives blank items a meaning cannot tell them apart from a shorter list. rfl::cli::read keeps each blank item as a missing value at its index, and the element type decides, as it does for a missing field: std::optional elements become std::nullopt, rfl::DefaultVal elements become T{}, smart pointers become null, and element types that need a value (strings, wide strings, numbers, bools, ...) fail with "Blank item at index 1 of '--tags'.", located at ["tags", 1] in rfl::Error::details(). Leading and trailing blanks count, an empty value is still an empty list, and every list type the reader supports behaves the same way, including under nested options. The Reader keeps blank pieces when splitting and passes each one on as a variable without a value. is_empty reports it as empty, while to_basic_type, to_array and to_object reject it. A Parser specialization for DefaultVal with the CLI reader returns the default for it, and one for std::wstring rejects it, as ParserWString would otherwise read the empty variable as "". Other formats ignore the setting. Without the setting, nothing changes. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 32 +++- include/rfl/cli.hpp | 1 + include/rfl/cli/BlankItemsAsMissing.hpp | 51 ++++++ include/rfl/cli/Parser.hpp | 50 ++++++ include/rfl/cli/Reader.hpp | 81 +++++++-- include/rfl/cli/read.hpp | 11 +- tests/cli/test_blank_list_items.cpp | 226 ++++++++++++++++++++++++ 7 files changed, 435 insertions(+), 17 deletions(-) create mode 100644 include/rfl/cli/BlankItemsAsMissing.hpp create mode 100644 tests/cli/test_blank_list_items.cpp diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index e82fa1a53..813d8633b 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -421,6 +421,33 @@ arguments unchanged. - Without `OptionsFirst`, options and positional arguments can be mixed. Other formats ignore the setting. +## Blank list items + +By default, blank items in a list are skipped: `--tags=a,,b` gives `[a, b]`. +Pass `rfl::cli::BlankItemsAsMissing` to keep each blank item as a missing +value at its index. The element type then decides, as it does for a missing +field: + +```cpp +const auto result = + rfl::cli::read(argc, argv); +``` + +| Element type | `--tags=a,,b` | +|---|---| +| `std::vector>` | `[a, nullopt, b]` | +| `std::vector>` | `[a, T{}, b]` | +| `std::vector` | Error: `Blank item at index 1 of '--tags'.` | + +`T` is any type that needs a value, such as `std::string`, `std::wstring`, +a number or a `bool`. Smart pointers (`std::shared_ptr`, +`std::unique_ptr`) are never required, so a blank one is null, as a +missing field of that type is. + +Leading and trailing blanks (`,b`, `a,`) are blank items, too. An empty +value (`--tags=`) is still an empty list. Other list types, such as +`std::set`, `std::deque` and `std::array`, behave the same way. + ## Combining wrappers `Short`, `Positional` and `ImplicitValue` can be nested with each other and @@ -468,7 +495,7 @@ leaving out `-o` gives `"out"`. | `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` or `--key a --key b,c` | Comma-separated; empty elements skipped; [repeatable](#lists-and-repeated-options) | +| `std::vector` | `--key=a,b,c` or `--key a --key b,c` | Comma-separated; blank items skipped unless [kept](#blank-list-items); [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 | @@ -502,8 +529,9 @@ Parsing proceeds in three stages: ## Files - `include/rfl/cli/read.hpp` — public API +- `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 +- `include/rfl/cli/Parser.hpp` — Parser type alias + blank `DefaultVal` and `std::wstring` items - `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/NoAbbreviations.hpp` — `NoAbbreviations` processor diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index 85a8e571f..72091bdf4 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -2,6 +2,7 @@ #define RFL_CLI_HPP_ #include "../rfl.hpp" +#include "cli/BlankItemsAsMissing.hpp" #include "cli/ListDelimiter.hpp" #include "cli/NoAbbreviations.hpp" #include "cli/OptionsFirst.hpp" diff --git a/include/rfl/cli/BlankItemsAsMissing.hpp b/include/rfl/cli/BlankItemsAsMissing.hpp new file mode 100644 index 000000000..a78f77479 --- /dev/null +++ b/include/rfl/cli/BlankItemsAsMissing.hpp @@ -0,0 +1,51 @@ +#ifndef RFL_CLI_BLANKITEMSASMISSING_HPP_ +#define RFL_CLI_BLANKITEMSASMISSING_HPP_ + +#include + +#include "../Processors.hpp" + +namespace rfl::cli { + +/// A setting that keeps blank items in comma-separated lists, reading each +/// one as a missing value at its index. The element type then decides, as it +/// does for a missing field: std::optional becomes std::nullopt, +/// rfl::DefaultVal becomes T{}, std::shared_ptr and std::unique_ptr +/// become null, and a required type, such as std::string, std::wstring or +/// int, is an error. Without this setting, blank items are skipped. +/// This is a marker type (doesn't modify data) and other formats ignore it. +/// Usage: rfl::cli::read(argc, argv) +struct BlankItemsAsMissing { + public: + /// Identity process function - returns the named tuple unchanged. + /// The blank items are handled by the reader, not here. + /// @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; + } +}; + +namespace internal { + +template +struct blank_items_as_missing : std::false_type {}; + +template <> +struct blank_items_as_missing : std::true_type {}; + +template +struct blank_items_as_missing> + : std::bool_constant<(blank_items_as_missing::value || ...)> {}; + +template +constexpr bool blank_items_as_missing_v = blank_items_as_missing< + std::remove_cvref_t>>::value; + +} // namespace internal + +} // namespace rfl::cli + +#endif diff --git a/include/rfl/cli/Parser.hpp b/include/rfl/cli/Parser.hpp index ae82964de..144003e92 100644 --- a/include/rfl/cli/Parser.hpp +++ b/include/rfl/cli/Parser.hpp @@ -1,10 +1,60 @@ #ifndef RFL_CLI_PARSER_HPP_ #define RFL_CLI_PARSER_HPP_ +#include +#include + +#include "../DefaultVal.hpp" +#include "../Result.hpp" #include "../generic/Writer.hpp" +#include "../parsing/AreReaderAndWriter.hpp" #include "../parsing/Parser.hpp" +#include "../parsing/ParserDefaultVal.hpp" +#include "../parsing/ParserWString.hpp" #include "Reader.hpp" +namespace rfl::parsing { + +/// With rfl::cli::BlankItemsAsMissing, a blank item in a comma-separated list +/// is a missing value. A DefaultVal element then takes its default value, +/// T{}, much like a missing DefaultVal field keeps its default. Everything +/// else is handled by ParserDefaultVal. +template + requires AreReaderAndWriter> +struct Parser, ProcessorsType> + : public ParserDefaultVal, ProcessorsType> { + static Result> read(const cli::Reader& _r, + const cli::CliVarType& _var) noexcept { + if constexpr (std::is_default_constructible_v< + typename DefaultVal::Type>) { + if (cli::internal::is_blank_item(_var)) { + return DefaultVal(); + } + } + return ParserDefaultVal, + ProcessorsType>::read(_r, _var); + } +}; + +/// With rfl::cli::BlankItemsAsMissing, a blank std::wstring item is an +/// error, as a blank std::string item is. ParserWString would read it as an +/// empty string, because the reader reports it as empty. Everything else is +/// handled by ParserWString. +template + requires AreReaderAndWriter +struct Parser + : public ParserWString { + static Result read(const cli::Reader& _r, + const cli::CliVarType& _var) noexcept { + if (cli::internal::is_blank_item(_var)) { + return error(_r.template to_basic_type(_var).error()); + } + return ParserWString::read(_r, _var); + } +}; + +} // namespace rfl::parsing + namespace rfl::cli { template diff --git a/include/rfl/cli/Reader.hpp b/include/rfl/cli/Reader.hpp index c15b53b59..68d1610ee 100644 --- a/include/rfl/cli/Reader.hpp +++ b/include/rfl/cli/Reader.hpp @@ -41,12 +41,17 @@ using CliLaterOccurrencesType = /// 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. +/// A blank array element kept by BlankItemsAsMissing has neither: it is a +/// missing value, see `blank_item_index`. 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; + /// Only set for a blank array element: its index. `path` is then the key + /// of the array. + const std::optional blank_item_index = std::nullopt; }; /// Represents a CLI object with a prefix path for accessing nested fields. @@ -62,6 +67,8 @@ struct CliObjectType { /// Typically created by splitting a comma-delimited argument value. struct CliArrayType { const std::vector values; + /// The key the values were read from, used to report blank items. + const std::string path = ""; }; // --- Constrained overloads for string-to-type parsing --- @@ -164,8 +171,12 @@ struct Reader { /// @param _list_delimiter The character at which list values are split /// into items, or std::nullopt to not split them, see ListDelimiter. - explicit Reader(const std::optional _list_delimiter) noexcept - : list_delimiter_(_list_delimiter) {} + /// @param _blank_items_as_missing Whether to keep blank items in lists + /// and read them as missing values, see BlankItemsAsMissing. + explicit Reader(const std::optional _list_delimiter, + const bool _blank_items_as_missing = false) noexcept + : list_delimiter_(_list_delimiter), + blank_items_as_missing_(_blank_items_as_missing) {} /// Gets a specific element from a CLI array by index. /// @param _idx The index of the element to retrieve @@ -177,7 +188,7 @@ struct Reader { return error( std::string("Index ") + std::to_string(_idx) + " out of bounds."); } - return InputVarType{nullptr, "", _arr.values[_idx]}; + return get_element(_idx, _arr); } /// Gets a specific field from a CLI object by name. @@ -196,6 +207,7 @@ struct Reader { /// Checks if a CLI variable is empty (has no value). /// A variable is empty if there's no direct value and no matching key in the argument map. + /// This includes blank array elements, which are missing values. /// @param _var The CLI variable to check /// @return true if the variable is empty, false otherwise bool is_empty(const InputVarType& _var) const noexcept { @@ -224,9 +236,8 @@ struct Reader { const ArrayReader& _array_reader, const InputArrayType& _arr ) const noexcept { - for (const auto& val : _arr.values) { - auto err = _array_reader.read( - InputVarType{nullptr, "", val}); + for (size_t i = 0; i < _arr.values.size(); ++i) { + auto err = _array_reader.read(get_element(i, _arr)); if (err) { return err; } @@ -278,6 +289,9 @@ struct Reader { /// @return A Result containing the converted value or an error template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { + if (_var.blank_item_index) { + return blank_item_error(_var); + } const auto str = get_value(_var); if (!str) { return error("No value for key '" + _var.path + "'."); @@ -292,11 +306,14 @@ struct Reader { /// @return A Result containing a CliArrayType with the split values rfl::Result to_array( const InputVarType& _var) const noexcept { + if (_var.blank_item_index) { + return blank_item_error(_var); + } const auto str = get_value(_var); if (!str) { return InputArrayType{{}}; } - return InputArrayType{split_items(*str, _var)}; + return InputArrayType{split_items(*str, _var), _var.path}; } /// Converts a CLI variable to an object for reading nested fields. @@ -305,6 +322,9 @@ struct Reader { /// @return A Result containing a CliObjectType or an error rfl::Result to_object( const InputVarType& _var) const noexcept { + if (_var.blank_item_index) { + return blank_item_error(_var); + } if (!_var.args) { return error("Cannot convert to object: no argument map available" + (_var.path.empty() @@ -329,6 +349,25 @@ struct Reader { } private: + /// Returns the element at _idx, which must be in bounds. A blank element + /// kept by BlankItemsAsMissing is a missing value, the others are direct + /// values. + InputVarType get_element( + const size_t _idx, const InputArrayType& _arr + ) const noexcept { + if (blank_items_as_missing_ && _arr.values[_idx].empty()) { + return InputVarType{.path = _arr.path, + .direct_value = std::nullopt, + .blank_item_index = _idx}; + } + return InputVarType{nullptr, "", _arr.values[_idx]}; + } + + static rfl::Unexpected blank_item_error(const InputVarType& _var) { + return error("Blank item at index " + std::to_string(*_var.blank_item_index) + + " of '--" + _var.path + "'."); + } + static std::optional get_value( const InputVarType& _var ) noexcept { @@ -345,8 +384,10 @@ struct Reader { return it->second; } + /// Splits _str at _delim. An empty _str has no pieces. Otherwise, empty + /// pieces are skipped, unless _keep_blank_items is set. static std::vector split( - const std::string& _str, char _delim + const std::string& _str, char _delim, const bool _keep_blank_items ) { std::vector result; if (_str.empty()) { @@ -356,12 +397,12 @@ struct Reader { while (true) { const auto pos = _str.find(_delim, start); if (pos == std::string::npos) { - if (start < _str.size()) { + if (start < _str.size() || _keep_blank_items) { result.emplace_back(_str.substr(start)); } break; } - if (pos > start) { + if (pos > start || _keep_blank_items) { result.emplace_back(_str.substr(start, pos - start)); } start = pos + 1; @@ -389,22 +430,38 @@ struct Reader { /// Adds the items of one occurrence of a list, split at the list /// delimiter, to _items. Without a delimiter, the occurrence is one item, - /// even if it is empty. + /// even if it is empty. With a delimiter, an empty occurrence has no + /// items, and blank items are skipped, unless blank_items_as_missing_ is + /// set. void add_items(const std::string& _occurrence, std::vector* _items) const { if (!list_delimiter_) { _items->push_back(_occurrence); return; } - for (auto& item : split(_occurrence, *list_delimiter_)) { + for (auto& item : + split(_occurrence, *list_delimiter_, blank_items_as_missing_)) { _items->emplace_back(std::move(item)); } } /// The character at which list values are split, see ListDelimiter. std::optional list_delimiter_ = array_delimiter; + + /// Whether blank items in lists are kept and read as missing values, see + /// BlankItemsAsMissing. + bool blank_items_as_missing_ = false; }; +namespace internal { + +/// Whether _var is a blank array element kept by BlankItemsAsMissing. +inline bool is_blank_item(const CliVarType& _var) noexcept { + return _var.blank_item_index.has_value(); +} + +} // namespace internal + } // namespace rfl::cli #endif diff --git a/include/rfl/cli/read.hpp b/include/rfl/cli/read.hpp index c31919dc7..b95040764 100644 --- a/include/rfl/cli/read.hpp +++ b/include/rfl/cli/read.hpp @@ -7,6 +7,7 @@ #include "../Processors.hpp" #include "../SnakeCaseToKebabCase.hpp" +#include "BlankItemsAsMissing.hpp" #include "ListDelimiter.hpp" #include "Parser.hpp" #include "Reader.hpp" @@ -32,7 +33,9 @@ rfl::Result parse_and_read(const ParseFn& _parse) { return resolve_args(std::move(_parsed), options); }) .and_then([](auto _args) -> rfl::Result { - const auto r = Reader(internal::list_delimiter_v); + 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); @@ -63,7 +66,8 @@ rfl::Result parse_and_read(const ParseFn& _parse) { /// @tparam T The struct type to parse into /// @tparam Ps Optional processors to apply during parsing, including the /// settings rfl::NoExtraFields, rfl::cli::NoAbbreviations, -/// rfl::cli::ListDelimiter and rfl::cli::OptionsFirst +/// rfl::cli::ListDelimiter, rfl::cli::OptionsFirst and +/// rfl::cli::BlankItemsAsMissing /// @param _args The command-line arguments to parse /// @return A Result containing the parsed struct or an error template read(R&& _args) { /// @tparam T The struct type to parse into /// @tparam Ps Optional processors to apply during parsing, including the /// settings rfl::NoExtraFields, rfl::cli::NoAbbreviations, -/// rfl::cli::ListDelimiter and rfl::cli::OptionsFirst +/// rfl::cli::ListDelimiter, rfl::cli::OptionsFirst and +/// rfl::cli::BlankItemsAsMissing /// @param argc Number of command-line arguments /// @param argv Array of command-line argument strings /// @return A Result containing the parsed struct or an error diff --git a/tests/cli/test_blank_list_items.cpp b/tests/cli/test_blank_list_items.cpp new file mode 100644 index 000000000..cd21be582 --- /dev/null +++ b/tests/cli/test_blank_list_items.cpp @@ -0,0 +1,226 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_blank_list_items { + +using Blanks = rfl::cli::BlankItemsAsMissing; +using Path = std::vector; + +struct Config { + std::vector> tags; +}; + +TEST(cli, test_blank_items_skipped_by_default) { + const char* args[] = {"program", "--tags=,a,,b,"}; + const auto result = rfl::cli::read(2, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().tags, + (std::vector>{"a", "b"})); +} + +TEST(cli, test_blank_items_optional) { + const char* args[] = {"program", "--tags=a,,b"}; + const auto result = + rfl::cli::read(2, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().tags, + (std::vector>{"a", std::nullopt, "b"})); +} + +TEST(cli, test_blank_items_leading_and_trailing) { + const char* args[] = {"program", "--tags=,a,"}; + const auto result = + rfl::cli::read(2, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().tags, + (std::vector>{std::nullopt, "a", + std::nullopt})); +} + +TEST(cli, test_blank_items_empty_value) { + const char* args[] = {"program", "--tags="}; + const auto result = + rfl::cli::read(2, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().tags.empty()); +} + +struct DefaultValConfig { + std::vector> names; + std::vector> counts; +}; + +TEST(cli, test_blank_items_default_val) { + const char* args[] = {"program", "--names=a,,b", "--counts=,2"}; + const auto result = + rfl::cli::read(3, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + const auto& names = result.value().names; + ASSERT_EQ(names.size(), 3u); + EXPECT_EQ(names[0].value(), "a"); + EXPECT_EQ(names[1].value(), ""); + EXPECT_EQ(names[2].value(), "b"); + const auto& counts = result.value().counts; + ASSERT_EQ(counts.size(), 2u); + EXPECT_EQ(counts[0].value(), 0); + EXPECT_EQ(counts[1].value(), 2); +} + +struct RequiredConfig { + std::vector tags; +}; + +TEST(cli, test_blank_items_required_error) { + const char* args[] = {"program", "--tags=a,,b"}; + const auto result = + rfl::cli::read(2, const_cast(args)); + ASSERT_FALSE(result); + EXPECT_EQ(result.error().what(), + "Failed to parse field 'tags': Blank item at index 1 of '--tags'."); + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 1u); + EXPECT_EQ(details[0].path, (Path{"tags", size_t{1}})); + EXPECT_EQ(details[0].message, "Blank item at index 1 of '--tags'."); +} + +struct BoolConfig { + std::vector flags; +}; + +TEST(cli, test_blank_items_required_bool_error) { + // A blank bool is not read as `true`, unlike `--flag` or `--flag=`. + const char* args[] = {"program", "--flags=true,"}; + const auto result = + rfl::cli::read(2, const_cast(args)); + ASSERT_FALSE(result); + EXPECT_EQ( + result.error().what(), + "Failed to parse field 'flags': Blank item at index 1 of '--flags'."); +} + +struct Inner { + std::vector> tags; + std::vector names; +}; + +struct Outer { + Inner a; +}; + +TEST(cli, test_blank_items_nested) { + const char* args[] = {"program", "--a.tags=x,,y", "--a.names=n"}; + const auto result = + rfl::cli::read(3, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().a.tags, + (std::vector>{"x", std::nullopt, "y"})); + EXPECT_EQ(result.value().a.names, (std::vector{"n"})); +} + +TEST(cli, test_blank_items_nested_error) { + const char* args[] = {"program", "--a.tags=x", "--a.names=,n"}; + const auto result = + rfl::cli::read(3, const_cast(args)); + ASSERT_FALSE(result); + EXPECT_EQ(result.error().what(), + "Failed to parse field 'a': Failed to parse field 'names': Blank " + "item at index 0 of '--a.names'."); + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 1u); + EXPECT_EQ(details[0].path, (Path{"a", "names", size_t{0}})); +} + +struct Containers { + std::array, 3> numbers; + std::set names; +}; + +TEST(cli, test_blank_items_other_containers) { + const char* ok_args[] = {"program", "--numbers=1,,3", "--names=b,a"}; + const auto ok = + rfl::cli::read(3, const_cast(ok_args)); + ASSERT_TRUE(ok) << ok.error().what(); + EXPECT_EQ(ok.value().numbers, + (std::array, 3>{1, std::nullopt, 3})); + EXPECT_EQ(ok.value().names, (std::set{"a", "b"})); + + const char* err_args[] = {"program", "--numbers=1,2,3", "--names=b,,a"}; + const auto err = + rfl::cli::read(3, const_cast(err_args)); + ASSERT_FALSE(err); + EXPECT_EQ( + err.error().what(), + "Failed to parse field 'names': Blank item at index 1 of '--names'."); +} + +struct WideConfig { + std::vector names; + std::vector> tags; +}; + +TEST(cli, test_blank_items_wstring) { + // A blank std::wstring is an error, as a blank std::string is, not "". + const char* ok_args[] = {"program", "--names=a,b", "--tags=x,,y"}; + const auto ok = + rfl::cli::read(3, const_cast(ok_args)); + ASSERT_TRUE(ok) << ok.error().what(); + EXPECT_EQ(ok.value().names, (std::vector{L"a", L"b"})); + EXPECT_EQ(ok.value().tags, (std::vector>{ + L"x", std::nullopt, L"y"})); + + const char* err_args[] = {"program", "--names=a,,b", "--tags=x"}; + const auto err = + rfl::cli::read(3, const_cast(err_args)); + ASSERT_FALSE(err); + EXPECT_EQ( + err.error().what(), + "Failed to parse field 'names': Blank item at index 1 of '--names'."); + const auto details = err.error().details(); + ASSERT_EQ(details.size(), 1u); + EXPECT_EQ(details[0].path, (Path{"names", size_t{1}})); +} + +struct PointerConfig { + std::vector> shared; + std::vector> unique; +}; + +TEST(cli, test_blank_items_smart_pointers) { + // A smart pointer is never required, so a blank one is null, as a + // missing field of that type is. + const char* args[] = {"program", "--shared=a,", "--unique=,2"}; + const auto result = + rfl::cli::read(3, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + const auto& shared = result.value().shared; + ASSERT_EQ(shared.size(), 2u); + ASSERT_TRUE(shared[0]); + EXPECT_EQ(*shared[0], "a"); + EXPECT_FALSE(shared[1]); + const auto& unique = result.value().unique; + ASSERT_EQ(unique.size(), 2u); + EXPECT_FALSE(unique[0]); + ASSERT_TRUE(unique[1]); + EXPECT_EQ(*unique[1], 2); +} + +TEST(cli, test_blank_items_setting_ignored_by_json) { + const auto config = Config{.tags = {"a", std::nullopt}}; + EXPECT_EQ(rfl::json::write(config), rfl::json::write(config)); + EXPECT_EQ((rfl::json::to_schema()), + rfl::json::to_schema()); + const auto result = + rfl::json::read(rfl::json::write(config)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().tags, config.tags); +} + +} // namespace test_blank_list_items From fb5122ba991b9dabfe76c76bda102c87ea4a87a7 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 13 Nov 2026 09:32:01 +0100 Subject: [PATCH 2/2] Test rfl::cli::BlankItemsAsMissing with repeated and positional lists BlankItemsAsMissing now sits on top of repeated list options, list positionals and rfl::cli::ListDelimiter. The reader splits each occurrence at the list delimiter and keeps its blank items, so: - a repeated option keeps the blank items of every occurrence, at their index in the combined list: `--tags a,b --tags c,,d` has a blank item at index 3. An empty occurrence still adds no items, as an empty value is an empty list. - ListDelimiter<";"> keeps the blank items between two ';'. - with ListDelimiter<"">, every occurrence is one item, so an empty one is a blank item, and `--tags=` alone is one blank item. With OptionsFirst, an empty argument in the rest of the command line is a blank item too, so a pass-through list of std::string fails on it. - a list positional splits each argument as an occurrence, and an error names the field by its long option: "Blank item at index 2 of '--files'." Without the setting, nothing changes. Add tests for these cases and describe them in the docs. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 21 +++ include/rfl/cli/BlankItemsAsMissing.hpp | 3 + tests/cli/test_blank_list_items.cpp | 176 ++++++++++++++++++++++++ 3 files changed, 200 insertions(+) diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 813d8633b..6a79c1021 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -448,6 +448,27 @@ Leading and trailing blanks (`,b`, `a,`) are blank items, too. An empty value (`--tags=`) is still an empty list. Other list types, such as `std::set`, `std::deque` and `std::array`, behave the same way. +The setting works with the other list features: + +- [Repeated options](#lists-and-repeated-options) keep the blank items of + every occurrence, and the index is the one in the combined list: + `--tags a,b --tags c,,d` has a blank item at index 3. An empty occurrence + (`--tags=`) still adds no items. +- [`rfl::cli::ListDelimiter<";">`](#list-delimiter) keeps the blank items + between two `;`, so `--tags='a;;b,,c'` gives `[a, nullopt, "b,,c"]`. +- With `rfl::cli::ListDelimiter<"">`, every occurrence is one item, so an + empty one is a blank item: `--tags a --tags ''` gives `[a, nullopt]`, and + `--tags=` alone gives `[nullopt]`. This includes the rest of the command + line with [`rfl::cli::OptionsFirst`](#options-first): the pass-through + `Recipe` above, whose `args` are `std::string`s, fails on an empty + argument (`./recipe build ''` gives `Blank item at index 0 of '--args'.`). + Use `std::optional` items to keep it as `nullopt`, or leave + the setting out to keep it as `""`. +- A [list as the last positional field](#a-list-as-the-last-positional-argument) + splits each argument as an occurrence: `./app run a,,b c` gives + `[a, nullopt, b, c]`. An error names the field by its long option, as in + `Blank item at index 1 of '--files'.` + ## Combining wrappers `Short`, `Positional` and `ImplicitValue` can be nested with each other and diff --git a/include/rfl/cli/BlankItemsAsMissing.hpp b/include/rfl/cli/BlankItemsAsMissing.hpp index a78f77479..66c3f93d1 100644 --- a/include/rfl/cli/BlankItemsAsMissing.hpp +++ b/include/rfl/cli/BlankItemsAsMissing.hpp @@ -13,6 +13,9 @@ namespace rfl::cli { /// rfl::DefaultVal becomes T{}, std::shared_ptr and std::unique_ptr /// become null, and a required type, such as std::string, std::wstring or /// int, is an error. Without this setting, blank items are skipped. +/// The index counts the items of every occurrence of a repeated list option, +/// or of a list positional argument. With ListDelimiter<"">, an empty +/// occurrence is a blank item. /// This is a marker type (doesn't modify data) and other formats ignore it. /// Usage: rfl::cli::read(argc, argv) struct BlankItemsAsMissing { diff --git a/tests/cli/test_blank_list_items.cpp b/tests/cli/test_blank_list_items.cpp index cd21be582..3576cc9c9 100644 --- a/tests/cli/test_blank_list_items.cpp +++ b/tests/cli/test_blank_list_items.cpp @@ -223,4 +223,180 @@ TEST(cli, test_blank_items_setting_ignored_by_json) { EXPECT_EQ(result.value().tags, config.tags); } +// --- With repeated options, ListDelimiter and list positionals --- + +template +rfl::Result read(std::vector _args) { + _args.insert(_args.begin(), "program"); + return rfl::cli::read(static_cast(_args.size()), + const_cast(_args.data())); +} + +using OptStrings = std::vector>; +using Semicolon = rfl::cli::ListDelimiter<";">; +using NoSplit = rfl::cli::ListDelimiter<"">; + +struct RepeatedConfig { + rfl::Short<"t", OptStrings> tags; +}; + +TEST(cli, test_blank_items_repeated_option) { + // The blank items of every occurrence are kept, at their index in the + // combined list. + const auto result = + read({"--tags", "a,", "-t", ",b", "--tags=c"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().tags(), + (OptStrings{"a", std::nullopt, std::nullopt, "b", "c"})); +} + +TEST(cli, test_blank_items_repeated_option_skipped_by_default) { + const auto result = + read({"--tags", "a,", "-t", ",b", "--tags=c"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().tags(), (OptStrings{"a", "b", "c"})); +} + +TEST(cli, test_blank_items_repeated_empty_occurrence) { + // An empty occurrence adds no items, as an empty value is an empty list. + const auto result = + read({"--tags=a", "--tags=", "-t", "", "-t=b"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().tags(), (OptStrings{"a", "b"})); +} + +TEST(cli, test_blank_items_repeated_option_error_index) { + const auto result = + read({"--tags", "a,b", "--tags", "c,,d"}); + ASSERT_FALSE(result); + EXPECT_EQ(result.error().what(), + "Failed to parse field 'tags': Blank item at index 3 of '--tags'."); + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 1u); + EXPECT_EQ(details[0].path, (Path{"tags", size_t{3}})); +} + +TEST(cli, test_blank_items_custom_delimiter) { + // Blank items are the ones between two delimiters; commas are not split. + const auto result = + read({"--tags=a;;b,,c", "-t", ";"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().tags(), + (OptStrings{"a", std::nullopt, "b,,c", std::nullopt, + std::nullopt})); + + const auto skipped = read({"--tags=a;;b,,c"}); + ASSERT_TRUE(skipped) << skipped.error().what(); + EXPECT_EQ(skipped.value().tags(), (OptStrings{"a", "b,,c"})); + + const auto err = read({"--tags=a,;;b"}); + ASSERT_FALSE(err); + EXPECT_EQ(err.error().what(), + "Failed to parse field 'tags': Blank item at index 1 of '--tags'."); +} + +TEST(cli, test_blank_items_no_delimiter) { + // Without a delimiter, every occurrence is one item, so an empty one is a + // blank item. On its own, `--tags=` is one blank item, not an empty list. + const auto result = + read({"--tags", "a,,b", "-t", ""}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().tags(), (OptStrings{"a,,b", std::nullopt})); + + const auto single = read({"--tags="}); + ASSERT_TRUE(single) << single.error().what(); + EXPECT_EQ(single.value().tags(), (OptStrings{std::nullopt})); + + const auto kept = read({"--tags", "a,,b", "-t", ""}); + ASSERT_TRUE(kept) << kept.error().what(); + EXPECT_EQ(kept.value().tags(), (OptStrings{"a,,b", ""})); + + const auto err = + read({"--tags", "a", "--tags", ""}); + ASSERT_FALSE(err); + EXPECT_EQ(err.error().what(), + "Failed to parse field 'tags': Blank item at index 1 of '--tags'."); +} + +struct PositionalConfig { + rfl::Positional command; + rfl::Positional files; +}; + +TEST(cli, test_blank_items_list_positional) { + // Each remaining argument is split as an occurrence of the list. + const auto result = + read({"run", "a,,b", "c", ",d", "", "e,"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().command(), "run"); + EXPECT_EQ(result.value().files(), + (OptStrings{"a", std::nullopt, "b", "c", std::nullopt, "d", "e", + std::nullopt})); + + const auto skipped = + read({"run", "a,,b", "c", ",d", "", "e,"}); + ASSERT_TRUE(skipped) << skipped.error().what(); + EXPECT_EQ(skipped.value().files(), (OptStrings{"a", "b", "c", "d", "e"})); +} + +struct RequiredPositionalConfig { + rfl::Positional command; + rfl::Positional> files; +}; + +TEST(cli, test_blank_items_list_positional_error) { + const auto result = + read({"run", "a", "b,,c"}); + ASSERT_FALSE(result); + EXPECT_EQ( + result.error().what(), + "Failed to parse field 'files': Blank item at index 2 of '--files'."); + const auto details = result.error().details(); + ASSERT_EQ(details.size(), 1u); + EXPECT_EQ(details[0].path, (Path{"files", size_t{2}})); +} + +struct Recipe { + rfl::Positional name; + rfl::Positional args; +}; + +TEST(cli, test_blank_items_options_first_no_delimiter) { + // The rest of the command line, unchanged, except that an empty argument + // is a blank item. + const auto result = + read( + {"build", "--jobs", "", "--", "a,,b"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().name(), "build"); + EXPECT_EQ(result.value().args(), + (OptStrings{"--jobs", std::nullopt, "--", "a,,b"})); + + const auto kept = read( + {"build", "--jobs", "", "--", "a,,b"}); + ASSERT_TRUE(kept) << kept.error().what(); + EXPECT_EQ(kept.value().args(), (OptStrings{"--jobs", "", "--", "a,,b"})); +} + +struct PassThrough { + rfl::Positional name; + rfl::Positional>> args; +}; + +TEST(cli, test_blank_items_pass_through_empty_argument) { + // With BlankItemsAsMissing, a list of std::string cannot take an empty + // argument: it is a blank item. + const auto result = read({"build", "--jobs", "", "x"}); + ASSERT_FALSE(result); + EXPECT_EQ(result.error().what(), + "Failed to parse field 'args': Blank item at index 1 of '--args'."); + + const auto kept = read( + {"build", "--jobs", "", "x"}); + ASSERT_TRUE(kept) << kept.error().what(); + EXPECT_EQ(kept.value().args.value()(), + (std::vector{"--jobs", "", "x"})); +} + } // namespace test_blank_list_items