1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use indicatif::{ProgressBar as PBar, ProgressStyle};

use crate::result::Result;

pub trait ProgressTrait {
    type ProgressResultType;

    fn update(&self, msg: &str) -> Result<Self::ProgressResultType>;
    fn done(&self, msg: &str) -> Result<Self::ProgressResultType>;
    fn done_without_indicator(&self, msg: &str) -> Result<Self::ProgressResultType>;
}

pub struct ProgressBar {
    bar: PBar,
}

impl ProgressBar {
    pub fn new() -> Self {
        let bar = PBar::new_spinner();
        bar.enable_steady_tick(80);
        bar.set_style(
            ProgressStyle::default_spinner()
                // https://github.com/sindresorhus/cli-spinners/blob/master/spinners.json
                .tick_strings(&["⢹", "⢺", "⢼", "⣸", "⣇", "⡧", "⡗", "✔"])
                .template("{spinner} {msg}"),
        );

        Self { bar }
    }
}

impl ProgressTrait for ProgressBar {
    type ProgressResultType = ();

    fn update(&self, msg: &str) -> Result<Self::ProgressResultType> {
        self.bar.set_message(msg);

        Ok(())
    }

    fn done(&self, msg: &str) -> Result<Self::ProgressResultType> {
        self.bar.finish_with_message(msg);

        Ok(())
    }

    fn done_without_indicator(&self, msg: &str) -> Result<Self::ProgressResultType> {
        self.bar.finish_and_clear();
        if !msg.is_empty() {
            println!("{}", msg);
        }

        Ok(())
    }
}