From ca639db826052f3ef3d75526367459683ed19bb1 Mon Sep 17 00:00:00 2001 From: rhpidfyre Date: Sat, 11 Jan 2025 14:37:56 -0500 Subject: [PATCH] the history file now stores the first line properly --- src/commands.rs | 16 ++++++---------- src/rc.rs | 33 +++++++++++++++++++++++++-------- 2 files changed, 31 insertions(+), 18 deletions(-) diff --git a/src/commands.rs b/src/commands.rs index 13cf25a..6335269 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -126,27 +126,23 @@ impl Command { } } - pub fn history_write(&self) { - if let Some(history_file) = &self.history { - history_file.write(&self.input); - }; - } - - pub fn spawn(&self, command_process: io::Result) { + pub fn spawn_handle(&mut self, command_process: io::Result) { if let Ok(mut child) = command_process { - self.history_write(); + if let Some(history_file) = self.history.as_mut() { + history_file.write(&self.input); + }; child.wait().ok(); } else { println!("Unknown command: {}", self.input) } } - pub fn exec(&self) { + pub fn exec(&mut self) { let mut args = self.input.split_whitespace(); if let Some(command) = args.next() { match command { "cd" => { self.change_directory(args); }, - command => { self.spawn(process::Command::new(command).args(args).spawn()); } + command => { self.spawn_handle(process::Command::new(command).args(args).spawn()); } } } } diff --git a/src/rc.rs b/src/rc.rs index dbf8f01..9cd084a 100644 --- a/src/rc.rs +++ b/src/rc.rs @@ -95,29 +95,46 @@ pub fn config_file() -> Option { config_file.is_valid_file_or_create(DEFAULT_CONFIG_CONTENT.as_bytes()) } -pub struct History(PathBuf); +pub struct History { + history_file: PathBuf, + checked_empty: bool +} impl History { pub fn init() -> Option { config_dir().map(|mut config| { config.push(".history"); config.is_valid_file_or_create(b""); - Self(config) + Self { + history_file: config, + checked_empty: false + } }) } - pub fn write>(&self, content: S) { - //feasible hack instead of using about 10 functions - OpenOptions::new().append(true).open(self.0.as_path()).map_or_display(|mut file| { - const NEXTLINE: &str = "\n"; + pub fn is_empty(&mut self) -> bool { + match self.checked_empty { + true => true, + false => self.read().map_or(false, |history_l| { + self.checked_empty = true; + history_l.is_empty() + }) + } + } - if let Err(write_err) = file.write_all(format!("{}{}", NEXTLINE, content.as_ref()).as_bytes()) { + pub fn write>(&mut self, content: S) { + OpenOptions::new().append(true).open(self.history_file.as_path()).map_or_display(|mut file| { + let write_data = match self.is_empty() { + true => content.as_ref().to_owned(), + false => format!("\n{}", content.as_ref()), + }; + if let Err(write_err) = file.write_all(write_data.as_bytes()) { shell_error(write_err); }; }); } pub fn read(&self) -> Option> { - File::open(&self.0).map_or_display_none(|file| { + File::open(&self.history_file).map_or_display_none(|file| { Some(BufReader::new(file).lines().map_while(Result::ok).collect::>()) }) }