use std::io::{stdout, IsTerminal, Write};
const WIDTH: usize = 30;
pub struct ProgressBar {
animate: bool,
label: String,
last_percent: Option<u32>,
}
impl ProgressBar {
pub fn start(label: &str) -> Self {
let mut bar = ProgressBar {
animate: stdout().is_terminal(),
label: label.to_string(),
last_percent: None,
};
bar.set(0.0);
bar
}
pub fn set(&mut self, fraction: f64) {
let percent = (fraction.clamp(0.0, 1.0) * 100.0).round() as u32;
if self.last_percent == Some(percent) {
return;
}
self.last_percent = Some(percent);
if self.animate {
let filled = (percent as usize * WIDTH) / 100;
print!(
"\r[{}{}] {:>3}% {}",
"#".repeat(filled),
".".repeat(WIDTH - filled),
percent,
self.label
);
let _ = stdout().flush();
}
}
pub fn finish(&mut self, completed: bool) {
if !self.animate {
return;
}
if completed {
self.set(1.0);
println!();
} else {
print!("\r\x1b[2K");
}
let _ = stdout().flush();
}
}
#[cfg(test)]
mod test_progress_integration {
use super::*;
use std::thread;
use std::time::Duration;
#[test]
fn progress_bar_fills_over_a_few_seconds() {
let mut bar = ProgressBar::start("Merging videos");
for step in 1..=30 {
thread::sleep(Duration::from_millis(100));
bar.set(step as f64 / 30.0);
}
bar.finish(true);
}
}