Skip to main content

pimalaya_cli/
spinner.rs

1//! Lightweight terminal spinner built on crossterm.
2//!
3//! Renders a single-line braille spinner with a live message on
4//! stderr (so stdout stays clean for piped data), runs on a
5//! background OS thread, and disables itself when stderr is not a
6//! TTY. Its glyphs are coloured on a TTY only, and never under a
7//! non-empty `NO_COLOR` (<https://no-color.org>).
8//!
9//! Typical use around a long-running operation:
10//!
11//! ```no_run
12//! use pimalaya_cli::spinner::Spinner;
13//!
14//! let spinner = Spinner::start("Connecting…");
15//! spinner.set_message("Listing mailboxes");
16//! // … run the long work …
17//! spinner.success("Listed 12 mailboxes");
18//! ```
19
20use std::{
21    env,
22    ffi::OsString,
23    io::{IsTerminal, Write, stderr},
24    sync::{
25        Arc, Mutex, OnceLock,
26        atomic::{AtomicBool, Ordering},
27    },
28    thread::{self, JoinHandle},
29    time::Duration,
30};
31
32use crossterm::{
33    QueueableCommand, cursor,
34    style::{Color, Print, PrintStyledContent, Stylize},
35    terminal::{Clear, ClearType},
36};
37
38use crate::signal;
39
40const FRAMES: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
41
42const FRAME_INTERVAL: Duration = Duration::from_millis(80);
43
44/// A single-line terminal spinner with a live message.
45pub struct Spinner {
46    message: Arc<Mutex<String>>,
47    stop: Arc<AtomicBool>,
48    handle: Option<JoinHandle<()>>,
49    colour: bool,
50}
51
52impl Spinner {
53    /// Start the spinner with an initial message.
54    ///
55    /// When stderr is not a TTY no thread is spawned and ticks are
56    /// suppressed; terminal completion lines (`success`/`failure`)
57    /// are still printed, as plain text, so logs remain informative.
58    ///
59    /// The first TTY-bound call also installs a process-wide SIGINT /
60    /// SIGTERM / SIGHUP handler and a panic hook that restore the
61    /// cursor before letting the process die: Drop is skipped on
62    /// signal-induced termination and on panic = abort, so without
63    /// these hooks `cursor::Hide` from the render loop would leak
64    /// past process exit.
65    pub fn start(message: impl Into<String>) -> Self {
66        let message = Arc::new(Mutex::new(message.into()));
67        let stop = Arc::new(AtomicBool::new(false));
68        let terminal = stderr().is_terminal();
69        let colour = colour_wanted(terminal, env::var_os("NO_COLOR"));
70
71        let handle = if terminal {
72            install_terminal_guards();
73            let message = message.clone();
74            let stop = stop.clone();
75            Some(thread::spawn(move || render_loop(message, stop, colour)))
76        } else {
77            None
78        };
79
80        Self {
81            message,
82            stop,
83            handle,
84            colour,
85        }
86    }
87
88    /// Replace the message displayed next to the spinner frame.
89    pub fn set_message(&self, message: impl Into<String>) {
90        if let Ok(mut current) = self.message.lock() {
91            *current = message.into();
92        }
93    }
94
95    /// Stop the spinner and print `✓` (green on a TTY) and `message`.
96    pub fn success(self, message: impl AsRef<str>) {
97        self.finish("✓", Color::Green, message.as_ref());
98    }
99
100    /// Stop the spinner and print `✗` (red on a TTY) and `message`.
101    pub fn failure(self, message: impl AsRef<str>) {
102        self.finish("✗", Color::Red, message.as_ref());
103    }
104
105    /// Stop the spinner and clear its line without printing anything
106    /// in its place.
107    pub fn clear(mut self) {
108        self.shutdown();
109    }
110
111    fn finish(mut self, glyph: &str, color: Color, message: &str) {
112        self.shutdown();
113
114        let mut out = stderr();
115        queue_glyph(&mut out, glyph, color, self.colour);
116        out.queue(Print(format!(" {message}\n"))).ok();
117        out.flush().ok();
118    }
119
120    fn shutdown(&mut self) {
121        self.stop.store(true, Ordering::Relaxed);
122        if let Some(handle) = self.handle.take() {
123            handle.join().ok();
124        }
125    }
126}
127
128impl Drop for Spinner {
129    fn drop(&mut self) {
130        self.shutdown();
131    }
132}
133
134static TERMINAL_GUARDS: OnceLock<()> = OnceLock::new();
135
136fn install_terminal_guards() {
137    TERMINAL_GUARDS.get_or_init(|| {
138        // NOTE: a signal ending the process bypasses Drop, so the render
139        // loop never reaches its `cursor::Show` tail: the shared handler
140        // restores the terminal first, then exits 130. Under an
141        // installed Shutdown the first signal only requests it, and the
142        // spinner is dropped as the command stops.
143        let _ = signal::install_handler_with(restore_terminal);
144
145        // panic = abort skips Drop too. Chain a hook in front of the
146        // default so the panic message still reaches stderr after the
147        // cursor is restored.
148        let default_hook = std::panic::take_hook();
149        std::panic::set_hook(Box::new(move |info| {
150            restore_terminal();
151            default_hook(info);
152        }));
153    });
154}
155
156fn restore_terminal() {
157    let mut out = stderr();
158    out.queue(cursor::MoveToColumn(0)).ok();
159    out.queue(Clear(ClearType::CurrentLine)).ok();
160    out.queue(cursor::Show).ok();
161    out.flush().ok();
162}
163
164/// Whether to colour: on a TTY, unless `NO_COLOR` is set and not empty.
165fn colour_wanted(terminal: bool, no_color: Option<OsString>) -> bool {
166    terminal && no_color.is_none_or(|value| value.is_empty())
167}
168
169/// Queue `glyph`, plain unless `colour`: crossterm under `NO_COLOR` still
170/// writes `ESC[m` around it.
171fn queue_glyph(out: &mut impl Write, glyph: &str, color: Color, colour: bool) {
172    if colour {
173        out.queue(PrintStyledContent(glyph.with(color))).ok();
174    } else {
175        out.queue(Print(glyph)).ok();
176    }
177}
178
179fn render_loop(message: Arc<Mutex<String>>, stop: Arc<AtomicBool>, colour: bool) {
180    let mut out = stderr();
181
182    out.queue(cursor::Hide).ok();
183    out.flush().ok();
184
185    let mut frame = 0;
186    while !stop.load(Ordering::Relaxed) {
187        let snapshot = message.lock().map(|m| m.clone()).unwrap_or_default();
188
189        out.queue(cursor::MoveToColumn(0)).ok();
190        out.queue(Clear(ClearType::CurrentLine)).ok();
191        queue_glyph(&mut out, FRAMES[frame], Color::Cyan, colour);
192        out.queue(Print(format!(" {snapshot}"))).ok();
193        out.flush().ok();
194
195        frame = (frame + 1) % FRAMES.len();
196        thread::sleep(FRAME_INTERVAL);
197    }
198
199    out.queue(cursor::MoveToColumn(0)).ok();
200    out.queue(Clear(ClearType::CurrentLine)).ok();
201    out.queue(cursor::Show).ok();
202    out.flush().ok();
203}
204
205#[cfg(test)]
206mod tests {
207    use std::{env, ffi::OsString, process::Command};
208
209    use super::{Spinner, colour_wanted};
210
211    const CHILD: &str = "PIMALAYA_CLI_SPINNER_CHILD";
212
213    #[test]
214    fn an_empty_no_color_keeps_the_colour() {
215        assert!(colour_wanted(true, None));
216        assert!(colour_wanted(true, Some(OsString::new())));
217        assert!(!colour_wanted(true, Some(OsString::from("0"))));
218        assert!(!colour_wanted(false, None));
219    }
220
221    #[test]
222    fn a_stream_that_is_no_terminal_gets_plain_lines() {
223        if env::var_os(CHILD).is_some() {
224            Spinner::start("Checking…").success("Checked");
225            Spinner::start("Sending…").failure("Not sent");
226            return;
227        }
228
229        // The test binary runs this test again, its stderr a pipe.
230        for no_color in [None, Some("1")] {
231            let mut child = Command::new(env::current_exe().unwrap());
232            child
233                .args([
234                    "--exact",
235                    "spinner::tests::a_stream_that_is_no_terminal_gets_plain_lines",
236                ])
237                .env(CHILD, "1");
238            match no_color {
239                Some(value) => child.env("NO_COLOR", value),
240                None => child.env_remove("NO_COLOR"),
241            };
242
243            let output = child.output().unwrap();
244            assert!(output.status.success());
245            assert_eq!(
246                String::from_utf8_lossy(&output.stderr),
247                "✓ Checked\n✗ Not sent\n",
248                "NO_COLOR={no_color:?}",
249            );
250        }
251    }
252}