From a3027a3d6d09eb91b2e323c716e8c0d9aeb06f55 Mon Sep 17 00:00:00 2001 From: Austen Adler Date: Fri, 16 Dec 2022 23:44:35 -0500 Subject: [PATCH] Handle command spawn failures more gracefully --- src/command.rs | 35 +++++++++++++++++++++-------------- src/main.rs | 15 +++++++++++---- 2 files changed, 32 insertions(+), 18 deletions(-) diff --git a/src/command.rs b/src/command.rs index 4c5db45..59643bf 100644 --- a/src/command.rs +++ b/src/command.rs @@ -1,3 +1,6 @@ +use anyhow::bail; +use anyhow::Context; +use anyhow::Result; use std::{ io::Write, process::{Command, Stdio}, @@ -22,15 +25,21 @@ impl Default for CommandResult { } pub fn run(app: &mut App) { + app.command_result = match run_inner(app) { + Ok(c) => c, + Err(e) => CommandResult { + status_success: false, + stdout: vec![], + stderr: format!("{e:?}").as_bytes().to_vec(), + }, + }; +} + +fn run_inner(app: &mut App) -> Result { let args = match shellwords::split(&app.cmdline) { Ok(a) => a, Err(e) => { - app.command_result = CommandResult { - status_success: false, - stdout: vec![], - stderr: format!("Argument error: {e:?}").as_bytes().to_vec(), - }; - return; + bail!("Argument error: {e:?}"); } }; @@ -41,22 +50,20 @@ pub fn run(app: &mut App) { .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() - .expect("Could not spawn child process"); + .context("Could not spawn child process")?; - let mut stdin = child.stdin.take().expect("Could not take stdin"); + let mut stdin = child.stdin.take().context("Could not take stdin")?; let text_orig_clone = app.text_orig.clone(); std::thread::spawn(move || { - stdin - .write_all(text_orig_clone.as_bytes()) - .expect("Failed to write to stdin"); + let _ = stdin.write_all(text_orig_clone.as_bytes()); }); // Collect the output - let output = child.wait_with_output().expect("Failed to read stdout"); + let output = child.wait_with_output().context("Failed to read stdout")?; - app.command_result = CommandResult { + Ok(CommandResult { status_success: output.status.success(), stdout: output.stdout, stderr: output.stderr, - } + }) } diff --git a/src/main.rs b/src/main.rs index bc7f9d9..5bfe67d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -107,8 +107,8 @@ impl App { hidden_options: vec![], }, Template::Perl => Self { - cmdline: String::from("-p -e 's/./_/'"), - cmdline_position: 3_u16, + cmdline: String::from("-p -e 's///'"), + cmdline_position: 10_u16, text_orig, command_result: CommandResult::default(), autorun: true, @@ -292,8 +292,15 @@ fn ui(f: &mut Frame, app: &App) { chunks[0], ); f.render_widget( - Paragraph::new(app.cmdline.as_ref()) - .block(Block::default().title("Cmdline").borders(Borders::ALL)), + Paragraph::new(app.cmdline.as_ref()).block( + Block::default() + .title(format!( + "Cmdline ({} {})", + app.command, + app.hidden_options.join(" ") + )) + .borders(Borders::ALL), + ), vertical_chunks[1], );