Skip to main content

navree_kernel/
command.rs

1//! CLI commands contributed by modules, and the built-in `check`, `help`
2//! and `introspect`.
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); 3] = [
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
96/// The text printed by `help`.
97pub(crate) fn help_text(report: &GraphReport) -> String {
98    let commands: Vec<(&str, &str)> = report
99        .modules
100        .iter()
101        .flat_map(|m| m.commands.iter().map(|c| (c.name, c.about)))
102        .collect();
103    let width = BUILT_INS
104        .iter()
105        .chain(commands.iter())
106        .map(|(name, _)| name.len())
107        .max()
108        .unwrap_or(0);
109    let mut out = String::from("Usage: <command> [args...]\n\nBuilt-in commands:\n");
110    for (name, about) in BUILT_INS {
111        out.push_str(&format!("  {name:width$}  {about}\n"));
112    }
113    if !commands.is_empty() {
114        out.push_str("\nCommands:\n");
115        for (name, about) in commands {
116            out.push_str(&format!("  {name:width$}  {about}\n"));
117        }
118    }
119    out
120}