Skip to main content

rtb_app/
command.rs

1//! The [`Command`] trait, its descriptor, and the link-time registration slice.
2//!
3//! A `Command` is an opinionated `async fn(App) -> Result<()>` bundled
4//! with a small static descriptor ([`CommandSpec`]). Commands self-
5//! register via a [`linkme`] distributed slice so no manual wiring is
6//! needed when authoring new commands.
7//!
8//! # Registration pattern
9//!
10//! ```ignore
11//! use rtb_app::command::{BUILTIN_COMMANDS, Command, CommandSpec};
12//! use rtb_app::linkme::distributed_slice;
13//!
14//! pub struct Deploy;
15//!
16//! #[async_trait::async_trait]
17//! impl Command for Deploy {
18//!     fn spec(&self) -> &CommandSpec {
19//!         static SPEC: CommandSpec = CommandSpec {
20//!             name: "deploy",
21//!             about: "Deploy the thing",
22//!             ..CommandSpec::DEFAULT
23//!         };
24//!         &SPEC
25//!     }
26//!
27//!     async fn run(&self, _app: rtb_app::app::App) -> miette::Result<()> {
28//!         Ok(())
29//!     }
30//! }
31//!
32//! #[distributed_slice(BUILTIN_COMMANDS)]
33//! fn __register_deploy() -> Box<dyn Command> { Box::new(Deploy) }
34//! ```
35//!
36//! `rtb-cli::Application::run` iterates `BUILTIN_COMMANDS` at startup,
37//! filters by the runtime `Features` set, and registers each remaining
38//! command with clap.
39
40use async_trait::async_trait;
41use linkme::distributed_slice;
42
43use crate::app::App;
44use crate::features::Feature;
45
46/// Static descriptor of a [`Command`].
47///
48/// Every field is `'static` because commands are compile-time entities —
49/// runtime-generated subcommands are a separate (unimplemented) concern.
50///
51/// Construct with struct-update over [`CommandSpec::DEFAULT`] so new
52/// optional fields do not churn every literal:
53///
54/// ```ignore
55/// static SPEC: CommandSpec = CommandSpec {
56///     name: "deploy",
57///     about: "Deploy the thing",
58///     ..CommandSpec::DEFAULT
59/// };
60/// ```
61#[derive(Debug, Clone, Copy)]
62pub struct CommandSpec {
63    /// The subcommand name as it appears on the CLI (`mytool deploy`).
64    pub name: &'static str,
65
66    /// One-line summary shown in `--help`.
67    pub about: &'static str,
68
69    /// Alternative names accepted on the CLI. Displayed in help text.
70    pub aliases: &'static [&'static str],
71
72    /// If `Some`, the command is only visible when the runtime
73    /// [`Features`](crate::features::Features) set has this feature
74    /// enabled. Unconditional commands leave this `None`.
75    pub feature: Option<Feature>,
76
77    /// Single-character short-flag alias — `mytool -d` invokes the command
78    /// like `mytool deploy`. `None` for most commands; set by
79    /// `rtb generate command --short`.
80    pub short: Option<char>,
81
82    /// Long-form help shown in the command's own `--help`. `None` falls
83    /// back to [`about`](Self::about); set by
84    /// `rtb generate command --long`.
85    pub long_about: Option<&'static str>,
86}
87
88impl CommandSpec {
89    /// A zero-valued descriptor for struct-update construction — see the
90    /// [type docs](Self). Only the fields that differ need be set at each
91    /// call site, so adding a new optional field later touches no existing
92    /// literal.
93    pub const DEFAULT: Self =
94        Self { name: "", about: "", aliases: &[], feature: None, short: None, long_about: None };
95}
96
97/// The contract every CLI subcommand implements.
98///
99/// Implementations are typically registered via the
100/// [`BUILTIN_COMMANDS`] distributed slice. `rtb-cli` provides a
101/// `#[rtb::command]` attribute macro that derives the boilerplate for
102/// downstream tools; hand-written impls follow the example in the
103/// module docs.
104#[async_trait]
105pub trait Command: Send + Sync + 'static {
106    /// The command's static descriptor.
107    fn spec(&self) -> &CommandSpec;
108
109    /// Execute the command. `app` is taken by value — `Clone` on `App`
110    /// is O(1) so subcommands that fan out can `.clone()` freely.
111    async fn run(&self, app: App) -> miette::Result<()>;
112
113    /// When `true`, `rtb-cli`'s top-level clap parser passes every
114    /// argument after `<name>` through to [`Self::run`] without
115    /// further validation. Commands that own their own clap subtree
116    /// (e.g. `docs list / show / browse / serve`, `update check / run`)
117    /// opt into this so the inner parser can produce its own help
118    /// and error messages.
119    ///
120    /// Defaults to `false` — most commands let the framework reject
121    /// unknown args at the outer layer.
122    fn subcommand_passthrough(&self) -> bool {
123        false
124    }
125
126    /// When `true`, this command is registered as an MCP tool by
127    /// `rtb_mcp::McpServer`. Defaults to `false` — additive trait
128    /// method, no impact on existing impls.
129    fn mcp_exposed(&self) -> bool {
130        false
131    }
132
133    /// Optional JSON Schema for the command's arguments — surfaced
134    /// to MCP clients in the tool listing. Default: `None`. Tool
135    /// authors with `clap::Args` structs typically derive this via
136    /// `serde_json::to_value(schemars::schema_for!(MyArgs))`.
137    fn mcp_input_schema(&self) -> Option<serde_json::Value> {
138        None
139    }
140}
141
142/// Link-time registry of [`Command`] factory functions.
143///
144/// The factories are thin — each produces a fresh `Box<dyn Command>`
145/// when invoked by `rtb-cli::Application`. They are expected to be
146/// cheap (no I/O, no allocation beyond the box). Heavy work belongs in
147/// `Command::run`.
148///
149/// See the module docs for the registration pattern.
150#[distributed_slice]
151pub static BUILTIN_COMMANDS: [fn() -> Box<dyn Command>];
152
153/// A boxed, `Send` future returned by a [`PreRunHook`].
154pub type PreRunFuture =
155    std::pin::Pin<Box<dyn std::future::Future<Output = miette::Result<()>> + Send>>;
156
157/// A pre-run hook, invoked with the [`App`] before command dispatch.
158///
159/// Runs after CLI parsing and before the matched command. Leaf crates
160/// register cross-cutting pre-dispatch logic here (e.g. the self-update
161/// policy check) via [`distributed_slice`], keeping `rtb-cli` decoupled
162/// from them — exactly like [`BUILTIN_COMMANDS`].
163///
164/// **Contract:** a hook must be fast and **order-independent** — link-time
165/// registration order across crates is not deterministic. A hook returning
166/// `Err` aborts the run before the command executes, so advisory hooks that
167/// must not block the command should swallow their own errors.
168pub type PreRunHook = fn(App) -> PreRunFuture;
169
170/// Link-time registry of [`PreRunHook`]s run before command dispatch.
171///
172/// `rtb-cli::Application::run` awaits each registered hook (in unspecified
173/// order) after parsing succeeds and before dispatching the matched
174/// command. See [`PreRunHook`] for the contract.
175#[distributed_slice]
176pub static BUILTIN_PRERUN_HOOKS: [PreRunHook];