diff options
| author | sigoden <sigoden@gmail.com> | 2024-12-01 10:06:20 +0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-12-01 10:06:20 +0800 |
| commit | 7e8e2a6ce6d96ffa31c202ead6f31f18dc73c618 (patch) | |
| tree | 907070ab6f81ebef46a1ae8793b553c99b2dd52e /src/utils/command.rs | |
| parent | efdec3497976ddb2e35e6302ee68f3d753f837a3 (diff) | |
| download | aichat-7e8e2a6ce6d96ffa31c202ead6f31f18dc73c618.tar.gz | |
feat: append shell execute command to history file (#1026)
Diffstat (limited to 'src/utils/command.rs')
| -rw-r--r-- | src/utils/command.rs | 73 |
1 files changed, 72 insertions, 1 deletions
diff --git a/src/utils/command.rs b/src/utils/command.rs index 9ec929c..32e470d 100644 --- a/src/utils/command.rs +++ b/src/utils/command.rs @@ -1,8 +1,17 @@ use super::*; -use std::{collections::HashMap, env, ffi::OsStr, path::Path, process::Command}; +use std::{ + collections::HashMap, + env, + ffi::OsStr, + fs::OpenOptions, + io::{self, Write}, + path::{Path, PathBuf}, + process::Command, +}; use anyhow::{anyhow, bail, Context, Result}; +use dirs::home_dir; lazy_static::lazy_static! { pub static ref SHELL: Shell = detect_shell(); @@ -152,3 +161,65 @@ pub fn edit_file(editor: &str, path: &Path) -> Result<()> { child.wait()?; Ok(()) } + +pub fn append_to_shell_history(shell: &str, command: &str, exit_code: i32) -> io::Result<()> { + if let Some(history_file) = get_history_file(shell) { + let command = command.replace('\n', " "); + let now = now_timestamp(); + let history_txt = if shell == "fish" { + format!("- cmd: {command}\n when: {now}") + } else if shell == "zsh" { + format!(": {now}:{exit_code};{command}",) + } else { + command + }; + let mut file = OpenOptions::new() + .create(true) + .append(true) + .open(&history_file)?; + writeln!(file, "{}", history_txt)?; + } + Ok(()) +} + +fn get_history_file(shell: &str) -> Option<PathBuf> { + match shell { + "bash" | "sh" => Some(home_dir()?.join(".bash_history")), + "zsh" => Some(home_dir()?.join(".zsh_history")), + "nushell" => Some(dirs::config_dir()?.join("nushell").join("history.txt")), + "fish" => Some( + home_dir()? + .join(".local") + .join("share") + .join("fish") + .join("fish_history"), + ), + "powershell" | "pwsh" => { + #[cfg(not(windows))] + { + Some( + home_dir()? + .join(".local") + .join("share") + .join("powershell") + .join("PSReadLine") + .join("ConsoleHost_history.txt"), + ) + } + #[cfg(windows)] + { + Some( + dirs::data_dir()? + .join("Microsoft") + .join("Windows") + .join("PowerShell") + .join("PSReadLine") + .join("ConsoleHost_history.txt"), + ) + } + } + "ksh" => Some(home_dir()?.join(".ksh_history")), + "tcsh" => Some(home_dir()?.join(".history")), + _ => None, + } +} |
