Skip to content

Commit

Permalink
add progress handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
MarinPostma committed Sep 24, 2024
1 parent 694ad6e commit aa5b54e
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 0 deletions.
26 changes: 26 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ wasmprinter = "0.2.78"
dialoguer = { workspace = true }
itertools = "0.12.1"
secrecy = { workspace = true }
indicatif = "0.17.8"

[dev-dependencies]
reqwest = { workspace = true }
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
#![deny(missing_docs)]

pub mod commands;
mod progress;
60 changes: 60 additions & 0 deletions src/progress.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use std::pin::Pin;
use std::task::{ready, Poll};

use indicatif::{ProgressBar, ProgressStyle};
use tokio::io::AsyncRead;

pub(crate) struct ProgressStream<R> {
bar: ProgressBar,
inner: R,
}

pub fn make_progress_handler(msg: String) -> impl FnMut(u64, u64) {
let bar = init_progress_bar();
bar.set_message(msg);
move |delta, total| {
bar.set_length(total);
bar.inc(delta);
}
}

fn init_progress_bar() -> ProgressBar {
let bar = indicatif::ProgressBar::new(0);
bar.set_style(
ProgressStyle::with_template(
"[{elapsed_precise}] {bar:30} {binary_bytes:.02}/{binary_total_bytes} {msg}",
)
.unwrap()
.progress_chars("##-"),
);

bar
}

impl<R> ProgressStream<R> {
pub fn new(inner: R, len: u64, msg: String) -> Self {
let bar = init_progress_bar();
bar.set_length(len);
bar.set_message(msg);

Self { bar, inner }
}
}

impl<R: AsyncRead + Unpin> AsyncRead for ProgressStream<R> {
fn poll_read(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> std::task::Poll<std::io::Result<()>> {
let initialized_before = buf.initialized().len() as u64;
match ready!(Pin::new(&mut self.inner).poll_read(cx, buf)) {
Ok(()) => {
self.bar
.inc(buf.initialized().len() as u64 - initialized_before);
Poll::Ready(Ok(()))
}
Err(e) => Poll::Ready(Err(e)),
}
}
}

0 comments on commit aa5b54e

Please sign in to comment.