novel_cli/utils/
progress.rs1use std::fmt::Write;
2
3use color_eyre::eyre::Result;
4use indicatif::{ProgressState, ProgressStyle};
5
6#[must_use]
7#[derive(Clone)]
8pub struct ProgressBar {
9 pb: indicatif::ProgressBar,
10 message_width: usize,
11}
12
13impl ProgressBar {
14 pub fn new(total_size: u64) -> Result<Self> {
15 let message_width = (super::terminal_size().0 / 3) as usize;
16
17 let pb = indicatif::ProgressBar::new(total_size);
18
19 pb.set_style(ProgressStyle::with_template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {pos:>7}/{len:7} {msg:40} ({eta})")
20 .unwrap()
21 .with_key("eta", |state: &ProgressState, w: &mut dyn Write| {
22 write!(w, "{:.1}s", state.eta().as_secs_f64()).unwrap()
23 })
24 .progress_chars("#>-"));
25
26 Ok(Self { pb, message_width })
27 }
28
29 pub fn inc<T>(&mut self, msg: T)
30 where
31 T: AsRef<str>,
32 {
33 self.pb.set_message(
34 console::truncate_str(msg.as_ref(), self.message_width, "...").to_string(),
35 );
36 self.pb.inc(1);
37 }
38
39 pub fn finish(self) {
40 self.pb.finish_and_clear();
41 }
42}