summaryrefslogtreecommitdiff
path: root/src/progress.rs
blob: f6f22279c418131d73caca54cd063795c22dac85 (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use std::io::{self, Write};

pub struct ProgressBar {
    total: usize,
    current: usize,
    message: String,
    width: usize,
}

impl ProgressBar {
    pub fn new(total: usize, message: &str) -> Self {
        Self {
            total,
            current: 0,
            message: message.to_string(),
            width: 38,
        }
    }


    pub fn inc(&mut self, msg: &str) {
        self.current += 1;
        self.message = msg.to_string();
        self.render();
    }

    fn render(&self) {
        let filled = if self.total == 0 {
            0
        } else {
            self.current * self.width / self.total
        };
        let arrow = if filled < self.width { ">" } else { "=" };
        let bar = format!(
            "{}{}{}",
            "=".repeat(filled.saturating_sub(1)),
            arrow,
            " ".repeat(self.width.saturating_sub(filled))
        );
        eprint!(
            "\r\x1b[K\x1b[36m[{}]\x1b[0m \x1b[32m{}/{}\x1b[0m  {}",
            bar,
            self.current,
            self.total,
            self.message
        );
        io::stderr().flush().ok();
    }

    pub fn finish(&self, msg: &str) {
        let bar = "=".repeat(self.width);
        eprintln!(
            "\r\x1b[K\x1b[36m[{}]\x1b[0m \x1b[32m{}/{}\x1b[0m  {}",
            bar, self.total, self.total, msg
        );
    }
}

pub struct Spinner {
    frames: &'static [&'static str],
    idx: usize,
    message: String,
}

impl Spinner {
    pub fn new(message: &str) -> Self {
        Self {
            frames: &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
            idx: 0,
            message: message.to_string(),
        }
    }

    pub fn tick(&mut self, msg: &str) {
        self.message = msg.to_string();
        eprint!("\r\x1b[K\x1b[36m{}\x1b[0m {}", self.frames[self.idx], self.message);
        io::stderr().flush().ok();
        self.idx = (self.idx + 1) % self.frames.len();
    }

    pub fn finish(&self, msg: &str) {
        eprintln!("\r\x1b[K\x1b[32m✓\x1b[0m {}", msg);
    }
}

pub fn format_bytes(bytes: u64) -> String {
    if bytes < 1024 {
        format!("{} B", bytes)
    } else if bytes < 1024 * 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else {
        format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
    }
}