Skip to content

Commit 9969d07

Browse files
committed
rustup_utils: Add a FileReaderWithProgress struct
In order to be able to report unpack progress, add support for a file reader which emits notifications akin to the downloading of a file. This allows the generic progress bar supporting downloads to also handle the installation of components. Signed-off-by: Daniel Silverstone <[email protected]>
1 parent b47800c commit 9969d07

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/rustup-utils/src/utils.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -858,6 +858,57 @@ fn rename(name: &'static str, src: &Path, dest: &Path) -> Result<()> {
858858
})
859859
}
860860

861+
pub struct FileReaderWithProgress<'a> {
862+
fh: std::fs::File,
863+
notify_handler: &'a Fn(Notification),
864+
sent_start: bool,
865+
nbytes: u64,
866+
flen: u64,
867+
}
868+
869+
impl<'a> FileReaderWithProgress<'a> {
870+
pub fn new_file(path: &Path, notify_handler: &'a Fn(Notification)) -> Result<Self> {
871+
let fh = match std::fs::File::open(path) {
872+
Ok(fh) => fh,
873+
Err(_) => Err(ErrorKind::ReadingFile {
874+
name: "downloaded",
875+
path: path.to_path_buf(),
876+
})?,
877+
};
878+
879+
Ok(FileReaderWithProgress {
880+
fh,
881+
notify_handler,
882+
sent_start: false,
883+
nbytes: 0,
884+
flen: 0,
885+
})
886+
}
887+
}
888+
889+
impl<'a> std::io::Read for FileReaderWithProgress<'a> {
890+
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
891+
if !self.sent_start {
892+
// Send the start notifications
893+
let flen = self.fh.metadata()?.len();
894+
self.flen = flen;
895+
(self.notify_handler)(Notification::DownloadContentLengthReceived(flen));
896+
}
897+
match self.fh.read(buf) {
898+
Ok(nbytes) => {
899+
self.nbytes += nbytes as u64;
900+
if (nbytes == 0) || (self.flen == self.nbytes) {
901+
(self.notify_handler)(Notification::DownloadFinished);
902+
} else {
903+
(self.notify_handler)(Notification::DownloadDataReceived(&buf[0..nbytes]));
904+
}
905+
Ok(nbytes)
906+
}
907+
Err(e) => Err(e),
908+
}
909+
}
910+
}
911+
861912
#[cfg(test)]
862913
mod tests {
863914
use super::*;

0 commit comments

Comments
 (0)