1use colored::Colorize;
42use std::io::Write;
43use std::sync::atomic::{AtomicU32, Ordering};
44use std::sync::{Arc, Mutex};
45use std::time::Duration;
46use tokio::sync::watch;
47use tokio::task::JoinHandle;
48
49type SharedWriter = Arc<Mutex<Box<dyn Write + Send>>>;
52
53pub const ANIMATION_INTERVAL: Duration = Duration::from_millis(200);
55
56pub const SPINNER_FRAMES: [char; 4] = ['⠋', '⠙', '⠹', '⠸'];
58
59pub const BAR_WIDTH: usize = 20;
61
62#[derive(Debug, Clone, Copy)]
64enum Mode {
65 Spinner,
67 Bar { total: u32 },
69}
70
71#[derive(Debug, Clone)]
73enum Status {
74 Running,
76 Complete(String),
78 Aborted,
80}
81
82pub fn spinner_line(message: &str, frame_index: usize) -> String {
93 let frame = SPINNER_FRAMES[frame_index % SPINNER_FRAMES.len()];
94 format!("\r\x1b[2K{message} {frame}")
95}
96
97pub fn bar_line(message: &str, step: u32, total: u32) -> String {
112 let total = total.max(1);
113 let step = step.min(total);
114 let percent = step * 100 / total;
115 let filled = (step as usize * BAR_WIDTH / total as usize).min(BAR_WIDTH);
116 let empty = BAR_WIDTH - filled;
117 let bar = format!("{}{}", "█".repeat(filled), "░".repeat(empty));
118 format!("\r\x1b[2K{message} [{bar}] {percent}%")
119}
120
121pub fn show_progress(message: &str, total_steps: u32) -> Progress {
131 show_progress_with(
132 message,
133 total_steps,
134 ANIMATION_INTERVAL,
135 Box::new(std::io::stdout()),
136 )
137}
138
139fn show_progress_with(
142 message: &str,
143 total_steps: u32,
144 interval: Duration,
145 writer: Box<dyn Write + Send>,
146) -> Progress {
147 let (status_tx, status_rx) = watch::channel(Status::Running);
148 let step = Arc::new(AtomicU32::new(0));
149 let mode = if total_steps == 0 {
150 Mode::Spinner
151 } else {
152 Mode::Bar { total: total_steps }
153 };
154 let writer: SharedWriter = Arc::new(Mutex::new(writer));
155 let task = tokio::spawn(animator(
156 message.to_string(),
157 mode,
158 interval,
159 status_rx,
160 Arc::clone(&step),
161 Arc::clone(&writer),
162 ));
163 Progress {
164 task: Some(task),
165 status: status_tx,
166 step,
167 writer,
168 finished: false,
169 }
170}
171
172pub struct Progress {
174 task: Option<JoinHandle<()>>,
175 status: watch::Sender<Status>,
176 step: Arc<AtomicU32>,
177 writer: SharedWriter,
178 finished: bool,
179}
180
181impl Progress {
182 pub fn advance(&self) -> u32 {
184 self.step.fetch_add(1, Ordering::Relaxed) + 1
185 }
186
187 pub fn step_to(&self, step: u32) {
189 self.step.store(step, Ordering::Relaxed);
190 }
191
192 pub async fn finish(mut self, completion: impl Into<String>) {
197 self.finished = true;
198 let _ = self.status.send(Status::Complete(completion.into()));
199 if let Some(task) = self.task.take() {
200 let _ = task.await;
201 }
202 }
203
204 pub async fn abort(mut self) {
206 self.finished = true;
207 let _ = self.status.send(Status::Aborted);
208 if let Some(task) = self.task.take() {
209 let _ = task.await;
210 }
211 }
212}
213
214impl Drop for Progress {
215 fn drop(&mut self) {
216 if self.finished {
217 return;
218 }
219 let _ = self.status.send(Status::Aborted);
220 if let Some(task) = self.task.take() {
221 task.abort();
222 }
223 if let Ok(mut writer) = self.writer.lock() {
225 let _ = writer.write_all(b"\r\x1b[2K\x1b[?25h");
226 }
227 }
228}
229
230async fn animator(
236 message: String,
237 mode: Mode,
238 interval: Duration,
239 mut status: watch::Receiver<Status>,
240 step: Arc<AtomicU32>,
241 writer: SharedWriter,
242) {
243 let _ = writer.lock().unwrap().write_all(b"\x1b[?25l");
244 let mut frame = 0usize;
245 loop {
246 tokio::select! {
247 _ = status.changed() => break,
248 _ = tokio::time::sleep(interval) => {
249 let line = match &mode {
250 Mode::Spinner => spinner_line(&message, frame),
251 Mode::Bar { total } => bar_line(
252 &message,
253 step.load(Ordering::Relaxed).min(*total),
254 *total,
255 ),
256 };
257 let mut out = writer.lock().unwrap();
258 let _ = out.write_all(line.as_bytes());
259 let _ = out.flush();
260 frame += 1;
261 }
262 }
263 }
264 {
265 let mut out = writer.lock().unwrap();
266 let _ = out.write_all(b"\r\x1b[2K");
267 if let Status::Complete(completion) = status.borrow().clone() {
268 let _ = writeln!(out, "{} {completion}", "✓".green());
269 }
270 let _ = out.write_all(b"\x1b[?25h");
271 let _ = out.flush();
272 }
273}
274
275#[cfg(test)]
276mod tests {
277 use super::*;
278 use std::io;
279
280 const TICK: Duration = Duration::from_millis(5);
282
283 #[derive(Debug, Default, Clone)]
285 struct SharedBuffer(Arc<Mutex<Vec<u8>>>);
286
287 impl SharedBuffer {
288 fn text(&self) -> String {
289 String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
290 }
291 }
292
293 impl Write for SharedBuffer {
294 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
295 self.0.lock().unwrap().extend_from_slice(buf);
296 Ok(buf.len())
297 }
298
299 fn flush(&mut self) -> io::Result<()> {
300 Ok(())
301 }
302 }
303
304 #[test]
309 fn spinner_frames_rotate_through_the_braille_cycle() {
310 assert_eq!(SPINNER_FRAMES, ['⠋', '⠙', '⠹', '⠸']);
311 }
312
313 #[test]
314 fn spinner_line_erases_and_cycles_per_frame() {
315 assert_eq!(
316 spinner_line("Detecting stack...", 0),
317 "\r\x1b[2KDetecting stack... ⠋"
318 );
319 assert_eq!(
320 spinner_line("Detecting stack...", 1),
321 "\r\x1b[2KDetecting stack... ⠙"
322 );
323 assert_eq!(
324 spinner_line("Detecting stack...", 4),
325 "\r\x1b[2KDetecting stack... ⠋"
326 );
327 }
328
329 #[test]
330 fn bar_line_renders_exact_width_and_percent() {
331 let line = bar_line("Running diagnostics...", 8, 20);
332 assert!(line.starts_with("\r\x1b[2KRunning diagnostics... "));
333 assert!(line.ends_with("] 40%"), "8/20 must read 40%, got: {line}");
334
335 let open = line.rfind('[').unwrap();
338 let close = line.find(']').unwrap();
339 let bar = &line[open + 1..close];
340 assert_eq!(
341 bar.chars().count(),
342 BAR_WIDTH,
343 "bar must fill {BAR_WIDTH} cells"
344 );
345 assert_eq!(
346 bar.chars().filter(|&c| c == '█').count(),
347 8,
348 "8 of 20 cells filled at 40%"
349 );
350 assert_eq!(
351 bar.chars().filter(|&c| c == '░').count(),
352 BAR_WIDTH - 8,
353 "the rest of the bar stays empty"
354 );
355 }
356
357 #[test]
358 fn bar_line_clamps_step_to_100_percent() {
359 let line = bar_line("Running diagnostics...", 99, 20);
360 assert!(line.ends_with("100%"));
361 assert!(line.contains(&"█".repeat(BAR_WIDTH)));
362 assert!(!line.contains('░'));
363 }
364
365 #[test]
366 fn bar_line_zero_step_is_empty_and_guards_zero_total() {
367 assert!(bar_line("Running diagnostics...", 0, 20).contains(&"░".repeat(BAR_WIDTH)));
368 assert!(bar_line("Running diagnostics...", 0, 0).ends_with("0%"));
369 }
370
371 #[tokio::test]
376 async fn spinner_rotates_and_finish_prints_checkmark_with_cleanup() {
377 let buf = SharedBuffer::default();
378 let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
379 tokio::time::sleep(Duration::from_millis(120)).await;
380 progress.finish("Stack detected: Node.js v18.12.0").await;
381
382 let out = buf.text();
383 assert!(out.starts_with("\x1b[?25l"));
385 let seen: Vec<char> = SPINNER_FRAMES
387 .iter()
388 .copied()
389 .filter(|f| out.contains(*f))
390 .collect();
391 assert!(
392 seen.len() >= 2,
393 "expected several rotation frames, saw {seen:?}"
394 );
395 assert!(out.contains("\r\x1b[2K✓ Stack detected: Node.js v18.12.0"));
397 assert!(out.ends_with("\x1b[?25h"), "cursor must be restored");
398 }
399
400 #[tokio::test]
401 async fn bar_advances_step_by_step_towards_completion() {
402 let buf = SharedBuffer::default();
403 let progress = show_progress_with("Running diagnostics...", 4, TICK, Box::new(buf.clone()));
404 tokio::time::sleep(Duration::from_millis(20)).await;
405 progress.advance(); tokio::time::sleep(Duration::from_millis(20)).await;
407 progress.advance(); tokio::time::sleep(Duration::from_millis(20)).await;
409 progress.finish("Diagnostics complete").await;
410
411 let out = buf.text();
412 assert!(out.contains("25%"), "second frame should show 25%");
413 assert!(out.contains("50%"), "later frames should show 50%");
414 assert!(!out.contains("100%"));
415 assert!(out.contains("\r\x1b[2K✓ Diagnostics complete"));
416 assert!(out.ends_with("\x1b[?25h"));
417 }
418
419 #[tokio::test]
420 async fn abort_cleans_up_without_printing_checkmark() {
421 let buf = SharedBuffer::default();
422 let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
423 tokio::time::sleep(Duration::from_millis(15)).await;
424 progress.abort().await;
425
426 let out = buf.text();
427 assert!(!out.contains('✓'));
428 assert!(out.ends_with("\x1b[?25h"));
429 assert!(out.contains("\x1b[2K"));
430 }
431
432 #[tokio::test]
433 async fn dropping_unfinished_handle_aborts_and_cleans_line() {
434 let buf = SharedBuffer::default();
435 let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
436 tokio::time::sleep(Duration::from_millis(15)).await;
437 drop(progress);
438
439 let out = buf.text();
440 assert!(
441 out.ends_with("\r\x1b[2K\x1b[?25h"),
442 "drop must clear the line"
443 );
444 }
445
446 #[tokio::test]
447 async fn finish_before_first_frame_still_prints_clean_completion() {
448 let buf = SharedBuffer::default();
449 let progress = show_progress_with("Detecting stack...", 0, TICK, Box::new(buf.clone()));
450 progress.finish("Stack detected: Rust v1.98.0").await;
451
452 let out = buf.text();
453 assert!(out.contains("\r\x1b[2K✓ Stack detected: Rust v1.98.0"));
454 assert!(out.ends_with("\x1b[?25h"));
455 }
456
457 #[test]
458 fn test_progress_bar_accuracy() {
459 let line = bar_line("Scanning", 5, 10);
460 assert!(line.starts_with("\r\x1b[2K"), "got: {line}");
461 assert!(line.contains("Scanning ["));
462 let filled = line.matches('█').count();
463 let empty = line.matches('░').count();
464 assert_eq!(filled + empty, BAR_WIDTH, "bar must fill BAR_WIDTH");
465 assert_eq!(filled, BAR_WIDTH / 2, "5/10 must fill half the bar");
466 assert!(line.ends_with("50%"));
467
468 assert_eq!(bar_line("Scanning", 0, 10).matches('█').count(), 0);
469 assert_eq!(
470 bar_line("Scanning", 0, 10).matches('░').count(),
471 BAR_WIDTH
472 );
473 assert!(bar_line("Scanning", 10, 10).ends_with("100%"));
474 assert_eq!(bar_line("Scanning", 10, 10).matches('█').count(), BAR_WIDTH);
475
476 assert!(bar_line("Scanning", 99, 20).ends_with("100%"));
478
479 assert!(bar_line("Scanning", 1, 0).ends_with("100%"));
481 }
482}