From 2f8bb6019d27c1ce360bceab6467a6cacd1a2053 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Sat, 14 Nov 2026 05:50:35 +0100 Subject: [PATCH] Accept grouped short options such as `-qfcsv` in rfl::cli rfl::cli::read now accepts several short options in one token: in `-qvf` every flag is set up to 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`). `-f=csv` keeps meaning "csv". A flag inside a group takes no value, and an unknown letter fails with "Unknown short argument: -x (in '-qxf').". Inputs that parsed before keep their meaning. Grouping needs the option table, so the public parse_argv still reads `-abc` as the short option "abc". Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 37 +++- include/rfl/cli/options.hpp | 6 + include/rfl/cli/parse_argv.hpp | 100 ++++++--- tests/cli/test_short_clusters.cpp | 281 ++++++++++++++++++++++++++ 4 files changed, 394 insertions(+), 30 deletions(-) create mode 100644 tests/cli/test_short_clusters.cpp diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index 6ef51f64..181af05f 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -145,6 +145,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> quiet; + rfl::Short<"v", std::optional> verbose; + rfl::Short<"f", std::optional> 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`, @@ -192,7 +227,7 @@ leaving out `-o` gives `"out"`. | `rfl::Flatten` | fields inlined | No prefix needed | | `rfl::Rename<"x", T>` | `--x=val` | Bypasses kebab conversion | | `rfl::Positional` | 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 diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index 8d7b50d4..5323cbda 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -88,6 +88,11 @@ struct Options { /// Whether options that match no field are an error (rfl::NoExtraFields). bool reject_unknown = 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`. + 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 @@ -511,6 +516,7 @@ template > Options make_options() { Options options; + options.group_short_options = true; options.reject_unknown = rfl::internal::no_extra_fields_v; using U = unwrapped_option_t; if constexpr (_all_paths) { diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index ba77cccd..ee25ed62 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -52,6 +52,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) @@ -146,46 +151,83 @@ inline rfl::Result 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('='); + // 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(group[j]); + auto key = std::string( + _options.group_short_options + ? group.substr( + j, c >= 0xF0 ? 4 : c >= 0xE0 ? 3 : c >= 0xC0 ? 2 : 1) + : 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); + } - // -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); + const auto r = add_short(std::move(key), std::move(val), arg_raw); if (!r) { return error(r.error().what()); } - continue; - } - - 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]); - } - } - else { - auto v = take_value(option, arg_raw, &i); - if (!v) { return error(v.error().what()); } - val = std::move(*v); + break; } - const auto r = add_short(std::move(key), std::move(val), arg_raw); - if (!r) { return error(r.error().what()); } continue; } diff --git a/tests/cli/test_short_clusters.cpp b/tests/cli/test_short_clusters.cpp new file mode 100644 index 00000000..acbfc394 --- /dev/null +++ b/tests/cli/test_short_clusters.cpp @@ -0,0 +1,281 @@ +#include + +#include +#include +#include +#include +#include + +namespace test_short_clusters { + +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 +std::string error_of(const rfl::Result& _result) { + return _result ? std::string("(no error)") + : std::string(_result.error().what()); +} + +struct Opts { + rfl::Short<"a", bool> all; + rfl::Short<"b", rfl::DefaultVal> brief = false; + rfl::Short<"c", std::optional> color; + rfl::Short<"q", rfl::DefaultVal> quiet = false; + rfl::Short<"f", std::optional> format; + rfl::Short<"p", std::optional> port; + rfl::Positional> input; + rfl::Positional> output; +}; + +TEST(cli, test_short_cluster_flags) { + const auto result = read({"-abc"}); + ASSERT_TRUE(result) << result.error().what(); + const auto& o = result.value(); + EXPECT_TRUE(o.all()); + EXPECT_TRUE(o.brief().value()); + EXPECT_EQ(o.color(), true); + EXPECT_FALSE(o.quiet().value()); + EXPECT_FALSE(o.format()); +} + +TEST(cli, test_short_cluster_flags_any_order) { + const auto result = read({"-cba", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().all()); + EXPECT_TRUE(result.value().brief().value()); + EXPECT_EQ(result.value().color(), true); + EXPECT_EQ(result.value().input(), "in.txt"); +} + +TEST(cli, test_short_attached_value) { + const auto result = read({"-a", "-fcsv"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().format(), "csv"); +} + +TEST(cli, test_short_cluster_then_attached_value) { + const auto result = read({"-a", "-qfcsv", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().quiet().value()); + EXPECT_EQ(result.value().format(), "csv"); + EXPECT_EQ(result.value().input(), "in.txt"); +} + +TEST(cli, test_short_cluster_value_takes_next_token) { + const auto result = read({"-a", "-qf", "csv", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().quiet().value()); + EXPECT_EQ(result.value().format(), "csv"); + EXPECT_EQ(result.value().input(), "in.txt"); +} + +TEST(cli, test_short_cluster_value_takes_rest_verbatim) { + // Everything after the first option that takes a value is its value, even + // letters that are short options themselves. + const auto result = read({"-afabc"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().all()); + EXPECT_FALSE(result.value().brief().value()); + EXPECT_EQ(result.value().format(), "abc"); +} + +TEST(cli, test_short_cluster_value_missing) { + for (const auto& args : std::vector>{ + {"-a", "-qf"}, {"-aqf", "-b"}, {"-aqf", "--format=x"}}) { + const auto result = read(args); + EXPECT_EQ(error_of(result), "Missing value for option '-f'."); + } +} + +TEST(cli, test_short_equals_value) { + // rfl keeps `-f=csv` meaning "csv", also in a group. getopt would give + // "=csv". + for (const auto& args : std::vector>{ + {"-a", "-f=csv"}, {"-aqf=csv"}}) { + const auto result = read(args); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().format(), "csv"); + } + const auto empty = read({"-af="}); + ASSERT_TRUE(empty) << empty.error().what(); + EXPECT_EQ(empty.value().format(), ""); + const auto twice = read({"-af==x"}); + ASSERT_TRUE(twice) << twice.error().what(); + EXPECT_EQ(twice.value().format(), "=x"); +} + +TEST(cli, test_short_flag_equals_value_alone) { + const auto result = read({"-a=false", "-q=true"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_FALSE(result.value().all()); + EXPECT_TRUE(result.value().quiet().value()); +} + +TEST(cli, test_short_cluster_flag_takes_no_attached_value) { + const auto result = read({"-aq=false"}); + EXPECT_EQ(error_of(result), + "Option '-q' does not take a value in '-aq=false'. Write " + "'-q=false' on its own."); + const auto second = read({"-a", "-bq=false"}); + EXPECT_EQ(error_of(second), + "Option '-q' does not take a value in '-bq=false'. Write " + "'-q=false' on its own."); +} + +TEST(cli, test_short_cluster_last_flag_takes_bool_literal) { + // The last option of a group treats the next token as it would alone. + const auto result = read({"-qa", "false", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().quiet().value()); + EXPECT_FALSE(result.value().all()); + EXPECT_EQ(result.value().input(), "in.txt"); + EXPECT_FALSE(result.value().output()); +} + +TEST(cli, test_short_cluster_flag_does_not_take_other_tokens) { + const auto result = read({"-ab", "in.txt", "out.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().all()); + EXPECT_TRUE(result.value().brief().value()); + EXPECT_EQ(result.value().input(), "in.txt"); + EXPECT_EQ(result.value().output(), "out.txt"); +} + +TEST(cli, test_short_cluster_unknown_letter) { + const auto middle = read({"-axf", "csv"}); + EXPECT_EQ(error_of(middle), "Unknown short argument: -x (in '-axf')."); + const auto first = read({"-xa"}); + EXPECT_EQ(error_of(first), "Unknown short argument: -x (in '-xa')."); + const auto last = read({"-abz"}); + EXPECT_EQ(error_of(last), "Unknown short argument: -z (in '-abz')."); + // A character that takes several bytes in UTF-8 is named whole. + const auto utf8 = read({"-a\xC3\xA9", "-\xE2\x82\xAC"}); + EXPECT_EQ(error_of(utf8), + "Unknown short argument: -\xC3\xA9 (in '-a\xC3\xA9')."); + const auto utf8_alone = read({"-a", "-\xE2\x82\xAC"}); + EXPECT_EQ(error_of(utf8_alone), "Unknown short argument: -\xE2\x82\xAC"); +} + +TEST(cli, test_short_unknown_alone) { + EXPECT_FALSE(read({"-a", "-x"})); + EXPECT_FALSE(read({"-a", "-x=1"})); +} + +TEST(cli, test_short_cluster_duplicate) { + EXPECT_FALSE(read({"-aa"})); + EXPECT_FALSE(read({"-ab", "-ba"})); +} + +TEST(cli, test_short_cluster_conflicts_with_long) { + EXPECT_FALSE(read({"-afcsv", "--format=json"})); +} + +TEST(cli, test_short_negative_number_value) { + for (const auto& args : std::vector>{ + {"-a", "-p", "-42"}, {"-a", "-p-42"}, {"-ap", "-42"}, + {"-ap-42"}, {"-a", "-p=-42"}}) { + const auto result = read(args); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().port(), -42); + } +} + +struct Numbers { + rfl::Short<"v", bool> verbose; + rfl::Short<"n", std::optional> number; + rfl::Positional x; + rfl::Positional> y; +}; + +TEST(cli, test_short_negative_number_positional) { + const auto result = read({"-v", "-42", "-.5"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().verbose()); + EXPECT_DOUBLE_EQ(result.value().x(), -42.0); + EXPECT_DOUBLE_EQ(result.value().y().value(), -0.5); + + const auto value = read({"-vn", "-1.5", "-3"}); + ASSERT_TRUE(value) << value.error().what(); + EXPECT_DOUBLE_EQ(value.value().number().value(), -1.5); + EXPECT_DOUBLE_EQ(value.value().x(), -3.0); +} + +struct DigitShort { + rfl::Short<"1", bool> one_per_line; + rfl::Short<"n", std::optional> count; + rfl::Positional> x; +}; + +struct DigitShortNumbers { + rfl::Short<"1", bool> one_per_line; + rfl::Positional> x; + rfl::Positional> y; + rfl::Positional> z; +}; + +TEST(cli, test_short_digit_option_negative_numbers_are_groups) { + // Once a short option's name is a digit, a token that looks like a + // negative number is a group of short options. + const auto grouped = read({"-1n2"}); + ASSERT_TRUE(grouped) << grouped.error().what(); + EXPECT_TRUE(grouped.value().one_per_line()); + EXPECT_EQ(grouped.value().count(), 2); + + EXPECT_EQ(error_of(read({"-1", "-5"})), + "Unknown short argument: -5"); + EXPECT_EQ(error_of(read({"-2"})), "Unknown short argument: -2"); + EXPECT_EQ(error_of(read({"-.5"})), + "Unknown short argument: -. (in '-.5')."); + EXPECT_EQ(error_of(read({"-1.5"})), + "Unknown short argument: -. (in '-1.5')."); + EXPECT_EQ(error_of(read({"-10"})), + "Unknown short argument: -0 (in '-10')."); + EXPECT_EQ(error_of(read({"-15"})), + "Unknown short argument: -5 (in '-15')."); + + const auto separated = + read({"-1", "--", "-1.5", "-10", "-15"}); + ASSERT_TRUE(separated) << separated.error().what(); + EXPECT_TRUE(separated.value().one_per_line()); + EXPECT_DOUBLE_EQ(separated.value().x().value(), -1.5); + EXPECT_DOUBLE_EQ(separated.value().y().value(), -10.0); + EXPECT_DOUBLE_EQ(separated.value().z().value(), -15.0); +} + +TEST(cli, test_short_cluster_after_separator) { + const auto result = read({"-ab", "--", "-qfcsv", "-x"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().all()); + EXPECT_FALSE(result.value().quiet().value()); + EXPECT_FALSE(result.value().format()); + EXPECT_EQ(result.value().input(), "-qfcsv"); + EXPECT_EQ(result.value().output(), "-x"); +} + +TEST(cli, test_short_cluster_value_after_separator_token) { + // `--` after an option that needs a value is not its value. + const auto result = read({"-af", "--", "x"}); + EXPECT_EQ(error_of(result), "Missing value for option '-f'."); +} + +struct Nested { + rfl::Description<"Be quiet", rfl::Short<"q", bool>> quiet; + rfl::DefaultVal> output; + std::optional> verbose; +}; + +TEST(cli, test_short_cluster_nested_wrappers) { + const auto result = read({"-vqoout.csv"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().quiet().value()); + EXPECT_EQ(result.value().output().value(), "out.csv"); + ASSERT_TRUE(result.value().verbose.has_value()); + EXPECT_TRUE(result.value().verbose.value().value()); +} + +} // namespace test_short_clusters