|
1 | 1 | use super::*;
|
2 | 2 |
|
3 |
| -use std::{collections::HashMap, env, ffi::OsStr, path::Path, process::Command}; |
| 3 | +use std::{ |
| 4 | + collections::HashMap, |
| 5 | + env, |
| 6 | + ffi::OsStr, |
| 7 | + fs::OpenOptions, |
| 8 | + io::{self, Write}, |
| 9 | + path::{Path, PathBuf}, |
| 10 | + process::Command, |
| 11 | +}; |
4 | 12 |
|
5 | 13 | use anyhow::{anyhow, bail, Context, Result};
|
| 14 | +use dirs::home_dir; |
6 | 15 |
|
7 | 16 | lazy_static::lazy_static! {
|
8 | 17 | pub static ref SHELL: Shell = detect_shell();
|
@@ -152,3 +161,65 @@ pub fn edit_file(editor: &str, path: &Path) -> Result<()> {
|
152 | 161 | child.wait()?;
|
153 | 162 | Ok(())
|
154 | 163 | }
|
| 164 | + |
| 165 | +pub fn append_to_shell_history(shell: &str, command: &str, exit_code: i32) -> io::Result<()> { |
| 166 | + if let Some(history_file) = get_history_file(shell) { |
| 167 | + let command = command.replace('\n', " "); |
| 168 | + let now = now_timestamp(); |
| 169 | + let history_txt = if shell == "fish" { |
| 170 | + format!("- cmd: {command}\n when: {now}") |
| 171 | + } else if shell == "zsh" { |
| 172 | + format!(": {now}:{exit_code};{command}",) |
| 173 | + } else { |
| 174 | + command |
| 175 | + }; |
| 176 | + let mut file = OpenOptions::new() |
| 177 | + .create(true) |
| 178 | + .append(true) |
| 179 | + .open(&history_file)?; |
| 180 | + writeln!(file, "{}", history_txt)?; |
| 181 | + } |
| 182 | + Ok(()) |
| 183 | +} |
| 184 | + |
| 185 | +fn get_history_file(shell: &str) -> Option<PathBuf> { |
| 186 | + match shell { |
| 187 | + "bash" | "sh" => Some(home_dir()?.join(".bash_history")), |
| 188 | + "zsh" => Some(home_dir()?.join(".zsh_history")), |
| 189 | + "nushell" => Some(dirs::config_dir()?.join("nushell").join("history.txt")), |
| 190 | + "fish" => Some( |
| 191 | + home_dir()? |
| 192 | + .join(".local") |
| 193 | + .join("share") |
| 194 | + .join("fish") |
| 195 | + .join("fish_history"), |
| 196 | + ), |
| 197 | + "powershell" | "pwsh" => { |
| 198 | + #[cfg(not(windows))] |
| 199 | + { |
| 200 | + Some( |
| 201 | + home_dir()? |
| 202 | + .join(".local") |
| 203 | + .join("share") |
| 204 | + .join("powershell") |
| 205 | + .join("PSReadLine") |
| 206 | + .join("ConsoleHost_history.txt"), |
| 207 | + ) |
| 208 | + } |
| 209 | + #[cfg(windows)] |
| 210 | + { |
| 211 | + Some( |
| 212 | + dirs::data_dir()? |
| 213 | + .join("Microsoft") |
| 214 | + .join("Windows") |
| 215 | + .join("PowerShell") |
| 216 | + .join("PSReadLine") |
| 217 | + .join("ConsoleHost_history.txt"), |
| 218 | + ) |
| 219 | + } |
| 220 | + } |
| 221 | + "ksh" => Some(home_dir()?.join(".ksh_history")), |
| 222 | + "tcsh" => Some(home_dir()?.join(".history")), |
| 223 | + _ => None, |
| 224 | + } |
| 225 | +} |
0 commit comments