Skip to main content

phoenix_console/
lib.rs

1//! Application console: `myapp update` with a one-function command.
2//! See `docs/QUEUE_MAIL_CONSOLE.md`.
3
4#![forbid(unsafe_code)]
5
6use std::{
7    error::Error,
8    fmt::{Display, Formatter},
9    future::Future,
10    pin::Pin,
11};
12
13/// Result type returned by console commands and [`Console::run`].
14pub type CommandResult = Result<(), Box<dyn Error + Send + Sync>>;
15
16/// Borrowed arguments for a single console invocation.
17#[derive(Clone, Copy, Debug)]
18pub struct CommandContext<'a> {
19    /// Remaining argv after the binary name and command name.
20    pub args: &'a [String],
21    /// Application binary name used in help text.
22    pub binary_name: &'a str,
23}
24
25type BoxedCommandFuture<'a> = Pin<Box<dyn Future<Output = CommandResult> + Send + 'a>>;
26type CommandHandler =
27    Box<dyn for<'a> Fn(CommandContext<'a>) -> BoxedCommandFuture<'a> + Send + Sync>;
28
29/// One registered application command.
30pub struct CommandEntry {
31    name: &'static str,
32    handler: CommandHandler,
33}
34
35impl CommandEntry {
36    /// Wrap an async command function for registration.
37    #[must_use]
38    pub fn new<F>(name: &'static str, handler: F) -> Self
39    where
40        F: for<'a> Fn(CommandContext<'a>) -> BoxedCommandFuture<'a> + Send + Sync + 'static,
41    {
42        Self {
43            name,
44            handler: Box::new(handler),
45        }
46    }
47
48    #[must_use]
49    pub const fn name(&self) -> &'static str {
50        self.name
51    }
52}
53
54/// Application CLI console built around a binary name and named commands.
55pub struct Console {
56    binary_name: String,
57    about: Option<String>,
58    serve: Option<CommandHandler>,
59    commands: Vec<CommandEntry>,
60}
61
62impl Console {
63    /// Create a console whose help text uses `binary_name`.
64    #[must_use]
65    pub fn new(binary_name: impl Into<String>) -> Self {
66        Self {
67            binary_name: binary_name.into(),
68            about: None,
69            serve: None,
70            commands: Vec::new(),
71        }
72    }
73
74    /// Short description printed above the usage block.
75    #[must_use]
76    pub fn about(mut self, about: impl Into<String>) -> Self {
77        self.about = Some(about.into());
78        self
79    }
80
81    /// Register the built-in `serve` command that starts the HTTP application.
82    #[must_use]
83    pub fn serve<F, Fut>(mut self, handler: F) -> Self
84    where
85        F: Fn(CommandContext<'_>) -> Fut + Send + Sync + 'static,
86        Fut: Future<Output = CommandResult> + Send + 'static,
87    {
88        self.serve = Some(Box::new(move |ctx| {
89            let args = ctx.args.to_vec();
90            let binary_name = ctx.binary_name.to_owned();
91            let future = handler(CommandContext {
92                args: &args,
93                binary_name: &binary_name,
94            });
95            Box::pin(future)
96        }));
97        self
98    }
99
100    /// Append user-registered commands from [`commands!`] or a manual list.
101    #[must_use]
102    pub fn commands(mut self, commands: impl IntoIterator<Item = CommandEntry>) -> Self {
103        self.commands.extend(commands);
104        self
105    }
106
107    /// Parse process argv and dispatch.
108    ///
109    /// # Errors
110    ///
111    /// Returns an error for unknown commands or when a command fails.
112    pub async fn run(self) -> CommandResult {
113        self.run_argv(std::env::args()).await
114    }
115
116    /// Parse an explicit argv (including argv0) and dispatch.
117    ///
118    /// # Errors
119    ///
120    /// Returns an error for unknown commands or when a command fails.
121    pub async fn run_argv(
122        self,
123        argv: impl IntoIterator<Item = impl Into<String>>,
124    ) -> CommandResult {
125        let argv = argv.into_iter().map(Into::into).collect::<Vec<_>>();
126        let binary_name = self.binary_name.as_str();
127        let command = argv.get(1).map(String::as_str);
128
129        match command {
130            None | Some("help" | "--help" | "-h") => {
131                print!("{}", self.usage());
132                Ok(())
133            }
134            Some("serve") => {
135                let Some(serve) = &self.serve else {
136                    return Err(Box::new(ConsoleError::ServeUnavailable));
137                };
138                let ctx = CommandContext {
139                    args: argv.get(2..).unwrap_or(&[]),
140                    binary_name,
141                };
142                serve(ctx).await
143            }
144            Some(name) => {
145                let ctx = CommandContext {
146                    args: argv.get(2..).unwrap_or(&[]),
147                    binary_name,
148                };
149                let Some(entry) = self.commands.iter().find(|entry| entry.name == name) else {
150                    return Err(Box::new(ConsoleError::UnknownCommand {
151                        command: name.to_owned(),
152                        usage: self.usage(),
153                    }));
154                };
155                (entry.handler)(ctx).await
156            }
157        }
158    }
159
160    fn usage(&self) -> String {
161        let mut lines = Vec::new();
162        if let Some(about) = &self.about {
163            lines.push(about.clone());
164            lines.push(String::new());
165        }
166        lines.push(format!(
167            "Usage:\n  {} <command> [args...]\n",
168            self.binary_name
169        ));
170        lines.push("Commands:".to_owned());
171        if self.serve.is_some() {
172            lines.push("  serve    Start the HTTP server".to_owned());
173        }
174        let mut names = self
175            .commands
176            .iter()
177            .map(CommandEntry::name)
178            .collect::<Vec<_>>();
179        names.sort_unstable();
180        for name in names {
181            lines.push(format!("  {name}"));
182        }
183        lines.push(String::new());
184        lines.push(format!("Run `{} help` for this message.", self.binary_name));
185        lines.push(String::new());
186        lines.join("\n")
187    }
188}
189
190enum ConsoleError {
191    UnknownCommand { command: String, usage: String },
192    ServeUnavailable,
193}
194
195impl Display for ConsoleError {
196    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
197        match self {
198            Self::UnknownCommand { command, usage } => {
199                write!(formatter, "unknown command `{command}`\n\n{usage}")
200            }
201            Self::ServeUnavailable => {
202                write!(
203                    formatter,
204                    "command `serve` is not configured; call Console::serve first"
205                )
206            }
207        }
208    }
209}
210
211impl std::fmt::Debug for ConsoleError {
212    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
213        Display::fmt(self, formatter)
214    }
215}
216
217impl Error for ConsoleError {}
218/// Register application commands without clap boilerplate.
219///
220/// # Examples
221///
222/// ```ignore
223/// commands! {
224///     update,
225///     "sync-users" => sync_users,
226/// }
227/// ```
228///
229/// Generates `pub fn registry() -> Vec<CommandEntry>` in the enclosing module.
230#[macro_export]
231macro_rules! commands {
232    (@push $entries:ident;) => {};
233    (@push $entries:ident; $name:ident) => {
234        $entries.push($crate::CommandEntry::new(
235            stringify!($name),
236            |__ctx| ::std::boxed::Box::pin($name(__ctx)),
237        ));
238    };
239    (@push $entries:ident; $name:ident,) => {
240        $crate::commands!(@push $entries; $name);
241    };
242    (@push $entries:ident; $name:ident, $($rest:tt)*) => {
243        $crate::commands!(@push $entries; $name);
244        $crate::commands!(@push $entries; $($rest)*);
245    };
246    (@push $entries:ident; $alias:literal => $handler:ident) => {
247        $entries.push($crate::CommandEntry::new(
248            $alias,
249            |__ctx| ::std::boxed::Box::pin($handler(__ctx)),
250        ));
251    };
252    (@push $entries:ident; $alias:literal => $handler:ident,) => {
253        $crate::commands!(@push $entries; $alias => $handler);
254    };
255    (@push $entries:ident; $alias:literal => $handler:ident, $($rest:tt)*) => {
256        $crate::commands!(@push $entries; $alias => $handler);
257        $crate::commands!(@push $entries; $($rest)*);
258    };
259    () => {
260        /// Registered application console commands.
261        #[must_use]
262        pub fn registry() -> Vec<$crate::CommandEntry> {
263            Vec::new()
264        }
265    };
266    ($($item:tt)*) => {
267        /// Registered application console commands.
268        #[must_use]
269        #[allow(clippy::vec_init_then_push)]
270        pub fn registry() -> Vec<$crate::CommandEntry> {
271            let mut __phoenix_commands = Vec::new();
272            $crate::commands!(@push __phoenix_commands; $($item)*);
273            __phoenix_commands
274        }
275    };
276}
277
278#[must_use]
279pub const fn crate_name() -> &'static str {
280    "phoenix-console"
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use std::sync::{
287        Arc,
288        atomic::{AtomicBool, Ordering},
289    };
290
291    #[allow(clippy::unused_async)]
292    async fn update(_ctx: CommandContext<'_>) -> CommandResult {
293        Ok(())
294    }
295
296    commands! {
297        update,
298    }
299
300    #[tokio::test]
301    async fn registered_update_command_runs() {
302        let result = Console::new("demo")
303            .about("Demo")
304            .commands(registry())
305            .run_argv(["demo", "update"])
306            .await;
307        assert!(result.is_ok());
308    }
309
310    #[tokio::test]
311    async fn unknown_command_fails() {
312        let result = Console::new("demo")
313            .commands(registry())
314            .run_argv(["demo", "nope"])
315            .await;
316        let error = result.expect_err("unknown command should fail");
317        assert!(error.to_string().contains("unknown command `nope`"));
318    }
319
320    #[tokio::test]
321    async fn help_does_not_panic() {
322        Console::new("demo")
323            .about("Demo app")
324            .serve(|_ctx| async move { Ok(()) })
325            .commands(registry())
326            .run_argv(["demo", "help"])
327            .await
328            .expect("help should succeed");
329        Console::new("demo")
330            .run_argv(["demo"])
331            .await
332            .expect("empty argv should print usage");
333    }
334
335    #[tokio::test]
336    async fn serve_invokes_handler() {
337        let called = Arc::new(AtomicBool::new(false));
338        let flag = Arc::clone(&called);
339        Console::new("demo")
340            .serve(move |_ctx| {
341                let flag = Arc::clone(&flag);
342                async move {
343                    flag.store(true, Ordering::SeqCst);
344                    Ok(())
345                }
346            })
347            .run_argv(["demo", "serve"])
348            .await
349            .expect("serve should succeed");
350        assert!(called.load(Ordering::SeqCst));
351    }
352
353    #[tokio::test]
354    async fn command_receives_remaining_args() {
355        #[allow(clippy::unused_async)]
356        async fn echo(ctx: CommandContext<'_>) -> CommandResult {
357            assert_eq!(ctx.binary_name, "demo");
358            assert_eq!(ctx.args, ["a".to_owned(), "b".to_owned()]);
359            Ok(())
360        }
361
362        let entry = CommandEntry::new("echo", |ctx| Box::pin(echo(ctx)));
363        Console::new("demo")
364            .commands([entry])
365            .run_argv(["demo", "echo", "a", "b"])
366            .await
367            .expect("echo should succeed");
368    }
369}