Skip to main content

navree_kernel/
command.rs

1//! CLI commands contributed by modules, and the built-in `check`, `help`,
2//! `introspect`, `plugins` and `plugin:publish`.
3
4use std::fmt;
5use std::future::Future;
6use std::sync::Arc;
7
8use crate::{AppContext, BoxError, BoxFuture, GraphReport};
9
10/// The function behind a [`CommandSpec`].
11pub type CommandFn =
12    Arc<dyn Fn(AppContext, Vec<String>) -> BoxFuture<'static, Result<(), BoxError>> + Send + Sync>;
13
14/// A command a module registers with [`ModuleBuilder::command`](crate::ModuleBuilder::command),
15/// run as `<binary> <name> [args...]` against a booted app.
16#[derive(Clone)]
17pub struct CommandSpec {
18    /// The command name, e.g. `serve` or `queue:work`.
19    pub name: &'static str,
20    /// A one-line description shown by `help`.
21    pub about: &'static str,
22    /// Runs the command with the arguments after its name.
23    pub run: CommandFn,
24    /// The command speaks a protocol on standard output (an MCP server over
25    /// stdio, for example), so nothing else may write there: the logger
26    /// writes to standard error instead. See [`CommandSpec::stdio`].
27    pub stdio: bool,
28    /// The command does not need a booted app: it runs against the module
29    /// graph, and builds only the providers it asks for. See
30    /// [`CommandSpec::offline`].
31    pub offline: bool,
32}
33
34impl CommandSpec {
35    /// A command running `f(ctx, args)`.
36    pub fn new<F, Fut>(name: &'static str, about: &'static str, f: F) -> Self
37    where
38        F: Fn(AppContext, Vec<String>) -> Fut + Send + Sync + 'static,
39        Fut: Future<Output = Result<(), BoxError>> + Send + 'static,
40    {
41        Self {
42            name,
43            about,
44            run: Arc::new(move |ctx, args| Box::pin(f(ctx, args))),
45            stdio: false,
46            offline: false,
47        }
48    }
49
50    /// Marks the command as owning standard output (it writes a protocol
51    /// there). The app knows the command it runs from boot on
52    /// ([`AppContext::command`]), so modules that would print to stdout,
53    /// navree-log's console output first among them, use stderr instead.
54    pub fn stdio(mut self) -> Self {
55        self.stdio = true;
56        self
57    }
58
59    /// Marks the command as one that needs no booted app. The runner does
60    /// not build every singleton (no database connection is opened, no
61    /// server started) and runs no lifecycle hook, before or after: the
62    /// command gets the [`AppContext`] of the module graph and resolves what
63    /// it needs with [`AppContext::get`], which builds a provider on first
64    /// use. Meant for commands that read the app's configuration or graph,
65    /// such as `config:show` and `config:check`.
66    pub fn offline(mut self) -> Self {
67        self.offline = true;
68        self
69    }
70}
71
72impl fmt::Debug for CommandSpec {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        f.debug_struct("CommandSpec")
75            .field("name", &self.name)
76            .field("about", &self.about)
77            .field("stdio", &self.stdio)
78            .field("offline", &self.offline)
79            .finish_non_exhaustive()
80    }
81}
82
83/// Built-in commands handled by [`AppBuilder::run_with_args`](crate::AppBuilder::run_with_args).
84pub(crate) const BUILT_INS: [(&str, &str); 5] = [
85    (
86        "check [--graph]",
87        "Validate the module graph without constructing providers",
88    ),
89    ("help", "List the available commands"),
90    (
91        "introspect --json",
92        "Print the module graph and commands as JSON without constructing providers",
93    ),
94    (
95        "plugins [--json]",
96        "List the plugins and what each adds, without constructing providers",
97    ),
98    (
99        "plugin:publish <plugin> [options]",
100        "Copy a plugin's templates, translations, config or files into the app",
101    ),
102];
103
104/// Built-in commands that give way to a module command of the same name.
105pub(crate) const YIELDING: [&str; 2] = ["plugins", "plugin:publish"];
106
107/// The names of the framework's own commands, sorted: the built-ins, the other
108/// names [`AppBuilder::run_with_args`](crate::AppBuilder::run_with_args) takes
109/// for them, and every command the framework's modules register. A module that
110/// acts for a plugin which is not first-party may not register a command of
111/// one of these names (the app's own module may, and runs in place of a
112/// built-in that yields). Not public API; Navree's own crates and tests use
113/// it.
114pub const FRAMEWORK_COMMANDS: &[&str] = &[
115    "--help",
116    "-h",
117    "access:explain",
118    "access:grant",
119    "access:role",
120    "ai:prune",
121    "audit:prune",
122    "automations:catalog",
123    "automations:list",
124    "billing:events",
125    "billing:plans",
126    "billing:prune-events",
127    "billing:report-usage",
128    "billing:sync",
129    "billing:webhook",
130    "cache:clear",
131    "check",
132    "config:check",
133    "config:publish",
134    "config:schema",
135    "config:show",
136    "conformity:check",
137    "db",
138    "db:monitor",
139    "db:seed",
140    "directory:connections",
141    "directory:prune",
142    "directory:runs",
143    "directory:sync",
144    "directory:token",
145    "documents:fonts",
146    "documents:render",
147    "domains:certificates",
148    "domains:list",
149    "domains:transfer",
150    "domains:verify",
151    "down",
152    "flags:forget",
153    "flags:kill",
154    "flags:list",
155    "flags:off",
156    "flags:on",
157    "flags:purge",
158    "flags:revive",
159    "flags:rollout",
160    "fleet",
161    "fleet:continue",
162    "fleet:forget",
163    "fleet:pause",
164    "fleet:status",
165    "fleet:terminate",
166    "fleet:work",
167    "graphql:schema",
168    "help",
169    "i18n:check",
170    "i18n:missing",
171    "i18n:publish",
172    "integrations:check",
173    "integrations:list",
174    "integrations:mailboxes",
175    "introspect",
176    "key:generate",
177    "lighthouse:prune",
178    "lighthouse:test-alerts",
179    "list",
180    "logbook:clear",
181    "mail:domains",
182    "mail:suppressions",
183    "mail:test",
184    "mcp:serve",
185    "media:regenerate",
186    "micro:emit",
187    "micro:failed",
188    "micro:flush",
189    "micro:listen",
190    "micro:patterns",
191    "micro:retry",
192    "micro:send",
193    "micro:setup",
194    "migrate",
195    "migrate:fresh",
196    "migrate:install",
197    "migrate:refresh",
198    "migrate:reset",
199    "migrate:rollback",
200    "migrate:status",
201    "model:prune",
202    "model:show",
203    "mongo:migrate",
204    "mongo:migrate:fresh",
205    "mongo:migrate:refresh",
206    "mongo:migrate:reset",
207    "mongo:migrate:rollback",
208    "mongo:migrate:status",
209    "native:coverage",
210    "notify:release",
211    "notify:vapid",
212    "oauth:client",
213    "oauth:client:revoke",
214    "oauth:client:secret",
215    "oauth:clients",
216    "oauth:keys",
217    "oauth:prune",
218    "openapi:export",
219    "plugin:publish",
220    "plugins",
221    "queue:batches",
222    "queue:failed",
223    "queue:flush",
224    "queue:prune",
225    "queue:retry",
226    "queue:watchdog",
227    "queue:work",
228    "routes",
229    "schedule:list",
230    "schedule:run",
231    "schedule:work",
232    "schema:dump",
233    "search:flush",
234    "search:import",
235    "search:settings",
236    "search:status",
237    "serve",
238    "settings:inherit",
239    "settings:list",
240    "settings:set",
241    "settings:show",
242    "sheets:prune",
243    "storage:sync",
244    "time:zones",
245    "ui:render",
246    "up",
247    "webhooks:endpoints",
248    "webhooks:prune",
249    "webhooks:retry",
250    "webhooks:test",
251    "workflows:cancel",
252    "workflows:list",
253    "workflows:prune",
254    "workflows:retry",
255    "workflows:show",
256    "workflows:tick",
257    "workspace:demo-create",
258    "workspace:demo-reset",
259    "workspace:migrate",
260    "workspace:prune-invitations",
261];
262
263/// The built-in commands of an app with `report`'s modules, as (usage,
264/// about): [`BUILT_INS`] without one that yields to a module command of its
265/// name.
266pub(crate) fn built_ins(
267    report: &GraphReport,
268) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
269    BUILT_INS.into_iter().filter(move |&(usage, _)| {
270        let name = usage.split_whitespace().next().unwrap_or(usage);
271        !(YIELDING.contains(&name) && report.has_command(name))
272    })
273}
274
275/// The text printed by `help`.
276pub(crate) fn help_text(report: &GraphReport) -> String {
277    let listed: Vec<(&str, &str)> = built_ins(report).collect();
278    let commands: Vec<(&str, &str)> = report
279        .modules
280        .iter()
281        .flat_map(|m| m.commands.iter().map(|c| (c.name, c.about)))
282        .collect();
283    let width = listed
284        .iter()
285        .chain(commands.iter())
286        .map(|(name, _)| name.len())
287        .max()
288        .unwrap_or(0);
289    let mut out = String::from("Usage: <command> [args...]\n\nBuilt-in commands:\n");
290    for (name, about) in listed {
291        out.push_str(&format!("  {name:width$}  {about}\n"));
292    }
293    if !commands.is_empty() {
294        out.push_str("\nCommands:\n");
295        for (name, about) in commands {
296            out.push_str(&format!("  {name:width$}  {about}\n"));
297        }
298    }
299    out
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305    use crate::{CommandInfo, ModuleReport};
306
307    #[test]
308    fn help_leaves_out_a_built_in_that_yields() {
309        struct Mine;
310        let own = GraphReport {
311            modules: vec![ModuleReport {
312                id: crate::ModuleId::of::<Mine>(),
313                name: "Mine",
314                global: false,
315                imports: Vec::new(),
316                providers: Vec::new(),
317                exports: Vec::new(),
318                commands: vec![CommandInfo {
319                    name: "plugins",
320                    about: "The app's own list",
321                }],
322            }],
323        };
324        let text = help_text(&own);
325        assert!(!text.contains("plugins [--json]"), "{text}");
326        assert!(
327            text.lines().any(
328                |l| l.trim_start().starts_with("plugins ") && l.ends_with("The app's own list")
329            ),
330            "{text}"
331        );
332        assert!(
333            help_text(&GraphReport {
334                modules: Vec::new()
335            })
336            .contains("plugins [--json]")
337        );
338        assert!(FRAMEWORK_COMMANDS.windows(2).all(|w| w[0] < w[1]));
339        for (usage, _) in BUILT_INS {
340            let name = usage.split_whitespace().next().unwrap_or(usage);
341            assert!(FRAMEWORK_COMMANDS.binary_search(&name).is_ok(), "{name}");
342        }
343    }
344}