Skip to main content

uv_command_support/
progress.rs

1use std::env;
2use std::fmt::{self, Write};
3use std::ops::Deref;
4use std::sync::{Arc, LazyLock, Mutex};
5
6use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
7use owo_colors::OwoColorize;
8use rustc_hash::FxHashMap;
9use uv_console::human_readable_bytes;
10use uv_redacted::DisplaySafeUrl;
11use uv_static::EnvVars;
12
13use crate::Printer;
14
15/// Since downloads, fetches and builds run in parallel, their message output order is
16/// non-deterministic, so can't capture them in test output.
17static HAS_UV_INTERNAL__TEST_NO_CLI_PROGRESS: LazyLock<bool> =
18    LazyLock::new(|| env::var(EnvVars::UV_INTERNAL__TEST_NO_CLI_PROGRESS).is_ok());
19
20#[derive(Debug)]
21pub struct ProgressReporter {
22    pub printer: Printer,
23    pub root: ProgressBar,
24    mode: ProgressMode,
25}
26
27#[derive(Debug)]
28enum ProgressMode {
29    /// Reports top-level progress.
30    Single,
31    /// Reports progress of all concurrent download, build, and checkout processes.
32    Multi {
33        multi_progress: MultiProgress,
34        state: Arc<Mutex<BarState>>,
35    },
36}
37
38#[derive(Debug)]
39enum ProgressBarKind {
40    /// A progress bar with an increasing value, such as a download.
41    Numeric {
42        progress: ProgressBar,
43        /// The download size in bytes, if known.
44        size: Option<u64>,
45    },
46    /// A progress spinner for a task, such as a build.
47    Spinner { progress: ProgressBar },
48}
49
50impl Deref for ProgressBarKind {
51    type Target = ProgressBar;
52
53    fn deref(&self) -> &Self::Target {
54        match self {
55            Self::Numeric { progress, .. } => progress,
56            Self::Spinner { progress } => progress,
57        }
58    }
59}
60
61#[derive(Debug)]
62struct BarState {
63    /// The number of bars that precede any download bars (i.e., build/checkout status).
64    headers: usize,
65    /// A list of download bar sizes, in descending order.
66    sizes: Vec<u64>,
67    /// A map of progress bars, by ID.
68    bars: FxHashMap<usize, ProgressBarKind>,
69    /// A monotonic counter for bar IDs.
70    id: usize,
71    /// The maximum length of all bar names encountered.
72    max_len: usize,
73}
74
75impl Default for BarState {
76    fn default() -> Self {
77        Self {
78            headers: 0,
79            sizes: Vec::default(),
80            bars: FxHashMap::default(),
81            id: 0,
82            // Avoid resizing the progress bar templates too often by starting with a padding
83            // that's wider than most package names.
84            max_len: 20,
85        }
86    }
87}
88
89impl BarState {
90    /// Returns a unique ID for a new progress bar.
91    fn id(&mut self) -> usize {
92        self.id += 1;
93        self.id
94    }
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum Direction {
99    Upload,
100    Download,
101    Extract,
102    Hash,
103}
104
105impl Direction {
106    fn as_str(&self) -> &str {
107        match self {
108            Self::Download => "Downloading",
109            Self::Upload => "Uploading",
110            Self::Extract => "Extracting",
111            Self::Hash => "Hashing",
112        }
113    }
114}
115
116impl ProgressReporter {
117    pub fn new(root: ProgressBar, multi_progress: MultiProgress, printer: Printer) -> Self {
118        let mode = if env::var(EnvVars::JPY_SESSION_NAME).is_ok() {
119            // Disable concurrent progress bars when running inside a Jupyter notebook
120            // because the Jupyter terminal does not support clearing previous lines.
121            // See: https://github.com/astral-sh/uv/issues/3887.
122            ProgressMode::Single
123        } else {
124            ProgressMode::Multi {
125                state: Arc::default(),
126                multi_progress,
127            }
128        };
129
130        Self {
131            printer,
132            root,
133            mode,
134        }
135    }
136
137    /// Start reporting a build using the caller's source display.
138    pub fn on_build_start(&self, source: &dyn fmt::Display) -> usize {
139        let ProgressMode::Multi {
140            multi_progress,
141            state,
142        } = &self.mode
143        else {
144            return 0;
145        };
146
147        let mut state = state.lock().unwrap();
148        let id = state.id();
149
150        let progress = multi_progress.insert_before(
151            &self.root,
152            ProgressBar::with_draw_target(None, self.printer.target()),
153        );
154
155        progress.set_style(ProgressStyle::with_template("{wide_msg}").unwrap());
156        let message = format!("   {} {}", "Building".bold().cyan(), source);
157        if multi_progress.is_hidden() && !*HAS_UV_INTERNAL__TEST_NO_CLI_PROGRESS {
158            let _ = writeln!(self.printer.stderr(), "{message}");
159        }
160        progress.set_message(message);
161
162        state.headers += 1;
163        state.bars.insert(id, ProgressBarKind::Spinner { progress });
164        id
165    }
166
167    /// Finish reporting a build using the caller's source display.
168    pub fn on_build_complete(&self, source: &dyn fmt::Display, id: usize) {
169        let ProgressMode::Multi {
170            state,
171            multi_progress,
172        } = &self.mode
173        else {
174            return;
175        };
176
177        let progress = {
178            let mut state = state.lock().unwrap();
179            state.headers -= 1;
180            state.bars.remove(&id).unwrap()
181        };
182
183        let message = format!("      {} {}", "Built".bold().green(), source);
184        if multi_progress.is_hidden() && !*HAS_UV_INTERNAL__TEST_NO_CLI_PROGRESS {
185            let _ = writeln!(self.printer.stderr(), "{message}");
186        }
187        progress.finish_with_message(message);
188    }
189
190    pub fn on_request_start(&self, direction: Direction, name: String, size: Option<u64>) -> usize {
191        let ProgressMode::Multi {
192            multi_progress,
193            state,
194        } = &self.mode
195        else {
196            return 0;
197        };
198
199        let mut state = state.lock().unwrap();
200
201        // Preserve ascending order.
202        let position = size.map_or(0, |size| state.sizes.partition_point(|&len| len < size));
203        state.sizes.insert(position, size.unwrap_or(0));
204        state.max_len = std::cmp::max(state.max_len, name.len());
205
206        let max_len = state.max_len;
207        for progress in state.bars.values_mut() {
208            // Ignore spinners, such as for builds.
209            if let ProgressBarKind::Numeric { progress, .. } = progress {
210                let template = format!(
211                    "{{msg:{max_len}.dim}} {{bar:30.green/black.dim}} {{binary_bytes:>7}}/{{binary_total_bytes:7}}"
212                );
213                progress.set_style(
214                    ProgressStyle::with_template(&template)
215                        .unwrap()
216                        .progress_chars("--"),
217                );
218                progress.tick();
219            }
220        }
221
222        let progress = multi_progress.insert(
223            // Make sure not to reorder the initial "Preparing..." bar, or any previous bars.
224            position + 1 + state.headers,
225            ProgressBar::with_draw_target(size, self.printer.target()),
226        );
227
228        if let Some(size) = size {
229            // We're using binary bytes to match `human_readable_bytes`.
230            progress.set_style(
231                ProgressStyle::with_template(
232                    &format!(
233                        "{{msg:{}.dim}} {{bar:30.green/black.dim}} {{binary_bytes:>7}}/{{binary_total_bytes:7}}", state.max_len
234                    ),
235                )
236                    .unwrap()
237                    .progress_chars("--"),
238            );
239            // If the file is larger than 1MB, show a message to indicate that this may take
240            // a while keeping the log concise.
241            if multi_progress.is_hidden()
242                && !*HAS_UV_INTERNAL__TEST_NO_CLI_PROGRESS
243                && size > 1024 * 1024
244            {
245                let _ = writeln!(
246                    self.printer.stderr(),
247                    "{} {} {}",
248                    direction.as_str().bold().cyan(),
249                    name,
250                    format!("({:.1})", human_readable_bytes(size)).dimmed()
251                );
252            }
253            progress.set_message(name);
254        } else {
255            progress.set_style(ProgressStyle::with_template("{wide_msg:.dim} ....").unwrap());
256            if multi_progress.is_hidden() && !*HAS_UV_INTERNAL__TEST_NO_CLI_PROGRESS {
257                let _ = writeln!(
258                    self.printer.stderr(),
259                    "{} {}",
260                    direction.as_str().bold().cyan(),
261                    name
262                );
263            }
264            progress.set_message(name);
265            progress.finish();
266        }
267
268        let id = state.id();
269        state
270            .bars
271            .insert(id, ProgressBarKind::Numeric { progress, size });
272        id
273    }
274
275    pub fn on_request_progress(&self, id: usize, bytes: u64) {
276        let ProgressMode::Multi { state, .. } = &self.mode else {
277            return;
278        };
279
280        // Avoid panics due to reads on failed requests.
281        // https://github.com/astral-sh/uv/issues/17090
282        // TODO(konsti): Add a debug assert once https://github.com/seanmonstar/reqwest/issues/2884
283        // is fixed
284        if let Some(bar) = state.lock().unwrap().bars.get(&id) {
285            bar.inc(bytes);
286        }
287    }
288
289    pub fn on_request_complete(&self, direction: Direction, id: usize) {
290        let ProgressMode::Multi {
291            state,
292            multi_progress,
293        } = &self.mode
294        else {
295            return;
296        };
297
298        let mut state = state.lock().unwrap();
299        if let ProgressBarKind::Numeric { progress, size } = state.bars.remove(&id).unwrap() {
300            if multi_progress.is_hidden()
301                && !*HAS_UV_INTERNAL__TEST_NO_CLI_PROGRESS
302                && size.is_none_or(|size| size > 1024 * 1024)
303            {
304                let _ = writeln!(
305                    self.printer.stderr(),
306                    " {} {}",
307                    match direction {
308                        Direction::Download => "Downloaded",
309                        Direction::Upload => "Uploaded",
310                        Direction::Extract => "Extracted",
311                        Direction::Hash => "Hashed",
312                    }
313                    .bold()
314                    .cyan(),
315                    progress.message()
316                );
317            }
318            progress.finish_and_clear();
319        } else {
320            debug_assert!(false, "Request progress bars are numeric");
321        }
322    }
323
324    pub fn on_download_progress(&self, id: usize, bytes: u64) {
325        self.on_request_progress(id, bytes);
326    }
327
328    pub fn on_download_complete(&self, id: usize) {
329        self.on_request_complete(Direction::Download, id);
330    }
331
332    pub fn on_download_start(&self, name: String, size: Option<u64>) -> usize {
333        self.on_request_start(Direction::Download, name, size)
334    }
335
336    pub fn on_upload_progress(&self, id: usize, bytes: u64) {
337        self.on_request_progress(id, bytes);
338    }
339
340    pub fn on_upload_complete(&self, id: usize) {
341        self.on_request_complete(Direction::Upload, id);
342    }
343
344    pub fn on_upload_start(&self, name: String, size: Option<u64>) -> usize {
345        self.on_request_start(Direction::Upload, name, size)
346    }
347
348    pub fn on_hash_progress(&self, id: usize, bytes: u64) {
349        self.on_request_progress(id, bytes);
350    }
351
352    pub fn on_hash_complete(&self, id: usize) {
353        self.on_request_complete(Direction::Hash, id);
354    }
355
356    pub fn on_hash_start(&self, name: String, size: Option<u64>) -> usize {
357        self.on_request_start(Direction::Hash, name, size)
358    }
359
360    pub fn on_checkout_start(&self, url: &DisplaySafeUrl, rev: &str) -> usize {
361        let ProgressMode::Multi {
362            multi_progress,
363            state,
364        } = &self.mode
365        else {
366            return 0;
367        };
368
369        let mut state = state.lock().unwrap();
370        let id = state.id();
371
372        let progress = multi_progress.insert_before(
373            &self.root,
374            ProgressBar::with_draw_target(None, self.printer.target()),
375        );
376
377        progress.set_style(ProgressStyle::with_template("{wide_msg}").unwrap());
378        let message = format!("   {} {} ({})", "Updating".bold().cyan(), url, rev.dimmed());
379        if multi_progress.is_hidden() && !*HAS_UV_INTERNAL__TEST_NO_CLI_PROGRESS {
380            let _ = writeln!(self.printer.stderr(), "{message}");
381        }
382        progress.set_message(message);
383        progress.finish();
384
385        state.headers += 1;
386        state.bars.insert(id, ProgressBarKind::Spinner { progress });
387        id
388    }
389
390    pub fn on_checkout_complete(&self, url: &DisplaySafeUrl, rev: &str, id: usize) {
391        let ProgressMode::Multi {
392            state,
393            multi_progress,
394        } = &self.mode
395        else {
396            return;
397        };
398
399        let progress = {
400            let mut state = state.lock().unwrap();
401            state.headers -= 1;
402            state.bars.remove(&id).unwrap()
403        };
404
405        let message = format!(
406            "    {} {} ({})",
407            "Updated".bold().green(),
408            url,
409            rev.dimmed()
410        );
411        if multi_progress.is_hidden() && !*HAS_UV_INTERNAL__TEST_NO_CLI_PROGRESS {
412            let _ = writeln!(self.printer.stderr(), "{message}");
413        }
414        progress.finish_with_message(message);
415    }
416}