Skip to main content

serenade_console/
application.rs

1//! Console Application runner (clap argv + registered commands).
2
3use std::io::{self, IsTerminal};
4use std::sync::Arc;
5
6use clap::{Arg, ArgAction, Command as ClapCommand};
7use serenade_di::Container;
8use serenade_kernel::Environment;
9
10use crate::{Command, ConsoleError, Input};
11
12/// Discoverable command registry and argv runner.
13#[derive(Clone, Default)]
14pub struct Application {
15    commands: Vec<Arc<dyn Command>>,
16}
17
18impl Application {
19    /// Empty application with no commands.
20    #[must_use]
21    pub fn new() -> Self {
22        Self::default()
23    }
24
25    /// Registers a command.
26    pub fn add(&mut self, command: Arc<dyn Command>) {
27        self.commands.push(command);
28    }
29
30    /// Registered commands in registration order.
31    #[must_use]
32    pub fn commands(&self) -> &[Arc<dyn Command>] {
33        &self.commands
34    }
35
36    /// Looks up a command by name.
37    #[must_use]
38    pub fn find(&self, name: &str) -> Option<&Arc<dyn Command>> {
39        self.commands.iter().find(|command| command.name() == name)
40    }
41
42    /// Parses `argv` (program name first) and runs the selected command.
43    ///
44    /// Global flags: `--env` / `APP_ENV`, `--no-debug`, `--interactive`.
45    /// With no command or `list`, prints available commands. With
46    /// `--interactive`, enters a rustyline REPL (↑/↓ history).
47    ///
48    /// # Errors
49    ///
50    /// Returns [`ConsoleError`] on parse failure, unknown command, or command error.
51    pub fn run<I, S>(&self, argv: I) -> Result<(), ConsoleError>
52    where
53        I: IntoIterator<Item = S>,
54        S: Into<std::ffi::OsString> + Clone,
55    {
56        self.run_with(argv, None)
57    }
58
59    /// Like [`Self::run`], attaching an optional DI [`Container`] for commands.
60    ///
61    /// # Errors
62    ///
63    /// Returns [`ConsoleError`] on parse failure, unknown command, or command error.
64    pub fn run_with<I, S>(
65        &self,
66        argv: I,
67        container: Option<Arc<Container>>,
68    ) -> Result<(), ConsoleError>
69    where
70        I: IntoIterator<Item = S>,
71        S: Into<std::ffi::OsString> + Clone,
72    {
73        let matches = clap_command()
74            .try_get_matches_from(argv)
75            .map_err(|error| ConsoleError::Failed(error.to_string()))?;
76
77        let env_name = matches
78            .get_one::<String>("env")
79            .map_or("dev", String::as_str);
80        let environment = Environment::from_name(env_name)
81            .map_err(|error| ConsoleError::InvalidEnvironment(error.to_string()))?;
82        let no_debug = matches.get_flag("no-debug");
83        let debug = if no_debug {
84            false
85        } else {
86            environment.is_debug()
87        };
88
89        if matches.get_flag("interactive") {
90            return self.run_interactive(&environment, debug, container.as_ref());
91        }
92
93        let command_name = matches.get_one::<String>("command").map(String::as_str);
94        let trailing: Vec<String> = matches
95            .get_many::<String>("args")
96            .map_or_default(|values| values.cloned().collect());
97
98        match command_name {
99            None | Some("list") => {
100                self.print_list()?;
101                Ok(())
102            }
103            Some(name) => {
104                let Some(command) = self.find(name) else {
105                    return Err(ConsoleError::NotFound(name.to_owned()));
106                };
107                let input = Input::new(environment, debug, trailing, container);
108                command.execute(&input)
109            }
110        }
111    }
112
113    pub(crate) fn print_list(&self) -> Result<(), ConsoleError> {
114        self.print_list_to(&mut io::stdout().lock())
115    }
116
117    pub(crate) fn print_list_to(&self, out: &mut dyn io::Write) -> Result<(), ConsoleError> {
118        writeln!(out, "Serenade Console")?;
119        writeln!(out)?;
120        writeln!(out, "Available commands:")?;
121        let mut names: Vec<_> = self.commands.iter().collect();
122        names.sort_by(|left, right| left.name().cmp(right.name()));
123        for command in names {
124            writeln!(out, "  {:24} {}", command.name(), command.description())?;
125        }
126        writeln!(out)?;
127        writeln!(
128            out,
129            "Usage: <binary> [--env ENV] [--no-debug] [--interactive] <command> [args…]"
130        )?;
131        Ok(())
132    }
133}
134
135fn clap_command() -> ClapCommand {
136    ClapCommand::new("serenade")
137        .about("Serenade console (bin/console analogue)")
138        .disable_help_subcommand(true)
139        .arg(
140            Arg::new("env")
141                .long("env")
142                .value_name("ENV")
143                .default_value("dev")
144                .env("APP_ENV")
145                .help("Runtime environment (dev, test, prod, or custom)"),
146        )
147        .arg(
148            Arg::new("no-debug")
149                .long("no-debug")
150                .action(ArgAction::SetTrue)
151                .help("Disable debug even in dev/test"),
152        )
153        .arg(
154            Arg::new("interactive")
155                .long("interactive")
156                .short('i')
157                .action(ArgAction::SetTrue)
158                .help("Interactive REPL with ↑/↓ command history"),
159        )
160        .arg(
161            Arg::new("command")
162                .value_name("COMMAND")
163                .help("Command name (for example serenade:about)"),
164        )
165        .arg(
166            Arg::new("args")
167                .value_name("ARGS")
168                .num_args(0..)
169                .trailing_var_arg(true)
170                .allow_hyphen_values(true)
171                .help("Arguments passed to the command"),
172        )
173}
174
175/// Returns whether stdout is an interactive terminal (for TUI commands).
176#[must_use]
177pub fn stdout_is_terminal() -> bool {
178    io::stdout().is_terminal()
179}