From af9bcaba2925096f1e1f7d9a2b38596429797ef0 Mon Sep 17 00:00:00 2001 From: hanseter Date: Sat, 19 Oct 2024 17:42:29 +0200 Subject: [PATCH] Start zsh and bash as interactive shells when adding to history. In order to have a history available the shell needs to be interactive (and history needs to be turned on in the case of bash). Also append the prompt that produced the result to make it easier to find in history search. --- src/lib/chatter.rs | 2 +- src/lib/command.rs | 20 +++++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/lib/chatter.rs b/src/lib/chatter.rs index df23500..8dbdc48 100644 --- a/src/lib/chatter.rs +++ b/src/lib/chatter.rs @@ -83,7 +83,7 @@ impl Chatter { match answer { "✅ Execute" => { debug!("{} {:?}", SHELL.cmd, &[&SHELL.arg, &command]); - let code = SHELL.run_command(&command)?; + let code = SHELL.run_command(&command, text)?; if code != 0 { process::exit(code); } diff --git a/src/lib/command.rs b/src/lib/command.rs index 54b4b50..af71950 100644 --- a/src/lib/command.rs +++ b/src/lib/command.rs @@ -26,30 +26,32 @@ pub struct Shell { pub name: String, pub cmd: String, pub arg: String, - pub history_cmd: Option, + pub history_cmd: Option<(String, String)>, } impl Shell { - pub fn new(name: &str, cmd: &str, arg: &str, history_cmd: Option<&str>) -> Self { + pub fn new(name: &str, cmd: &str, arg: &str, history_cmd: Option<(&str, &str)>) -> Self { Self { name: name.to_string(), cmd: cmd.to_string(), arg: arg.to_string(), - history_cmd: history_cmd.map(|cmd| cmd.to_string()), + history_cmd: history_cmd.map(|cmd| (cmd.0.to_string(), cmd.1.to_string())), } } - pub fn run_command(&self, eval_str: &str) -> Result { + pub fn run_command(&self, eval_str: &str, prompt: &str) -> Result { let status = Command::new(&self.cmd) .arg(&self.arg) .arg(eval_str) .status()?; if status.success() { + println!("Success"); if let Some(history_cmd) = &self.history_cmd { let _ = Command::new(&self.cmd) .arg(&self.arg) - .arg(format!("{} \"{}\"", history_cmd, eval_str)) + .arg(&history_cmd.0) + .arg(format!("{} \"{}\" \\#shc: \"{}\"", &history_cmd.1, eval_str, prompt)) .status(); } } @@ -84,8 +86,8 @@ pub fn detect_shell() -> Shell { None => &shell, }; match shell { - "bash" => Shell::new(shell, shell, "-c", Some("history -s")), - "zsh" => Shell::new(shell, shell, "-c", Some("print -s")), + "bash" => Shell::new(shell, shell, "-c", Some(("-i", "set -o history; history -s"))), + "zsh" => Shell::new(shell, shell, "-c", Some(("-i", "print -s"))), "fish" | "pwsh" => Shell::new(shell, shell, "-c", None), _ => Shell::new("sh", "sh", "-c", None), } @@ -112,8 +114,8 @@ mod tests { #[test] fn test_run_command() { - let result = SHELL.run_command("echo Hello, world!"); + let result = SHELL.run_command("echo Hello, world!", "User prompt"); assert!(result.is_ok()); assert_eq!(result.unwrap(), 0); } -} \ No newline at end of file +}