cargo-binstall/src/helpers/ui_thread.rs
Jiahao XU 88c3f15b3f
Rename Confirmer to UIThread
Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
2022-06-11 12:59:27 +10:00

97 lines
2.6 KiB
Rust

use std::io::{self, BufRead, Write};
use tokio::sync::mpsc;
use tokio::task::spawn_blocking;
use crate::BinstallError;
#[derive(Debug)]
struct UIThreadInner {
/// Request for confirmation
request_tx: mpsc::Sender<()>,
/// Confirmation
confirm_rx: mpsc::Receiver<Result<(), BinstallError>>,
}
impl UIThreadInner {
fn new() -> Self {
let (request_tx, mut request_rx) = mpsc::channel(1);
let (confirm_tx, confirm_rx) = mpsc::channel(10);
spawn_blocking(move || {
// This task should be the only one able to
// access stdin
let mut stdin = io::stdin().lock();
let mut input = String::with_capacity(16);
loop {
if request_rx.blocking_recv().is_none() {
break;
}
// Lock stdout so that nobody can interfere
// with confirmation.
let mut stdout = io::stdout().lock();
let res = loop {
writeln!(&mut stdout, "Do you wish to continue? yes/[no]").unwrap();
write!(&mut stdout, "? ").unwrap();
stdout.flush().unwrap();
input.clear();
stdin.read_line(&mut input).unwrap();
match input.as_str().trim() {
"yes" | "y" | "YES" | "Y" => break Ok(()),
"no" | "n" | "NO" | "N" | "" => break Err(BinstallError::UserAbort),
_ => continue,
}
};
confirm_tx
.blocking_send(res)
.expect("entry exits when confirming request");
}
});
Self {
request_tx,
confirm_rx,
}
}
async fn confirm(&mut self) -> Result<(), BinstallError> {
self.request_tx
.send(())
.await
.map_err(|_| BinstallError::UserAbort)?;
self.confirm_rx
.recv()
.await
.unwrap_or(Err(BinstallError::UserAbort))
}
}
#[derive(Debug)]
pub struct UIThread(Option<UIThreadInner>);
impl UIThread {
/// * `enable` - `true` to enable confirmation, `false` to disable it.
pub fn new(enable: bool) -> Self {
Self(if enable {
Some(UIThreadInner::new())
} else {
None
})
}
pub async fn confirm(&mut self) -> Result<(), BinstallError> {
if let Some(inner) = self.0.as_mut() {
inner.confirm().await
} else {
Ok(())
}
}
}