diff --git a/main/src/optparse.hxx b/main/src/optparse.hxx index 490d03f177e9c..fa5d6762bdbad 100644 --- a/main/src/optparse.hxx +++ b/main/src/optparse.hxx @@ -37,11 +37,19 @@ /// ~~~ /// /// ## Additional Notes -/// If all the short flags you pass (those starting with a single `-`) are 1 character long, the parser will accept -/// grouped flags like "-abc" as equivalent to "-a -b -c". The last flag in the group may also accept an argument, in -/// which case "-abc foo" will count as "-a -b -c foo" where "foo" is the argument to "-c". /// -/// Multiple repeated flags, like `-vvv`, are supported but must explicitly be marked as such: +/// ### Flag grouping +/// By default, if all the short flags you pass (those starting with a single `-`) are 1 character long, the parser will +/// accept grouped flags like "-abc" as equivalent to "-a -b -c". The last flag in the group may also accept an +/// argument, in which case "-abc foo" will count as "-a -b -c foo" where "foo" is the argument to "-c". If you want to +/// disable flag grouping, use: +/// +/// ~~~{.cpp} +/// ROOT::RCmdLineOpts opts({ EFlagTreatment::kSimple }); +/// ~~~ +/// +/// ### Repeated flags +/// Multiple repeated flags, like `-vvv`, are supported but must explicitly be marked as such on a per-flag basis: /// ~~~{.cpp} /// opts.AddFlag({"-v"}, RCmdLineOpts::EFlagType::kSwitch, "", RCmdLineOpts::kFlagAllowMultiple); /// ~~~ @@ -49,9 +57,23 @@ /// appeared; for flags with arguments `GetFlagValues` and `GetFlagValuesAs` can be used to access the values as /// vectors. /// +/// ### Positional argument separator /// The string "--" is treated as the positional argument separator: all strings after it will be treated as positional /// arguments even if they start with "-". /// +/// ## Prefix flags (aka no space between flag and argument) +/// If you need your flags to support the syntax "-fXYZ" where "-f" is your flag and "XYZ" its argument, you can enable +/// that per-flag by using `RCmdLineOpts::kFlagPrefixArg`: +/// +/// ~~~{.cpp} +/// opts.AddFlag({"-I", "--include"}, RCmdLineOpts::EFlagType::kWithArg, RCmdLineOpts::kFlagPrefixArg }); +/// ~~~ +/// +/// (see EFlagTreatment for more details). This will **disable** flag grouping globally, but allows the parser to +/// interpret flags and arguments that are not separated by spaces. If prefix arg is used, the equal sign will *not* +/// be considered as the key-value separator (`-Dfoo=bar` if `-D` is a prefix arg flag will be parsed as `"-D", +/// "foo=bar"`). Note that this option only makes sense for flags with arguments. +/// /// \author Giacomo Parolini /// \date 2025-10-09 @@ -59,6 +81,7 @@ #define ROOT_OptParse #include +#include #include #include #include @@ -75,6 +98,22 @@ namespace ROOT { class RCmdLineOpts { public: + enum class EFlagTreatment { + /// Will result to kGrouped if you don't define any short flag longer than 1 character, otherwise kSimple. + kDefault, + /// `-abc` will always be treated as the single flag "-abc" + kSimple, + /// `-abc` will be treated as "-a -b -c". This is only valid for short flags. + /// With this setting you cannot define short flags that are more than 1 character long nor ones that are marked + /// with kFlagPrefixArg. + kGrouped, + }; + + struct RSettings { + /// Affects how flags are parsed (\see EFlagTreatment). + EFlagTreatment fFlagTreatment; + }; + enum class EFlagType { kSwitch, kWithArg @@ -90,15 +129,15 @@ public: enum EFlagOpt { /// Flag is allowed to appear multiple times (default: it's an error to see the same flag twice) kFlagAllowMultiple = 1 << 0, + /// Flag argument can appear right after this flag without a space or equal sign in between. + /// Note that marking any short flag with this disables flag grouping! + kFlagPrefixArg = 1 << 1, }; private: + RSettings fSettings; std::vector fFlags; std::vector fArgs; - // If true, many short flags may be grouped: "-abc" == "-a -b -c". - // This is automatically true if all short flags given are 1 character long, otherwise it's false. - // (a short flag is a flag with a single `-` as its prefix). - bool fAllowFlagGrouping = true; struct RExpectedFlag { EFlagType fFlagType = EFlagType::kSwitch; @@ -116,14 +155,27 @@ private: const RExpectedFlag *GetExpectedFlag(std::string_view name) const { + const auto StartsWith = [](std::string_view string, std::string_view prefix) { + return string.size() >= prefix.size() && string.substr(0, prefix.size()) == prefix; + }; + for (const auto &flag : fExpectedFlags) { - if (flag.fName == name) + if (flag.fOpts & kFlagPrefixArg) { + if (StartsWith(name, flag.fName)) { + // NOTE: we can't have ambiguities here because we make sure that no flags share a common prefix in + // AddFlag(). + return &flag; + } + } else if (flag.fName == name) { return &flag; + } } return nullptr; } public: + explicit RCmdLineOpts(RSettings settings = {EFlagTreatment::kDefault}) : fSettings(settings) {} + /// Returns all parsing errors const std::vector &GetErrors() const { return fErrors; } /// Retrieves all positional arguments @@ -142,6 +194,7 @@ public: /// Defines a new flag (either a switch or a flag with argument). /// The flag may be referred to as any of the values inside `aliases` (e.g. { "-h", "--help" }). + /// You must pass at least 1 string inside `aliases`. /// All strings inside `aliases` must start with `-` or `--` and be at least 1 character long (aside the dashes). /// Flags starting with a single `-` are considered "short", regardless of their actual length. /// If all short flags are 1 character long, they may be collapsed into one and parsed as individual flags @@ -155,6 +208,21 @@ public: void AddFlag(std::initializer_list aliases, EFlagType type = EFlagType::kSwitch, std::string_view help = "", std::uint32_t flagOpts = 0) { + const auto IsPrefixOf = [](std::string_view a, std::string_view b) { + return a.size() < b.size() && std::equal(a.begin(), a.end(), b.begin()); + }; + + if (aliases.size() == 0) + throw std::invalid_argument("AddFlag must receive at least 1 name for the flag!"); + + if ((flagOpts & kFlagPrefixArg) && type != EFlagType::kWithArg) + throw std::invalid_argument("Flag `" + std::string(*aliases.begin()) + + "` has option kFlagPrefixArg but it's a Switch, so the option makes no sense."); + + std::vector flagsToBeAdded; + flagsToBeAdded.reserve(aliases.size()); + + const auto nCurrentFlags = fExpectedFlags.size(); int aliasIdx = -1; for (auto f : aliases) { auto prefixLen = f.find_first_not_of('-'); @@ -164,19 +232,66 @@ public: if (f.size() == prefixLen) throw std::invalid_argument("Flag name cannot be empty"); - fAllowFlagGrouping = fAllowFlagGrouping && (prefixLen > 1 || f.size() == 2); + auto flagName = f.substr(prefixLen); + + // Check that we're not introducing ambiguities with prefix flags. + // While we're at it, also check that none of the given aliases were already added. Note that it is valid to + // add the same flag name as both a long and short flag (like "-foo" and "--foo") but only if they are aliases + // of the same flag. + for (const auto &expFlag : fExpectedFlags) { + if (expFlag.fName == flagName) { + throw std::invalid_argument( + "Flag `" + std::string(flagName) + + "` was added multiple times. Note that adding flags with the same name but different number of `-` " + "can only be done as aliases of the same call to AddFlag()."); + } + + if (!(flagOpts & kFlagPrefixArg) && !(expFlag.fOpts & kFlagPrefixArg)) + continue; + + // At least one of expFlag and f is a prefix flag: this means that they must not share a common prefix. + if (((expFlag.fOpts & kFlagPrefixArg) && IsPrefixOf(expFlag.fName, flagName)) || + ((flagOpts & kFlagPrefixArg) && IsPrefixOf(flagName, expFlag.fName))) { + throw std::invalid_argument("Flags `" + expFlag.AsStr() + "` and `" + std::string(f) + + "` have a common prefix. This causes ambiguity because at least one of them " + "is marked with kFlagPrefixArg."); + } + } + + // Check that the user didn't pass the very same flag multiple times in the same AddFlag invocation, as that's + // likely a mistake. This is different from the check done in the previous loop as that one only concerns + // flags that were already added before this AddFlag invocation. + for (const auto &expFlag : flagsToBeAdded) { + if (expFlag.AsStr() == f) + throw std::invalid_argument("The same flag `" + expFlag.AsStr() + + "` was passed multiple times to AddFlag()."); + } + + bool disallowsGrouping = (prefixLen == 1 && (f.size() > 2 || (flagOpts & kFlagPrefixArg))); + if (disallowsGrouping) { + if (fSettings.fFlagTreatment == EFlagTreatment::kDefault) { + fSettings.fFlagTreatment = EFlagTreatment::kSimple; + } else if (fSettings.fFlagTreatment == EFlagTreatment::kGrouped) { + throw std::invalid_argument( + std::string("Flags starting with a single dash must be 1 character long when `FlagTreatment == " + "EFlagTreatment::kGrouped'! Cannot accept given flag `") + + std::string(f) + "`"); + } + } RExpectedFlag expected; expected.fFlagType = type; - expected.fName = f.substr(prefixLen); + expected.fName = flagName; expected.fHelp = help; expected.fAlias = aliasIdx; expected.fShort = prefixLen == 1; expected.fOpts = flagOpts; - fExpectedFlags.push_back(expected); + flagsToBeAdded.push_back(expected); if (aliasIdx < 0) - aliasIdx = fExpectedFlags.size() - 1; + aliasIdx = nCurrentFlags + flagsToBeAdded.size() - 1; } + + fExpectedFlags.insert(fExpectedFlags.end(), flagsToBeAdded.begin(), flagsToBeAdded.end()); } /// If `name` refers to a previously-defined switch (i.e. a boolean flag), returns how many times @@ -218,8 +333,7 @@ public: if (!exp) throw std::invalid_argument(std::string("Flag `") + std::string(name) + "` is not expected"); if (exp->fFlagType != EFlagType::kWithArg) - throw std::invalid_argument(std::string("Flag `") + std::string(name) + - "` is a switch, use GetSwitch()"); + throw std::invalid_argument(std::string("Flag `") + std::string(name) + "` is a switch, use GetSwitch()"); std::string_view lookedUpName = name; if (exp->fAlias >= 0) @@ -312,6 +426,11 @@ public: { bool forcePositional = false; + // If flag treatment is still Default by now it means we can safely group short flags (otherwise we'd have + // already changed it to Simple). + if (fSettings.fFlagTreatment == EFlagTreatment::kDefault) + fSettings.fFlagTreatment = EFlagTreatment::kGrouped; + // Contains one or more flags coming from one of the arguments (e.g. "-abc" may be split // into flags "a", "b", and "c", which will be stored in `argStr`). std::vector argStr; @@ -329,17 +448,35 @@ public: if (!isFlag) { // positional argument fArgs.push_back(arg); - } else { + continue; + } + + ++arg; // eat first `-`. + + // Parse long or short flag and its argument into `argStr` / `nxtArgStr`. + // Note that `argStr` may contain multiple flags in case of grouped short flags (in which case nxtArgStr + // refers only to the last one). + argStr.clear(); + std::string_view nxtArgStr; + // If this is false `nxtArgStr` *must* refer to the next arg, otherwise it might or might not be. + bool nxtArgIsTentative = true; + if (arg[0] == '-') { + // long flag ++arg; - // Parse long or short flag and its argument into `argStr` / `nxtArgStr`. - // Note that `argStr` may contain multiple flags in case of grouped short flags (in which case nxtArgStr - // refers only to the last one). - argStr.clear(); - std::string_view nxtArgStr; - bool nxtArgIsTentative = true; - if (arg[0] == '-') { - // long flag - ++arg; + + // if we have prefix flags we need to check them first, as in that case the `=` sign should not be treated + // as the key-value separator. + const auto argLen = strlen(arg); + for (const auto &flag : fExpectedFlags) { + if ((flag.fOpts & kFlagPrefixArg) && flag.fName.size() < argLen && + strncmp(arg, flag.fName.c_str(), flag.fName.size()) == 0) { + argStr.push_back(std::string_view(arg, flag.fName.size())); + nxtArgStr = std::string_view(arg + flag.fName.size(), argLen - flag.fName.size()); + break; + } + } + + if (argStr.empty()) { const char *eq = strchr(arg, '='); if (eq) { argStr.push_back(std::string_view(arg, eq - arg)); @@ -352,79 +489,102 @@ public: ++i; } } - } else { - // short flag. - // If flag grouping is active, all flags except the last one will have an implicitly empty argument. - auto argLen = strlen(arg); - while (fAllowFlagGrouping && argLen > 1) { - argStr.push_back(std::string_view{arg, 1}); - ++arg, --argLen; - } + } + } else { + // short flag. + // If flag grouping is active, all flags except the last one will have an implicitly empty argument. + auto argLen = strlen(arg); + while (fSettings.fFlagTreatment == EFlagTreatment::kGrouped && argLen > 1) { + argStr.push_back(std::string_view{arg, 1}); + ++arg, --argLen; + } - argStr.push_back(std::string_view(arg)); - if (i < nArgs - 1 && args[i + 1][0] != '-') { - nxtArgStr = args[i + 1]; - ++i; - } + argStr.push_back(std::string_view(arg)); + if (i < nArgs - 1 && args[i + 1][0] != '-') { + nxtArgStr = args[i + 1]; + ++i; + } + } + + assert(argStr.size() < 2 || fSettings.fFlagTreatment == EFlagTreatment::kGrouped); + + for (auto j = 0u; j < argStr.size(); ++j) { + std::string_view argS = argStr[j]; + + const auto *exp = GetExpectedFlag(argS); + if (!exp) { + fErrors.push_back(std::string("Unknown flag: ") + argOrig); + break; } - for (auto j = 0u; j < argStr.size(); ++j) { - std::string_view argS = argStr[j]; - const auto *exp = GetExpectedFlag(argS); - if (!exp) { + // In Prefix mode, check if the returned expected flag is shorter than `argS`. This can mean two things: + // - if `nxtArgIsTentative == false` then this flag was followed by an equal sign, and in that case + // the intention is interpreted as "I want this flag's argument to be whatever follows the equal sign", + // which means we treat this as an unknown flag; + // - otherwise, we use the rest of `argS` as the argument to the flag. + // More concretely: if the user added flag "-D" and argS is "-Dfoo=bar", we parse it as + // {flag: "-Dfoo", arg: "bar"}, rather than {flag: "-D", arg: "foo=bar"}. + if ((exp->fOpts & kFlagPrefixArg) && argS.size() > exp->fName.size()) { + if (nxtArgIsTentative) { + i -= !nxtArgStr.empty(); // if we had already picked a candidate next arg, undo that. + nxtArgStr = argS.substr(exp->fName.size()); + nxtArgIsTentative = false; + } else { fErrors.push_back(std::string("Unknown flag: ") + argOrig); break; } + } else { + assert(exp->fName.size() == argS.size()); + } - std::string_view nxtArg = (j == argStr.size() - 1) ? nxtArgStr : ""; - - RCmdLineOpts::RFlag flag; - flag.fHelp = exp->fHelp; - // If the flag is an alias (e.g. long version of a short one), save its name as the aliased one, so we - // can fetch the value later by using any of the aliases. - if (exp->fAlias < 0) - flag.fName = argS; - else - flag.fName = fExpectedFlags[exp->fAlias].fName; - - // Check for duplicate flags - if (!(exp->fOpts & kFlagAllowMultiple)) { - auto existingIt = std::find_if(fFlags.begin(), fFlags.end(), - [&flag](const auto &f) { return f.fName == flag.fName; }); - if (existingIt != fFlags.end()) { - std::string err = std::string("Flag ") + exp->AsStr() + " appeared more than once"; - if (exp->fFlagType == RCmdLineOpts::EFlagType::kWithArg) - err += " with the value: " + existingIt->fValue; - fErrors.push_back(err); - break; - } + std::string_view nxtArg = (j == argStr.size() - 1) ? nxtArgStr : ""; + + RCmdLineOpts::RFlag flag; + flag.fHelp = exp->fHelp; + // If the flag is an alias (e.g. long version of a short one), save its name as the aliased one, so we + // can fetch the value later by using any of the aliases. + if (exp->fAlias < 0) + flag.fName = exp->fName; + else + flag.fName = fExpectedFlags[exp->fAlias].fName; + + // Check for duplicate flags + if (!(exp->fOpts & kFlagAllowMultiple)) { + auto existingIt = + std::find_if(fFlags.begin(), fFlags.end(), [&flag](const auto &f) { return f.fName == flag.fName; }); + if (existingIt != fFlags.end()) { + std::string err = std::string("Flag ") + exp->AsStr() + " appeared more than once"; + if (exp->fFlagType == RCmdLineOpts::EFlagType::kWithArg) + err += " with the value: " + existingIt->fValue; + fErrors.push_back(err); + break; } + } - // Check that arguments are what we expect. - if (exp->fFlagType == RCmdLineOpts::EFlagType::kWithArg) { - if (!nxtArg.empty()) { - flag.fValue = nxtArg; - } else { - fErrors.push_back("Missing argument for flag " + exp->AsStr()); - } + // Check that arguments are what we expect. + if (exp->fFlagType == RCmdLineOpts::EFlagType::kWithArg) { + if (!nxtArg.empty()) { + flag.fValue = nxtArg; } else { - if (!nxtArg.empty()) { - if (nxtArgIsTentative) - --i; - else - fErrors.push_back("Flag " + exp->AsStr() + " does not expect an argument"); - } + fErrors.push_back("Missing argument for flag " + exp->AsStr()); + } + } else { + if (!nxtArg.empty()) { + if (nxtArgIsTentative) + --i; + else + fErrors.push_back("Flag " + exp->AsStr() + " does not expect an argument"); } - - if (!fErrors.empty()) - break; - - fFlags.push_back(flag); } if (!fErrors.empty()) break; + + fFlags.push_back(flag); } + + if (!fErrors.empty()) + break; } } }; diff --git a/main/test/optparse_test.cxx b/main/test/optparse_test.cxx index 2f904723f9361..9e166416e9c08 100644 --- a/main/test/optparse_test.cxx +++ b/main/test/optparse_test.cxx @@ -589,3 +589,185 @@ TEST(OptParse, MultipleFlagsAsIntError) EXPECT_TRUE(opts.GetErrors().empty()); EXPECT_THROW(opts.GetFlagValuesAs("a"), std::invalid_argument); } + +TEST(OptParse, PrefixShort) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"-D"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", + ROOT::RCmdLineOpts::kFlagAllowMultiple | ROOT::RCmdLineOpts::kFlagPrefixArg); + opts.AddFlag({"-b"}, ROOT::RCmdLineOpts::EFlagType::kSwitch); + + const char *args[] = {"somename", "-b", "-Dname"}; + opts.Parse(args, std::size(args)); + + EXPECT_TRUE(opts.GetErrors().empty()); + EXPECT_TRUE(opts.GetSwitch("b")); + EXPECT_EQ(opts.GetFlagValue("D"), "name"); +} + +TEST(OptParse, PrefixLong) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"--D"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", + ROOT::RCmdLineOpts::kFlagAllowMultiple | ROOT::RCmdLineOpts::kFlagPrefixArg); + + const char *args[] = {"somename", "--Dname", "--DotherName"}; + opts.Parse(args, std::size(args)); + + EXPECT_TRUE(opts.GetErrors().empty()); + EXPECT_EQ(opts.GetFlagValues("D"), std::vector({"name", "otherName"})); +} + +TEST(OptParse, PrefixAmbiguous) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"-f"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", ROOT::RCmdLineOpts::kFlagPrefixArg); + EXPECT_THROW(opts.AddFlag({"-foo"}, ROOT::RCmdLineOpts::EFlagType::kSwitch), std::invalid_argument); +} + +TEST(OptParse, PrefixAmbiguous2) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"-f2"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", ROOT::RCmdLineOpts::kFlagPrefixArg); + EXPECT_THROW(opts.AddFlag({"-f22"}, ROOT::RCmdLineOpts::EFlagType::kSwitch), std::invalid_argument); +} + +TEST(OptParse, PrefixAmbiguous3) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"-f22"}, ROOT::RCmdLineOpts::EFlagType::kSwitch); + EXPECT_THROW(opts.AddFlag({"-f2"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", ROOT::RCmdLineOpts::kFlagPrefixArg), + std::invalid_argument); +} + +TEST(OptParse, PrefixNonAmbiguous) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"-f22"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", ROOT::RCmdLineOpts::kFlagPrefixArg); + opts.AddFlag({"-f2"}, ROOT::RCmdLineOpts::EFlagType::kSwitch); +} + +TEST(OptParse, PrefixNonAmbiguous2) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"-f1"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", ROOT::RCmdLineOpts::kFlagPrefixArg); + opts.AddFlag({"-f2"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", ROOT::RCmdLineOpts::kFlagPrefixArg); +} + +TEST(OptParse, PrefixMultiple) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"--D"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", + ROOT::RCmdLineOpts::kFlagAllowMultiple | ROOT::RCmdLineOpts::kFlagPrefixArg); + + const char *args[] = {"somename", "--D", "name", "--D=name", "--Dname"}; + opts.Parse(args, std::size(args)); + + EXPECT_TRUE(opts.GetErrors().empty()); + EXPECT_EQ(opts.GetFlagValues("D"), std::vector({"name", "=name", "name"})); +} + +TEST(OptParse, PrefixWithEqual) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"--D"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", + ROOT::RCmdLineOpts::kFlagAllowMultiple | ROOT::RCmdLineOpts::kFlagPrefixArg); + + const char *args[] = {"somename", "--Df=a", "--D", "f=a"}; + opts.Parse(args, std::size(args)); + + EXPECT_TRUE(opts.GetErrors().empty()); + EXPECT_EQ(opts.GetFlagValues("D"), std::vector({"f=a", "f=a"})); +} + +TEST(OptParse, PrefixShortMulticharacter) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"-includeI"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", + ROOT::RCmdLineOpts::kFlagAllowMultiple | ROOT::RCmdLineOpts::kFlagPrefixArg); + + const char *args[] = {"somename", "-includeI/foo/bar", "-includeI", "/foo/bar"}; + opts.Parse(args, std::size(args)); + + EXPECT_TRUE(opts.GetErrors().empty()); + EXPECT_EQ(opts.GetFlagValues("includeI"), std::vector({"/foo/bar", "/foo/bar"})); +} + +TEST(OptParse, PrefixDisablesGrouping) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"-D"}, ROOT::RCmdLineOpts::EFlagType::kWithArg, "", ROOT::RCmdLineOpts::kFlagPrefixArg); + opts.AddFlag({"-e"}, ROOT::RCmdLineOpts::EFlagType::kSwitch); + opts.AddFlag({"-f"}, ROOT::RCmdLineOpts::EFlagType::kSwitch); + + const char *args[] = {"somename", "-efDfoo"}; + opts.Parse(args, std::size(args)); + + EXPECT_GT(opts.GetErrors().size(), 0); + EXPECT_TRUE(opts.GetFlagValues("D").empty()); +} + +TEST(OptParse, PrefixSwitch) +{ + ROOT::RCmdLineOpts opts; + try { + opts.AddFlag({"-D"}, ROOT::RCmdLineOpts::EFlagType::kSwitch, "", ROOT::RCmdLineOpts::kFlagPrefixArg); + FAIL() << "adding a Switch with FlagPrefixArg should fail"; + } catch (const std::invalid_argument &ex) { + EXPECT_STREQ(ex.what(), "Flag `-D` has option kFlagPrefixArg but it's a Switch, so the option makes no sense."); + } +} + +TEST(OptParse, EmptyAliases) +{ + ROOT::RCmdLineOpts opts; + try { + opts.AddFlag({}, ROOT::RCmdLineOpts::EFlagType::kSwitch); + FAIL() << "adding a flag with no names should fail"; + } catch (const std::invalid_argument &ex) { + EXPECT_STREQ(ex.what(), "AddFlag must receive at least 1 name for the flag!"); + } +} + +TEST(OptParse, DuplicateFlag) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"-a"}, ROOT::RCmdLineOpts::EFlagType::kSwitch); + try { + opts.AddFlag({"-a"}, ROOT::RCmdLineOpts::EFlagType::kSwitch); + FAIL() << "adding the same flag twice should fail"; + } catch (const std::invalid_argument &ex) { + EXPECT_STREQ(ex.what(), "Flag `a` was added multiple times. Note that adding flags with the same name but " + "different number of `-` can only be done as aliases of the same call to AddFlag()."); + } +} + +TEST(OptParse, DuplicateFlagLongShort) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"-a"}, ROOT::RCmdLineOpts::EFlagType::kSwitch); + try { + opts.AddFlag({"--a"}, ROOT::RCmdLineOpts::EFlagType::kSwitch); + FAIL() << "adding the same flag twice should fail"; + } catch (const std::invalid_argument &ex) { + EXPECT_STREQ(ex.what(), "Flag `a` was added multiple times. Note that adding flags with the same name but " + "different number of `-` can only be done as aliases of the same call to AddFlag()."); + } +} + +TEST(OptParse, DuplicateFlagLongShortOk) +{ + ROOT::RCmdLineOpts opts; + opts.AddFlag({"-a", "--a"}, ROOT::RCmdLineOpts::EFlagType::kSwitch); +} + +TEST(OptParse, DuplicateFlagAlias) +{ + ROOT::RCmdLineOpts opts; + try { + opts.AddFlag({"--a", "--a"}, ROOT::RCmdLineOpts::EFlagType::kSwitch); + FAIL() << "adding the same flag twice should fail"; + } catch (const std::invalid_argument &ex) { + EXPECT_STREQ(ex.what(), "The same flag `--a` was passed multiple times to AddFlag()."); + } +}