Skip to main content

rust_analyzer/cli/
progress_report.rs

1//! A simple progress bar
2//!
3//! A single thread non-optimized progress bar
4use std::io::{self, IsTerminal, Write};
5
6/// A Simple ASCII Progress Bar
7pub(crate) struct ProgressReport<'a> {
8    curr: f32,
9    text: String,
10    hidden: bool,
11
12    len: usize,
13    pos: u64,
14    msg: Option<Box<dyn Fn() -> String + 'a>>,
15}
16
17impl<'a> ProgressReport<'a> {
18    pub(crate) fn new(len: usize) -> ProgressReport<'a> {
19        let is_tty = io::stdout().is_terminal();
20        ProgressReport { curr: 0.0, text: String::new(), hidden: !is_tty, len, pos: 0, msg: None }
21    }
22
23    pub(crate) fn hidden() -> ProgressReport<'a> {
24        ProgressReport { curr: 0.0, text: String::new(), hidden: true, len: 0, pos: 0, msg: None }
25    }
26
27    pub(crate) fn set_message(&mut self, msg: impl Fn() -> String + 'a) {
28        if !self.hidden {
29            self.msg = Some(Box::new(msg));
30        }
31        self.tick();
32    }
33
34    pub(crate) fn println<I: Into<String>>(&mut self, msg: I) {
35        self.clear();
36        println!("{}", msg.into());
37        self.tick();
38    }
39
40    pub(crate) fn inc(&mut self, delta: u64) {
41        self.pos += delta;
42        if self.len == 0 {
43            self.set_value(0.0)
44        } else {
45            self.set_value((self.pos as f32) / (self.len as f32))
46        }
47        self.tick();
48    }
49
50    pub(crate) fn finish_and_clear(&mut self) {
51        self.clear();
52    }
53
54    pub(crate) fn tick(&mut self) {
55        if self.hidden {
56            return;
57        }
58        let percent = (self.curr * 100.0) as u32;
59        let text = format!(
60            "{}/{} {percent:3>}% {}",
61            self.pos,
62            self.len,
63            self.msg.as_ref().map_or_else(String::new, |it| it())
64        );
65        self.update_text(&text);
66    }
67
68    fn update_text(&mut self, text: &str) {
69        let output = render_text_update(&self.text, text);
70        let _ = io::stdout().write(output.as_bytes());
71        let _ = io::stdout().flush();
72        text.clone_into(&mut self.text);
73    }
74
75    fn set_value(&mut self, value: f32) {
76        self.curr = value.clamp(0.0, 1.0);
77    }
78
79    fn clear(&mut self) {
80        if self.hidden {
81            return;
82        }
83
84        // Fill all last text to space and return the cursor
85        let len = self.text.chars().count();
86        let spaces = " ".repeat(len);
87        let backspaces = "\x08".repeat(len);
88        print!("{backspaces}{spaces}{backspaces}");
89        let _ = io::stdout().flush();
90
91        self.text = String::new();
92    }
93}
94
95fn render_text_update(old: &str, new: &str) -> String {
96    let old_len = old.chars().count();
97    let new_len = new.chars().count();
98
99    // Get length of common portion
100    let mut common_prefix_length = 0;
101    let common_length = usize::min(old_len, new_len);
102
103    while common_prefix_length < common_length
104        && new.chars().nth(common_prefix_length).unwrap()
105            == old.chars().nth(common_prefix_length).unwrap()
106    {
107        common_prefix_length += 1;
108    }
109
110    // Backtrack to the first differing character
111    let mut output = String::new();
112    output += &'\x08'.to_string().repeat(old_len - common_prefix_length);
113    // Output new suffix, using chars() iter to ensure unicode compatibility
114    output.extend(new.chars().skip(common_prefix_length));
115
116    // If the new text is shorter than the old one: delete overlapping characters
117    if let Some(overlap_count) = old_len.checked_sub(new_len)
118        && overlap_count > 0
119    {
120        output += &" ".repeat(overlap_count);
121        output += &"\x08".repeat(overlap_count);
122    }
123
124    output
125}
126
127#[cfg(test)]
128mod tests {
129    use super::render_text_update;
130
131    #[test]
132    fn ascii_prefix_reuse() {
133        let old = "1/7 14% processing: foo";
134        let new = "1/7 28% processing: bar";
135        let update = render_text_update(old, new);
136
137        let common = "1/7 ";
138        let backspaces = old.chars().count() - common.chars().count();
139        let expected = format!("{}{}", "\x08".repeat(backspaces), "28% processing: bar");
140        assert_eq!(update, expected);
141    }
142
143    #[test]
144    fn unicode_identifiers_do_not_panic() {
145        // Regression test for rust-lang/rust-analyzer#22844: previous code
146        // compared byte lengths with char indices, so `chars().nth(...).unwrap()`
147        // panicked on non-ASCII.
148        let old = "1/7 14% processing: f::消息";
149        let new = "2/7 28% processing: f::消息内容";
150        let update = render_text_update(old, new);
151
152        let backspaces = old.chars().count();
153        let expected = format!("{}{new}", "\x08".repeat(backspaces));
154        assert_eq!(update, expected);
155    }
156
157    #[test]
158    fn shorter_unicode_message_clears_overlap() {
159        let old = "processing: 消息内容";
160        let new = "processing: 消息";
161        let update = render_text_update(old, new);
162
163        // Drop the last two chars, then blank/backspace the leftover width.
164        let expected = "\x08\x08  \x08\x08";
165        assert_eq!(update, expected);
166    }
167}