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
|
use std::{
fs::File,
io::{BufRead, BufReader, ErrorKind},
path::PathBuf,
};
use clap::Args;
use directories::ProjectDirs;
use crate::{session::SessionWriter, Session};
#[derive(Debug, Clone, Args)]
#[group(skip)]
pub struct History {
/// Update the history file from the current sessions
#[arg(short, long)]
pub update: bool,
/// path to history file [default: $XDG_DATA_HOME/sshr/history]
#[arg(short = 'f', long = "history_file")]
path: Option<PathBuf>,
}
impl History {
pub fn new(History { update, path }: History) -> Self {
Self {
path: path.or_else(History::default_path),
update,
}
}
pub fn read(&self) -> Result<Vec<Session>, std::io::Error> {
let Some(path) = &self.path() else {
tracing::warn!(?self.path, "History file does not exist");
return Ok(Vec::new());
};
let sessions = BufReader::new(File::open(path)?)
.lines()
.flatten()
.flat_map(|item| ron::from_str(&item))
.collect();
Ok(sessions)
}
fn default_path() -> Option<PathBuf> {
ProjectDirs::from("", "", env!("CARGO_CRATE_NAME"))?
.state_dir()?
.join("history")
.into()
}
pub fn path(&self) -> Option<PathBuf> {
self.path.clone().or_else(History::default_path)
}
}
impl SessionWriter for History {
type Writer = File;
type Error = ron::Error;
fn format(&self, session: &Session) -> Result<String, Self::Error> {
ron::to_string(session)
}
fn filter(&self, session: &Session) -> bool {
self.update && !matches!(session.state, crate::State::Discovered)
}
fn writer(&self) -> Result<Self::Writer, std::io::Error> {
match &self.path {
Some(path) => File::create(path),
None => Err(std::io::Error::from(ErrorKind::NotFound)),
}
}
}
|