Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add simple download progress tracker #6098

Merged
merged 7 commits into from
Dec 2, 2023
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 50 additions & 2 deletions crates/packaging/src/https.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
io::{self, Read},
io::{self, Read, Write},
path::Path,
};

Expand Down Expand Up @@ -275,9 +275,12 @@ pub fn download_and_hash(
Encoding::new(content_encoding, url)?
};

let content_length = resp.content_length().map(|n| n as usize);

// Use .take to prevent a malicious server from sending back bytes
// until system resources are exhausted!
decompress_into(dest_dir, encoding, resp.take(max_download_bytes))
let resp = ProgressReporter::new(resp.take(max_download_bytes), content_length);
decompress_into(dest_dir, encoding, resp)
}

/// The content encodings we support
Expand Down Expand Up @@ -405,3 +408,48 @@ impl<R: Read> Read for HashReader<R> {
Ok(bytes_read)
}
}

/// Prints download progress to stdout
struct ProgressReporter<R: Read> {
read: usize,
total: Option<usize>,
reader: R,
}

impl<R: Read> ProgressReporter<R> {
fn new(reader: R, total: Option<usize>) -> Self {
ProgressReporter {
read: 0,
total,
reader,
}
}
}

impl<R: Read> Read for ProgressReporter<R> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let size = self.reader.read(buf)?;

self.read += size;

if let Some(total) = self.total {
print!(
horriblename marked this conversation as resolved.
Show resolved Hide resolved
"\u{001b}[2K\u{001b}[G[{:.1} / {:.1} MB]",
self.read as f32 / 1_000_000.0,
total as f32 / 1_000_000.0,
);
} else {
print!(
"\u{001b}[2K\u{001b}[G[{:.1} MB]",
self.read as f32 / 1_000_000.0,
);
}
std::io::stdout().flush()?;

if self.total.is_some_and(|total| self.read >= total) {
println!();
}

Ok(size)
}
}