86 lines
2.7 KiB
C++
86 lines
2.7 KiB
C++
#pragma once
|
|
#include <optional>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
struct FlagInfo {
|
|
std::string canonical_name;
|
|
bool expects_arg;
|
|
std::optional<std::string> arg;
|
|
};
|
|
|
|
/// A class that provides a convenient interface for parsing commands.
|
|
class ArgsParser {
|
|
public:
|
|
/// Constructor from traditional argc, argv
|
|
ArgsParser(int argc, char** argv, bool keep_program_name = false);
|
|
|
|
/// @return True if there is another unconsumed token in the argument list.
|
|
bool has_next() const;
|
|
|
|
/// Retrieves then next unconsumed token in the argument list.
|
|
/// @return The next token in the argument list.
|
|
std::string get_next() const;
|
|
|
|
std::string consume_next();
|
|
|
|
/// Constructor from an existing vector of strings,
|
|
explicit ArgsParser(const std::vector<std::string>& value): args(value) {}
|
|
|
|
bool has_flag(const std::string& option);
|
|
|
|
bool has_flag(const std::initializer_list<std::string>& flags);
|
|
|
|
/// Searches the arguments for all given flag tokens, and removes all occurrences of it.
|
|
/// @return true if the flag was found in the arguments.
|
|
bool consume_flag(const std::string& option);
|
|
|
|
|
|
/// Searches the arguments for all given flag tokens, and removes them.
|
|
/// @return True if the flag was found in the arguments.
|
|
bool consume_flag(const std::initializer_list<std::string>& flags);
|
|
|
|
/// Searches for a specific flag and its argument.
|
|
bool has_flag_arg(const std::string& option);
|
|
|
|
/// Retrieves the argument for the given flag.
|
|
std::optional<std::string> get_flag_arg(const std::string& option);
|
|
|
|
/// Searches for a specific flag and its argument, removes both, and returns the argument.
|
|
std::optional<std::string> consume_flag_arg(const std::string& flag);
|
|
|
|
std::tuple<bool, std::string> consume_flag_arg(const std::initializer_list<std::string>& flags);
|
|
|
|
std::vector<std::string> get_remaining_args() const;
|
|
|
|
std::vector<std::string> get_unmatched() const { return get_remaining_args(); }
|
|
|
|
|
|
|
|
bool contains(const std::string& token) const;
|
|
bool has_flag_contains(const std::string& match);
|
|
|
|
std::optional<std::string> get_flag_contains(std::string& match) {
|
|
for (auto& token : args) {
|
|
if (token.find(match) != std::string::npos)
|
|
return token;
|
|
}
|
|
|
|
return std::nullopt;
|
|
}
|
|
|
|
bool has_flag_starts_with(const std::string& value) const;
|
|
std::string get_flag_starts_with(const std::string& prefix) const;
|
|
|
|
|
|
|
|
|
|
|
|
protected:
|
|
/// The list of arguments that have yet to be consumed.
|
|
std::vector<std::string> args{};
|
|
/// The full list of arguments originally passed to the instance. This vector will not be modified.
|
|
std::vector<std::string> original_args{};
|
|
private:
|
|
};
|