RSTools 3.1.0
Versatile C++20 utility library
Loading...
Searching...
No Matches
Argument.hpp
Go to the documentation of this file.
1#pragma once
2
4
5#include <cstddef>
6#include <cstdint>
7#include <format>
8#include <functional>
9#include <limits>
10#include <optional>
11#include <string>
12#include <string_view>
13#include <type_traits>
14#include <utility>
15#include <vector>
16
17namespace RST::Parser {
18
20 struct Nargs {
21 int min = 1;
22 int max = 1;
23
24 static Nargs exactly(int n) { return {n, n}; }
25 static Nargs atLeast(int n) { return {n, -1}; }
26 static Nargs between(int mn, int mx) { return {mn, mx}; }
27 static Nargs zeroOrMore() { return {0, -1}; }
28 static Nargs oneOrMore() { return {1, -1}; }
29 static Nargs optional() { return {0, 1}; }
30 };
31
32
41 class Argument {
42 public:
43 // ── Declaration ──────────────────────────────────────────────────────
45 template <typename T>
46 Argument& defaultValue(const T& value) { _defaultValue = std::format("{}", value); return *this; }
47
49 Argument& required(bool isRequired = true) { _required = isRequired; return *this; }
51 Argument& valueName(std::string name) { _valueName = std::move(name); return *this; }
53 Argument& nargs(int exactly) { return nargs(Nargs::exactly(exactly)); }
55 Argument& choices(std::vector<std::string> values) { _choices = std::move(values); return *this; }
57 Argument& integer() { _valueType = ValueType::Integer; return *this; }
59 Argument& number() { _valueType = ValueType::Number; return *this; }
61 Argument& range(double min, double max) { _range = {min, max}; return *this; }
63 Argument& mustExist() { _mustExist = true; return *this; }
65 Argument& extension(std::vector<std::string> extensions) { _extensions = std::move(extensions); return *this; }
67 Argument& envFallback(std::string variable) { _envVariable = std::move(variable); return *this; }
69 Argument& allowNegation() { _negatable = true; return *this; }
70
73 {
74 _nargs = count;
75 _required = _required && count.min > 0;
76 return *this;
77 }
78
80 Argument& validate(std::function<bool(const std::string&)> check, std::string message = "")
81 {
82 _check = std::move(check);
83 _checkMessage = std::move(message);
84 return *this;
85 }
86
87 // ── Result ───────────────────────────────────────────────────────────
89 [[nodiscard]] bool isSet() const noexcept { return _isSet; }
91 [[nodiscard]] std::size_t count() const noexcept { return _count; }
92
94 template <typename T = std::string>
95 [[nodiscard]] std::optional<T> get() const
96 {
97 if (!_values.empty())
98 return convert<T>(_values.back());
99 return _defaultValue ? convert<T>(*_defaultValue) : std::nullopt;
100 }
101
103 template <typename T = std::string>
104 [[nodiscard]] std::vector<T> getAll() const
105 {
106 std::vector<std::string> values = _values;
107 if (values.empty() && _defaultValue)
108 values.push_back(*_defaultValue);
109
110 std::vector<T> result;
111 for (const std::string& value : values) {
112 if (std::optional<T> converted = convert<T>(value))
113 result.push_back(std::move(*converted));
114 }
115 return result;
116 }
117
118 private:
119 friend class ArgParser;
120
121 enum class Kind : std::uint8_t { Flag, Option, Positional };
122 enum class ValueType : std::uint8_t { Text, Integer, Number };
123
124 Argument(Kind kind, std::vector<std::string> flags, std::string name, std::string description);
125
126 template <typename T>
127 [[nodiscard]] static std::optional<T> convert(const std::string& value)
128 {
129 if constexpr (std::is_same_v<T, bool>)
130 return String::parseBool(value);
131 else if constexpr (std::is_arithmetic_v<T>)
132 return String::parseNumber<T>(value);
133 else
134 return T(value);
135 }
136
137 [[nodiscard]] bool isFlag() const noexcept { return _kind == Kind::Flag; }
138 [[nodiscard]] bool isPositional() const noexcept { return _kind == Kind::Positional; }
139 [[nodiscard]] bool hasFlag(std::string_view flag) const;
140 [[nodiscard]] std::size_t minValues() const noexcept { return static_cast<std::size_t>(_nargs.min); }
141 [[nodiscard]] std::size_t maxValues() const noexcept { return _nargs.max < 0 ? std::numeric_limits<std::size_t>::max() : static_cast<std::size_t>(_nargs.max); }
142 [[nodiscard]] bool isFull() const noexcept { return _values.size() >= maxValues(); }
143
144 void add(const std::vector<std::string_view>& values);
145 void setFlag(bool value);
146 void setFallback(std::string value);
147 void clear();
148
149 [[nodiscard]] std::string displayName() const;
150 [[nodiscard]] std::string checkValue(const std::string& value) const;
151 [[nodiscard]] std::string helpFlags() const;
152 [[nodiscard]] std::string helpDetails() const;
153
154 Kind _kind;
155 std::vector<std::string> _flags;
156 std::string _name;
157 std::string _description;
158 std::string _valueName;
159 std::optional<std::string> _defaultValue;
160 std::string _envVariable;
161 std::vector<std::string> _choices;
162 std::vector<std::string> _extensions;
163 std::optional<std::pair<double, double>> _range;
164 std::function<bool(const std::string&)> _check;
165 std::string _checkMessage;
166 Nargs _nargs;
167 ValueType _valueType = ValueType::Text;
168 bool _required = false;
169 bool _negatable = false;
170 bool _mustExist = false;
171
172 std::vector<std::string> _values;
173 std::size_t _count = 0;
174 bool _isSet = false;
175 };
176}
Command-line parser with flags, options, positionals, subcommands and generated help.
Definition ArgParser.hpp:34
A flag, option or positional argument, configured with chained calls.
Definition Argument.hpp:41
bool isSet() const noexcept
Whether a value came from the command line, the environment or the config file.
Definition Argument.hpp:89
Argument & envFallback(std::string variable)
Reads the environment variable variable when the argument is not given.
Definition Argument.hpp:67
Argument & validate(std::function< bool(const std::string &)> check, std::string message="")
Custom check: values for which check returns false are rejected with message.
Definition Argument.hpp:80
std::size_t count() const noexcept
How many times the argument was given, such as 3 for -vvv.
Definition Argument.hpp:91
Argument & integer()
Only accepts integers.
Definition Argument.hpp:57
Argument & nargs(int exactly)
Takes exactly that many values.
Definition Argument.hpp:53
Argument & extension(std::vector< std::string > extensions)
Only accepts paths ending with one of extensions, such as .json.
Definition Argument.hpp:65
std::optional< T > get() const
The last value, or the default value, converted to T; std::nullopt if there is none or it does not co...
Definition Argument.hpp:95
Argument & range(double min, double max)
Only accepts numbers from min to max, inclusive.
Definition Argument.hpp:61
Argument & choices(std::vector< std::string > values)
Only accepts one of values.
Definition Argument.hpp:55
Argument & valueName(std::string name)
Name of the value in the help, such as FILE.
Definition Argument.hpp:51
Argument & number()
Only accepts numbers.
Definition Argument.hpp:59
Argument & defaultValue(const T &value)
Value used when the argument is not given.
Definition Argument.hpp:46
Argument & required(bool isRequired=true)
Makes the argument mandatory.
Definition Argument.hpp:49
Argument & mustExist()
Only accepts paths that exist.
Definition Argument.hpp:63
std::vector< T > getAll() const
Every value converted to T, skipping those that do not convert, or the default value.
Definition Argument.hpp:104
Argument & nargs(Nargs count)
How many values to take, such as Nargs::oneOrMore().
Definition Argument.hpp:72
Argument & allowNegation()
Lets --no-name unset a flag declared as --name.
Definition Argument.hpp:69
Command-line parser with subcommands, typed and validated values and generated help.
Definition ArgParser.hpp:17
constexpr std::optional< bool > parseBool(std::string_view text) noexcept
Parses true, yes, on, 1 or false, no, off, 0, ignoring case.
Definition Convert.hpp:49
std::optional< T > parseNumber(std::string_view text, int base=10) noexcept
Parses text as a number, or returns std::nullopt if it is not entirely one.
Definition Convert.hpp:23
How many values an option or positional takes.
Definition Argument.hpp:20
static Nargs exactly(int n)
Definition Argument.hpp:24
static Nargs zeroOrMore()
Definition Argument.hpp:27
int min
Definition Argument.hpp:21
int max
-1 means unlimited.
Definition Argument.hpp:22
static Nargs optional()
Definition Argument.hpp:29
static Nargs oneOrMore()
Definition Argument.hpp:28
static Nargs atLeast(int n)
Definition Argument.hpp:25
static Nargs between(int mn, int mx)
Definition Argument.hpp:26