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: 36 additions & 1 deletion docs/content/supported_formats/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,41 @@ looks like an option (`-` followed by anything except a digit or `.`):
`Missing value for option '-o'.` Use `=` to pass an empty value or one that
starts with `-`: `-o=`, `-o=-x`.

### Grouped short options

As in getopt, short options can share one token, and a value can be
attached to its option:

```cpp
struct Config {
rfl::Short<"q", std::optional<bool>> quiet;
rfl::Short<"v", std::optional<bool>> verbose;
rfl::Short<"f", std::optional<std::string>> format;
};

// ./app -qv -fcsv -> quiet, verbose, format = "csv"
// ./app -qvfcsv -> the same
// ./app -qf csv -> quiet, format = "csv"
```

Flags are set up to the first option that takes a value. That option takes
the rest of the token, or the next token if nothing is left. The last
option in a token treats the next token as it would alone (`-qv false` sets
`verbose` to `false`).

- `-f=csv` and `-qf=csv` give `csv`: the `=` is not part of the value.
- A flag inside a group takes no value: `-vq=false` is an error.
- A letter that is not a short option is an error:
`Unknown short argument: -x (in '-qxf').`
- A token like `-42`, `-1.5` or `-.5` is a negative number, so `-p -42`,
`-p-42` and a positional `-42` work. If a short option's name is a digit
(see [Positional arguments](#positional-arguments)), such a token is a
group of short options instead: `-15` is `-1 -5`, and `-10` and `-1.5`
fail with `Unknown short argument: -0 (in '-10').` and
`-. (in '-1.5')`.
- Grouping needs the struct: the public `rfl::cli::parse_argv` reads `-abc`
as the one short option `abc`.

## Combining wrappers

`Short` and `Positional` can be nested with `DefaultVal`, `std::optional`,
Expand Down Expand Up @@ -192,7 +227,7 @@ leaving out `-o` gives `"out"`.
| `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::Short<"x", T>` | `-x value` or `-x=value` | Single-character alias |
| `rfl::Short<"x", T>` | `-x value`, `-x=value` or `-xvalue` | Single-character alias, can be grouped (`-qv`) |

## Architecture

Expand Down
6 changes: 6 additions & 0 deletions include/rfl/cli/options.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ struct Options {
/// Whether options that match no field are an error (rfl::NoExtraFields).
bool reject_unknown = false;

/// Whether short options can be grouped (`-qv`, `-fcsv`). make_options
/// sets it. Without a table (the table-less parse_argv), `-abc` is the
/// one short option `abc`.
bool group_short_options = false;

/// 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
Expand Down Expand Up @@ -511,6 +516,7 @@ template <class T, class ProcessorsType,
bool _all_paths = rfl::internal::no_extra_fields_v<ProcessorsType>>
Options make_options() {
Options options;
options.group_short_options = true;
options.reject_unknown = rfl::internal::no_extra_fields_v<ProcessorsType>;
using U = unwrapped_option_t<T, ProcessorsType>;
if constexpr (_all_paths) {
Expand Down
100 changes: 71 additions & 29 deletions include/rfl/cli/parse_argv.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ namespace internal {
/// argument unless `_options.negative_numbers_are_options` is set, as it is
/// without `_options` and when the struct has a short option whose name
/// looks like a number (rfl::Short<"1", ...>), as in argparse.
/// Short options known to `_options` can be grouped as in getopt: in `-qvf`
/// every flag is set until the first option that takes a value, which
/// takes the rest of the token (`-qfcsv`) or, if nothing is left, the next
/// 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.
/// @param _args The command-line arguments to parse
/// @param _options The options of the target struct (see make_options)
Expand Down Expand Up @@ -146,46 +151,83 @@ inline rfl::Result<ParsedArgs> parse_string_views(
continue;
}

// Short argument: -x value, -x=value, or -x (bool).
// Short options: -x, -x value, -x=value, and groups of them in one
// token, as in getopt: -qv, -fvalue, -qfvalue, -qf value.
if (arg_raw.size() >= 2 && arg_raw[0] == '-') {
const auto group = arg_raw.substr(1);

// A negative number such as -42 or -.5 is a positional argument,
// unless, as in argparse, a short option's name looks like a number
// (-1). Without a table, it is the short option "42".
// (-1). Then -42 is a group of short options. Without a table, it is
// the short option "42".
if (!looks_like_option(arg_raw) && !negative_numbers_are_options) {
result.positional.emplace_back(arg_raw);
continue;
}

const auto arg = arg_raw.substr(1);
const auto eq = arg.find('=');
// Without a table, the short options are not known, so -abc is the one
// short option "abc": -abc value, -abc=value or -abc.
for (size_t j = 0; j < group.size(); ++j) {
// Short names are single ASCII characters. An unknown character may
// take several bytes in UTF-8, so take them all for the message.
const auto c = static_cast<unsigned char>(group[j]);
auto key = std::string(
_options.group_short_options
? group.substr(
j, c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : c >= 0xC0 ? 2 : 1)
: group.substr(0, group.find('=')));
const auto option = _options.find_short(key);
const auto rest = group.substr(j + key.size());
const auto name = "-" + key;
const bool alone = j == 0 && rest.empty();
auto val = std::string();

if (j == 0 && rest.starts_with('=')) {
// -x=value, whatever -x is. Unlike getopt, where -f=csv gives
// "=csv", the '=' is not part of the value.
val = std::string(rest.substr(1));
}
else if (option.kind == OptionKind::unknown) {
if (!alone) {
return error("Unknown short argument: " + name + " (in '"
+ std::string(arg_raw) + "').");
}
// Not in `_options`: consume the next token as the value if it
// doesn't look like an option. resolve_args reports unknown short
// options.
if (i + 1 < _args.size() && !looks_like_option(_args[i + 1])) {
val = std::string(_args[++i]);
}
}
else if (option.kind == OptionKind::flag && !rest.empty()) {
// -qv: a flag followed by more options. Like getopt, a flag in a
// group takes no value: -vq=false is an error, -q=false is not.
if (rest.starts_with('=')) {
return error("Option '" + name + "' does not take a value in '"
+ std::string(arg_raw) + "'. Write '" + name
+ std::string(rest) + "' on its own.");
}
const auto r = add_short(std::move(key), "", arg_raw);
if (!r) { return error(r.error().what()); }
continue;
}
else if (!rest.empty()) {
// -fvalue, -qfvalue: the rest of the token is the value. -qf=value
// is the same as -qfvalue, as -f=value is.
val = std::string(rest.starts_with('=') ? rest.substr(1) : rest);
}
else {
// The last option of the token handles the next one as it would
// alone: -qf csv takes "csv", -vq false takes "false".
auto v = take_value(option, name, &i);
if (!v) { return error(v.error().what()); }
val = std::move(*v);
}

// -x=value
if (eq != std::string_view::npos) {
const auto r = add_short(
std::string(arg.substr(0, eq)),
std::string(arg.substr(eq + 1)), arg_raw);
const auto r = add_short(std::move(key), std::move(val), arg_raw);
if (!r) { return error(r.error().what()); }
continue;
}

auto key = std::string(arg);
const auto option = _options.find_short(key);
auto val = std::string();
if (option.kind == OptionKind::unknown) {
// Not in `_options`: consume the next token as the value if it
// doesn't look like an option. resolve_args reports unknown short
// options.
if (i + 1 < _args.size() && !looks_like_option(_args[i + 1])) {
val = std::string(_args[++i]);
}
}
else {
auto v = take_value(option, arg_raw, &i);
if (!v) { return error(v.error().what()); }
val = std::move(*v);
break;
}
const auto r = add_short(std::move(key), std::move(val), arg_raw);
if (!r) { return error(r.error().what()); }
continue;
}

Expand Down
Loading