util/OptionParser: collect remaining arguments

Allow the caller to use a simple "for" loop without checking
arguments.
This commit is contained in:
Max Kellermann 2018-01-16 11:03:04 +01:00
parent 0066f7a818
commit 68f660dbcc
3 changed files with 13 additions and 10 deletions

View File

@ -357,11 +357,9 @@ ParseCommandLine(int argc, char **argv, struct options *options)
// Second pass: find non-option parameters (i.e. config file) // Second pass: find non-option parameters (i.e. config file)
const char *config_file = nullptr; const char *config_file = nullptr;
for (int i = 1; i < argc; ++i) { for (const char *i : parser.GetRemaining()) {
if (OptionParser::IsOption(argv[i]))
continue;
if (config_file == nullptr) { if (config_file == nullptr) {
config_file = argv[i]; config_file = i;
continue; continue;
} }

View File

@ -53,7 +53,9 @@ OptionParser::ParseNext() noexcept
option_raw = arg; option_raw = arg;
return true; return true;
} }
option = nullptr; option = nullptr;
option_raw = nullptr; option_raw = nullptr;
*remaining_tail++ = arg;
return false; return false;
} }

View File

@ -36,12 +36,16 @@ class OptionParser
const char *option_raw = nullptr; const char *option_raw = nullptr;
bool is_long = false; bool is_long = false;
const char **const remaining_head, **remaining_tail;
public: public:
/** /**
* Constructs #OptionParser. * Constructs #OptionParser.
*/ */
constexpr OptionParser(int _argc, char *const*_argv) noexcept constexpr OptionParser(int _argc, char **_argv) noexcept
:args(_argv + 1, _argc - 1) {} :args(_argv + 1, _argc - 1),
remaining_head(const_cast<const char **>(_argv + 1)),
remaining_tail(remaining_head) {}
/** /**
* Checks if there are command line entries to process. * Checks if there are command line entries to process.
@ -81,11 +85,10 @@ public:
bool ParseNext() noexcept; bool ParseNext() noexcept;
/** /**
* Checks if specified string is a command line option. * Returns the remaining non-option arguments.
*/ */
static bool IsOption(const char *s) noexcept { ConstBuffer<const char *> GetRemaining() const noexcept {
assert(s != nullptr); return {remaining_head, remaining_tail};
return s[0] == '-';
} }
}; };