Skip to content
Closed
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
53 changes: 51 additions & 2 deletions docs/content/supported_formats/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,54 @@ 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<Config, rfl::cli::BlankItemsAsMissing>(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: `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<T>`,
`std::unique_ptr<T>`) 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.

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<std::string>` 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
Expand Down Expand Up @@ -468,7 +516,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<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; blank items skipped unless [kept](#blank-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 @@ -502,8 +550,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
Expand Down
1 change: 1 addition & 0 deletions include/rfl/cli.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
54 changes: 54 additions & 0 deletions include/rfl/cli/BlankItemsAsMissing.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#ifndef RFL_CLI_BLANKITEMSASMISSING_HPP_
#define RFL_CLI_BLANKITEMSASMISSING_HPP_

#include <type_traits>

#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<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, 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<MyStruct, rfl::cli::BlankItemsAsMissing>(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 <class StructType>
static auto process(auto&& _named_tuple) {
return _named_tuple;
}
};

namespace internal {

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

template <>
struct blank_items_as_missing<BlankItemsAsMissing> : std::true_type {};

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

template <class T>
constexpr bool blank_items_as_missing_v = blank_items_as_missing<
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::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 <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_blank_item(_var)) {
return DefaultVal<T>();
}
}
return ParserDefaultVal<cli::Reader, W, DefaultVal<T>,
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 <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_blank_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.
/// A blank array element kept by BlankItemsAsMissing has neither: it is a
/// missing value, see `blank_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 a blank array element: its index. `path` is then the key
/// of the array.
const std::optional<size_t> blank_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 blank 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 _blank_items_as_missing Whether to keep blank items in lists
/// and read them as missing values, see BlankItemsAsMissing.
explicit Reader(const std::optional<char> _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
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,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 {
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -278,6 +289,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.blank_item_index) {
return blank_item_error(_var);
}
const auto str = get_value(_var);
if (!str) {
return error("No value for key '" + _var.path + "'.");
Expand All @@ -292,11 +306,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.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.
Expand All @@ -305,6 +322,9 @@ struct Reader {
/// @return A Result containing a CliObjectType or an error
rfl::Result<InputObjectType> 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()
Expand All @@ -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<Error> 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<std::string> get_value(
const InputVarType& _var
) noexcept {
Expand All @@ -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<std::string> split(
const std::string& _str, char _delim
const std::string& _str, char _delim, const bool _keep_blank_items
) {
std::vector<std::string> result;
if (_str.empty()) {
Expand All @@ -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;
Expand Down Expand Up @@ -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<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_, blank_items_as_missing_)) {
_items->emplace_back(std::move(item));
}
}

/// The character at which list values are split, see ListDelimiter.
std::optional<char> 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
Loading