1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
use std::{
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
path::PathBuf,
};
use directories::ProjectDirs;
use crate::{Session, 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);
impl History {
pub fn new(history_file: PathBuf) -> Self {
Self(history_file)
}
pub fn default_path() -> Option<PathBuf> {
ProjectDirs::from("", "", env!("CARGO_CRATE_NAME"))?
.state_dir()?
.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 {
type Error = std::io::Error;
type Iter = Vec<Session>;
fn sessions(&self) -> Result<Self::Iter, Self::Error> {
let mut sessions = Vec::new();
let file = File::open(&self.0)?;
for res in BufReader::new(file).lines() {
let entry = match res {
Ok(entry) => entry,
Err(err) => {
tracing::warn!(?err, "Failed to read line from history file");
continue;
}
};
match ron::from_str(&entry) {
Ok(session) => sessions.push(session),
Err(err) => tracing::warn!(?err, "Invalid history entry"),
}
}
Ok(sessions)
}
}
impl std::ops::Deref for History {
type Target = PathBuf;
fn deref(&self) -> &Self::Target {
&self.0
}
}
|