summaryrefslogtreecommitdiffstats
path: root/src/utils
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils')
-rw-r--r--src/utils/command.rs73
-rw-r--r--src/utils/mod.rs7
2 files changed, 77 insertions, 3 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,
+ }
+}
diff --git a/src/utils/mod.rs b/src/utils/mod.rs
index 873c5c8..5271571 100644
--- a/src/utils/mod.rs
+++ b/src/utils/mod.rs
@@ -35,8 +35,11 @@ lazy_static::lazy_static! {
}
pub fn now() -> String {
- let now = chrono::Local::now();
- now.to_rfc3339_opts(chrono::SecondsFormat::Secs, false)
+ chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, false)
+}
+
+pub fn now_timestamp() -> i64 {
+ chrono::Local::now().timestamp()
}
pub fn get_env_name(key: &str) -> String {