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
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,17 @@ struct Config {
// ./app data.csv -o /tmp/out -v --count=10
```

`rfl::cli::usage` generates the help text from the same struct, for instance for `--help`:

```cpp
if (argc > 1 && std::string_view(argv[1]) == "--help") {
std::cout << rfl::cli::usage<Config>(argv[0], true).value();
// Usage: ./app <input-file> -o|--output-dir=<value> -v|--verbose[=<bool>] --count=<value>
//
// Arguments: ...
}
```

Nested structs, `std::optional`, `std::vector`, enums, `rfl::Flatten` and `rfl::Rename` are all supported. Refer to the [documentation](https://munich-data-engineering.github.io/reflect-cpp/cli) for details.

### Error messages
Expand Down
112 changes: 111 additions & 1 deletion docs/content/supported_formats/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,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 @@ -160,6 +195,80 @@ struct Config {
// ./app data.csv -o /tmp/out -v --count=10
```

## Usage / help

`rfl::cli::usage<T, Ps...>(program_name, detailed = false)` generates the
help text from the same struct, and with the same processors, as
`rfl::cli::read<T, Ps...>()`. So the names always match what the parser
accepts, including kebab-case, `rfl::Rename`, `rfl::Flatten` and nested paths.
It returns an `rfl::Result<std::string>`.

```cpp
enum class LogLevel { debug, info, warn };

struct Database {
std::string host;
int port;
};

struct Config {
rfl::Positional<rfl::Description<"Path to the input file", std::string>>
input_file;
rfl::Short<"p", rfl::Description<"Port to listen on", int>> port;
rfl::Description<"Minimum level to log", std::optional<LogLevel>> log_level;
rfl::Description<"Tags to attach", std::vector<std::string>> tags;
Database database;
};
```

`rfl::cli::usage<Config>("app", true).value()` is the usage line, where
optional arguments are in brackets, and one line per argument, with its
description and whether it is required. `rfl::cli::usage<Config>("app")`
gives only the usage line.

```
Usage: app <input-file> -p|--port=<value> [--log-level=<debug|info|warn>] --tags=<v1,v2,...> --database.host=<value> --database.port=<value>

Arguments:
<input-file> Path to the input file. Required.
-p, --port=<value> Port to listen on. Required.
--log-level=<debug|info|warn> Minimum level to log
--tags=<v1,v2,...> Tags to attach. Required.
--database.host=<value> Required.
--database.port=<value> Required.
```

Fields wrapped in `rfl::DefaultVal` are optional, and so are all fields if you
pass `rfl::DefaultIfMissing` (to both `read` and `usage`). The parser takes
the defaults of `rfl::DefaultVal` fields from a default-constructed struct. If
a struct with `rfl::DefaultVal` cannot be default-constructed (for instance
because a validator rejects another field's default value), it cannot be read,
and `usage` returns the error, as it does for two fields with the same short
name.

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>]`), and
every other option takes a value (`--port=<value>`).

`rfl::Positional` and `rfl::Short` are found through the other wrappers, as
the parser does (see [Combining wrappers](#combining-wrappers)), so
`rfl::Description<"...", rfl::Positional<std::string>>` is listed as a
positional argument.

`read` does not handle `--help`: check `argv` for it and print `usage`
yourself:

```cpp
int main(int argc, char* argv[]) {
if (argc > 1 && std::string_view(argv[1]) == "--help") {
std::cout << rfl::cli::usage<Config>(argv[0], true).value();
return 0;
}
const auto config = rfl::cli::read<Config>(argc, argv).value();
}
```

## Supported types

| Type | CLI format | Notes |
Expand All @@ -175,7 +284,7 @@ struct Config {
| `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 Expand Up @@ -204,6 +313,7 @@ Parsing proceeds in three stages:
- `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/resolve_args.hpp` — `ParsedArgs` -> `map<string, string>`
- `include/rfl/cli/usage.hpp` — `usage()` help text, built on `rfl::parsing::schema` and the internal option table
- `include/rfl/cli.hpp` — aggregator header
- `include/rfl/SnakeCaseToKebabCase.hpp` — processor
- `include/rfl/Positional.hpp` — `Positional<T>` wrapper
Expand Down
1 change: 1 addition & 0 deletions include/rfl/cli.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
#include "cli/parse_argv.hpp"
#include "cli/read.hpp"
#include "cli/resolve_args.hpp"
#include "cli/usage.hpp"

#endif
6 changes: 6 additions & 0 deletions include/rfl/cli/options.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ struct Options {
/// argument.
std::vector<std::string> positionals;

/// 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 @@ -334,6 +339,7 @@ void collect_short_and_positional(Options* _options) {
template <class T, class ProcessorsType>
Options make_options() {
Options options;
options.group_short_options = true;
using U = unwrapped_option_t<T, ProcessorsType>;
if constexpr (is_option_struct_v<U>) {
collect_options<U, ProcessorsType>(&options);
Expand Down
110 changes: 82 additions & 28 deletions include/rfl/cli/parse_argv.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,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 @@ -141,46 +146,95 @@ 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('=');

// -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);
if (!r) { return error(r.error().what()); }
continue;
if (group.starts_with('=')) {
return error("Invalid short option '" + std::string(arg_raw) + "'.");
}

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]);
// 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]);
size_t len = 1;
if (_options.group_short_options && c >= 0xC0) {
const size_t expected = c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : 2;
while (len < expected && j + len < group.size()
&& (static_cast<unsigned char>(group[j + len]) & 0xC0)
== 0x80) {
++len;
}
}
auto key = std::string(
_options.group_short_options
? group.substr(j, len)
: 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);
}

const auto r = add_short(std::move(key), std::move(val), arg_raw);
if (!r) { return error(r.error().what()); }
break;
}
else {
auto v = take_value(option, arg_raw, &i);
if (!v) { return error(v.error().what()); }
val = std::move(*v);
}
const auto r = add_short(std::move(key), std::move(val), arg_raw);
if (!r) { return error(r.error().what()); }
continue;
}

Expand Down
Loading
Loading