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
219 changes: 218 additions & 1 deletion docs/content/supported_formats/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,221 @@ a `std::optional` or an `rfl::DefaultVal`, so the argument may be omitted:
with `rfl::Short<"o", rfl::DefaultVal<std::string>> output_dir = "out";`,
leaving out `-o` gives `"out"`.

## 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.

```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",
rfl::Validator<int, rfl::Minimum<1>,
rfl::Maximum<65535>>>>
port;
rfl::Description<"Minimum level to log", std::optional<LogLevel>> log_level;
rfl::Description<"Tags to attach",
rfl::Validator<std::vector<std::string>,
rfl::Size<rfl::Minimum<1>>>>
tags;
Database database;
};
```

`rfl::cli::usage<Config>("app")` returns the usage line, where optional
arguments are in brackets:

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

`rfl::cli::usage<Config>("app", true)` adds one line per argument, with its
description, the constraints of its validators, its default and whether it is
required:

```
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. Range: 1..65535. Required.
--log-level=<debug|info|warn> Minimum level to log
--tags=<v1,v2,...> Tags to attach. Size: >= 1. Required.
--database.host=<value> Required.
--database.port=<value> Required.
```

Defaults are shown for fields wrapped in `rfl::DefaultVal`, and for all fields
if you pass `rfl::DefaultIfMissing` (to both `read` and `usage`), as long as
the struct can be default-constructed:

```cpp
struct Server {
rfl::DefaultVal<std::string> host = "localhost";
rfl::DefaultVal<int> threads = 4;
rfl::DefaultVal<bool> dry_run = false;
};
```

```
Arguments:
--host=<value> Default: localhost.
--threads=<value> Default: 4.
--dry-run[=<bool>] Default: false.
```

The parser takes the defaults of `rfl::DefaultVal` fields from a
default-constructed struct. If the struct cannot be default-constructed, for
instance because a validator rejects another field's default value, those
fields are required, and the help says so.

An `rfl::DefaultVal` inside `rfl::Short`, `rfl::Positional`, `rfl::Description`
or `rfl::Deprecated`, in any order, makes the field optional for the parser,
and the help shows it in brackets with its default:

```cpp
struct Logging {
rfl::Short<"l", rfl::Description<"Minimum level to log",
rfl::DefaultVal<LogLevel>>>
log_level = LogLevel::info;
};
```

```
Usage: app [-l|--log-level=<debug|info|warn>]

Arguments:
-l, --log-level=<debug|info|warn> Minimum level to log. Default: info.
```

The help is built from the same internal option table that `read` parses
with (see [Architecture](#architecture)), so it shows how each argument can
be given:

| Field | Synopsis | Detail |
|---|---|---|
| `bool` | `--verbose[=<bool>]` | |
| `rfl::ImplicitValue<std::optional<Color>, "always">` | `--color[=<never\|always>]` | `Without a value: always.` |
| list (vector, set, array, ...) | `--tags=<v1,v2,...>` | `Can be repeated.` |
| list, with `rfl::cli::ListDelimiter<";">` | `--tags=<v1;v2;...>` | defaults joined with `;` |
| list, with `rfl::cli::ListDelimiter<"">` | `--tags=<value>` | `Can be repeated.` |
| list as the last `rfl::Positional` | `<files>...` | |

`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. The usage line lists the positional arguments in the
order in which the parser fills them, and leaves out a short alias that the
parser does not give a field because another field has it.

With `rfl::cli::OptionsFirst`, the options end at the first positional
argument, so the usage line lists every option before the positional
arguments. The rows of the detailed form keep the declaration order:

```cpp
struct Recipe {
rfl::Short<"v", std::optional<bool>> verbose;
rfl::Positional<std::string> name;
rfl::Positional<rfl::DefaultVal<std::vector<std::string>>> args;
rfl::Short<"j", std::optional<int>> jobs;
};

rfl::cli::usage<Recipe, rfl::cli::OptionsFirst>("recipe");
// Usage: recipe [-v|--verbose[=<bool>]] [-j|--jobs=<value>] <name> [<args>...]
```

## Help and version

`--help` and `--version` are off by default: `rfl::cli::read` treats them
as it treats any option that matches no field. To turn them on, pass the
setting `rfl::cli::App<"name", "version", "description">` (each part is
optional) and call `rfl::cli::read_app` instead of `read`. It returns either
the struct or an `rfl::cli::HelpOrVersion` with the text to print:

```cpp
using CopyApp = rfl::cli::App<"copy", "1.2.0", "Copies a file.">;

struct Copy {
rfl::Positional<rfl::Description<"File to copy", std::string>> source;
rfl::Short<"o", rfl::Description<"Where to copy it", std::string>> output;
rfl::Short<"v", std::optional<bool>> verbose;
rfl::Short<"j", rfl::DefaultVal<int>> jobs = 1;
};

int main(int argc, char* argv[]) {
const auto result = rfl::cli::read_app<Copy, CopyApp>(argc, argv);
if (!result) {
std::cerr << result.error().what() << "\n\n"
<< rfl::cli::usage<Copy, CopyApp>(argv[0]);
return 2;
}
if (const auto* info = std::get_if<rfl::cli::HelpOrVersion>(&*result)) {
std::cout << info->text; // info->kind is help or version
return 0;
}
const Copy& copy = std::get<Copy>(*result);
// ...
}
```

`./copy --help` prints the detailed usage, with a header from the setting
and rows for the two options:

```
copy 1.2.0
Copies a file.

Usage: ./copy [-h|--help] [--version] <source> -o|--output=<value> [-v|--verbose[=<bool>]] [-j|--jobs=<value>]

Arguments:
-h, --help Show this help
--version Show the version
<source> File to copy. Required.
-o, --output=<value> Where to copy it. Required.
-v, --verbose[=<bool>]
-j, --jobs=<value> Default: 1.
```

and `./copy --version` prints `copy 1.2.0`.

- The help is returned before the struct is read, so it works when required
fields are missing or other values are invalid. A token before it that
cannot be split into options at all, such as `-o` without its value, is
still an error. If both are given, the help wins.
- `-h`, `--help` and `--version` are flags in the same option table as the
fields, so `--hel` and `-vh` work, `--ver` is ambiguous if there is also a
`--verbose`, `--` ends them, and with `rfl::cli::OptionsFirst` they are
passed through after the first positional argument. `--help=false` does
not ask for the help.
- **A field takes precedence.** If a field has `rfl::Short<"h", ...>`, `-h`
is that field's and the help is `--help` only. That includes an
`rfl::Short` inside other wrappers, unless another field has the same
short name, in which case the parser gives `-h` to neither field (see
[Combining wrappers](#combining-wrappers)) and it stays the help. A field named `help` turns
the built-in help off and is read like any other field, so you can define
your own, for instance `--help[=<topic>]` with
`rfl::ImplicitValue<std::optional<std::string>, "all"> help;`. A field
named `version` turns `--version` off.
- An empty version leaves out `--version`. An empty name is replaced by the
program name (`argv[0]`).
- Pass the same settings to `usage` as to `read_app`: `usage` shows the
header (in the detailed form only) and the rows of the options that
`read_app` handles.
- `read_app` takes `argc` and `argv` (narrow or wide, const or not), since
the help and the version show the program name. `rfl::cli::read<T,
rfl::cli::App<...>>` does not compile, in any of its forms: its result has
no room for a help request. Other formats ignore the setting.

## Supported types

| Type | CLI format | Notes |
Expand Down Expand Up @@ -549,7 +764,8 @@ Parsing proceeds in three stages:

## Files

- `include/rfl/cli/read.hpp` — public API
- `include/rfl/cli/read.hpp` — public API: `read` and `read_app`
- `include/rfl/cli/App.hpp` — `App<"name", "version", "description">` setting for `--help` and `--version`
- `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 + blank `DefaultVal` and `std::wstring` items
Expand All @@ -559,6 +775,7 @@ Parsing proceeds in three stages:
- `include/rfl/cli/ListDelimiter.hpp` — `ListDelimiter<"x">` processor
- `include/rfl/cli/OptionsFirst.hpp` — `OptionsFirst` processor
- `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
2 changes: 2 additions & 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/App.hpp"
#include "cli/BlankItemsAsMissing.hpp"
#include "cli/ListDelimiter.hpp"
#include "cli/NoAbbreviations.hpp"
Expand All @@ -12,5 +13,6 @@
#include "cli/parse_argv.hpp"
#include "cli/read.hpp"
#include "cli/resolve_args.hpp"
#include "cli/usage.hpp"

#endif
Loading