simplify cleanups

This commit is contained in:
figsoda 2022-11-07 14:18:07 -05:00
parent 9ad8a7fa6e
commit dbd4a70e76

View file

@ -44,26 +44,39 @@ use crate::{
mpd::{Client, PlayerState}, mpd::{Client, PlayerState},
}; };
fn cleanup() -> Result<()> { fn cleanup() {
let mut stdout = stdout(); let mut stdout = stdout();
stdout
if let Err(e) = stdout
.execute(LeaveAlternateScreen) .execute(LeaveAlternateScreen)
.context("Failed to leave alternate screen")?; .context("Failed to leave alternate screen")
stdout {
eprintln!("{e:?}");
}
if let Err(e) = stdout
.execute(DisableMouseCapture) .execute(DisableMouseCapture)
.context("Failed to disable mouse capture")?; .context("Failed to disable mouse capture")
disable_raw_mode().context("Failed to disable raw mode")?; {
Ok(()) eprintln!("{e:?}");
}
if let Err(e) = disable_raw_mode().context("Failed to disable raw mode") {
eprintln!("{e:?}");
}
} }
fn main() { struct Cleanup;
let res = block_on(run()); impl Drop for Cleanup {
if let Err(e) = cleanup().and(res) { fn drop(&mut self) {
eprintln!("{e:?}"); cleanup();
exit(1);
} }
} }
fn main() -> Result<()> {
block_on(run())
}
async fn run() -> Result<()> { async fn run() -> Result<()> {
let opts = Opts::parse(); let opts = Opts::parse();
@ -100,7 +113,7 @@ async fn run() -> Result<()> {
for cmd in cmd { for cmd in cmd {
cl.command_stdout(&cmd).await?; cl.command_stdout(&cmd).await?;
} }
exit(0); // skip cleanup return Ok(());
} }
let status = cl.status().await?; let status = cl.status().await?;
@ -125,6 +138,7 @@ async fn run() -> Result<()> {
stdout stdout
.execute(EnterAlternateScreen) .execute(EnterAlternateScreen)
.context("Failed to enter alternate screen")?; .context("Failed to enter alternate screen")?;
let __ = Cleanup;
let mut term = let mut term =
Terminal::new(CrosstermBackend::new(stdout)).context("Failed to initialize terminal")?; Terminal::new(CrosstermBackend::new(stdout)).context("Failed to initialize terminal")?;
@ -169,7 +183,7 @@ async fn run() -> Result<()> {
Ok((false, true)) => 0b011, Ok((false, true)) => 0b011,
Ok(_) => continue, Ok(_) => continue,
Err(e) => { Err(e) => {
eprintln!("{:?}", cleanup().map_or_else(|x| x, |_| e)); eprintln!("{e:?}");
exit(1); exit(1);
} }
}, },