From d7fc72e65d36b60a1945dc79dc44054ba1b92a26 Mon Sep 17 00:00:00 2001 From: Raptorox <70806316+Raptorox@users.noreply.github.com> Date: Sat, 20 Sep 2025 20:07:21 +0200 Subject: [PATCH] save history to file --- src/data.rs | 48 +++++++++++++++++++++++++++++++++++++++++++++++- src/main.rs | 4 ++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/src/data.rs b/src/data.rs index e59da09..0cf8566 100644 --- a/src/data.rs +++ b/src/data.rs @@ -1,4 +1,4 @@ -use std::{env, path::PathBuf}; +use std::{env, fs::{File, OpenOptions}, io::{BufRead, ErrorKind, Write}, path::PathBuf}; #[derive(Debug)] pub struct Data { @@ -6,6 +6,7 @@ pub struct Data { curr_path: PathBuf, history: Vec, + hist_file: String, hist_pos: usize, hist_partial: String } @@ -15,6 +16,7 @@ impl Default for Data { let prev_path = PathBuf::new(); let curr_path = env::current_dir().unwrap(); let history: Vec = Vec::new(); + let hist_file = String::new(); let hist_pos = 0; let hist_partial = String::new(); @@ -23,6 +25,7 @@ impl Default for Data { curr_path, history, + hist_file, hist_pos, hist_partial } @@ -46,6 +49,7 @@ impl Data { pub fn add_to_hist(&mut self, command: String) { self.history.push(command); self.hist_pos += 1; + self.save_history(); } pub fn save_command(&mut self, command: String) { @@ -68,4 +72,46 @@ impl Data { pub fn at_hist_end(&self) -> bool { self.hist_pos+1 == self.history.len() } + + pub fn set_hist_file(&mut self, hist_file: &str) { + self.hist_file = hist_file.to_string(); + } + + pub fn save_history(&self) { + let mut hist_file = match OpenOptions::new().create(true).write(true).open(&self.hist_file) { + Ok(file) => file, + Err(e) => { + eprint!("\r\n{e}"); + return + } + }; + for line in &self.history { + write!(hist_file, "{line}\n").unwrap(); + } + } + + pub fn load_history(&mut self) { + let hist_file = match File::open(&self.hist_file) { + Ok(file) => file, + Err(e) => { + if e.kind() == ErrorKind::NotFound {eprint!("\r\nHistory file not found, creating")} + else { eprint!("\r\n{e}"); } + return + } + }; + let reader = std::io::BufReader::new(hist_file); + + for line in reader.lines() { + match line { + Ok(line) => { + self.history.push(line.trim().to_string()); + self.hist_pos += 1; + }, + Err(e) => { + eprint!("\r\n{e}"); + return + } + } + } + } } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index c92703b..c45dc2e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -163,6 +163,10 @@ fn rush_loop(data: &mut Data, orig: libc::termios) -> io::Result<()> { fn main() { let mut data = Data::default(); + let home = env::home_dir().unwrap(); + let home_str = home.into_os_string().into_string().unwrap(); + data.set_hist_file(&format!("{}/.rush_history", home_str)); + data.load_history(); let orig = enable_raw_mode();