Skip to main content

serenade_console/
interactive.rs

1//! Interactive console loop with ↑/↓ history (`rustyline`).
2
3use std::io::{self, IsTerminal, Write};
4use std::path::PathBuf;
5
6use rustyline::DefaultEditor;
7use rustyline::error::ReadlineError;
8use serenade_di::Container;
9use serenade_kernel::Environment;
10
11use crate::{Application, ConsoleError, Input};
12use std::sync::Arc;
13
14/// Default history file under `$HOME`.
15pub const HISTORY_FILE_NAME: &str = ".serenade_history";
16
17/// Resolves `~/.serenade_history` when `HOME` is set.
18#[must_use]
19pub fn history_path() -> Option<PathBuf> {
20    std::env::var_os("HOME").map(|home| PathBuf::from(home).join(HISTORY_FILE_NAME))
21}
22
23impl Application {
24    /// Runs an interactive prompt with line editing and persistent history.
25    ///
26    /// TTY: `rustyline` (↑/↓ history). Non-TTY: plain stdin lines.
27    ///
28    /// # Errors
29    ///
30    /// Returns [`ConsoleError`] on I/O or command failure.
31    pub fn run_interactive(
32        &self,
33        environment: &Environment,
34        debug: bool,
35        container: Option<&Arc<Container>>,
36    ) -> Result<(), ConsoleError> {
37        let mut out = io::stdout();
38        writeln!(
39            out,
40            "Serenade interactive console - type a command, `list`, or `quit` (↑ history)"
41        )?;
42        out.flush()?;
43        self.print_list()?;
44
45        if io::stdin().is_terminal() {
46            self.run_interactive_readline(environment, debug, container)
47        } else {
48            self.run_interactive_plain(environment, debug, container)
49        }
50    }
51
52    fn run_interactive_readline(
53        &self,
54        environment: &Environment,
55        debug: bool,
56        container: Option<&Arc<Container>>,
57    ) -> Result<(), ConsoleError> {
58        let mut rl =
59            DefaultEditor::new().map_err(|error| ConsoleError::Failed(error.to_string()))?;
60        let hist = history_path();
61        if let Some(path) = hist.as_ref() {
62            let _ = rl.load_history(path);
63        }
64
65        loop {
66            match rl.readline("serenade> ") {
67                Ok(line) => {
68                    let trimmed = line.trim();
69                    if trimmed.is_empty() {
70                        continue;
71                    }
72                    let _ = rl.add_history_entry(trimmed);
73                    if self.dispatch_interactive_line(trimmed, environment, debug, container)? {
74                        break;
75                    }
76                }
77                Err(ReadlineError::Interrupted) => {}
78                Err(ReadlineError::Eof) => {
79                    println!();
80                    break;
81                }
82                Err(error) => return Err(ConsoleError::Failed(error.to_string())),
83            }
84        }
85
86        if let Some(path) = hist.as_ref() {
87            let _ = rl.save_history(path);
88        }
89        Ok(())
90    }
91
92    fn run_interactive_plain(
93        &self,
94        environment: &Environment,
95        debug: bool,
96        container: Option<&Arc<Container>>,
97    ) -> Result<(), ConsoleError> {
98        let mut out = io::stdout();
99        loop {
100            write!(out, "serenade> ")?;
101            out.flush()?;
102            let mut line = String::new();
103            let n = io::stdin().read_line(&mut line)?;
104            if n == 0 {
105                writeln!(out)?;
106                break;
107            }
108            let trimmed = line.trim();
109            if trimmed.is_empty() {
110                continue;
111            }
112            if self.dispatch_interactive_line(trimmed, environment, debug, container)? {
113                break;
114            }
115        }
116        Ok(())
117    }
118
119    /// Returns `true` when the session should exit.
120    pub(crate) fn dispatch_interactive_line(
121        &self,
122        line: &str,
123        environment: &Environment,
124        debug: bool,
125        container: Option<&Arc<Container>>,
126    ) -> Result<bool, ConsoleError> {
127        let mut parts = line.split_whitespace();
128        let Some(name) = parts.next() else {
129            return Ok(false);
130        };
131        if matches!(name, "quit" | "exit" | "q") {
132            return Ok(true);
133        }
134        if name == "list" {
135            self.print_list()?;
136            return Ok(false);
137        }
138        let trailing: Vec<String> = parts.map(str::to_owned).collect();
139        let Some(command) = self.find(name) else {
140            eprintln!("command `{name}` was not found; type `list`");
141            return Ok(false);
142        };
143        let input = Input::new(environment.clone(), debug, trailing, container.cloned());
144        if let Err(error) = command.execute(&input) {
145            eprintln!("{error}");
146        }
147        Ok(false)
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use crate::Command;
155    use std::sync::Arc;
156
157    struct Ping;
158
159    impl Command for Ping {
160        fn name(&self) -> &'static str {
161            "app:ping"
162        }
163
164        fn description(&self) -> &'static str {
165            "pong"
166        }
167
168        fn execute(&self, _input: &Input) -> Result<(), ConsoleError> {
169            Ok(())
170        }
171    }
172
173    #[test]
174    fn history_path_uses_home_when_set() {
175        let path = history_path();
176        if std::env::var_os("HOME").is_some() {
177            let path = path.expect("HOME set");
178            assert!(path.ends_with(HISTORY_FILE_NAME));
179        }
180    }
181
182    #[test]
183    fn dispatch_quit_and_unknown() {
184        let mut app = Application::new();
185        app.add(Arc::new(Ping));
186        assert!(
187            app.dispatch_interactive_line("quit", &Environment::Dev, true, None)
188                .expect("quit")
189        );
190        assert!(
191            !app.dispatch_interactive_line("missing:cmd", &Environment::Dev, true, None)
192                .expect("missing")
193        );
194        assert!(
195            !app.dispatch_interactive_line("app:ping", &Environment::Dev, true, None)
196                .expect("ping")
197        );
198    }
199}