use colored::Colorize;
use std::io::Write;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::watch;
use tokio::task::JoinHandle;
type SharedWriter = Arc<Mutex<Box<dyn Write + Send>>>;
pub const ANIMATION_INTERVAL: Duration = Duration::from_millis(200);
pub const SPINNER_FRAMES: [char; 4] = ['⠋', '⠙', '⠹', '⠸'];
pub const BAR_WIDTH: usize = 20;
#[derive(Debug, Clone, Copy)]
enum Mode {
Spinner,
Bar { total: u32 },
}
#[derive(Debug, Clone)]
enum Status {
Running,
Complete(String),
Aborted,
}
pub fn spinner_line(message: &str, frame_index: usize) -> String {
let frame = SPINNER_FRAMES[frame_index % SPINNER_FRAMES.len()];
format!("\r\x1b[2K{message} {frame}")
}
pub fn bar_line(message: &str, step: u32, total: u32) -> String {
let total = total.max(1);
let step = step.min(total);
let percent = step * 100 / total;
let filled = (step as usize * BAR_WIDTH / total as usize).min(BAR_WIDTH);
let empty = BAR_WIDTH - filled;
let bar = format!("{}{}", "█".repeat(filled), "░".repeat(empty));
format!("\r\x1b[2K{message} [{bar}] {percent}%")
}
pub fn show_progress(message: &str, total_steps: u32) -> Progress {
show_progress_with(
message,
total_steps,
ANIMATION_INTERVAL,
Box::new(std::io::stdout()),
)
}
fn show_progress_with(
message: &str,
total_steps: u32,
interval: Duration,
writer: Box<dyn Write + Send>,
) -> Progress {
let (status_tx, status_rx) = watch::channel(Status::Running);
let step = Arc::new(AtomicU32::new(0));
let mode = if total_steps == 0 {
Mode::Spinner
} else {
Mode::Bar { total: total_steps }
};
let writer: SharedWriter = Arc::new(Mutex::new(writer));
let task = tokio::spawn(animator(
message.to_string(),
mode,
interval,
status_rx,
Arc::clone(&step),
Arc::clone(&writer),
));
Progress {
task: Some(task),
status: status_tx,
step,
writer,
finished: false,
}
}
pub struct Progress {
task: Option<JoinHandle<()>>,
status: watch::Sender<Status>,
step: Arc<AtomicU32>,
writer: SharedWriter,
finished: bool,
}
impl Progress {
pub fn advance(&self) -> u32 {
self.step.fetch_add(1, Ordering::Relaxed) + 1
}
pub fn step_to(&self, step: u32) {
self.step.store(step, Ordering::Relaxed);
}
pub async fn finish(mut self, completion: impl Into<String>) {
self.finished = true;
let _ = self.status.send(Status::Complete(completion.into()));
if let Some(task) = self.task.take() {
let _ = task.await;
}
}
pub async fn abort(mut self) {
self.finished = true;
let _ = self.status.send(Status::Aborted);
if let Some(task) = self.task.take() {
let _ = task.await;
}
}
}
impl Drop for Progress {
fn drop(&mut self) {
if self.finished {
return;
}
let _ = self.status.send(Status::Aborted);
if let Some(task) = self.task.take() {
task.abort();
}
if let Ok(mut writer) = self.writer.lock() {
let _ = writer.write_all(b"\r\x1b[2K\x1b[?25h");
}
}
}
async fn animator(
message: String,
mode: Mode,
interval: Duration,
mut status: watch::Receiver<Status>,
step: Arc<AtomicU32>,
writer: SharedWriter,
) {
let _ = writer.lock().unwrap().write_all(b"\x1b[?25l");
let mut frame = 0usize;
loop {
tokio::select! {
_ = status.changed() => break,
_ = tokio::time::sleep(interval) => {
let line = match &mode {
Mode::Spinner => spinner_line(&message, frame),
Mode::Bar { total } => bar_line(
&message,
step.load(Ordering::Relaxed).min(*total),
*total,
),
};
let mut out = writer.lock().unwrap();
let _ = out.write_all(line.as_bytes());
let _ = out.flush();
frame += 1;
}
}
}
{
let mut out = writer.lock().unwrap();
let _ = out.write_all(b"\r\x1b[2K");
if let Status::Complete(completion) = status.borrow().clone() {
let _ = writeln!(out, "{} {completion}", "✓".green());
}
let _ = out.write_all(b"\x1b[?25h");
let _ = out.flush();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io;
const TICK: Duration = Duration::from_millis(5);
#[derive(Debug, Default, Clone)]
struct SharedBuffer(Arc<Mutex<Vec<u8>>>);
impl SharedBuffer {
fn text(&self) -> String {
String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
}
}
impl Write for SharedBuffer {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn spinner_frames_rotate_through_the_braille_cycle() {
assert_eq!(SPINNER_FRAMES, ['⠋', '⠙', '⠹', '⠸']);
}
#[test]
fn spinner_line_erases_and_cycles_per_frame() {
assert_eq!(
spinner_line("Detecting stack...", 0),
"\r\x1b[2KDetecting stack... ⠋"
);
assert_eq!(
spinner_line("Detecting stack...", 1),
"\r\x1b[2KDetecting stack... ⠙"
);
assert_eq!(
spinner_line("Detecting stack...", 4),
"\r\x1b[2KDetecting stack... ⠋"
);
}
#[test]
fn bar_line_renders_exact_width_and_percent() {
let line = bar_line("Running diagnostics...", 8, 20);
assert!(line.starts_with("\r\x1b[2KRunning diagnostics... "));
assert!(line.ends_with("] 40%"), "8/20 must read 40%, got: {line}");
let open = line.rfind('[').unwrap();
let close = line.find(']').unwrap();
let bar = &line[open + 1..close];
assert_eq!(
bar.chars().count(),
BAR_WIDTH,
"bar must fill {BAR_WIDTH} cells"
);
assert_eq!(
bar.chars().filter(|&c| c == '█').count(),
8,
"8 of 20 cells filled at 40%"
);
assert_eq!(
bar.chars().filter(|&c| c == '░').count(),
BAR_WIDTH - 8,
"the rest of the bar stays empty"
);
}
#[test]
fn bar_line_clamps_step_to_100_percent() {
let line = bar_line("Running diagnostics...", 99, 20);
assert!(line.ends_with("100%"));
assert!(line.contains(&"█".repeat(BAR_WIDTH)));
assert!(!line.contains('░'));
}
#[test]
fn bar_line_zero_step_is_empty_and_guards_zero_total() {
assert!(bar_line("Running diagnostics...", 0, 20).contains(&"░".repeat(BAR_WIDTH)));
assert!(bar_line("Running diagnostics...", 0, 0).ends_with("0%"));
}
#[tokio::test]
async fn spinner_rotates_and_finish_prints_checkmark_with_cleanup() {
let buf = SharedBuffer::default();
let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
tokio::time::sleep(Duration::from_millis(120)).await;
progress.finish("Stack detected: Node.js v18.12.0").await;
let out = buf.text();
assert!(out.starts_with("\x1b[?25l"));
let seen: Vec<char> = SPINNER_FRAMES
.iter()
.copied()
.filter(|f| out.contains(*f))
.collect();
assert!(
seen.len() >= 2,
"expected several rotation frames, saw {seen:?}"
);
assert!(out.contains("\r\x1b[2K✓ Stack detected: Node.js v18.12.0"));
assert!(out.ends_with("\x1b[?25h"), "cursor must be restored");
}
#[tokio::test]
async fn bar_advances_step_by_step_towards_completion() {
let buf = SharedBuffer::default();
let progress = show_progress_with("Running diagnostics...", 4, TICK, Box::new(buf.clone()));
tokio::time::sleep(Duration::from_millis(20)).await;
progress.advance(); tokio::time::sleep(Duration::from_millis(20)).await;
progress.advance(); tokio::time::sleep(Duration::from_millis(20)).await;
progress.finish("Diagnostics complete").await;
let out = buf.text();
assert!(out.contains("25%"), "second frame should show 25%");
assert!(out.contains("50%"), "later frames should show 50%");
assert!(!out.contains("100%"));
assert!(out.contains("\r\x1b[2K✓ Diagnostics complete"));
assert!(out.ends_with("\x1b[?25h"));
}
#[tokio::test]
async fn abort_cleans_up_without_printing_checkmark() {
let buf = SharedBuffer::default();
let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
tokio::time::sleep(Duration::from_millis(15)).await;
progress.abort().await;
let out = buf.text();
assert!(!out.contains('✓'));
assert!(out.ends_with("\x1b[?25h"));
assert!(out.contains("\x1b[2K"));
}
#[tokio::test]
async fn dropping_unfinished_handle_aborts_and_cleans_line() {
let buf = SharedBuffer::default();
let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
tokio::time::sleep(Duration::from_millis(15)).await;
drop(progress);
let out = buf.text();
assert!(
out.ends_with("\r\x1b[2K\x1b[?25h"),
"drop must clear the line"
);
}
#[tokio::test]
async fn finish_before_first_frame_still_prints_clean_completion() {
let buf = SharedBuffer::default();
let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
progress.finish("Stack detected: Rust v1.98.0").await;
let out = buf.text();
assert!(out.contains("\r\x1b[2K✓ Stack detected: Rust v1.98.0"));
assert!(out.ends_with("\x1b[?25h"));
}
#[test]
fn test_progress_bar_accuracy() {
let line = bar_line("Scanning", 5, 10);
assert!(line.starts_with("\r\x1b[2K"), "got: {line}");
assert!(line.contains("Scanning ["));
let filled = line.matches('█').count();
let empty = line.matches('░').count();
assert_eq!(filled + empty, BAR_WIDTH, "bar must fill BAR_WIDTH");
assert_eq!(filled, BAR_WIDTH / 2, "5/10 must fill half the bar");
assert!(line.ends_with("50%"));
assert_eq!(bar_line("Scanning", 0, 10).matches('█').count(), 0);
assert_eq!(
bar_line("Scanning", 0, 10).matches('░').count(),
BAR_WIDTH
);
assert!(bar_line("Scanning", 10, 10).ends_with("100%"));
assert_eq!(bar_line("Scanning", 10, 10).matches('█').count(), BAR_WIDTH);
assert!(bar_line("Scanning", 99, 20).ends_with("100%"));
assert!(bar_line("Scanning", 1, 0).ends_with("100%"));
}
}