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: the built-ins, and the other
108/// names [`AppBuilder::run_with_args`](crate::AppBuilder::run_with_args) takes
109/// for them. A module of a plugin that is not first-party may not register a
110/// command of one of these names (the app's own module may, and runs in place
111/// of a built-in that yields).
112pub(crate) const FRAMEWORK_COMMANDS: [&str; 8] = [
113    "--help",
114    "-h",
115    "check",
116    "help",
117    "introspect",
118    "list",
119    "plugin:publish",
120    "plugins",
121];
122
123/// The built-in commands of an app with `report`'s modules, as (usage,
124/// about): [`BUILT_INS`] without one that yields to a module command of its
125/// name.
126pub(crate) fn built_ins(
127    report: &GraphReport,
128) -> impl Iterator<Item = (&'static str, &'static str)> + '_ {
129    BUILT_INS.into_iter().filter(move |&(usage, _)| {
130        let name = usage.split_whitespace().next().unwrap_or(usage);
131        !(YIELDING.contains(&name) && report.has_command(name))
132    })
133}
134
135/// The text printed by `help`.
136pub(crate) fn help_text(report: &GraphReport) -> String {
137    let listed: Vec<(&str, &str)> = built_ins(report).collect();
138    let commands: Vec<(&str, &str)> = report
139        .modules
140        .iter()
141        .flat_map(|m| m.commands.iter().map(|c| (c.name, c.about)))
142        .collect();
143    let width = listed
144        .iter()
145        .chain(commands.iter())
146        .map(|(name, _)| name.len())
147        .max()
148        .unwrap_or(0);
149    let mut out = String::from("Usage: <command> [args...]\n\nBuilt-in commands:\n");
150    for (name, about) in listed {
151        out.push_str(&format!("  {name:width$}  {about}\n"));
152    }
153    if !commands.is_empty() {
154        out.push_str("\nCommands:\n");
155        for (name, about) in commands {
156            out.push_str(&format!("  {name:width$}  {about}\n"));
157        }
158    }
159    out
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use crate::{CommandInfo, ModuleReport};
166
167    #[test]
168    fn help_leaves_out_a_built_in_that_yields() {
169        struct Mine;
170        let own = GraphReport {
171            modules: vec![ModuleReport {
172                id: crate::ModuleId::of::<Mine>(),
173                name: "Mine",
174                global: false,
175                imports: Vec::new(),
176                providers: Vec::new(),
177                exports: Vec::new(),
178                commands: vec![CommandInfo {
179                    name: "plugins",
180                    about: "The app's own list",
181                }],
182            }],
183        };
184        let text = help_text(&own);
185        assert!(!text.contains("plugins [--json]"), "{text}");
186        assert!(
187            text.lines().any(
188                |l| l.trim_start().starts_with("plugins ") && l.ends_with("The app's own list")
189            ),
190            "{text}"
191        );
192        assert!(
193            help_text(&GraphReport {
194                modules: Vec::new()
195            })
196            .contains("plugins [--json]")
197        );
198    }
199}