VoltMod
C++23 framework for CS2 server plugins
Loading...
Searching...
No Matches
CommandBuilder.hpp
Go to the documentation of this file.
1#pragma once
2
8#include <cstdint>
9#include <functional>
10#include <span>
11#include <string>
12#include <string_view>
13#include <type_traits>
14#include <utility>
15#include <vector>
16
17namespace VoltMod
18{
19
20/**
21 * @brief What a command handler answers with.
22 *
23 * An empty @ref Text sends no reply.
24 */
25struct Reply
26{
27 std::string Text;
28
29 /** Handled, with nothing more to say. */
30 static Reply Silent() { return {}; }
31};
32
33/**
34 * @brief Who invoked the command, and how to answer them.
35 *
36 * A handler's first parameter. @ref Player is null and @ref Slot is -1 for console commands;
37 * reply helpers use the caller's language.
38 */
39struct Caller
40{
41 /** The player who typed the command, or null for console commands. */
43 /** @ref Player's slot, or -1 for the console - which is also the server-language slot. */
44 int Slot = -1;
45 /** The plugin's translations. `Get(key)` with no slot resolves the server language. */
47 /** Sends a reply to chat or the console for the duration of the handler call. */
48 std::function<void(const std::string&)> Send;
49
50 /** True when the server ran the command: the server console, rcon or a cfg file. */
51 bool IsServer() const { return Player == nullptr; }
52
53 /** Return localized @p key with `{token}` substitution. */
54 std::string Text(std::string_view key, Tokens tokens = {}) const;
55
56 /** Succeed, replying with @p key localized for this caller. */
57 Result<Reply> Ok(std::string_view key, Tokens tokens = {}) const;
58
59 /**
60 * Fail, replying with @p key localized for this caller.
61 *
62 * The error keeps @p key in `Key` and the localized line in `Text`. Errors from other
63 * services carry only a key and are localized by dispatch.
64 */
65 Result<Reply> Fail(std::string_view key, Tokens tokens = {}) const;
66
67 /** Send one extra localized line; finish a multi-line reply with `Ok` or `Reply::Silent`. */
68 void Say(std::string_view key, Tokens tokens = {}) const;
69
70 /** Send @p line verbatim: an already-formatted row that has no translation of its own. */
71 void SayRaw(std::string_view line) const;
72};
73
74/** Who may run a command, and so where it can be typed. */
75enum class CommandAccess : uint8_t
76{
77 /** Players, from chat. The default. */
79 /** Players, from chat or their own console, so they can bind it to a key. The server cannot run it. */
81 /** Players from chat or their own console, and the server from its console, rcon and cfg files. */
83 /** The server only, from its console, rcon and cfg files. Players are ignored. */
85};
86
87/**
88 * @brief One command as the builder assembled it.
89 *
90 * The engine-free command definition built by @ref CommandBuilder and installed by
91 * @ref CommandManager.
92 */
94{
95 std::string Name;
96 std::vector<std::string> Aliases;
97 std::string Description;
98 /** Empty means no permission check. Never checked when the server runs the command. */
99 std::string PermissionName;
100 /** Translation key for the whole usage line; empty derives one from @ref Args. */
101 std::string UsageKey;
103 std::vector<ArgDesc> Args;
104 /** The type-erased handler: unpacks @p bound back into the parameter list it was written
105 * with. Built by @ref CommandBuilder::Run. */
106 std::function<Result<Reply>(const Caller&, std::span<const BoundArg>)> Invoke;
107};
108
109/** Marker holding the parameter types recovered from a handler's signature. */
110template <class... A>
112{};
113
114/** A callable with exactly one `operator()` to name: a plain lambda or functor, but not a generic
115 * one (`auto` parameters) and not one carrying overloads. */
116template <class F>
117concept HasOneCallOperator = requires { &std::remove_reference_t<F>::operator(); };
118
119/**
120 * @brief The parameter list of a handler, after the leading @ref Caller.
121 *
122 * @ref CommandBuilder::Run deduces `A...` from the callable, so the signature is the argument
123 * specification. The specializations below cover the shapes a handler is written in - a lambda, a
124 * functor, a function - and anything else lands on the primary and says so.
125 */
126template <class F>
128{
129 static_assert(false,
130 "A command handler takes (Caller, Args::...) and returns Result<Reply> or nothing. A generic lambda "
131 "cannot be one: its parameter list is the argument specification, so the types have to be "
132 "written out.");
133};
134
135/** A lambda or functor, through the one `operator()` it has. */
136template <HasOneCallOperator F>
137struct CommandHandlerArgs<F> : CommandHandlerArgs<decltype(&std::remove_reference_t<F>::operator())>
138{};
139
140/** The one place the list is named; every shape below reduces to this. */
141template <class R, class... A>
143{
144 using List = CommandArgList<A...>;
145};
146
147/** @{ A lambda's `operator()`, and a function pointer. `Run` decays the callable first, so a
148 * function passed by name arrives here as a pointer. */
149template <class C, class R, class... A>
150struct CommandHandlerArgs<R (C::*)(Caller, A...) const> : CommandHandlerArgs<R(Caller, A...)>
151{};
152
153template <class C, class R, class... A>
154struct CommandHandlerArgs<R (C::*)(Caller, A...) const noexcept> : CommandHandlerArgs<R(Caller, A...)>
155{};
156
157template <class C, class R, class... A>
158struct CommandHandlerArgs<R (C::*)(Caller, A...)> : CommandHandlerArgs<R(Caller, A...)>
159{};
160
161template <class C, class R, class... A>
162struct CommandHandlerArgs<R (C::*)(Caller, A...) noexcept> : CommandHandlerArgs<R(Caller, A...)>
163{};
164
165template <class R, class... A>
166struct CommandHandlerArgs<R (*)(Caller, A...)> : CommandHandlerArgs<R(Caller, A...)>
167{};
168
169template <class R, class... A>
170struct CommandHandlerArgs<R (*)(Caller, A...) noexcept> : CommandHandlerArgs<R(Caller, A...)>
171{};
172/** @} */
173
174/**
175 * @brief Fluent command registration, returned by @ref CommandManager::Add.
176 *
177 * @code
178 * commands.Add("ban")
179 * .Describe("Ban a player.")
180 * .Alias("b")
181 * .Permission("admin.ban")
182 * .Run([&app](Caller c, Args::Target t, Args::Duration d, Args::Opt<Args::Rest> why) {
183 * std::string name = t->Name(); // capture first: a ban drops the target
184 * std::string reason = why.ValueOr(c.Translations.Get("reason.bannedByAdmin"));
185 * if (!app.Ban(*c.Player, *t.Value, reason, d.Value))
186 * return c.Fail("cmd.banFailed");
187 * return c.Ok("cmd.banSuccess", {{"name", name}});
188 * });
189 * @endcode
190 *
191 * @ref Run installs the command. The manager owns it for the plugin load cycle.
192 */
194{
195public:
196 /** How @ref Run hands the finished definition back to the manager that made this builder. */
197 using Installer = std::function<void(CommandDefinition)>;
198
199 CommandBuilder(Installer install, std::string_view name) : _install(std::move(install))
200 {
201 _def.Name = std::string(name);
202 }
203
204 /** Another name for the same command. Collisions are refused and logged at registration. */
205 CommandBuilder& Alias(std::string_view alias)
206 {
207 _def.Aliases.emplace_back(alias);
208 return *this;
209 }
210
211 /** Operator-facing description; also the console command's help text. */
212 CommandBuilder& Describe(std::string_view text)
213 {
214 _def.Description = std::string(text);
215 return *this;
216 }
217
218 /** Gate on `Policy::Authorize`, which denies while no plugin publishes `IPermissions`. */
219 CommandBuilder& Permission(std::string_view permission)
220 {
221 _def.PermissionName = std::string(permission);
222 return *this;
223 }
224
225 /** Also register a tier1 ConCommand that only players can run, so they can type it in their
226 * console or bind it to a key. The server console, rcon and cfg files are refused. */
228 {
229 _def.Access = CommandAccess::Players;
230 return *this;
231 }
232
233 /** Also register a tier1 ConCommand, so players can type it in their console and the server
234 * can run it from its console, rcon, cfg files and `ExecuteServerCommand`. */
236 {
238 return *this;
239 }
240
241 /** Register only the ConCommand, for an operator command players cannot run. */
243 {
244 _def.Access = CommandAccess::ServerOnly;
245 return *this;
246 }
247
248 /** Translation key for the whole usage line, replacing the one derived from the argument
249 * types. */
250 CommandBuilder& UsageKey(std::string_view key)
251 {
252 _def.UsageKey = std::string(key);
253 return *this;
254 }
255
256 /**
257 * Install the command. The handler takes a @ref Caller and one `Args::` value per argument;
258 * that list defines arity, parsing, and usage. A handler that returns nothing succeeds silently.
259 *
260 * The command is unregistered when @ref CommandManager is destroyed.
261 */
262 template <class F>
263 void Run(F&& handler)
264 {
265 Bind(std::forward<F>(handler), typename CommandHandlerArgs<std::decay_t<F>>::List{});
266 }
267
268private:
269 template <class F, class... A>
270 void Bind(F&& handler, CommandArgList<A...>)
271 {
272 static_assert((CommandArg<A> && ...), "Every command handler parameter after Caller must be an Args:: type.");
273 static_assert(OptionalsTrail<A...>(), "Only trailing command arguments may be Args::Opt.");
274 static_assert(RestIsLast<A...>(), "Args::Rest must be the last command argument.");
275
276 std::function<Result<Reply>(Caller, A...)> fn;
277 if constexpr (std::is_void_v<std::invoke_result_t<std::decay_t<F>&, Caller, A...>>)
278 {
279 fn = [h = std::forward<F>(handler)](Caller c, A... args) mutable -> Result<Reply> {
280 h(c, std::move(args)...);
281 return Reply::Silent();
282 };
283 }
284 else
285 {
286 fn = std::forward<F>(handler);
287 }
288
289 _def.Args = DescribeArgs<A...>();
290 _def.Invoke = [fn = std::move(fn)](const Caller& caller, std::span<const BoundArg> bound) {
291 return Unpack(fn, caller, bound, std::index_sequence_for<A...>{});
292 };
293 _install(std::move(_def));
294 }
295
296 /** The trampoline: one `std::get` per declared argument, in descriptor order. */
297 template <class... A, std::size_t... I>
298 static Result<Reply> Unpack(const std::function<Result<Reply>(Caller, A...)>& fn, const Caller& caller,
299 std::span<const BoundArg> bound, std::index_sequence<I...>)
300 {
301 return fn(caller, ArgUnpack<A>::From(bound[I])...);
302 }
303
304 Installer _install;
305 CommandDefinition _def;
306};
307
308} // namespace VoltMod
std::function< void(CommandDefinition)> Installer
CommandBuilder & Alias(std::string_view alias)
CommandBuilder & UsageKey(std::string_view key)
CommandBuilder & Describe(std::string_view text)
CommandBuilder & PlayersAndServer()
CommandBuilder(Installer install, std::string_view name)
CommandBuilder & Permission(std::string_view permission)
CommandBuilder & PlayersOnly()
CommandBuilder & ServerOnly()
One connected player, owned by PlayerManager for the length of the connection.
Definition Player.hpp:23
Localization system. Loads one JSON file per language; nested objects flatten into dotted keys (categ...
consteval bool RestIsLast()
Definition Args.hpp:260
std::expected< T, Error > Result
Definition Result.hpp:64
std::map< std::string, std::string > Tokens
Definition Strings.hpp:14
std::vector< ArgDesc > DescribeArgs()
Definition Args.hpp:280
consteval bool OptionalsTrail()
Definition Args.hpp:239
static T From(const BoundArg &bound)
Definition Args.hpp:289
Who invoked the command, and how to answer them.
void SayRaw(std::string_view line) const
Result< Reply > Ok(std::string_view key, Tokens tokens={}) const
std::function< void(const std::string &)> Send
VoltMod::Translations & Translations
std::string Text(std::string_view key, Tokens tokens={}) const
Result< Reply > Fail(std::string_view key, Tokens tokens={}) const
bool IsServer() const
void Say(std::string_view key, Tokens tokens={}) const
VoltMod::Player * Player
One command as the builder assembled it.
std::function< Result< Reply >(const Caller &, std::span< const BoundArg >)> Invoke
std::vector< std::string > Aliases
std::vector< ArgDesc > Args
The parameter list of a handler, after the leading Caller.
What a command handler answers with.
static Reply Silent()