Ask user’s consent before executing a command

This commit is contained in:
Zykino 2023-01-14 22:56:23 +01:00
parent 448430b749
commit 118640ec1c

View File

@ -3,6 +3,7 @@ use enumset::EnumSetType;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt; use std::fmt;
use std::io::{stdout, Write};
use std::path::PathBuf; use std::path::PathBuf;
use std::process::Command; use std::process::Command;
@ -55,7 +56,6 @@ impl Updater {
/// To create a sample config from code /// To create a sample config from code
#[doc(hidden)] #[doc(hidden)]
fn write_config(&self, opt: &Opt) { fn write_config(&self, opt: &Opt) {
use ::std::io::Write;
use std::fs::OpenOptions; use std::fs::OpenOptions;
let mut f = OpenOptions::new() let mut f = OpenOptions::new()
@ -157,13 +157,24 @@ impl Cmd {
cmd.current_dir(std::fs::canonicalize(cdir).unwrap()); cmd.current_dir(std::fs::canonicalize(cdir).unwrap());
} }
println!("Executing {}", self); let confirm = "[Y/n]? ";
// TODO: Ask if ok or
if cmd.status().unwrap().success() { print!("Will execute {}{}", self, confirm);
println!("Youpi !"); stdout().flush().unwrap();
// Other checks?
let mut yes_no = String::new();
std::io::stdin()
.read_line(&mut yes_no)
.expect("Unable to read users 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(()) Ok(())
} }
@ -171,20 +182,22 @@ impl Cmd {
impl fmt::Display for Cmd { impl fmt::Display for Cmd {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let command = if self.params.is_empty() { let command = if !self.params.is_empty() {
self.exe.clone()
} else {
format!("{} {}", &self.exe, &self.params.join(" ")) format!("{} {}", &self.exe, &self.params.join(" "))
} else {
self.exe.clone()
}; };
write!(f, "`{}`", command)?; write!(f, "`{}`", command)?;
if let Some(cdir) = &self.current_dir { if let Some(cdir) = &self.current_dir {
write!(f, " in {:?}", cdir)?; write!(f, " in {:?}", cdir)?;
} }
if !self.env.is_empty() { if !self.env.is_empty() {
writeln!(f, " with the following environment variable:")?; writeln!(f, " with the following environment variable:")?;
writeln!(f, "{:?}", self.env) writeln!(f, "{:?}", self.env)
} else { } else {
writeln!(f, " without any environment variable.") write!(f, " without any environment variable. ")
} }
} }
} }