From 118640ec1c48d40c255a829b95c3e9cd2b4ddda5 Mon Sep 17 00:00:00 2001 From: Zykino Date: Sat, 14 Jan 2023 22:56:23 +0100 Subject: [PATCH] =?UTF-8?q?Ask=20user=E2=80=99s=20consent=20before=20execu?= =?UTF-8?q?ting=20a=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/command.rs | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/src/command.rs b/src/command.rs index 8d58b8f..447b38e 100644 --- a/src/command.rs +++ b/src/command.rs @@ -3,6 +3,7 @@ use enumset::EnumSetType; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::fmt; +use std::io::{stdout, Write}; use std::path::PathBuf; use std::process::Command; @@ -55,7 +56,6 @@ impl Updater { /// To create a sample config from code #[doc(hidden)] fn write_config(&self, opt: &Opt) { - use ::std::io::Write; use std::fs::OpenOptions; let mut f = OpenOptions::new() @@ -157,13 +157,24 @@ impl Cmd { cmd.current_dir(std::fs::canonicalize(cdir).unwrap()); } - println!("Executing {}", self); - // TODO: Ask if ok or - if cmd.status().unwrap().success() { - println!("Youpi !"); - // Other checks? + let confirm = "[Y/n]? "; + + print!("Will execute {}{}", self, confirm); + stdout().flush().unwrap(); + + let mut yes_no = String::new(); + std::io::stdin() + .read_line(&mut yes_no) + .expect("Unable to read user’s input"); + + if !yes_no.to_lowercase().starts_with('n') { + if cmd.status().unwrap().success() { + eprintln!("Youpi !"); + // Other checks? + } else { + eprintln!("Error executing the command") + } } - println!("Exécutée"); Ok(()) } @@ -171,20 +182,22 @@ impl Cmd { impl fmt::Display for Cmd { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let command = if self.params.is_empty() { - self.exe.clone() - } else { + let command = if !self.params.is_empty() { format!("{} {}", &self.exe, &self.params.join(" ")) + } else { + self.exe.clone() }; write!(f, "`{}`", command)?; + if let Some(cdir) = &self.current_dir { write!(f, " in {:?}", cdir)?; } + if !self.env.is_empty() { writeln!(f, " with the following environment variable:")?; writeln!(f, "{:?}", self.env) } else { - writeln!(f, " without any environment variable.") + write!(f, " without any environment variable. ") } } }