Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions docs/content/supported_formats/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,38 @@ rfl::cli::read<Config, rfl::cli::ListDelimiter<"">>(argc, argv);
exactly one item, even if it is empty.
- Other formats ignore it.

### Empty list items

By default, empty items in a split list are skipped: `--tags=a,,b` gives
`[a, b]`. Pass `rfl::cli::KeepEmptyItems` to keep each empty 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<Config, rfl::cli::KeepEmptyItems>(argc, argv);
```

| Element type | `--tags=a,,b` |
|---|---|
| `std::vector<std::optional<T>>` | `[a, nullopt, b]` |
| `std::vector<rfl::DefaultVal<T>>` | `[a, T{}, b]` |
| `std::vector<T>` | Error: `Failed to parse field 'tags': Empty item at index 1.` |

`T` is any type that needs a value, such as `std::string`, `std::wstring`,
a number or a `bool`. Smart pointers (`std::shared_ptr<T>`,
`std::unique_ptr<T>`) are never required, so an empty one is null, as a
missing field of that type is.

Leading and trailing empty items (`,b`, `a,`) count, 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. A
[repeated option](#lists-and-repeated-options) keeps the empty items of
every occurrence, at their index in the combined list: `--tags=a,b
--tags=c,,d` has an empty item at index 3. With `rfl::cli::ListDelimiter<"">`,
lists are not split, so the setting would change nothing, and combining the
two is a compile-time error.

### A list as the last positional argument

If the last positional field (in declaration order) is a list, it takes all
Expand Down Expand Up @@ -524,7 +556,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<T>` | omit for `nullopt` | |
| `std::vector<T>` | `--key=a,b,c` or `--key=a --key=b,c` | Comma-separated; empty elements skipped; [repeatable](#lists-and-repeated-options) |
| `std::vector<T>` | `--key=a,b,c` or `--key=a --key=b,c` | Comma-separated; empty items skipped unless [kept](#empty-list-items); [repeatable](#lists-and-repeated-options) |
| Nested struct | `--parent.child=val` | Dot-separated path |
| `rfl::Flatten<T>` | fields inlined | No prefix needed |
| `rfl::Rename<"x", T>` | `--x=val` | Bypasses kebab conversion |
Expand Down Expand Up @@ -555,7 +587,8 @@ Parsing proceeds in three stages:

- `include/rfl/cli/read.hpp` — public API
- `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 + empty `DefaultVal` and `std::wstring` items
- `include/rfl/cli/KeepEmptyItems.hpp` — `KeepEmptyItems` processor
- `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/AllowAbbreviations.hpp` — `AllowAbbreviations` processor
Expand Down
1 change: 1 addition & 0 deletions include/rfl/cli.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

#include "../rfl.hpp"
#include "cli/AllowAbbreviations.hpp"
#include "cli/KeepEmptyItems.hpp"
#include "cli/ListDelimiter.hpp"
#include "cli/Parser.hpp"
#include "cli/Reader.hpp"
Expand Down
57 changes: 57 additions & 0 deletions include/rfl/cli/KeepEmptyItems.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#ifndef RFL_CLI_KEEPEMPTYITEMS_HPP_
#define RFL_CLI_KEEPEMPTYITEMS_HPP_

#include <type_traits>

#include "../Processors.hpp"

namespace rfl::cli {

/// A setting that keeps the empty items of split lists (`--tags=a,,b`),
/// reading each one as a missing value at its index. The element type then
/// decides, as it does for a missing field: std::optional<T> becomes
/// std::nullopt, rfl::DefaultVal<T> becomes T{}, std::shared_ptr<T> and
/// std::unique_ptr<T> become null, and a required type, such as std::string,
/// std::wstring or int, is an error. Without this setting, empty items are
/// skipped.
/// The index counts the items of every occurrence of a repeated list option,
/// or of a list positional argument. With ListDelimiter<"">, lists are not
/// split: every occurrence is one item as it is, even if it is empty, so
/// combining the two settings is a compile-time error.
/// This is a marker type (doesn't modify data) and other formats ignore it.
/// Usage: rfl::cli::read<MyStruct, rfl::cli::KeepEmptyItems>(argc, argv)
struct KeepEmptyItems {
public:
/// Identity process function - returns the named tuple unchanged.
/// The empty 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 <class StructType>
static auto process(auto&& _named_tuple) {
return _named_tuple;
}
};

namespace internal {

template <class T>
struct keep_empty_items : std::false_type {};

template <>
struct keep_empty_items<KeepEmptyItems> : std::true_type {};

template <class... Ps>
struct keep_empty_items<Processors<Ps...>>
: std::bool_constant<(keep_empty_items<Ps>::value || ...)> {};

/// Whether the processors contain rfl::cli::KeepEmptyItems.
template <class T>
constexpr bool keep_empty_items_v = keep_empty_items<
std::remove_cvref_t<std::remove_pointer_t<T>>>::value;

} // namespace internal

} // namespace rfl::cli

#endif
50 changes: 50 additions & 0 deletions include/rfl/cli/Parser.hpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,60 @@
#ifndef RFL_CLI_PARSER_HPP_
#define RFL_CLI_PARSER_HPP_

#include <string>
#include <type_traits>

#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::KeepEmptyItems, an empty item in a split 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 <class W, class T, class ProcessorsType>
requires AreReaderAndWriter<cli::Reader, W, DefaultVal<T>>
struct Parser<cli::Reader, W, DefaultVal<T>, ProcessorsType>
: public ParserDefaultVal<cli::Reader, W, DefaultVal<T>, ProcessorsType> {
static Result<DefaultVal<T>> read(const cli::Reader& _r,
const cli::CliVarType& _var) noexcept {
if constexpr (std::is_default_constructible_v<
typename DefaultVal<T>::Type>) {
if (cli::internal::is_empty_item(_var)) {
return DefaultVal<T>();
}
}
return ParserDefaultVal<cli::Reader, W, DefaultVal<T>,
ProcessorsType>::read(_r, _var);
}
};

/// With rfl::cli::KeepEmptyItems, an empty std::wstring item is an
/// error, as an empty 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 <class W, class ProcessorsType>
requires AreReaderAndWriter<cli::Reader, W, std::wstring>
struct Parser<cli::Reader, W, std::wstring, ProcessorsType>
: public ParserWString<cli::Reader, W, ProcessorsType> {
static Result<std::wstring> read(const cli::Reader& _r,
const cli::CliVarType& _var) noexcept {
if (cli::internal::is_empty_item(_var)) {
return error(_r.template to_basic_type<std::string>(_var).error());
}
return ParserWString<cli::Reader, W, ProcessorsType>::read(_r, _var);
}
};

} // namespace rfl::parsing

namespace rfl::cli {

template <class T, class ProcessorsType>
Expand Down
81 changes: 69 additions & 12 deletions include/rfl/cli/Reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
/// An empty array element kept by KeepEmptyItems has neither: it is a
/// missing value, see `empty_item_index`.
struct CliVarType {
const std::map<std::string, std::string>* const args = nullptr;
const std::string path;
const std::optional<std::string> direct_value;
/// The later occurrences of repeated list options, if any.
const internal::CliLaterOccurrencesType* const later_occurrences = nullptr;
/// Only set for an empty array element: its index. `path` is then the key
/// of the array.
const std::optional<size_t> empty_item_index = std::nullopt;
};

/// Represents a CLI object with a prefix path for accessing nested fields.
Expand All @@ -62,6 +67,8 @@ struct CliObjectType {
/// Typically created by splitting a comma-delimited argument value.
struct CliArrayType {
const std::vector<std::string> values;
/// The key the values were read from, used to report empty items.
const std::string path = "";
};

// --- Constrained overloads for string-to-type parsing ---
Expand Down Expand Up @@ -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<char> _list_delimiter) noexcept
: list_delimiter_(_list_delimiter) {}
/// @param _keep_empty_items Whether to keep empty items in split lists
/// and read them as missing values, see KeepEmptyItems.
explicit Reader(const std::optional<char> _list_delimiter,
const bool _keep_empty_items = false) noexcept
: list_delimiter_(_list_delimiter),
keep_empty_items_(_keep_empty_items) {}

/// Gets a specific element from a CLI array by index.
/// @param _idx The index of the element to retrieve
Expand All @@ -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.
Expand All @@ -196,6 +207,8 @@ 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 empty array elements kept by KeepEmptyItems, 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 {
Expand Down Expand Up @@ -224,9 +237,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;
}
Expand Down Expand Up @@ -278,6 +290,9 @@ struct Reader {
/// @return A Result containing the converted value or an error
template <class T>
rfl::Result<T> to_basic_type(const InputVarType& _var) const noexcept {
if (_var.empty_item_index) {
return empty_item_error(_var);
}
const auto str = get_value(_var);
if (!str) {
return error("No value for key '" + _var.path + "'.");
Expand All @@ -292,11 +307,14 @@ struct Reader {
/// @return A Result containing a CliArrayType with the split values
rfl::Result<InputArrayType> to_array(
const InputVarType& _var) const noexcept {
if (_var.empty_item_index) {
return empty_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.
Expand All @@ -305,6 +323,9 @@ struct Reader {
/// @return A Result containing a CliObjectType or an error
rfl::Result<InputObjectType> to_object(
const InputVarType& _var) const noexcept {
if (_var.empty_item_index) {
return empty_item_error(_var);
}
if (!_var.args) {
return error("Cannot convert to object: no argument map available"
+ (_var.path.empty()
Expand All @@ -329,6 +350,26 @@ struct Reader {
}

private:
/// Returns the element at _idx, which must be in bounds. An empty element
/// of a split list kept by KeepEmptyItems is a missing value, the others
/// are direct values. Without a list delimiter, nothing was split, so an
/// empty element is the empty string.
InputVarType get_element(
const size_t _idx, const InputArrayType& _arr
) const noexcept {
if (keep_empty_items_ && list_delimiter_ && _arr.values[_idx].empty()) {
return InputVarType{.path = _arr.path,
.direct_value = std::nullopt,
.empty_item_index = _idx};
}
return InputVarType{nullptr, "", _arr.values[_idx]};
}

static rfl::Unexpected<Error> empty_item_error(const InputVarType& _var) {
return error("Empty item at index "
+ std::to_string(*_var.empty_item_index) + ".");
}

static std::optional<std::string> get_value(
const InputVarType& _var
) noexcept {
Expand All @@ -345,8 +386,10 @@ struct Reader {
return it->second;
}

/// Splits _str at _delim. An empty _str has no pieces. Otherwise, empty
/// pieces are skipped, unless _keep_empty_items is set.
static std::vector<std::string> split(
const std::string& _str, char _delim
const std::string& _str, char _delim, const bool _keep_empty_items
) {
std::vector<std::string> result;
if (_str.empty()) {
Expand All @@ -356,12 +399,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_empty_items) {
result.emplace_back(_str.substr(start));
}
break;
}
if (pos > start) {
if (pos > start || _keep_empty_items) {
result.emplace_back(_str.substr(start, pos - start));
}
start = pos + 1;
Expand Down Expand Up @@ -389,22 +432,36 @@ 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 empty items are skipped, unless keep_empty_items_ is set.
void add_items(const std::string& _occurrence,
std::vector<std::string>* _items) const {
if (!list_delimiter_) {
_items->push_back(_occurrence);
return;
}
for (auto& item : split(_occurrence, *list_delimiter_)) {
for (auto& item : split(_occurrence, *list_delimiter_, keep_empty_items_)) {
_items->emplace_back(std::move(item));
}
}

/// The character at which list values are split, see ListDelimiter.
std::optional<char> list_delimiter_ = array_delimiter;

/// Whether empty items in split lists are kept and read as missing values,
/// see KeepEmptyItems.
bool keep_empty_items_ = false;
};

namespace internal {

/// Whether _var is an empty array element kept by KeepEmptyItems.
inline bool is_empty_item(const CliVarType& _var) noexcept {
return _var.empty_item_index.has_value();
}

} // namespace internal

} // namespace rfl::cli

#endif
Loading