unwrap AppState::progress RefCell

This commit is contained in:
Jörn-Michael Miehe 2025-06-24 01:35:21 +00:00
parent 72e9a5d40f
commit 14e1bed708

View file

@ -1,4 +1,4 @@
use std::{cell::RefCell, fmt, io, time::Duration}; use std::{fmt, io, time::Duration};
use console::style; use console::style;
use indicatif::{ProgressBar, ProgressStyle}; use indicatif::{ProgressBar, ProgressStyle};
@ -12,7 +12,7 @@ use crate::{
}; };
pub struct AppState { pub struct AppState {
progress: RefCell<Option<ProgressBar>>, progress: Option<ProgressBar>,
http: ureq::Agent, http: ureq::Agent,
inner: CacheFile, inner: CacheFile,
} }
@ -35,7 +35,7 @@ fn new_http(timeout: Option<Duration>) -> ureq::Agent {
impl AppState { impl AppState {
fn new(http: ureq::Agent, inner: CacheFile) -> Self { fn new(http: ureq::Agent, inner: CacheFile) -> Self {
Self { Self {
progress: RefCell::new(None), progress: None,
http, http,
inner, inner,
} }
@ -57,9 +57,8 @@ impl AppState {
Ok(Self::new(http, CacheFile::from_args(args, share_id))) Ok(Self::new(http, CacheFile::from_args(args, share_id)))
} }
fn with_progressbar(&self, drop_bar: bool, f: impl FnOnce(&ProgressBar)) { fn with_progressbar(&mut self, f: impl FnOnce(&ProgressBar), drop_bar: bool) {
let mut slot = self.progress.borrow_mut(); let bar = &*self.progress.get_or_insert_with(|| {
let bar = &*slot.get_or_insert_with(|| {
ProgressBar::no_length().with_style( ProgressBar::no_length().with_style(
ProgressStyle::with_template(&format!( ProgressStyle::with_template(&format!(
concat!( concat!(
@ -89,12 +88,16 @@ impl AppState {
f(bar); f(bar);
if drop_bar { if drop_bar {
*slot = None; self.progress = None;
} }
} }
fn touch_progressbar(&self) { fn touch_progressbar(&mut self) {
self.with_progressbar(false, |_| ()); self.with_progressbar(|_| (), false);
}
fn drop_progressbar(&mut self, f: impl FnOnce(&ProgressBar)) {
self.with_progressbar(f, true);
} }
fn next_chunk<'t>(&mut self, buffer: &'t mut [u8]) -> sharry::Result<Option<Chunk<'t>>> { fn next_chunk<'t>(&mut self, buffer: &'t mut [u8]) -> sharry::Result<Option<Chunk<'t>>> {
@ -119,7 +122,7 @@ impl AppState {
fn is_done(&mut self) -> bool { fn is_done(&mut self) -> bool {
if let Some(path) = self.inner.check_eof() { if let Some(path) = self.inner.check_eof() {
debug!("Finished {:?}!", path.display()); debug!("Finished {:?}!", path.display());
self.with_progressbar(true, ProgressBar::finish); self.drop_progressbar(ProgressBar::finish);
} else if self.inner.peek_uploading().is_some() { } else if self.inner.peek_uploading().is_some() {
self.touch_progressbar(); self.touch_progressbar();
@ -151,7 +154,7 @@ impl AppState {
pub fn abort_upload(&mut self) { pub fn abort_upload(&mut self) {
self.inner.abort_upload(); self.inner.abort_upload();
self.with_progressbar(true, ProgressBar::abandon); self.drop_progressbar(ProgressBar::abandon);
} }
pub fn rebuild_share(self, args: &Cli) -> sharry::Result<Self> { pub fn rebuild_share(self, args: &Cli) -> sharry::Result<Self> {