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
31 changes: 29 additions & 2 deletions docs/content/supported_formats/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,32 @@ 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.`

### A list as the last positional argument

If the last positional field (in declaration order) is a list, it takes all
remaining positional arguments, and each argument is split at the commas:

```cpp
struct Config {
rfl::Positional<std::string> command;
rfl::Positional<std::vector<std::string>> files;
};

// ./app run a,b -> files = {"a", "b"}
// ./app run a b -> files = {"a", "b"}
// ./app run a,b c -> files = {"a", "b", "c"}
```

- A plain list needs at least one argument. With `std::optional` or
`rfl::DefaultVal`, no arguments give `std::nullopt` or the default.
- Options can still come anywhere (`./app run a --verbose b`).
- The long form works as for any list: `--files=a,b`, or
`--files=a --files=b`. It cannot be mixed with bare arguments:
`Conflict: positional argument and '--files' both provided.`
- Only the last positional field takes the remaining arguments. A list
before other positional fields, such as `std::vector`, `std::set`, a
pair or a `std::array`, takes one argument, split at the commas.

## Combining wrappers

`Short` and `Positional` can be nested with `DefaultVal`, `std::optional`,
Expand Down Expand Up @@ -404,7 +430,8 @@ 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[=<bool>]`), a list
takes comma-separated items and can be repeated (`--tags=<v1,v2,...>`, with
`Can be repeated.` in its row), and every other option takes a value
`Can be repeated.` in its row), a list as the last `rfl::Positional` takes
the remaining arguments (`<files>...`), and every other option takes a value
(`--port=<value>`).

`rfl::Positional` and `rfl::Short` are found through the other wrappers, as
Expand Down Expand Up @@ -439,7 +466,7 @@ int main(int argc, char* argv[]) {
| 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 |
| `rfl::Positional<T>` | bare token | Matched in declaration order |
| `rfl::Positional<T>` | bare token | Matched in declaration order; a list last takes the rest |
| `rfl::Short<"x", T>` | `-x value`, `-x=value` or `-xvalue` | Single-character alias, can be grouped (`-qv`) |

## Architecture
Expand Down
9 changes: 8 additions & 1 deletion include/rfl/cli/options.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ struct Options {

/// The paths of the rfl::Positional fields, in declaration order, wherever
/// rfl::Positional sits among a field's wrappers. Each takes one positional
/// argument.
/// argument, except that a list as the last one takes the remaining
/// positional arguments (see last_positional_is_list).
std::vector<std::string> positionals;

/// Prefixes (ending in path_separator, or empty for the root) under which
Expand Down Expand Up @@ -204,6 +205,12 @@ struct Options {
return it == short_options.end() ? Option{} : find_long(it->second);
}

/// Whether the last rfl::Positional field is a list. It then takes every
/// positional argument after those of the other positional fields.
bool last_positional_is_list() const {
return !positionals.empty() && find_long(positionals.back()).is_list;
}

private:
static bool has_prefix(
const std::map<std::string, Option>& _map, const std::string& _prefix
Expand Down
20 changes: 18 additions & 2 deletions include/rfl/cli/resolve_args.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ inline rfl::Unexpected<Error> too_many_positionals(const size_t _expected,
/// target struct.
/// This function:
/// 1. Maps positional arguments to their corresponding field names based on declaration order
/// If the last positional field is a list, it takes all remaining
/// positional arguments, as later occurrences of the list.
/// 2. Expands short arguments (e.g., -p) to long names (e.g., --port) using Short<> annotations
/// 3. Detects conflicts between different ways of specifying the same field
/// The caller checks the short names first (check_short_names).
Expand All @@ -107,11 +109,19 @@ inline rfl::Result<ResolvedArgs> resolve_args(

// Merge positional args.
const auto& positional_names = _options.positionals;
if (_parsed.positional.size() > positional_names.size()) {
if (_parsed.positional.size() > positional_names.size()
&& !_options.last_positional_is_list()) {
return internal::too_many_positionals(positional_names.size(),
_parsed.positional.size());
}
for (size_t i = 0; i < _parsed.positional.size(); ++i) {
if (i >= positional_names.size()) {
// A list as the last positional field takes the rest, one occurrence
// per argument.
_parsed.later_occurrences[positional_names.back()].emplace_back(
std::move(_parsed.positional[i]));
continue;
}
const auto& long_name = positional_names[i];
if (result.count(long_name)) {
return rfl::error(
Expand Down Expand Up @@ -184,7 +194,9 @@ inline rfl::Result<std::map<std::string, std::string>> expand_abbreviations(
/// 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. A flat map cannot hold the occurrences of a
/// repeated list option, which parse_argv without the options rejects.
/// repeated list option, which parse_argv without the options rejects, so
/// a list as the last positional field does not take the remaining
/// positional arguments here either: each positional field takes one.
/// With rfl::cli::AllowAbbreviations, long options that match no field are
/// expanded here (`--rep=a` for `--report=a`), but parse_argv, which does
/// not know the struct, has already read `--rep value` as `--rep` and a
Expand Down Expand Up @@ -215,6 +227,10 @@ rfl::Result<std::map<std::string, std::string>> resolve_args(
_parsed.named = std::move(*named);
}
internal::apply_option_kinds(options, &_parsed);
if (_parsed.positional.size() > options.positionals.size()) {
return internal::too_many_positionals(options.positionals.size(),
_parsed.positional.size());
}
return internal::resolve_args(std::move(_parsed), options)
.transform([](internal::ResolvedArgs _args) {
return std::move(_args.values);
Expand Down
22 changes: 20 additions & 2 deletions include/rfl/cli/usage.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ struct UsageArg {
OptionKind kind = OptionKind::value;
/// Whether the field is a list, which can be repeated.
bool is_list = false;
/// Whether the field is the last positional one and a list, so that it
/// takes the remaining positional arguments.
bool takes_rest = false;
bool required = true;
/// Whether `required` was taken from the parser's compile-time traits, so
/// that the schema must not override it.
Expand Down Expand Up @@ -322,6 +325,7 @@ class UsageCollector {
auto root = UsageArg{};
root.required = !_all_optional;
add(definition_->root_, std::move(root), _defaults, false);
mark_rest_positional();
return std::move(args_);
}

Expand Down Expand Up @@ -472,6 +476,18 @@ class UsageCollector {
args_.emplace_back(std::move(_arg));
}

/// Marks the positional argument that takes the remaining arguments: a
/// list as the last one (Options::last_positional_is_list).
void mark_rest_positional() {
if (!options_->last_positional_is_list()) {
return;
}
for (auto& arg : args_) {
arg.takes_rest =
arg.positional && arg.name == options_->positionals.back();
}
}

private:
const parsing::schema::Definition* definition_;
const std::map<std::string, UsageFieldMeta>* meta_;
Expand All @@ -493,11 +509,13 @@ inline std::string usage_value_to_string(const UsageArg& _arg) {
return "<v1" + d + "v2" + d + "...>";
}

/// "<input-file>", "-p|--port=<value>", "--verbose[=<bool>]"
/// "<input-file>", "<files>...", "-p|--port=<value>", "--verbose[=<bool>]"
inline std::string usage_arg_to_string(const UsageArg& _arg,
const std::string& _short_sep) {
if (_arg.positional) {
return "<" + _arg.name + ">";
// A list as the last positional field takes the remaining arguments.
// Any other positional field takes one.
return "<" + _arg.name + ">" + (_arg.takes_rest ? "..." : "");
}
auto str = _arg.short_name.empty() ? std::string()
: "-" + _arg.short_name + _short_sep;
Expand Down
Loading