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
44 changes: 44 additions & 0 deletions docs/content/supported_formats/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,49 @@ const auto result = rfl::cli::read<Config, rfl::NoExtraFields>(argc, argv);

Unknown short options are always an error.

## Abbreviated long options

Pass `rfl::cli::AllowAbbreviations` to accept abbreviated long options, like
argparse's `allow_abbrev`. Other formats ignore it:

```cpp
rfl::cli::read<Config, rfl::cli::AllowAbbreviations>(argc, argv);
```

A long option can then be shortened to a prefix that matches only one option:
with fields `report` and `format`, `--rep=a` and `--form` stand for
`--report=a` and `--format`. This works for flags,
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'.`
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.
- The two-step API expands abbreviations in `resolve_args<T, Ps>` when `Ps`
contains `rfl::cli::AllowAbbreviations`. `parse_argv` does not know the
struct, so there the value of an abbreviated option must follow `=`.

With `rfl::cli::AllowAbbreviations`, 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. Without `rfl::cli::AllowAbbreviations`, only exact
names match:

```cpp
rfl::cli::read<Config>(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 @@ -394,6 +437,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/AllowAbbreviations.hpp` — `AllowAbbreviations` 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
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/AllowAbbreviations.hpp"
#include "cli/Parser.hpp"
#include "cli/Reader.hpp"
#include "cli/SeparateOptionValues.hpp"
Expand Down
51 changes: 51 additions & 0 deletions include/rfl/cli/AllowAbbreviations.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#ifndef RFL_CLI_ALLOWABBREVIATIONS_HPP_
#define RFL_CLI_ALLOWABBREVIATIONS_HPP_

#include <type_traits>

#include "../Processors.hpp"

namespace rfl::cli {

/// A processor that turns on abbreviated long options in rfl::cli::read,
/// like argparse's allow_abbrev. With AllowAbbreviations, a long option may
/// be shortened to any prefix that matches exactly one option, so `--rep`
/// stands for `--report`. By default, 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::AllowAbbreviations>(argc, argv)
struct AllowAbbreviations {
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 allow_abbreviations : std::false_type {};

template <>
struct allow_abbreviations<AllowAbbreviations> : std::true_type {};

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

/// Whether the processors contain rfl::cli::AllowAbbreviations.
template <class T>
constexpr bool allow_abbreviations_v =
allow_abbreviations<std::remove_cvref_t<std::remove_pointer_t<T>>>::value;

} // namespace internal

} // namespace rfl::cli

#endif
44 changes: 39 additions & 5 deletions include/rfl/cli/options.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
#include "../internal/no_extra_fields_v.hpp"
#include "../internal/processed_t.hpp"
#include "../parsing/is_string_map.hpp"
#include "AllowAbbreviations.hpp"
#include "Parser.hpp"
#include "SeparateOptionValues.hpp"
#include "Reader.hpp"
Expand Down Expand Up @@ -90,6 +91,10 @@ 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 (rfl::cli::AllowAbbreviations).
bool allow_abbreviations = 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`.
Expand All @@ -110,6 +115,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 @@ -515,20 +545,24 @@ void collect_top_level_options(Options* _options) {
/// @tparam ProcessorsType The processors applied to the struct
/// @tparam _all_paths Whether to list every long option through nested
/// structs, maps and rfl::ExtraFields, rather than only the top-level fields.
/// Only rfl::NoExtraFields, to reject unknown options, and
/// Only rfl::NoExtraFields, to reject unknown options,
/// rfl::cli::SeparateOptionValues, to tell whether a nested option takes the
/// next token, need them all.
/// next token, and rfl::cli::AllowAbbreviations, to abbreviate nested
/// options, need them all.
/// @return The options, with reject_unknown set if ProcessorsType contains
/// rfl::NoExtraFields, and separate_values if it contains
/// rfl::cli::SeparateOptionValues
/// rfl::NoExtraFields, separate_values if it contains
/// rfl::cli::SeparateOptionValues, and allow_abbreviations if it contains
/// rfl::cli::AllowAbbreviations
template <class T, class ProcessorsType,
bool _all_paths = rfl::internal::no_extra_fields_v<ProcessorsType>
|| separate_option_values_v<ProcessorsType>>
|| separate_option_values_v<ProcessorsType>
|| allow_abbreviations_v<ProcessorsType>>
Options make_options() {
Options options;
options.group_short_options = true;
options.reject_unknown = rfl::internal::no_extra_fields_v<ProcessorsType>;
options.separate_values = separate_option_values_v<ProcessorsType>;
options.allow_abbreviations = allow_abbreviations_v<ProcessorsType>;
using U = unwrapped_option_t<T, ProcessorsType>;
if constexpr (_all_paths) {
collect_value_options<T, ProcessorsType, type_list<>>(&options);
Expand Down
20 changes: 18 additions & 2 deletions include/rfl/cli/parse_argv.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ namespace internal {
/// 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`.
/// If `_options.allow_abbreviations` is set (rfl::cli::AllowAbbreviations),
/// a long option that matches no field stands for the one long option it is
/// a prefix of (`--rep` for `--report`), and a prefix of several is an
/// error.
/// 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 @@ -144,15 +148,27 @@ inline rfl::Result<ParsedArgs> parse_string_views(
if (key.empty()) {
return error("Empty key in argument: " + std::string(arg_raw));
}
const auto option = _options.find_long(key);
auto option = _options.find_long(key);
if (option.kind == OptionKind::unknown && _options.allow_abbreviations) {
// --rep for --report: a prefix of exactly one long option.
const auto names = _options.find_abbreviations(key);
if (names.size() > 1) {
return error(internal::ambiguous_option_message(key, names));
}
if (names.size() == 1) {
key = names.front();
option = _options.find_long(key);
}
}
if (option.kind == OptionKind::unknown && _options.reject_unknown) {
return error("Unknown option '--" + key + "'.");
}
if (eq == std::string_view::npos && option.kind == OptionKind::value
&& _options.separate_values) {
// --key value (rfl::cli::SeparateOptionValues). A flag never takes
// the next token: `--verbose 0` leaves "0" positional.
auto v = take_value(option, arg_raw, &i);
// The message names the option that `key` abbreviates.
auto v = take_value(option, "--" + key, &i);
if (!v) { return error(v.error().what()); }
val = std::move(*v);
}
Expand Down
6 changes: 4 additions & 2 deletions include/rfl/cli/read.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ rfl::Result<T> parse_and_read(const ParseFn& _parse) {
/// yourself: `std::span(argv, argc)` would parse the program name as an
/// argument.
/// @tparam T The struct type to parse into
/// @tparam Ps Optional processors to apply during parsing
/// @tparam Ps Optional processors to apply during parsing, including
/// settings such as rfl::NoExtraFields and rfl::cli::AllowAbbreviations
/// @param _args The command-line arguments to parse
/// @return A Result containing the parsed struct or an error
template <class T, class... Ps,
Expand All @@ -79,7 +80,8 @@ rfl::Result<T> read(R&& _args) {
/// argv[0] is skipped as the program name. See the sequence overload above
/// for the supported syntax.
/// @tparam T The struct type to parse into
/// @tparam Ps Optional processors to apply during parsing
/// @tparam Ps Optional processors to apply during parsing, including
/// settings such as rfl::NoExtraFields and rfl::cli::AllowAbbreviations
/// @param argc Number of command-line arguments
/// @param argv Array of command-line argument strings
/// @return A Result containing the parsed struct or an error
Expand Down
50 changes: 49 additions & 1 deletion include/rfl/cli/resolve_args.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,53 @@ inline rfl::Result<std::map<std::string, std::string>> resolve_args(
return std::move(result);
}

/// The error for a long option that abbreviates several options, worded
/// like getopt_long's: "Option '--for' is ambiguous; possibilities:
/// '--force-export', '--format'."
inline std::string ambiguous_option_message(
const std::string& _key, const std::vector<std::string>& _names
) {
auto msg = "Option '--" + _key + "' is ambiguous; possibilities: ";
for (size_t i = 0; i < _names.size(); ++i) {
msg += (i == 0 ? "'--" : ", '--") + _names[i] + "'";
}
return msg + ".";
}

/// Replaces the long options in `_named` that match no field by the one long
/// option they abbreviate (rfl::cli::AllowAbbreviations), as
/// parse_string_views does while parsing.
inline rfl::Result<std::map<std::string, std::string>> expand_abbreviations(
std::map<std::string, std::string> _named, const Options& _options) {
std::map<std::string, std::string> expanded;
for (auto& [key, value] : _named) {
auto name = key;
if (_options.find_long(key).kind == OptionKind::unknown) {
const auto names = _options.find_abbreviations(key);
if (names.size() > 1) {
return rfl::error(ambiguous_option_message(key, names));
}
if (names.size() == 1) {
name = names.front();
}
}
if (!expanded.emplace(name, std::move(value)).second) {
return rfl::error("Duplicate argument: --" + name);
}
}
return expanded;
}

} // namespace internal

/// Resolves ParsedArgs into a flat key-value map using compile-time
/// metadata from the target struct T. Like the overload taking the options
/// 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.
/// positional arguments. 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 positional argument.
/// @tparam T The target struct type
/// @tparam ProcessorsType The processors applied to the struct
/// @param _parsed The parsed command-line arguments
Expand All @@ -143,6 +183,14 @@ rfl::Result<std::map<std::string, std::string>> resolve_args(
if (!short_names) {
return rfl::error(short_names.error().what());
}
if (options.allow_abbreviations) {
auto named =
internal::expand_abbreviations(std::move(_parsed.named), options);
if (!named) {
return rfl::error(named.error().what());
}
_parsed.named = std::move(*named);
}
internal::apply_option_kinds(options, &_parsed);
return internal::resolve_args(std::move(_parsed), options);
}
Expand Down
Loading