From 61b5343d433435a44d0d4e4404ce0c364987a927 Mon Sep 17 00:00:00 2001 From: Luke Harding Date: Wed, 24 Apr 2024 15:35:53 -0400 Subject: [PATCH] Add error handling for pacman update --- src/main.rs | 18 ++++++++++++++++-- src/shell_commands.rs | 24 +++++++++++++++++++++--- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2228940..638d433 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,6 +11,8 @@ This file contains the primary logic of the application */ +use std::io; + mod pacman_install_check; mod shell_commands; @@ -22,9 +24,21 @@ fn main() { return; } - println!("Here we do things"); + println!("Running pacman update"); + if let Err(e) = shell_commands::execute_in_sh("pacman -Syu") { + match e.kind() { + io::ErrorKind::PermissionDenied => { + eprintln!("Permission to use pacman has been denied. Please try again with sudo."); + return; + } + _ => { + eprintln!("{}", e); + return; + } + } + } - shell_commands::execute_in_sh("sudo pacman -Syu").unwrap(); + println!("Move onto something else"); } fn copyright_notice() -> &'static str { diff --git a/src/shell_commands.rs b/src/shell_commands.rs index ae55771..a42d020 100644 --- a/src/shell_commands.rs +++ b/src/shell_commands.rs @@ -13,18 +13,36 @@ use std::ffi::OsStr; use std::io; -use std::process::Command; +use std::io::{ErrorKind, Read}; +use std::process::{Command, Stdio}; pub fn execute_and_display, I>(cmd: S, args: I) -> io::Result<()> where I: IntoIterator, I::Item: AsRef, { - let mut child = Command::new(cmd).args(args).spawn()?; + let mut child = Command::new(cmd) + .args(args) + .stderr(Stdio::piped()) + .spawn()?; child.wait()?; - Ok(()) + if let Some(mut child_stderr) = child.stderr { + let mut output = String::new(); + child_stderr.read_to_string(&mut output)?; + + // TODO: Relocate to future pacman api + if output == "error: you cannot perform this operation unless you are root.\n" { + Err(io::Error::from(ErrorKind::PermissionDenied)) + } else if output.is_empty() { + Ok(()) + } else { + Err(io::Error::new(ErrorKind::Other, output)) + } + } else { + Ok(()) + } } pub fn execute_in_sh(cmd: &'static str) -> io::Result<()> {