|
| 1 | +use std::fs; |
| 2 | +use std::path::PathBuf; |
| 3 | + |
| 4 | +fn get_history_file_path() -> Result<PathBuf, String> { |
| 5 | + let home_dir = dirs::home_dir() |
| 6 | + .ok_or_else(|| "Failed to get home directory".to_string())?; |
| 7 | + |
| 8 | + Ok(home_dir.join(".term_history")) |
| 9 | +} |
| 10 | + |
| 11 | +#[tauri::command] |
| 12 | +pub fn save_command_to_history(command: String) -> Result<(), String> { |
| 13 | + let history_file = get_history_file_path()?; |
| 14 | + |
| 15 | + // Read existing history |
| 16 | + let mut history = if history_file.exists() { |
| 17 | + fs::read_to_string(&history_file) |
| 18 | + .map_err(|e| format!("Failed to read history file: {}", e))? |
| 19 | + } else { |
| 20 | + String::new() |
| 21 | + }; |
| 22 | + |
| 23 | + // Append new command with newline |
| 24 | + if !history.is_empty() && !history.ends_with('\n') { |
| 25 | + history.push('\n'); |
| 26 | + } |
| 27 | + history.push_str(&command); |
| 28 | + history.push('\n'); |
| 29 | + |
| 30 | + // Write back to file |
| 31 | + fs::write(&history_file, history) |
| 32 | + .map_err(|e| format!("Failed to write history file: {}", e))?; |
| 33 | + |
| 34 | + Ok(()) |
| 35 | +} |
| 36 | + |
| 37 | +#[tauri::command] |
| 38 | +pub fn load_command_history() -> Result<Vec<String>, String> { |
| 39 | + let history_file = get_history_file_path()?; |
| 40 | + |
| 41 | + if !history_file.exists() { |
| 42 | + return Ok(Vec::new()); |
| 43 | + } |
| 44 | + |
| 45 | + let content = fs::read_to_string(&history_file) |
| 46 | + .map_err(|e| format!("Failed to read history file: {}", e))?; |
| 47 | + |
| 48 | + let history: Vec<String> = content |
| 49 | + .lines() |
| 50 | + .filter(|line| !line.trim().is_empty()) |
| 51 | + .map(|line| line.to_string()) |
| 52 | + .collect(); |
| 53 | + |
| 54 | + Ok(history) |
| 55 | +} |
| 56 | + |
| 57 | +#[tauri::command] |
| 58 | +pub fn clear_command_history() -> Result<(), String> { |
| 59 | + let history_file = get_history_file_path()?; |
| 60 | + |
| 61 | + if history_file.exists() { |
| 62 | + fs::remove_file(&history_file) |
| 63 | + .map_err(|e| format!("Failed to clear history file: {}", e))?; |
| 64 | + } |
| 65 | + |
| 66 | + Ok(()) |
| 67 | +} |
0 commit comments