From 176379f233b95ad3bc40b5862c7ab85e2018c7bf Mon Sep 17 00:00:00 2001 From: clockblocker Date: Tue, 10 Nov 2026 12:45:25 +0100 Subject: [PATCH 1/2] Accept grouped short options such as -qfcsv in rfl::cli parse_argv took everything after a single '-' as one short name, so the getopt spellings failed: `-qf csv` with "Unknown short argument: -qf" and `-fcsv` with "Unknown short argument: -fcsv". parse_argv now reads the token one character at a time with the option table, as getopt does: - Flags are set up to the first option that takes a value, so -abc sets a, b and c. - That option takes the rest of the token (-fcsv and -qfcsv give f=csv), or the next token if nothing is left (-qf csv). - An rfl::ImplicitValue option takes the rest of the token if there is any (-hfoo), and its implicit value otherwise. It never takes the next token, like getopt's optional arguments. - The last option of a token treats the next token as it would alone, so `-qv false` sets v to false. - -f=csv still gives csv, also in a group (-qf=csv). getopt gives =csv. - A flag inside a group takes no value. -vq=false fails with "Option '-q' does not take a value in '-vq=false'. Write '-q=false' on its own." - An unknown character in a group fails with "Unknown short argument: -x (in '-qxf')." resolve_args still reports a lone unknown -x. - A token that looks like a negative number (-42, -.5) stays positional, unless a short option's name looks like a number (-1). Then, as in argparse, every such token is a group of short options: -15 is -1 -5, and -10 and -1.5 fail. Negative positionals need `--`. `-p -42` works as before. All the inputs that change meaning used to fail. parse_argv without the option table does not know the short options, so it does not group them: -abc stays the one short option "abc", and -5 the short option "5", as before. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 60 +++- include/rfl/cli/options.hpp | 6 + include/rfl/cli/parse_argv.hpp | 123 +++++--- tests/cli/test_short_clusters.cpp | 394 ++++++++++++++++++++++++++ 4 files changed, 536 insertions(+), 47 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 9532d551..bfcead59 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -131,16 +131,17 @@ 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 @@ -212,6 +213,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> quiet; + rfl::Short<"v", std::optional> verbose; + rfl::Short<"f", std::optional> format; + rfl::Short<"h", rfl::ImplicitValue>> 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 @@ -264,7 +304,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`) | | `rfl::ImplicitValue` | `--key` or `--key=value` | Bare means `x` | ## Architecture @@ -275,9 +315,9 @@ 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` and grouped short options work, 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. 2. **`resolve_args`** — uses the same table to map short aliases to long names and to merge positional arguments. Produces a flat `map`. diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index aa822156..c4c842b3 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -98,6 +98,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 @@ -601,6 +606,7 @@ void collect_short_and_positional(Options* _options) { 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; collect_value_options>(&options); diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index b26f5411..1a7fa5b6 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -49,11 +49,16 @@ namespace internal { /// implicit value. Other long options never consume it. Short options /// missing from `_options` consume it unless it looks like an option, as /// they do without `_options`. +/// 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`). An rfl::ImplicitValue option takes the rest of the +/// token if there is one, and never the next token. A token that looks like +/// a negative number (`-42`, `-.5`) is a positional argument, unless a short +/// option's name looks like a number (`-1`), as in argparse. Without +/// `_options` from make_options, short options are not grouped: `-abc` is +/// the short option `abc`, and `-42` the short option `42`. /// Every element of `_args` is parsed; nothing is skipped as the program name. -/// A token that looks like a negative number (-5, -.5) is a positional -/// argument unless `_options` has a short option whose name looks like a -/// number (rfl::Short<"1", ...>). Then such tokens are short options, as in -/// argparse. /// @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 @@ -165,44 +170,88 @@ inline rfl::Result parse_string_views( continue; } - // Short argument: -x value, -x=value, or -x (bool). - // A negative number such as -5 or -.5 is not an option; it falls through - // to positional, unless the struct has a short option such as -1. - if (looks_like_option(arg_raw) - || (negative_numbers_are_options && arg_raw.size() >= 2 - && arg_raw[0] == '-')) { - const auto arg = arg_raw.substr(1); - const auto eq = arg.find('='); - - // -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); - if (!r) { return error(r.error().what()); } + // 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). 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; } - auto key = std::string(arg); - const auto option = _options.find_short(key); - const auto start = i; - 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]); + // 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. + const bool takes_next = + i + 1 < _args.size() && !looks_like_option(_args[i + 1]); + if (takes_next) { + val = std::string(_args[++i]); + } + result.short_without_equals[key] = takes_next; + } + 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, -hvalue: 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". + const auto start = i; + auto v = take_value(option, name, true, &i); + if (!v) { return error(v.error().what()); } + val = std::move(*v); + result.short_without_equals[key] = i != start; + } + + const auto r = add_short(std::move(key), std::move(val), arg_raw); + if (!r) { return error(r.error().what()); } + break; } - else { - auto v = take_value(option, arg_raw, true, &i); - if (!v) { return error(v.error().what()); } - val = std::move(*v); - } - result.short_without_equals[key] = i != start; - 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..914b1bfa --- /dev/null +++ b/tests/cli/test_short_clusters.cpp @@ -0,0 +1,394 @@ +#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::Short<"h", rfl::ImplicitValue>> help; + rfl::Short<"l", rfl::ImplicitValue, "3">> level; + 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) { + const auto alone = read({"-a", "-x"}); + EXPECT_EQ(error_of(alone), "Unknown short argument: -x"); + const auto with_value = read({"-a", "-x=1"}); + EXPECT_EQ(error_of(with_value), "Unknown short argument: -x"); +} + +TEST(cli, test_short_cluster_duplicate) { + const auto result = read({"-aa"}); + EXPECT_EQ(error_of(result), "Duplicate short argument: -aa"); + const auto across = read({"-ab", "-ba"}); + EXPECT_EQ(error_of(across), "Duplicate short argument: -ba"); +} + +TEST(cli, test_short_cluster_conflicts_with_long) { + const auto result = read({"-afcsv", "--format=json"}); + EXPECT_EQ(error_of(result), + "Conflict: '-f' and '--format' both provided."); +} + +TEST(cli, test_short_cluster_implicit_value_attached) { + // getopt's optional argument: the rest of the token, if any. + const auto result = read({"-a", "-hfoo"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().help().value(), "foo"); + + const auto grouped = read({"-aqhfoo", "-l7"}); + ASSERT_TRUE(grouped) << grouped.error().what(); + EXPECT_TRUE(grouped.value().quiet().value()); + EXPECT_EQ(grouped.value().help().value(), "foo"); + EXPECT_EQ(grouped.value().level().value(), 7); + + const auto equals = read({"-aqh=foo"}); + ASSERT_TRUE(equals) << equals.error().what(); + EXPECT_EQ(equals.value().help().value(), "foo"); +} + +TEST(cli, test_short_cluster_implicit_value_bare) { + // Without an attached value, the implicit value. The next token is never + // taken. + const auto result = read({"-aqh", "in.txt", "-l"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().quiet().value()); + EXPECT_EQ(result.value().help().value(), ""); + EXPECT_EQ(result.value().level().value(), 3); + EXPECT_EQ(result.value().input(), "in.txt"); +} + +TEST(cli, test_short_cluster_implicit_value_takes_rest_verbatim) { + const auto result = read({"-ahab"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().all()); + EXPECT_FALSE(result.value().brief().value()); + EXPECT_EQ(result.value().help().value(), "ab"); +} + +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; +}; + +TEST(cli, test_short_digit_option) { + // As in argparse: once a short option's name looks like a number, every + // token that looks like a negative number is a short option, and negative + // positionals need "--". + const auto result = read({"-1", "--", "-5"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().one_per_line()); + EXPECT_EQ(result.value().x(), -5); + + const auto grouped = read({"-1n2"}); + ASSERT_TRUE(grouped) << grouped.error().what(); + EXPECT_TRUE(grouped.value().one_per_line()); + EXPECT_EQ(grouped.value().count(), 2); + + // An option still takes a following negative number as its value. + const auto value = read({"-1", "-n", "-5"}); + ASSERT_TRUE(value) << value.error().what(); + EXPECT_EQ(value.value().count(), -5); +} + +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) { + 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_parse_argv_does_not_group) { + // Without the target struct, parse_argv does not know the short options, + // so -abc is the one short option "abc", and -5 the short option "5". + const char* args[] = {"prog", "-abc", "x", "-de=f", "-g"}; + const auto parsed = rfl::cli::parse_argv(5, const_cast(args)); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed.value().short_args, + (std::map{ + {"abc", "x"}, {"de", "f"}, {"g", ""}})); + EXPECT_TRUE(parsed.value().positional.empty()); + + const auto range = + rfl::cli::parse_argv(std::vector{"-abc", "x", "-5"}); + ASSERT_TRUE(range) << range.error().what(); + EXPECT_EQ(range.value().short_args, + (std::map{{"abc", "x"}, {"5", ""}})); + EXPECT_TRUE(range.value().positional.empty()); +} + +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'."); +} + +TEST(cli, test_short_cluster_no_extra_fields) { + const auto result = + read({"-abqfcsv", "-hx", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().all()); + EXPECT_EQ(result.value().format(), "csv"); + EXPECT_EQ(result.value().help().value(), "x"); + EXPECT_EQ(result.value().input(), "in.txt"); + + const auto unknown = read({"-aby"}); + EXPECT_EQ(error_of(unknown), "Unknown short argument: -y (in '-aby')."); +} + +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()); +} + +TEST(cli, test_short_cluster_wide_char) { + const wchar_t* args[] = {L"program", L"-aqfcsv", L"-hx", L"in.txt"}; + const auto result = rfl::cli::read(4, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_TRUE(result.value().quiet().value()); + EXPECT_EQ(result.value().format(), "csv"); + EXPECT_EQ(result.value().help().value(), "x"); + EXPECT_EQ(result.value().input(), "in.txt"); +} + +TEST(cli, test_short_cluster_parse_argv) { + const auto options = rfl::cli::internal::make_options>(); + const char* args[] = {"program", "-abfcsv", "-p", "-1", "-7"}; + const auto parsed = + rfl::cli::internal::parse_argv(5, const_cast(args), options); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed.value().short_args, + (std::map{ + {"a", ""}, {"b", ""}, {"f", "csv"}, {"p", "-1"}})); + EXPECT_EQ(parsed.value().short_order, + (std::vector{"a", "b", "f", "p"})); + EXPECT_EQ(parsed.value().positional, (std::vector{"-7"})); +} + +} // namespace test_short_clusters From 8a2f21fc0dfb998f258c6603f028308170eb2ee2 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Tue, 10 Nov 2026 12:46:52 +0100 Subject: [PATCH 2/2] Accept abbreviated long options in rfl::cli getopt_long, argparse and Boost.Program_options let a long option be shortened to a unique prefix, so `--rep` stands for `--report`. rfl::cli ignored `--rep`, or failed with "Unknown option '--rep'." under rfl::NoExtraFields. When a long option matches no field, parse_argv now looks for the long options it is a prefix of. It matches their dotted names after the processors, shortening only the last part, so `--database.h` is `--database.host` but `--data` and `--database.` match nothing: - An exact match always wins: `--format` is `--format` even when `--format-version` exists. - One match: the option is read as that one, with `=value`, with the next token, as a flag or with its rfl::ImplicitValue. Errors name the full option: "Missing value for option '--report'." - Several matches fail, with or 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. A field has only one long name in rfl, so the matches are always different fields. - No match: an unknown option, as before. Positional fields count by their long names. Short options, map keys and rfl::ExtraFields keys are never abbreviated. The processor rfl::cli::NoAbbreviations turns this off, like argparse's allow_abbrev=False. It is named after rfl::NoExtraFields and rfl::NoOptionals, and sits in rfl::cli because only rfl::cli::read looks at it. Other formats ignore it. Options::allow_abbreviations carries it to parse_argv. This changes what an unknown long option does when it is a prefix of an option name: it used to be ignored (or rejected with NoExtraFields), and now it sets that option, or fails if it is a prefix of several. Co-Authored-By: Claude Opus 5.5 --- docs/content/supported_formats/cli.md | 48 +++- include/rfl/cli.hpp | 1 + include/rfl/cli/NoAbbreviations.hpp | 51 ++++ include/rfl/cli/options.hpp | 34 ++- include/rfl/cli/parse_argv.hpp | 31 ++- tests/cli/test_abbreviations.cpp | 352 ++++++++++++++++++++++++++ 6 files changed, 509 insertions(+), 8 deletions(-) create mode 100644 include/rfl/cli/NoAbbreviations.hpp create mode 100644 tests/cli/test_abbreviations.cpp diff --git a/docs/content/supported_formats/cli.md b/docs/content/supported_formats/cli.md index bfcead59..d31c3111 100644 --- a/docs/content/supported_formats/cli.md +++ b/docs/content/supported_formats/cli.md @@ -145,8 +145,9 @@ read and write `rfl::ImplicitValue` as its inner type, as they do ## 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(argc, argv); @@ -155,6 +156,41 @@ const auto result = rfl::cli::read(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(argc, argv); +// ./app --rep=a -> --rep is an unknown option +``` + ## Positional arguments Wrap a field with `rfl::Positional` to accept it as a bare (non-flag) argument: @@ -315,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` and grouped short options work, 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`. @@ -332,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` - `include/rfl/cli.hpp` — aggregator header - `include/rfl/SnakeCaseToKebabCase.hpp` — processor diff --git a/include/rfl/cli.hpp b/include/rfl/cli.hpp index 85881e7b..2cd15eef 100644 --- a/include/rfl/cli.hpp +++ b/include/rfl/cli.hpp @@ -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" diff --git a/include/rfl/cli/NoAbbreviations.hpp b/include/rfl/cli/NoAbbreviations.hpp new file mode 100644 index 00000000..636683a0 --- /dev/null +++ b/include/rfl/cli/NoAbbreviations.hpp @@ -0,0 +1,51 @@ +#ifndef RFL_CLI_NOABBREVIATIONS_HPP_ +#define RFL_CLI_NOABBREVIATIONS_HPP_ + +#include + +#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(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 + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +namespace internal { + +template +struct no_abbreviations : std::false_type {}; + +template <> +struct no_abbreviations : std::true_type {}; + +template +struct no_abbreviations> + : std::bool_constant<(no_abbreviations::value || ...)> {}; + +/// Whether the processors contain rfl::cli::NoAbbreviations. +template +constexpr bool no_abbreviations_v = + no_abbreviations>>::value; + +} // namespace internal + +} // namespace rfl::cli + +#endif diff --git a/include/rfl/cli/options.hpp b/include/rfl/cli/options.hpp index c4c842b3..83ab5cc6 100644 --- a/include/rfl/cli/options.hpp +++ b/include/rfl/cli/options.hpp @@ -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" @@ -98,6 +99,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 (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`. @@ -114,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 find_abbreviations( + const std::string& _prefix + ) const { + std::vector 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); @@ -602,12 +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 Options make_options() { Options options; options.group_short_options = true; options.reject_unknown = rfl::internal::no_extra_fields_v; + options.allow_abbreviations = !no_abbreviations_v; using U = unwrapped_option_t; collect_value_options>(&options); if constexpr (is_option_struct_v) { diff --git a/include/rfl/cli/parse_argv.hpp b/include/rfl/cli/parse_argv.hpp index 1a7fa5b6..1e7da9f3 100644 --- a/include/rfl/cli/parse_argv.hpp +++ b/include/rfl/cli/parse_argv.hpp @@ -35,6 +35,19 @@ inline bool looks_like_option(std::string_view _token) noexcept { namespace internal { +/// 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& _names +) { + auto msg = "Option '--" + _key + "' is ambiguous; possibilities: "; + for (size_t i = 0; i < _names.size(); ++i) { + msg += (i == 0 ? "'--" : ", '--") + _names[i] + "'"; + } + return msg + "."; +} + /// Parses command-line arguments into categorized buckets. /// Handles three types of arguments: /// - Long options: --key=value, --key value or --flag (stored in `named`) @@ -58,6 +71,9 @@ namespace internal { /// option's name looks like a number (`-1`), as in argparse. Without /// `_options` from make_options, short options are not grouped: `-abc` is /// the short option `abc`, and `-42` the short option `42`. +/// A long option that matches no field stands for the one long option it +/// is a prefix of (`--rep` for `--report`), unless several match, which is +/// an error, or `_options.allow_abbreviations` is false. /// 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) @@ -148,7 +164,18 @@ inline rfl::Result 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 + "'."); } @@ -157,7 +184,7 @@ inline rfl::Result parse_string_views( val = std::string(arg.substr(eq + 1)); } else { - auto v = take_value(option, arg_raw, false, &i); + auto v = take_value(option, "--" + key, false, &i); if (!v) { return error(v.error().what()); } val = std::move(*v); if (option.kind != OptionKind::value) { diff --git a/tests/cli/test_abbreviations.cpp b/tests/cli/test_abbreviations.cpp new file mode 100644 index 00000000..9e62f42b --- /dev/null +++ b/tests/cli/test_abbreviations.cpp @@ -0,0 +1,352 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace test_abbreviations { + +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 Database { + std::optional host; + std::optional port; +}; + +struct Export { + std::optional format; + std::optional format_version; + std::optional force_export; + std::optional> report; + rfl::ImplicitValue, "all"> help_reports; + rfl::Short<"o", std::optional> output; + rfl::Positional> input_file; + std::optional database; + std::optional> labels; +}; + +TEST(cli, test_abbreviation_with_equals) { + const auto result = read({"--rep=a,b"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().report, + (std::vector{"a", "b"})); +} + +TEST(cli, test_abbreviation_with_space) { + const auto result = read({"--rep", "a", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().report, (std::vector{"a"})); + EXPECT_EQ(result.value().input_file(), "in.txt"); +} + +TEST(cli, test_abbreviation_flag) { + const auto result = read({"--forc", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().force_export, true); + EXPECT_EQ(result.value().input_file(), "in.txt"); + + // Like `--force-export`, an abbreviated long flag never takes the next + // token, even if it is a bool literal. + const auto with_value = read({"--force-e", "false"}); + ASSERT_TRUE(with_value) << with_value.error().what(); + EXPECT_EQ(with_value.value().force_export, true); + EXPECT_EQ(with_value.value().input_file(), "false"); + + const auto with_equals = read({"--forc=false"}); + ASSERT_TRUE(with_equals) << with_equals.error().what(); + EXPECT_EQ(with_equals.value().force_export, false); +} + +TEST(cli, test_abbreviation_implicit_value) { + const auto bare = read({"--help", "in.txt"}); + ASSERT_TRUE(bare) << bare.error().what(); + EXPECT_EQ(bare.value().help_reports().value(), "all"); + EXPECT_EQ(bare.value().input_file(), "in.txt"); + + const auto with_value = read({"--help-r=memory"}); + ASSERT_TRUE(with_value) << with_value.error().what(); + EXPECT_EQ(with_value.value().help_reports().value(), "memory"); +} + +TEST(cli, test_abbreviation_exact_match_wins) { + const auto result = read({"--format", "csv", "--format-v", "2"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().format, "csv"); + EXPECT_EQ(result.value().format_version, "2"); +} + +TEST(cli, test_abbreviation_ambiguous) { + for (const auto& args : std::vector>{ + {"--form", "csv"}, {"--form=csv"}, {"in.txt", "--form"}}) { + const auto result = read(args); + EXPECT_EQ(error_of(result), + "Option '--form' is ambiguous; possibilities: '--format', " + "'--format-version'."); + } + // Past the end of `--format`, only `--format-version` is left. + const auto unique = read({"--format-", "1"}); + ASSERT_TRUE(unique) << unique.error().what(); + EXPECT_EQ(unique.value().format_version, "1"); +} + +TEST(cli, test_abbreviation_ambiguous_lists_all_candidates) { + const auto result = read({"--for", "x"}); + EXPECT_EQ(error_of(result), + "Option '--for' is ambiguous; possibilities: '--force-export', " + "'--format', '--format-version'."); +} + +TEST(cli, test_abbreviation_ambiguous_with_no_extra_fields) { + const auto result = read({"--for=x"}); + EXPECT_EQ(error_of(result), + "Option '--for' is ambiguous; possibilities: '--force-export', " + "'--format', '--format-version'."); +} + +TEST(cli, test_abbreviation_nested) { + const auto result = + read({"--database.h", "db", "--database.p=5432"}); + ASSERT_TRUE(result) << result.error().what(); + ASSERT_TRUE(result.value().database); + EXPECT_EQ(result.value().database->host, "db"); + EXPECT_EQ(result.value().database->port, 5432); + + // Only the last part of a dotted name is shortened, so the struct's name + // cannot be, and an abbreviation cannot end at or inside it. + const auto inner = read({"--datab.h=db"}); + EXPECT_EQ(error_of(inner), "Unknown option '--datab.h'."); + const auto parent = read({"--data=x"}); + EXPECT_EQ(error_of(parent), "Unknown option '--data'."); +} + +struct Cache { + std::optional host; +}; + +struct WithCache { + std::optional cache; +}; + +TEST(cli, test_abbreviation_does_not_end_in_parent) { + // `cache.host` is the only option starting with `cac` or `cache.`, but + // neither spells out `cache` and a part of `host`. + for (const auto arg : {"--cac=db", "--cache.=db"}) { + const auto lenient = read({arg}); + ASSERT_TRUE(lenient) << lenient.error().what(); + EXPECT_FALSE(lenient.value().cache && lenient.value().cache->host) << arg; + } + EXPECT_EQ(error_of(read({"--cac=db"})), + "Unknown option '--cac'."); + EXPECT_EQ(error_of(read({"--cache.=db"})), + "Unknown option '--cache.'."); + const auto last_part = read({"--cache.h=db"}); + ASSERT_TRUE(last_part) << last_part.error().what(); + ASSERT_TRUE(last_part.value().cache); + EXPECT_EQ(last_part.value().cache->host, "db"); +} + +TEST(cli, test_abbreviation_positional_long_form) { + const auto result = read({"--inp", "in.txt"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().input_file(), "in.txt"); + + const auto conflict = read({"--inp", "a", "b"}); + EXPECT_EQ(error_of(conflict), + "Conflict: positional argument and '--input-file' both provided."); +} + +TEST(cli, test_abbreviation_short_alias_long_form) { + const auto result = read({"--out", "o.csv"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().output(), "o.csv"); + + const auto conflict = read({"-o", "a", "--outp=b"}); + EXPECT_EQ(error_of(conflict), + "Conflict: '-o' and '--output' both provided."); +} + +TEST(cli, test_abbreviation_duplicate) { + const auto result = read({"--format-v=a", "--format-version=b"}); + EXPECT_EQ(error_of(result), "Duplicate argument: --format-version=b"); + const auto both_short = + read({"--format-v=a", "--format-ver", "b"}); + EXPECT_EQ(error_of(both_short), "Duplicate argument: --format-ver"); +} + +TEST(cli, test_abbreviation_missing_value_names_the_option) { + const auto result = read({"in.txt", "--rep"}); + EXPECT_EQ(error_of(result), "Missing value for option '--report'."); +} + +TEST(cli, test_abbreviation_never_into_map_keys) { + // Map keys are not known in advance: `--labels.e` is the key "e". + const auto key = read({"--labels.e", "prod"}); + ASSERT_TRUE(key) << key.error().what(); + EXPECT_EQ(key.value().labels, + (std::map{{"e", "prod"}})); + + // The map's own name is not abbreviated either. + const auto map_name = read({"--lab.env=prod"}); + EXPECT_EQ(error_of(map_name), "Unknown option '--lab.env'."); +} + +TEST(cli, test_abbreviation_no_match) { + // Without rfl::NoExtraFields an unknown option is ignored. + const auto lenient = read({"--nope", "in.txt"}); + ASSERT_TRUE(lenient) << lenient.error().what(); + EXPECT_EQ(lenient.value().input_file(), "in.txt"); + EXPECT_FALSE(lenient.value().report); + + const auto strict = read({"--reps=a"}); + EXPECT_EQ(error_of(strict), "Unknown option '--reps'."); +} + +TEST(cli, test_abbreviation_no_extra_fields) { + const auto result = + read({"--rep", "a", "--forc", "--help-r"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().report, (std::vector{"a"})); + EXPECT_EQ(result.value().force_export, true); + EXPECT_EQ(result.value().help_reports().value(), "all"); +} + +TEST(cli, test_abbreviation_not_after_separator) { + const auto result = read({"--", "--rep"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_FALSE(result.value().report); + EXPECT_EQ(result.value().input_file(), "--rep"); +} + +TEST(cli, test_abbreviation_not_for_short_options) { + // A single dash starts short options, never an abbreviated long option. + const auto result = read({"-out.csv"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().output(), "ut.csv"); + const auto unknown = read({"-rep"}); + EXPECT_EQ(error_of(unknown), "Unknown short argument: -r (in '-rep')."); +} + +TEST(cli, test_no_abbreviations) { + const auto ignored = read( + {"--rep=a", "--for", "in.txt"}); + ASSERT_TRUE(ignored) << ignored.error().what(); + EXPECT_FALSE(ignored.value().report); + EXPECT_FALSE(ignored.value().force_export); + EXPECT_EQ(ignored.value().input_file(), "in.txt"); + + const auto exact = + read({"--report=a", "--format=x"}); + ASSERT_TRUE(exact) << exact.error().what(); + EXPECT_EQ(exact.value().report, (std::vector{"a"})); + EXPECT_EQ(exact.value().format, "x"); +} + +TEST(cli, test_no_abbreviations_with_no_extra_fields) { + for (const auto& args : std::vector>{ + {"--rep=a"}, {"--rep", "a"}}) { + const auto result = + read(args); + EXPECT_EQ(error_of(result), "Unknown option '--rep'."); + } + const auto other_order = + read({"--for"}); + EXPECT_EQ(error_of(other_order), "Unknown option '--for'."); +} + +TEST(cli, test_no_abbreviations_in_options) { + EXPECT_TRUE((rfl::cli::internal::make_options>() + .allow_abbreviations)); + EXPECT_FALSE((rfl::cli::internal::make_options< + Export, rfl::Processors>() + .allow_abbreviations)); +} + +TEST(cli, test_no_abbreviations_ignored_by_other_formats) { + Export e; + e.format = "csv"; + e.report = std::vector{"a"}; + e.database = Database{std::nullopt, 1}; + const auto json = rfl::json::write(e); + EXPECT_EQ(json, rfl::json::write(e)); + const auto back = + rfl::json::read(json); + ASSERT_TRUE(back) << back.error().what(); + EXPECT_EQ(back.value().format, "csv"); + ASSERT_TRUE(back.value().database); + EXPECT_EQ(back.value().database->port, 1); + EXPECT_EQ(rfl::json::write(back.value()), json); +} + +struct Renamed { + rfl::Rename<"outDir", std::optional> out_dir; + std::optional dry_run; +}; + +TEST(cli, test_abbreviation_renamed_and_kebab_case) { + // A field has one long name: rfl::Rename replaces it. + const auto result = read({"--out=x", "--dry"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().out_dir(), "x"); + EXPECT_EQ(result.value().dry_run, true); + + const auto old_name = read({"--out-d=x"}); + EXPECT_EQ(error_of(old_name), "Unknown option '--out-d'."); +} + +struct WithExtra { + std::optional report; + rfl::ExtraFields extra; +}; + +TEST(cli, test_abbreviation_not_with_extra_fields) { + // Under rfl::ExtraFields every name is a key of its own, so nothing is + // abbreviated. + const auto result = read({"--rep=a", "--report=b"}); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().report, "b"); + EXPECT_EQ(result.value().extra.at("rep"), "a"); +} + +TEST(cli, test_abbreviation_parse_argv) { + const auto options = rfl::cli::internal::make_options< + Export, rfl::Processors>(); + EXPECT_EQ(options.find_abbreviations("rep"), + (std::vector{"report"})); + EXPECT_EQ(options.find_abbreviations("form"), + (std::vector{"format", "format-version"})); + EXPECT_TRUE(options.find_abbreviations("labels.e").empty()); + + const char* args[] = {"program", "--rep", "a", "--database.h=x"}; + const auto parsed = + rfl::cli::internal::parse_argv(4, const_cast(args), options); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed.value().named, + (std::map{{"report", "a"}, + {"database.host", "x"}})); +} + +TEST(cli, test_abbreviation_wide_char) { + const wchar_t* args[] = {L"program", L"--rep", L"a", L"--forc"}; + const auto result = rfl::cli::read(4, const_cast(args)); + ASSERT_TRUE(result) << result.error().what(); + EXPECT_EQ(result.value().report, (std::vector{"a"})); + EXPECT_EQ(result.value().force_export, true); +} + +} // namespace test_abbreviations