Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
optparse.hxx
Go to the documentation of this file.
1/// \file optparse.hxx
2/// \author Giacomo Parolini <giacomo.parolini@cern.ch>
3/// \date 2025-10-09
4#ifndef ROOT_OptParse
5#define ROOT_OptParse
6
7#include <algorithm>
8#include <cassert>
9#include <charconv>
10#include <cstring>
11#include <cstdint>
12#include <iostream>
13#include <limits>
14#include <optional>
15#include <sstream>
16#include <stdexcept>
17#include <string>
18#include <string_view>
19#include <vector>
20
21namespace ROOT {
22
23/// \brief Small utility to parse cmdline options.
24///
25/// Usage:
26/// ~~~{.cpp}
27/// MyAppOpts ParseArgs(const char **args, int nArgs) {
28/// ROOT::RCmdLineOpts opts;
29/// // will parse '-c VAL', '--compress VAL' or '--compress=VAL'
30/// opts.AddFlag({"-c", "--compress"}, RCmdLineOpts::EFlagType::kWithArg);
31/// // will toggle a switch '--recreate' (no args).
32/// opts.AddFlag({"--recreate"});
33/// opts.AddFlag({"-o"}, RCmdLineOpts::EFlagType::kWithArg);
34///
35/// // NOTE: `args` should not contain the program name! It should usually be `argv + 1`.
36/// // For example `main(int argc, const char **argv)` might call this function as:
37/// // `ParseArgs(argv + 1, argc - 1);`
38/// opts.Parse(args, nArgs);
39///
40/// // Check for errors:
41/// for (const auto &err : opts.GetErrors()) {
42/// // print errors ...
43/// }
44/// if (!opts.GetErrors().empty()) return {};
45///
46/// // Convert the parsed options from string if necessary:
47/// MyAppOpts myOpts;
48/// // switch (boolean flag):
49/// myOpts.fRecreate = opts.GetSwitch("recreate");
50/// // string flag:
51/// myOpts.fOutput = opts.GetFlagValue("o");
52/// // integer flag:
53/// myOpts.fCompression = opts.GetFlagValueAs<int>("compress"); // (could also have used "c" instead of "compress")
54/// // positional arguments:
55/// myOpts.fArgs = opts.GetArgs();
56///
57/// return myOpts;
58/// }
59/// ~~~
60///
61/// ## Additional Notes
62///
63/// ### Flag grouping
64/// By default, if all the short flags you pass (those starting with a single `-`) are 1 character long, the parser will
65/// accept grouped flags like "-abc" as equivalent to "-a -b -c". The last flag in the group may also accept an
66/// argument, in which case "-abc foo" will count as "-a -b -c foo" where "foo" is the argument to "-c". If you want to
67/// disable flag grouping, use:
68///
69/// ~~~{.cpp}
70/// ROOT::RCmdLineOpts opts({ EFlagTreatment::kSimple });
71/// ~~~
72///
73/// ### Repeated flags
74/// Multiple repeated flags, like `-vvv`, are supported but must explicitly be marked as such on a per-flag basis:
75/// ~~~{.cpp}
76/// opts.AddFlag({"-v"}, RCmdLineOpts::EFlagType::kSwitch, "", RCmdLineOpts::kFlagAllowMultiple);
77/// ~~~
78/// This works both for switches and flags with arguments. `GetSwitch` returns the number of times a specific flag
79/// appeared; for flags with arguments `GetFlagValues` and `GetFlagValuesAs<T>` can be used to access the values as
80/// vectors.
81///
82/// ### Positional argument separator
83/// The string "--" is treated as the positional argument separator: all strings after it will be treated as positional
84/// arguments even if they start with "-".
85///
86/// ## Prefix flags (aka no space between flag and argument)
87/// If you need your flags to support the syntax "-fXYZ" where "-f" is your flag and "XYZ" its argument, you can enable
88/// that per-flag by using `RCmdLineOpts::kFlagPrefixArg`:
89///
90/// ~~~{.cpp}
91/// opts.AddFlag({"-I", "--include"}, RCmdLineOpts::EFlagType::kWithArg, RCmdLineOpts::kFlagPrefixArg });
92/// ~~~
93///
94/// (see EFlagTreatment for more details). This will **disable** flag grouping globally, but allows the parser to
95/// interpret flags and arguments that are not separated by spaces. If prefix arg is used, the equal sign will *not*
96/// be considered as the key-value separator (`-Dfoo=bar` if `-D` is a prefix arg flag will be parsed as `"-D",
97/// "foo=bar"`). Note that this option only makes sense for flags with arguments.
99public:
100 enum class EFlagTreatment {
101 /// Will result to kGrouped if you don't define any short flag longer than 1 character, otherwise kSimple.
102 kDefault,
103 /// `-abc` will always be treated as the single flag "-abc"
104 kSimple,
105 /// `-abc` will be treated as "-a -b -c". This is only valid for short flags.
106 /// With this setting you cannot define short flags that are more than 1 character long nor ones that are marked
107 /// with kFlagPrefixArg.
108 kGrouped,
109 };
110
111 struct RSettings {
112 /// Affects how flags are parsed (\see EFlagTreatment).
115
117 };
118
119 enum class EFlagType {
120 kSwitch,
122 };
123
124 struct RFlag {
125 std::string fName;
126 std::string fValue;
127 std::string fHelp;
128 // Index into the given array of arguments
129 std::size_t fIndex = 0;
130 };
131
132 // Technically these are bit flags, but EFlagFlag is confusing, so let's call them opts.
133 enum EFlagOpt {
134 /// Flag is allowed to appear multiple times (default: it's an error to see the same flag twice)
136 /// Flag argument can appear right after this flag without a space or equal sign in between.
137 /// Note that marking any short flag with this disables flag grouping!
139 };
140
141private:
143 /// Flags, in order of appearance
144 std::vector<RFlag> fFlags;
145 /// Positional arguments, in order of appearance
146 std::vector<std::string> fArgs;
147 std::vector<std::size_t> fArgIndices;
148 /// Index of the first element in fArgs that appeared after `--`.
149 std::optional<std::size_t> fFirstPostDashDashArg;
150 /// Indices of all args passed to Parse() that were skipped.
151 std::vector<std::size_t> fUnprocessedArgsIndices;
152
155 std::string fName;
156 std::string fHelp;
157 // If >= 0, this flag is an alias of the RExpectedFlag at index fAlias.
158 int fAlias = -1;
159 bool fShort = false;
160 // A bitmask of EFlagOpt
161 std::uint32_t fOpts = 0;
162
163 std::string AsStr() const { return std::string(fShort ? "-" : "--") + fName; }
164 };
165 std::vector<RExpectedFlag> fExpectedFlags;
166 std::vector<std::string> fErrors;
167
168 const RExpectedFlag *GetExpectedFlag(std::string_view name) const
169 {
170 const auto StartsWith = [](std::string_view string, std::string_view prefix) {
171 return string.size() >= prefix.size() && string.substr(0, prefix.size()) == prefix;
172 };
173
174 for (const auto &flag : fExpectedFlags) {
175 if (flag.fOpts & kFlagPrefixArg) {
176 if (StartsWith(name, flag.fName)) {
177 // NOTE: we can't have ambiguities here because we make sure that no flags share a common prefix in
178 // AddFlag().
179 return &flag;
180 }
181 } else if (flag.fName == name) {
182 return &flag;
183 }
184 }
185 return nullptr;
186 }
187
188public:
189 explicit RCmdLineOpts(RSettings settings = {}) : fSettings(settings) {}
190
191 const RSettings &GetSettings() const { return fSettings; }
192
193 /// Returns all parsing errors
194 const std::vector<std::string> &GetErrors() const { return fErrors; }
195
196 /// Retrieves all positional arguments
197 const std::vector<std::string> &GetArgs() const { return fArgs; }
198
199 /// Retrieves all positional arguments alongside their original position in the given args array.
200 std::vector<std::pair<std::size_t, std::string>> GetArgsWithIndices() const
201 {
202 assert(fArgs.size() == fArgIndices.size());
203 std::vector<std::pair<std::size_t, std::string>> res;
204 res.reserve(fArgs.size());
205 for (std::size_t i = 0; i < fArgs.size(); ++i) {
206 res.emplace_back(fArgIndices[i], fArgs[i]);
207 }
208 return res;
209 }
210
211 /// Retrieves all parsed flags
212 const std::vector<RFlag> &GetFlags() const { return fFlags; }
213
214 /// Conveniency method to print any errors to `stream`.
215 /// \return true if any error was printed
216 bool ReportErrors(std::ostream &stream = std::cerr) const
217 {
218 for (const auto &err : fErrors)
219 stream << err << "\n";
220 return !fErrors.empty();
221 }
222
223 /// Defines a new flag (either a switch or a flag with argument).
224 /// The flag may be referred to as any of the values inside `aliases` (e.g. { "-h", "--help" }).
225 /// You must pass at least 1 string inside `aliases`.
226 /// All strings inside `aliases` must start with `-` or `--` and be at least 1 character long (aside the dashes).
227 /// Flags starting with a single `-` are considered "short", regardless of their actual length.
228 /// If all short flags are 1 character long, they may be collapsed into one and parsed as individual flags
229 /// (meaning a string like "-fgk" will be parsed as "-f -g -k") and the final flag may have a following argument.
230 /// This does NOT happen if any short flag is longer than 1 character, to avoid ambiguity.
231 ///
232 /// \param aliases All the equivalent names of this flag
233 /// \param type What kind of flag is this: with arguments or not
234 /// \param help Help string for the flag
235 /// \param flagOpts Bitmask of EFlagOpt for additional options
236 /// \throw std::invalid_argument if `aliases` is empty.
237 /// \throw std::invalid_argument if `flagOpts` and `type` are inconsistent (e.g. a Switch is given the opt
238 /// `kFlagPrefixArg`).
239 /// \throw std::invalid_argument if any flag in `aliases` does not start with `-` or is empty after the prefix.
240 /// \throw std::invalid_argument if any of the values in `aliases` was already added previously.
241 /// \throw std::invalid_argument if the same value appears multiple times in `aliases`.
242 /// \throw std::invalid_argument if any of the values in `aliases` have a common prefix with another flag which is
243 /// marked as `kFlagPrefixArg`.
244 /// \throw std::invalid_argument if the flag treatment was explicitly specified as kGrouped but a short flag is given
245 /// in `aliases` which is longer than one character.
246 void AddFlag(std::initializer_list<std::string_view> aliases, EFlagType type = EFlagType::kSwitch,
247 std::string_view help = "", std::uint32_t flagOpts = 0)
248 {
249 const auto IsPrefixOf = [](std::string_view a, std::string_view b) {
250 return a.size() < b.size() && std::equal(a.begin(), a.end(), b.begin());
251 };
252
253 if (aliases.size() == 0)
254 throw std::invalid_argument("AddFlag must receive at least 1 name for the flag!");
255
256 if ((flagOpts & kFlagPrefixArg) && type != EFlagType::kWithArg)
257 throw std::invalid_argument("Flag `" + std::string(*aliases.begin()) +
258 "` has option kFlagPrefixArg but it's a Switch, so the option makes no sense.");
259
260 std::vector<RExpectedFlag> flagsToBeAdded;
261 flagsToBeAdded.reserve(aliases.size());
262
263 const auto nCurrentFlags = fExpectedFlags.size();
264 int aliasIdx = -1;
265 for (auto f : aliases) {
266 auto prefixLen = f.find_first_not_of('-');
267 if (prefixLen != 1 && prefixLen != 2)
268 throw std::invalid_argument(std::string("Invalid flag `") + std::string(f) +
269 "`: flags must start with '-' or '--'");
270 if (f.size() == prefixLen)
271 throw std::invalid_argument("Flag name cannot be empty");
272
273 auto flagName = f.substr(prefixLen);
274
275 // Check that we're not introducing ambiguities with prefix flags.
276 // While we're at it, also check that none of the given aliases were already added. Note that it is valid to
277 // add the same flag name as both a long and short flag (like "-foo" and "--foo") but only if they are aliases
278 // of the same flag.
279 for (const auto &expFlag : fExpectedFlags) {
280 if (expFlag.fName == flagName) {
281 throw std::invalid_argument(
282 "Flag `" + std::string(flagName) +
283 "` was added multiple times. Note that adding flags with the same name but different number of `-` "
284 "can only be done as aliases of the same call to AddFlag().");
285 }
286
287 if (!(flagOpts & kFlagPrefixArg) && !(expFlag.fOpts & kFlagPrefixArg))
288 continue;
289
290 // At least one of expFlag and f is a prefix flag: this means that they must not share a common prefix.
291 if (((expFlag.fOpts & kFlagPrefixArg) && IsPrefixOf(expFlag.fName, flagName)) ||
292 ((flagOpts & kFlagPrefixArg) && IsPrefixOf(flagName, expFlag.fName))) {
293 throw std::invalid_argument("Flags `" + expFlag.AsStr() + "` and `" + std::string(f) +
294 "` have a common prefix. This causes ambiguity because at least one of them "
295 "is marked with kFlagPrefixArg.");
296 }
297 }
298
299 // Check that the user didn't pass the very same flag multiple times in the same AddFlag invocation, as that's
300 // likely a mistake. This is different from the check done in the previous loop as that one only concerns
301 // flags that were already added before this AddFlag invocation.
302 for (const auto &expFlag : flagsToBeAdded) {
303 if (expFlag.AsStr() == f)
304 throw std::invalid_argument("The same flag `" + expFlag.AsStr() +
305 "` was passed multiple times to AddFlag().");
306 }
307
308 bool disallowsGrouping = (prefixLen == 1 && (f.size() > 2 || (flagOpts & kFlagPrefixArg)));
309 if (disallowsGrouping) {
313 throw std::invalid_argument(
314 std::string("Flags starting with a single dash must be 1 character long when `FlagTreatment == "
315 "EFlagTreatment::kGrouped'! Cannot accept given flag `") +
316 std::string(f) + "`");
317 }
318 }
319
320 RExpectedFlag expected;
321 expected.fFlagType = type;
322 expected.fName = flagName;
323 expected.fHelp = help;
324 expected.fAlias = aliasIdx;
325 expected.fShort = prefixLen == 1;
326 expected.fOpts = flagOpts;
327 flagsToBeAdded.push_back(expected);
328 if (aliasIdx < 0)
329 aliasIdx = nCurrentFlags + flagsToBeAdded.size() - 1;
330 }
331
332 fExpectedFlags.insert(fExpectedFlags.end(), flagsToBeAdded.begin(), flagsToBeAdded.end());
333 }
334
335 /// If `name` refers to a previously-defined switch (i.e. a boolean flag), returns how many times
336 /// the flag appeared (this will never be more than 1 unless the flag is allowed to appear multiple times).
337 /// \throw std::invalid_argument if the flag was undefined or defined as a flag with arguments
338 int GetSwitch(std::string_view name) const
339 {
340 const auto *exp = GetExpectedFlag(name);
341 if (!exp)
342 throw std::invalid_argument(std::string("Flag `") + std::string(name) + "` is not expected");
343 if (exp->fFlagType != EFlagType::kSwitch)
344 throw std::invalid_argument(std::string("Flag `") + std::string(name) + "` is not a switch");
345
346 std::string_view lookedUpName = name;
347 if (exp->fAlias >= 0)
348 lookedUpName = fExpectedFlags[exp->fAlias].fName;
349
350 int n = 0;
351 for (const auto &f : fFlags) {
352 n += f.fName == lookedUpName;
353 }
354 return n;
355 }
356
357 /// If `name` refers to a previously-defined non-switch flag, gets its value.
358 /// Throws the same exceptions as GetFlagValues
359 std::string_view GetFlagValue(std::string_view name) const
360 {
361 auto values = GetFlagValues(name);
362 return values.empty() ? "" : values[0];
363 }
364
365 /// If `name` refers to a previously-defined non-switch flag, gets its values.
366 /// This will never return more than 1 value unless the flag is allowed to appear multiple times.
367 /// \throw std::invalid_argument if the flag was undefined or defined as a switch flag
368 std::vector<std::string_view> GetFlagValues(std::string_view name) const
369 {
370 const auto *exp = GetExpectedFlag(name);
371 if (!exp)
372 throw std::invalid_argument(std::string("Flag `") + std::string(name) + "` is not expected");
373 if (exp->fFlagType != EFlagType::kWithArg)
374 throw std::invalid_argument(std::string("Flag `") + std::string(name) + "` is a switch, use GetSwitch()");
375
376 std::string_view lookedUpName = name;
377 if (exp->fAlias >= 0)
378 lookedUpName = fExpectedFlags[exp->fAlias].fName;
379
380 std::vector<std::string_view> values;
381 for (const auto &f : fFlags) {
382 if (f.fName == lookedUpName)
383 values.push_back(f.fValue);
384 }
385 return values;
386 }
387
388 /// Tries to retrieve the flag value as a type T.
389 /// The only supported types are integral and floating point types.
390 /// \return A value of type T if the flag is present and convertible
391 /// \return nullopt if the flag is not there
392 /// \throw std::invalid_argument if the flag was undefined or defined as a switch flag.
393 /// \throw std::runtime_error if the flag is there but not convertible.
394 template <typename T>
395 std::optional<T> GetFlagValueAs(std::string_view name) const
396 {
397 auto values = GetFlagValuesAs<T>(name);
398 return values.empty() ? std::nullopt : std::make_optional(values[0]);
399 }
400
401 /// Tries to retrieve the flag values as a type T.
402 /// The only supported types are integral and floating point types.
403 /// \return An array of values of type T if the flag is present and all its values are convertible to T
404 /// \throw std::invalid_argument if the flag was undefined or defined as a switch flag.
405 /// \throw std::runtime_error if the flag has values but any of them is not convertible.
406 template <typename T>
407 std::vector<T> GetFlagValuesAs(std::string_view name) const
408 {
409 static_assert(std::is_integral_v<T> || std::is_floating_point_v<T>);
410
411 std::vector<T> values;
412 for (auto val : GetFlagValues(name)) {
413 // NOTE: on paper std::from_chars is supported since C++17, however some compilers don't properly support it
414 // (e.g. it's not available at all on MacOS < 26 and only the integer overload is available in AlmaLinux 8).
415 // There is also no compiler define that we can use to determine the availability, so we just use it only
416 // from C++20 and hope for the best.
417#if __cplusplus >= 202002L && !defined(__APPLE__)
418 T converted;
419 auto res = std::from_chars(val.data(), val.data() + val.size(), converted);
420 if (res.ptr == val.data() + val.size() && res.ec == std::errc{}) {
421 values.push_back(converted);
422 } else {
423 std::stringstream err;
424 err << "Failed to parse flag `" << name << "` with value `" << val << "`";
425 if constexpr (std::is_integral_v<T>)
426 err << " as an integer.\n";
427 else
428 err << " as a floating point number.\n";
429
430 throw std::runtime_error(err.str());
431 }
432#else
433 std::conditional_t<std::is_integral_v<T>, long long, long double> converted = 0;
434 std::size_t unconvertedPos = 0;
435 try {
436 if constexpr (std::is_integral_v<T>) {
437 converted = std::stoll(std::string(val), &unconvertedPos);
438 } else {
439 converted = std::stold(std::string(val), &unconvertedPos);
440 }
441 } catch (...) {
442 unconvertedPos = 0;
443 }
444
445 if (unconvertedPos != val.size() || converted > std::numeric_limits<T>::max()) {
446 std::stringstream err;
447 err << "Failed to parse flag `" << name << "` with value `" << val << "`";
448 if constexpr (std::is_integral_v<T>)
449 err << " as an integer.\n";
450 else
451 err << " as a floating point number.\n";
452
453 throw std::runtime_error(err.str());
454 }
455
456 values.push_back(converted);
457#endif
458 }
459 return values;
460 }
461
462 /// Parses the given arguments, allowing for their retrieval via GetSwitch, GetFlagValue, etc.
463 void Parse(const char *const *const args, std::size_t nArgs)
464 {
465 bool forcePositional = false;
466
467 // If flag treatment is still Default by now it means we can safely group short flags (otherwise we'd have
468 // already changed it to Simple).
471
472 // Contains one or more flags coming from one of the arguments (e.g. "-abc" may be split
473 // into flags "a", "b", and "c", which will be stored in `argStr`).
474 std::vector<std::string_view> argStr;
475
476 for (std::size_t argIndex = 0; argIndex < nArgs && fErrors.empty(); ++argIndex) {
477 const char *arg = args[argIndex];
478 const char *const argOrig = arg;
479 const auto argIndexOrig = argIndex;
480
481 if (strcmp(arg, "--") == 0 && !forcePositional) {
482 forcePositional = true;
483 continue;
484 }
485
486 bool isFlag = !forcePositional && arg[0] == '-';
487 if (!isFlag) {
488 // positional argument
489 if (forcePositional && !fFirstPostDashDashArg)
491 fArgs.push_back(arg);
492 fArgIndices.push_back(argIndex);
493 continue;
494 }
495
496 ++arg; // eat first `-`.
497
498 // Parse long or short flag and its argument into `argStr` / `nxtArgStr`.
499 // Note that `argStr` may contain multiple flags in case of grouped short flags (in which case nxtArgStr
500 // refers only to the last one).
501 argStr.clear();
502 std::string_view nxtArgStr;
503 // If this is false `nxtArgStr` *must* refer to the next arg, otherwise it might or might not be.
504 bool nxtArgIsTentative = true;
505 if (arg[0] == '-') {
506 // long flag
507 ++arg;
508
509 // if we have prefix flags we need to check them first, as in that case the `=` sign should not be treated
510 // as the key-value separator.
511 const auto argLen = strlen(arg);
512 for (const auto &flag : fExpectedFlags) {
513 if ((flag.fOpts & kFlagPrefixArg) && flag.fName.size() < argLen &&
514 strncmp(arg, flag.fName.c_str(), flag.fName.size()) == 0) {
515 argStr.push_back(std::string_view(arg, flag.fName.size()));
516 nxtArgStr = std::string_view(arg + flag.fName.size(), argLen - flag.fName.size());
517 break;
518 }
519 }
520
521 if (argStr.empty()) {
522 const char *eq = strchr(arg, '=');
523 if (eq) {
524 argStr.push_back(std::string_view(arg, eq - arg));
525 nxtArgStr = std::string_view(eq + 1);
526 nxtArgIsTentative = false;
527 } else {
528 argStr.push_back(std::string_view(arg));
529 if (argIndex < nArgs - 1 && args[argIndex + 1][0] != '-') {
530 nxtArgStr = args[argIndex + 1];
531 ++argIndex;
532 }
533 }
534 }
535 } else {
536 // short flag.
537 // If flag grouping is active, all flags except the last one will have an implicitly empty argument.
538 auto argLen = strlen(arg);
539 while (fSettings.fFlagTreatment == EFlagTreatment::kGrouped && argLen > 1) {
540 argStr.push_back(std::string_view{arg, 1});
541 ++arg, --argLen;
542 }
543
544 argStr.push_back(std::string_view(arg));
545 if (argIndex < nArgs - 1 && args[argIndex + 1][0] != '-') {
546 nxtArgStr = args[argIndex + 1];
547 ++argIndex;
548 }
549 }
550
551 assert(argStr.size() < 2 || fSettings.fFlagTreatment == EFlagTreatment::kGrouped);
552
553 for (auto j = 0u; j < argStr.size(); ++j) {
554 std::string_view argS = argStr[j];
555
556 const auto *exp = GetExpectedFlag(argS);
557 if (!exp) {
559 fUnprocessedArgsIndices.push_back(argIndexOrig);
560 continue;
561 } else {
562 fErrors.push_back(std::string("Unknown flag: ") + argOrig);
563 break;
564 }
565 }
566
567 // In Prefix mode, check if the returned expected flag is shorter than `argS`. This can mean two things:
568 // - if `nxtArgIsTentative == false` then this flag was followed by an equal sign, and in that case
569 // the intention is interpreted as "I want this flag's argument to be whatever follows the equal sign",
570 // which means we treat this as an unknown flag;
571 // - otherwise, we use the rest of `argS` as the argument to the flag.
572 // More concretely: if the user added flag "-D" and argS is "-Dfoo=bar", we parse it as
573 // {flag: "-Dfoo", arg: "bar"}, rather than {flag: "-D", arg: "foo=bar"}.
574 if ((exp->fOpts & kFlagPrefixArg) && argS.size() > exp->fName.size()) {
575 if (nxtArgIsTentative) {
576 argIndex -= !nxtArgStr.empty(); // if we had already picked a candidate next arg, undo that.
577 nxtArgStr = argS.substr(exp->fName.size());
578 nxtArgIsTentative = false;
579 } else if (fSettings.fIgnoreUnknownFlags) {
580 fUnprocessedArgsIndices.push_back(argIndexOrig);
581 continue;
582 } else {
583 fErrors.push_back(std::string("Unknown flag: ") + argOrig);
584 break;
585 }
586 } else {
587 assert(exp->fName.size() == argS.size());
588 }
589
590 std::string_view nxtArg = (j == argStr.size() - 1) ? nxtArgStr : "";
591
593 flag.fIndex = argIndexOrig;
594 flag.fHelp = exp->fHelp;
595 // If the flag is an alias (e.g. long version of a short one), save its name as the aliased one, so we
596 // can fetch the value later by using any of the aliases.
597 if (exp->fAlias < 0)
598 flag.fName = exp->fName;
599 else
600 flag.fName = fExpectedFlags[exp->fAlias].fName;
601
602 // Check for duplicate flags
603 if (!(exp->fOpts & kFlagAllowMultiple)) {
604 auto existingIt =
605 std::find_if(fFlags.begin(), fFlags.end(), [&flag](const auto &f) { return f.fName == flag.fName; });
606 if (existingIt != fFlags.end()) {
607 std::string err = std::string("Flag ") + exp->AsStr() + " appeared more than once";
608 if (exp->fFlagType == RCmdLineOpts::EFlagType::kWithArg)
609 err += " with the value: " + existingIt->fValue;
610 fErrors.push_back(err);
611 break;
612 }
613 }
614
615 // Check that arguments are what we expect.
616 if (exp->fFlagType == RCmdLineOpts::EFlagType::kWithArg) {
617 if (!nxtArg.empty()) {
618 flag.fValue = nxtArg;
619 } else {
620 fErrors.push_back("Missing argument for flag " + exp->AsStr());
621 }
622 } else {
623 if (!nxtArg.empty()) {
624 if (nxtArgIsTentative)
625 --argIndex;
626 else
627 fErrors.push_back("Flag " + exp->AsStr() + " does not expect an argument");
628 }
629 }
630
631 if (!fErrors.empty())
632 break;
633
634 fFlags.push_back(flag);
635 }
636
637 if (!fErrors.empty())
638 break;
639 }
640 }
641
642 /// Returns the index of the first positional argument that appeared after `--`. If not null, it is guaranteed
643 /// to be less than the size of GetArgs().
644 std::optional<std::size_t> GetFirstPostDashDashArg() const { return fFirstPostDashDashArg; }
645
646 /// Returns a list of the indices of all args passed to Parse() that were not parsed.
647 /// This will typically be empty, unless the RCmdLineOpts was created with `fIgnoreUnknownFlags == true`, in which
648 /// case this will contain all skipped unknown flags.
649 const std::vector<std::size_t> &GetUnprocessedArgsIndices() const { return fUnprocessedArgsIndices; }
650};
651
652} // namespace ROOT
653
654#endif
#define b(i)
Definition RSha256.hxx:100
#define f(i)
Definition RSha256.hxx:104
#define a(i)
Definition RSha256.hxx:99
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
char name[80]
Definition TGX11.cxx:142
Small utility to parse cmdline options.
Definition optparse.hxx:98
std::vector< RFlag > fFlags
Flags, in order of appearance.
Definition optparse.hxx:144
@ kSimple
-abc will always be treated as the single flag "-abc"
@ kDefault
Will result to kGrouped if you don't define any short flag longer than 1 character,...
@ kGrouped
-abc will be treated as "-a -b -c".
const RExpectedFlag * GetExpectedFlag(std::string_view name) const
Definition optparse.hxx:168
void AddFlag(std::initializer_list< std::string_view > aliases, EFlagType type=EFlagType::kSwitch, std::string_view help="", std::uint32_t flagOpts=0)
Defines a new flag (either a switch or a flag with argument).
Definition optparse.hxx:246
void Parse(const char *const *const args, std::size_t nArgs)
Parses the given arguments, allowing for their retrieval via GetSwitch, GetFlagValue,...
Definition optparse.hxx:463
const std::vector< std::string > & GetErrors() const
Returns all parsing errors.
Definition optparse.hxx:194
int GetSwitch(std::string_view name) const
If name refers to a previously-defined switch (i.e.
Definition optparse.hxx:338
std::vector< std::size_t > fArgIndices
Definition optparse.hxx:147
const std::vector< std::string > & GetArgs() const
Retrieves all positional arguments.
Definition optparse.hxx:197
std::vector< T > GetFlagValuesAs(std::string_view name) const
Tries to retrieve the flag values as a type T.
Definition optparse.hxx:407
const std::vector< std::size_t > & GetUnprocessedArgsIndices() const
Returns a list of the indices of all args passed to Parse() that were not parsed.
Definition optparse.hxx:649
std::string_view GetFlagValue(std::string_view name) const
If name refers to a previously-defined non-switch flag, gets its value.
Definition optparse.hxx:359
std::vector< RExpectedFlag > fExpectedFlags
Definition optparse.hxx:165
const std::vector< RFlag > & GetFlags() const
Retrieves all parsed flags.
Definition optparse.hxx:212
std::vector< std::size_t > fUnprocessedArgsIndices
Indices of all args passed to Parse() that were skipped.
Definition optparse.hxx:151
std::vector< std::string > fArgs
Positional arguments, in order of appearance.
Definition optparse.hxx:146
std::vector< std::string_view > GetFlagValues(std::string_view name) const
If name refers to a previously-defined non-switch flag, gets its values.
Definition optparse.hxx:368
std::optional< std::size_t > GetFirstPostDashDashArg() const
Returns the index of the first positional argument that appeared after --.
Definition optparse.hxx:644
RSettings fSettings
Definition optparse.hxx:142
bool ReportErrors(std::ostream &stream=std::cerr) const
Conveniency method to print any errors to stream.
Definition optparse.hxx:216
RCmdLineOpts(RSettings settings={})
Definition optparse.hxx:189
std::optional< T > GetFlagValueAs(std::string_view name) const
Tries to retrieve the flag value as a type T.
Definition optparse.hxx:395
@ kFlagPrefixArg
Flag argument can appear right after this flag without a space or equal sign in between.
Definition optparse.hxx:138
@ kFlagAllowMultiple
Flag is allowed to appear multiple times (default: it's an error to see the same flag twice)
Definition optparse.hxx:135
const RSettings & GetSettings() const
Definition optparse.hxx:191
std::vector< std::pair< std::size_t, std::string > > GetArgsWithIndices() const
Retrieves all positional arguments alongside their original position in the given args array.
Definition optparse.hxx:200
std::optional< std::size_t > fFirstPostDashDashArg
Index of the first element in fArgs that appeared after --.
Definition optparse.hxx:149
std::vector< std::string > fErrors
Definition optparse.hxx:166
const Int_t n
Definition legend1.C:16
bool StartsWith(std::string_view string, std::string_view prefix)
EFlagTreatment fFlagTreatment
Affects how flags are parsed (.
Definition optparse.hxx:113