save history to file

This commit is contained in:
Raptorox 2025-09-20 20:07:21 +02:00
parent ec1a840bb6
commit d7fc72e65d
No known key found for this signature in database
GPG key ID: 8B3556FC3ED1F6D8
2 changed files with 51 additions and 1 deletions

View file

@ -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<String>,
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<String> = 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
}
}
}
}
}

View file

@ -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();