From 6234e78fa23c4422720590c37d2f970f903c49f3 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Sat, 14 Nov 2026 05:50:35 +0100 Subject: [PATCH] Accept `--key value` for long options that take a value With the new processor rfl::cli::SeparateOptionValues, rfl::cli::read takes the value of a long option from the next token when it is given without '=': `--sql "SELECT 1"`. The next token is taken unless it looks like an option; if there is none, parsing fails with "Missing value for option '--sql'.". Bool flags, variants, rfl::Generic and unknown options never take the next token. Without the processor nothing changes: a long option takes its value only after '='. The public parse_argv, which has no option table, is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 40 +++++- include/rfl/cli.hpp | 1 + include/rfl/cli/SeparateOptionValues.hpp | 51 ++++++++ include/rfl/cli/options.hpp | 21 +++- include/rfl/cli/parse_argv.hpp | 35 ++++-- tests/cli/test_long_option_values.cpp | 154 +++++++++++++++++++++++ 6 files changed, 283 insertions(+), 19 deletions(-) create mode 100644 include/rfl/cli/SeparateOptionValues.hpp create mode 100644 tests/cli/test_long_option_values.cpp diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 6ef51f64..7bb57428 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -69,10 +69,46 @@ const auto result = rfl::cli::read(args); `rfl::cli::parse_argv` has the same overloads. +## Long options + +A long option takes its value after `=`. With the processor +`rfl::cli::SeparateOptionValues`, it can also take it from the next token, +as in getopt_long and argparse: + +```cpp +const auto result = + rfl::cli::read(argc, argv); +``` + +``` +./app --host-name=localhost --port=8080 --verbose --tags=a,b,c +./app --host-name localhost --port 8080 --verbose --tags a,b,c --rate -0.5 +``` + +This works for every field that takes a value, including nested fields +(`--database.host db.local`), entries of maps with string keys +(`--labels.env prod`; other maps need `=`) and fields inside wrappers such +as `rfl::Short`, `rfl::Description` or `rfl::DefaultVal`. The next token is +the value unless it looks like an option (`-` followed by anything except a +digit or `.`), so `--offset -5` works. If the value is missing, parsing +fails with `Missing value for option '--sql'.` Use `=` to pass an empty +value or one that starts with `-`: `--sql=`, `--pattern=-x`. + +Boolean fields (`bool`, `std::optional` and wrapped bools) are flags +and never consume the next token: `--verbose input.txt` sets `verbose` and +passes `input.txt` as a positional argument, and so does `--verbose 0` with +`0`. To set a flag to `false`, write `--verbose=false`. A `std::variant`, +`rfl::Variant`, `rfl::TaggedUnion` or `rfl::Generic` may hold a bool, so +its long option never takes the next token either: pass its value with `=`. + +Without the processor, `--sql SELECT` sets `sql` to an empty string and +passes `SELECT` as a positional argument. The public `rfl::cli::parse_argv` +does not know the struct, so it always reads it that way. + ## Unknown options -By default, long options that match no field are ignored. Pass -`rfl::NoExtraFields` to reject them: +By default, long options that match no field are ignored, and they do not +consume the next token. Pass `rfl::NoExtraFields` to reject them: ```cpp const auto result = rfl::cli::read(argc, argv); diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index 85881e7b..677b8b58 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -4,6 +4,7 @@ #include "../rfl.hpp" #include "cli/Parser.hpp" #include "cli/Reader.hpp" +#include "cli/SeparateOptionValues.hpp" #include "cli/options.hpp" #include "cli/parse_argv.hpp" #include "cli/read.hpp" diff --git a/include/rfl/cli/SeparateOptionValues.hpp b/include/rfl/cli/SeparateOptionValues.hpp new file mode 100644 index 00000000..dab29b51 --- /dev/null +++ b/include/rfl/cli/SeparateOptionValues.hpp @@ -0,0 +1,51 @@ +#ifndef RFL_CLI_SEPARATEOPTIONVALUES_HPP_ +#define RFL_CLI_SEPARATEOPTIONVALUES_HPP_ + +#include + +#include "../Processors.hpp" + +namespace rfl::cli { + +/// A processor that lets a long option in rfl::cli::read take its value from +/// the next argument, as in getopt_long and argparse: `--sql "SELECT 1"` as +/// well as `--sql="SELECT 1"`. By default, a long option takes its value only +/// after '=', and `--sql "SELECT 1"` sets `sql` to an empty string and makes +/// "SELECT 1" a positional argument. +/// This is a marker type (doesn't modify data) that only rfl::cli::read looks +/// at. Other formats ignore it. +/// Usage: rfl::cli::read(argc, argv) +struct SeparateOptionValues { + 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 + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +namespace internal { + +template +struct separate_option_values : std::false_type {}; + +template <> +struct separate_option_values : std::true_type {}; + +template +struct separate_option_values> + : std::bool_constant<(separate_option_values::value || ...)> {}; + +/// Whether the processors contain rfl::cli::SeparateOptionValues. +template +constexpr bool separate_option_values_v = separate_option_values< + std::remove_cvref_t>>::value; + +} // namespace internal + +} // namespace rfl::cli + +#endif diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index 8d7b50d4..af076702 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -30,6 +30,7 @@ #include "../internal/processed_t.hpp" #include "../parsing/is_string_map.hpp" #include "Parser.hpp" +#include "SeparateOptionValues.hpp" #include "Reader.hpp" namespace rfl::cli::internal { @@ -39,7 +40,8 @@ enum class OptionKind { /// A boolean field: `--flag` or `-f`. `--flag` never takes the next /// token; `-f` takes it only if it is `true`, `false`, `1` or `0`. flag, - /// A field that takes a value: `--key=value`, `-k value` or `-k=value`. + /// A field that takes a value: `--key=value`, `-k value`, `-k=value`, and + /// with rfl::cli::SeparateOptionValues `--key value`. value, /// A known path whose kind cannot be decided from the type (a nested /// struct, a variant, rfl::Generic, or a sub-key of a variant). `--key` @@ -56,7 +58,7 @@ struct Option { }; /// The options that a target struct accepts, built from its fields by -/// make_options on every read. parse_argv uses it to decide whether a short +/// make_options on every read. parse_argv uses it to decide whether an /// option takes the next token as its value and whether a long option is /// known, and resolve_args to map short aliases and positional arguments to /// fields. Paths are dotted @@ -88,6 +90,10 @@ struct Options { /// Whether options that match no field are an error (rfl::NoExtraFields). bool reject_unknown = false; + /// Whether a long option that takes a value takes it from the next token + /// when it is given without '=' (rfl::cli::SeparateOptionValues). + bool separate_values = 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 @@ -504,14 +510,19 @@ 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 needs them all, to reject unknown options. +/// Only rfl::NoExtraFields, to reject unknown options, and +/// rfl::cli::SeparateOptionValues, to tell whether a nested option takes the +/// next token, need them all. /// @return The options, with reject_unknown set if ProcessorsType contains -/// rfl::NoExtraFields +/// rfl::NoExtraFields, and separate_values if it contains +/// rfl::cli::SeparateOptionValues template > + bool _all_paths = rfl::internal::no_extra_fields_v + || separate_option_values_v> Options make_options() { Options options; options.reject_unknown = rfl::internal::no_extra_fields_v; + options.separate_values = separate_option_values_v; using U = unwrapped_option_t; if constexpr (_all_paths) { collect_value_options>(&options); diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index ba77cccd..9fc43187 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -37,17 +37,20 @@ namespace internal { /// Parses command-line arguments into categorized buckets. /// Handles three types of arguments: -/// - Long options: --key=value or --flag (stored in `named`) +/// - Long options: --key=value, --key value (with +/// `_options.separate_values`) or --flag (stored in `named`) /// - Short options: -x value, -x=value, or -x (stored in `short_args`) /// - Positional arguments: bare arguments not prefixed with dashes (stored in `positional`) /// The special argument "--" forces all subsequent arguments to be treated as positional. -/// `_options` says what each short option does with the token that follows -/// it when it is given without '='. One that takes a value consumes it, and -/// fails if there is none. A bool flag consumes it only if it is "true", -/// "false", "1" or "0". Short options missing from `_options` consume it -/// unless it looks like an option, as they do without `_options`. Long -/// options never consume it. With `_options.reject_unknown`, a long option -/// that matches no field is an error. +/// `_options` says what each option does with the token that follows it +/// when it is given without '='. A short option that takes a value consumes +/// it, and fails if there is none; so does a long one with +/// `_options.separate_values` (rfl::cli::SeparateOptionValues). A long +/// boolean flag never consumes it; a short one consumes it only if it is +/// "true", "false", "1" or "0". Other long options never consume it. Short options missing from `_options` +/// consume it unless it looks like an option, as they do without +/// `_options`. With `_options.reject_unknown`, a long option that matches +/// no field is an error. /// A token that looks like a negative number (-5, -.5) is a positional /// argument unless `_options.negative_numbers_are_options` is set, as it is /// without `_options` and when the struct has a short option whose name @@ -56,7 +59,7 @@ namespace internal { /// @param _args The command-line arguments to parse /// @param _options The options of the target struct (see make_options) /// @return A Result containing ParsedArgs with categorized arguments or an error -/// --key=value / --flag → named +/// --key=value / --key value (with separate_values) / --flag → named /// -x value / -x=value / -x → short_args /// bare arguments → positional /// -- → everything after goes to positional @@ -75,8 +78,8 @@ inline rfl::Result parse_string_views( return true; }; - // The value of the short option _args[*_i], given without '=', taking the - // next token if the option says so. + // The value of the option _args[*_i], given without '=', taking the next + // token if the option says so. const auto take_value = [&](const Option& _option, std::string_view _raw, size_t* _i) -> rfl::Result { const bool has_next = *_i + 1 < _args.size(); @@ -125,7 +128,7 @@ inline rfl::Result parse_string_views( continue; } - // Long argument: --key=value or --flag. + // Long argument: --key=value, --key value or --flag. if (arg_raw.starts_with("--")) { const auto arg = arg_raw.substr(2); const auto eq = arg.find('='); @@ -140,6 +143,14 @@ inline rfl::Result parse_string_views( 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); + if (!v) { return error(v.error().what()); } + val = std::move(*v); + } if (!result.named.emplace(std::move(key), std::move(val)).second) { return error("Duplicate argument: " + std::string(arg_raw)); } diff --git a/tests/cli/test_long_option_values.cpp b/tests/cli/test_long_option_values.cpp new file mode 100644 index 00000000..fd626b75 --- /dev/null +++ b/tests/cli/test_long_option_values.cpp @@ -0,0 +1,154 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +// `--key value` with rfl::cli::SeparateOptionValues. +namespace test_long_option_values { + +template +rfl::Result read(std::vector _args) { + _args.insert(_args.begin(), "program"); + return rfl::cli::read(static_cast(_args.size()), + const_cast(_args.data())); +} + +template +rfl::Result read_separate(std::vector _args) { + return read(std::move(_args)); +} + +struct Database { + std::string host; + int port; + std::optional ssl; +}; + +struct Config { + std::string sql; + int offset; + std::vector tags; + rfl::Description<"A label", std::optional> label; + Database database; +}; + +TEST(cli, test_long_space_value) { + const auto result = read_separate( + {"--sql", "SELECT 1", "--offset", "-5", "--tags", "a,b", "--label", "x", + "--database.host", "localhost", "--database.port", "5432", + "--database.ssl"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& c = result.value(); + EXPECT_EQ(c.sql, "SELECT 1"); + EXPECT_EQ(c.offset, -5); + EXPECT_EQ(c.tags, (std::vector{"a", "b"})); + EXPECT_EQ(c.label(), "x"); + EXPECT_EQ(c.database.host, "localhost"); + EXPECT_EQ(c.database.port, 5432); + EXPECT_EQ(c.database.ssl, true); +} + +struct Query { + std::optional sql; + std::optional verbose; + rfl::Positional input_file; +}; + +TEST(cli, test_long_space_value_is_opt_in) { + // Without the processor, a long option takes its value only after '='. + const auto next = read({"--sql", "in.txt"}); + ASSERT_TRUE(next) << next.error().what(); + EXPECT_EQ(next.value().sql, ""); + EXPECT_EQ(next.value().input_file(), "in.txt"); + + const auto before_option = read({"--sql", "--verbose", "in.txt"}); + ASSERT_TRUE(before_option) << before_option.error().what(); + EXPECT_EQ(before_option.value().sql, ""); + EXPECT_EQ(before_option.value().verbose, true); + + const auto last = read({"in.txt", "--sql"}); + ASSERT_TRUE(last) << last.error().what(); + EXPECT_EQ(last.value().sql, ""); +} + +TEST(cli, test_long_missing_value) { + // At the end, before another option and before `--`. `--sql=` passes an + // empty value. + for (const auto& args : std::vector>{ + {"in.txt", "--sql"}, + {"--sql", "--verbose", "in.txt"}, + {"--sql", "--", "in.txt"}}) { + const auto result = read_separate(args); + ASSERT_FALSE(result); + EXPECT_EQ(std::string(result.error().what()), + "Missing value for option '--sql'."); + } + const auto empty = read_separate({"--sql=", "in.txt"}); + ASSERT_TRUE(empty) << empty.error().what(); + EXPECT_EQ(empty.value().sql, ""); +} + +struct Force { + bool force; + rfl::Short<"q", std::optional> quiet; + rfl::Positional input_file; +}; + +TEST(cli, test_long_bool_does_not_take_next_token) { + // Unlike `-q 0`, a long flag never takes the next token, even if it is a + // boolean literal. + for (const char* next : {"in.txt", "0"}) { + const auto result = read_separate({"--force", next, "--quiet"}); + ASSERT_TRUE(result) << next << ": " << result.error().what(); + EXPECT_TRUE(result.value().force) << next; + EXPECT_EQ(result.value().quiet(), true) << next; + EXPECT_EQ(result.value().input_file(), next); + } +} + +TEST(cli, test_long_unknown_option_does_not_take_next_token) { + // Without rfl::NoExtraFields, unknown options are ignored. + const auto result = + read_separate({"--nope", "in.txt", "--sql", "x"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().sql, "x"); + EXPECT_EQ(result.value().input_file(), "in.txt"); +} + +struct WithMaps { + std::map labels; + std::map features; + rfl::Positional input_file; +}; + +TEST(cli, test_long_space_map) { + const auto result = read_separate( + {"--labels.env", "prod", "--labels.team=data", "--features.fast", + "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& m = result.value(); + EXPECT_EQ(m.labels, (std::map{ + {"env", "prod"}, {"team", "data"}})); + EXPECT_EQ(m.features, (std::map{{"fast", true}})); + EXPECT_EQ(m.input_file(), "in.txt"); +} + +struct WithVariants { + std::optional> mode; + rfl::Positional> input_file; +}; + +TEST(cli, test_long_variant_without_value) { + // A variant may hold a bool, so the next token is never its value. + const auto result = read_separate({"--mode", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().mode, (std::variant(true))); + EXPECT_EQ(result.value().input_file(), "in.txt"); +} + +} // namespace test_long_option_values