diff options
Diffstat (limited to 'src/history.rs')
-rw-r--r-- | src/history.rs | 46 |
1 files changed, 43 insertions, 3 deletions
diff --git a/src/history.rs b/src/history.rs index 9d29468..d7e7063 100644 --- a/src/history.rs +++ b/src/history.rs @@ -1,14 +1,25 @@ use std::{ fs::File, - io::{BufRead, BufReader}, + io::{BufRead, BufReader, BufWriter, Write}, path::PathBuf, }; use directories::ProjectDirs; -use crate::Session; +use crate::{Session, SessionSource}; -use super::SessionSource; +pub use error::Error; + +mod error { + #[derive(Debug, thiserror::Error)] + pub enum Error { + #[error("IO error: {0}")] + IO(#[from] std::io::Error), + + #[error(transparent)] + Format(#[from] ron::Error), + } +} #[derive(Debug)] pub struct History(PathBuf); @@ -24,6 +35,27 @@ impl History { .join("history") .into() } + + pub fn update_session(&self, session: Session) -> Result<(), Error> { + std::fs::create_dir_all(&self.0)?; + + let mut sessions: Vec<Session> = self + .sessions()? + .into_iter() + .filter(|s| s.name == session.name) + .collect(); + + sessions.push(session); + + let mut writer = BufWriter::new(File::create(&self.0)?); + + Ok(sessions + .into_iter() + .try_for_each(|s| match ron::to_string(&s) { + Ok(ser) => writeln!(writer, "{ser}"), + Err(err) => Ok(tracing::warn!(?err, "Failed to re-serialize session")), + })?) + } } impl SessionSource for History { @@ -53,3 +85,11 @@ impl SessionSource for History { Ok(sessions) } } + +impl std::ops::Deref for History { + type Target = PathBuf; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} |