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
102 changes: 90 additions & 12 deletions docs/content/supported_formats/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,21 +131,23 @@ struct Config {
// ./app --help-reports -> help_reports = "all"
// ./app --help-reports=memory -> help_reports = "memory"
// ./app --help-reports in.txt -> help_reports = "all", input = "in.txt"
// ./app -h / -h=tag -> help = "" / "tag"
// ./app -h / -h=tag / -htag -> help = "" / "tag" / "tag"
// ./app --verbosity -> verbosity = 2
```

A bare option stands for the text, which is parsed like any other value
(the default text is empty). A value can only be given after `=`: the next
token is never taken. If the option is absent, the field is read as usual:
`std::optional` gives `std::nullopt`, `rfl::DefaultVal` its default, and any
other field is required. Other formats read and write `rfl::ImplicitValue`
as its inner type, as they do `rfl::Short`.
(the default text is empty). A value can only be given after `=` or attached
to a short option (`-htag`): the next token is never taken. If the option is
absent, the field is read as usual: `std::optional` gives `std::nullopt`,
`rfl::DefaultVal` its default, and any other field is required. Other formats
read and write `rfl::ImplicitValue` as its inner type, as they do
`rfl::Short`.

## Unknown options

By default, long options that match no field are ignored, and they do not
consume the next token. Pass `rfl::NoExtraFields` to reject them:
By default, long options that match no field, not even as an abbreviation
(below), are ignored, and they do not consume the next token. Pass
`rfl::NoExtraFields` to reject them:

```cpp
const auto result = rfl::cli::read<Config, rfl::NoExtraFields>(argc, argv);
Expand All @@ -154,6 +156,41 @@ const auto result = rfl::cli::read<Config, rfl::NoExtraFields>(argc, argv);

Unknown short options are always an error.

## Abbreviated long options

As in getopt_long and argparse, a long option can be shortened to a prefix
that matches only one option: with fields `report` and `format`, `--rep=a`,
`--rep a` and `--form` stand for `--report=a`, `--report a` and `--format`.
This works for flags, `rfl::ImplicitValue` options, positional fields given
by name and nested fields, where only the last part of the dotted name is
shortened: `--database.h` stands for `--database.host`, but `--data` and
`--database.` stand for nothing.

- An exact name always wins: `--format` is `--format` even when
`--format-version` exists.
- A prefix of several options is an error, even without `rfl::NoExtraFields`:
`Option '--for' is ambiguous; possibilities: '--force-export', '--format'.`
getopt_long accepts several matches if they all name the same option and
argparse rejects them, but in rfl a field has only one long name, so the
matches are always different fields.
- A prefix of no option is an unknown option, as above.
- Short options, map keys and `rfl::ExtraFields` keys are never
abbreviated. Under `rfl::ExtraFields`, an unknown name is an extra key.

Abbreviations are on by default, so an option that matches no field is
not always unknown: `--rep` sets `--report` if that is its only match. With
a field `verbose_logging` and no `verbose`, `--verbose` sets
`verbose_logging`. `rfl::NoExtraFields` does not stop this: with a field
`port_range` and no `port`, `--port=8080` fills `port_range` instead of
failing. Adding an option can make an abbreviation ambiguous, so scripts
should spell options out. `rfl::cli::NoAbbreviations` accepts exact names
only, and other formats ignore it:

```cpp
rfl::cli::read<Config, rfl::cli::NoAbbreviations>(argc, argv);
// ./app --rep=a -> --rep is an unknown option
```

## Positional arguments

Wrap a field with `rfl::Positional<T>` to accept it as a bare (non-flag) argument:
Expand Down Expand Up @@ -212,6 +249,45 @@ flag to `false`. Write `-v -- 1` to pass such a token as a positional
argument. To explicitly set a bool short flag, use `=` syntax: `-v=true`,
`-v=false`.

### 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;
rfl::Short<"h", rfl::ImplicitValue<std::optional<std::string>>> help;
};

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

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. An
`rfl::ImplicitValue` option takes the rest of the token if there is any and
its implicit value otherwise, never the next token. 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`, where getopt gives `=csv`.
- 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.
- As in argparse, that changes if a short option's name is a digit, such as
`rfl::Short<"1", bool>` for `ls -1`. Then such a token is a group of
short options: `-15` is `-1 -5`, and `-10` and `-1.5` fail with
`Unknown short argument: -0 (in '-10').` and `-. (in '-1.5')`. Pass
negative positionals after `--` (`./app -1 -- -1.5 -10`). An option still
takes a negative number as its value (`-n -5`).

## Combining wrappers

`Short`, `Positional` and `ImplicitValue` can be nested with each other and
Expand Down Expand Up @@ -264,7 +340,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`) |
| `rfl::ImplicitValue<T, "x">` | `--key` or `--key=value` | Bare means `x` |

## Architecture
Expand All @@ -275,9 +351,10 @@ Parsing proceeds in three stages:
and `positional` buckets (`ParsedArgs` struct). `rfl::cli::read` gives
it an internal option table derived from the target struct, which says
which long and short options are flags, take a value or have an implicit
value, so that `--key value` works, and whether a short option's name
looks like a number. The public `parse_argv`, which has no table, reads
`-5` as a short option.
value, so that `--key value`, grouped short options and abbreviated long
options work, and whether a short option's name looks like a number. The
public `parse_argv`, which has no table, does none of these: `-abc` is the
one short option `abc`, and `-5` the short option `5`.
2. **`resolve_args`** — uses the same table to map short aliases to long
names and to merge positional arguments. Produces a flat
`map<string, string>`.
Expand All @@ -292,6 +369,7 @@ Parsing proceeds in three stages:
- `include/rfl/cli/Parser.hpp` — Parser type alias
- `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
- `include/rfl/cli/resolve_args.hpp` — `ParsedArgs` -> `map<string, string>`
- `include/rfl/cli.hpp` — aggregator header
- `include/rfl/SnakeCaseToKebabCase.hpp` — 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/NoAbbreviations.hpp"
#include "cli/Parser.hpp"
#include "cli/Reader.hpp"
#include "cli/options.hpp"
Expand Down
51 changes: 51 additions & 0 deletions include/rfl/cli/NoAbbreviations.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#ifndef RFL_CLI_NOABBREVIATIONS_HPP_
#define RFL_CLI_NOABBREVIATIONS_HPP_

#include <type_traits>

#include "../Processors.hpp"

namespace rfl::cli {

/// A processor that turns off abbreviated long options in rfl::cli::read,
/// like argparse's allow_abbrev=False. By default, a long option may be
/// shortened to any prefix that matches exactly one option, so `--rep`
/// stands for `--report`. With NoAbbreviations, a long option must be
/// spelled out, and `--rep` is an unknown option.
/// This is a marker type (doesn't modify data) that only rfl::cli::read looks
/// at. Other formats ignore it.
/// Usage: rfl::cli::read<Config, rfl::cli::NoAbbreviations>(argc, argv)
struct NoAbbreviations {
public:
/// Identity process function - returns the named tuple unchanged.
/// @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 no_abbreviations : std::false_type {};

template <>
struct no_abbreviations<NoAbbreviations> : std::true_type {};

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

/// Whether the processors contain rfl::cli::NoAbbreviations.
template <class T>
constexpr bool no_abbreviations_v =
no_abbreviations<std::remove_cvref_t<std::remove_pointer_t<T>>>::value;

} // namespace internal

} // namespace rfl::cli

#endif
40 changes: 39 additions & 1 deletion include/rfl/cli/options.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
#include "../internal/no_extra_fields_v.hpp"
#include "../internal/processed_t.hpp"
#include "../parsing/is_string_map.hpp"
#include "NoAbbreviations.hpp"
#include "Parser.hpp"
#include "Reader.hpp"

Expand Down Expand Up @@ -98,6 +99,15 @@ struct Options {
/// Whether options that match no field are an error (rfl::NoExtraFields).
bool reject_unknown = false;

/// Whether a long option that matches no field may be an abbreviation of
/// one (turned off by rfl::cli::NoAbbreviations).
bool allow_abbreviations = true;

/// 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 All @@ -109,6 +119,31 @@ struct Options {
/// struct fails.
std::string duplicate_short_name;

/// Returns the long options that `--_prefix` could abbreviate: every
/// long option that starts with `_prefix`, in alphabetical order. Only the
/// last segment of a dotted name is abbreviated, so `_prefix` must spell
/// out the others and end inside the last one: `database.h` abbreviates
/// `database.host`, but `data` and `database.` do not. Keys of maps and of
/// rfl::ExtraFields are not known in advance, so they are never among
/// them. Only meaningful if find_long(_prefix) is unknown: an exact match
/// always wins.
std::vector<std::string> find_abbreviations(
const std::string& _prefix
) const {
std::vector<std::string> names;
if (_prefix.empty() || _prefix.back() == path_separator) {
return names;
}
const auto last_separator = _prefix.rfind(path_separator);
for (auto it = long_options.lower_bound(_prefix);
it != long_options.end() && it->first.starts_with(_prefix); ++it) {
if (it->first.rfind(path_separator) == last_separator) {
names.push_back(it->first);
}
}
return names;
}

/// Returns the long option `--_name`.
Option find_long(const std::string& _name) const {
const auto it = long_options.find(_name);
Expand Down Expand Up @@ -597,11 +632,14 @@ void collect_short_and_positional(Options* _options) {
/// @tparam T The target struct type
/// @tparam ProcessorsType The processors applied to the struct
/// @return The options, with reject_unknown set if ProcessorsType contains
/// rfl::NoExtraFields
/// rfl::NoExtraFields, and allow_abbreviations cleared if it contains
/// rfl::cli::NoAbbreviations
template <class T, class ProcessorsType>
Options make_options() {
Options options;
options.group_short_options = true;
options.reject_unknown = rfl::internal::no_extra_fields_v<ProcessorsType>;
options.allow_abbreviations = !no_abbreviations_v<ProcessorsType>;
using U = unwrapped_option_t<T, ProcessorsType>;
collect_value_options<T, ProcessorsType, type_list<>>(&options);
if constexpr (is_option_struct_v<U>) {
Expand Down
Loading