Skip to main content

syncbox/utils/
progress.rs

1use indicatif::{ProgressBar, ProgressStyle, ProgressState};
2use std::fmt::Write;
3use crate::utils::format::format_file_size;
4
5pub fn create_progress_bar(total: u64) -> ProgressBar {
6    let pb = ProgressBar::new(total);
7    pb.set_style(
8        ProgressStyle::with_template(
9            "{spinner:.green} {bytes}/{total_bytes} [{bar:40.cyan/blue}] {bytes_per_sec} ({elapsed_precise} / {eta})"
10        )
11            .unwrap()
12            .with_key("eta", |state: &ProgressState, w: &mut dyn Write| {
13                if state.pos() >= state.len().unwrap_or(0) {
14                    write!(w, "0.0s").unwrap();
15                } else {
16                    write!(w, "{:.1}s", state.eta().as_secs_f64()).unwrap();
17                }
18            })
19            .with_key("bytes", |state: &ProgressState, w: &mut dyn Write| {
20                write!(w, "{}", format_file_size(state.pos())).unwrap();
21            })
22            .with_key("total_bytes", |state: &ProgressState, w: &mut dyn Write| {
23                write!(w, "{}", format_file_size(state.len().unwrap_or(0))).unwrap();
24            })
25            .with_key("bytes_per_sec", |state: &ProgressState, w: &mut dyn Write| {
26                let rate = state.per_sec();
27                if rate.is_nan() || rate <= 0.0 {
28                    write!(w, "-").unwrap();
29                } else if rate < 1024.0 {
30                    write!(w, "{:.1} B/s", rate).unwrap();
31                } else if rate < 1024.0 * 1024.0 {
32                    write!(w, "{:.1} KB/s", rate / 1024.0).unwrap();
33                } else if rate < 1024.0 * 1024.0 * 1024.0 {
34                    write!(w, "{:.1} MB/s", rate / (1024.0 * 1024.0)).unwrap();
35                } else {
36                    write!(w, "{:.1} GB/s", rate / (1024.0 * 1024.0 * 1024.0)).unwrap();
37                }
38            })
39            .progress_chars("#>-")
40    );
41    pb
42}