summaryrefslogtreecommitdiffstats
path: root/src/history.rs
blob: 9d294685cfbf25f507e10494f9a01d52cdfe1c41 (plain)
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
use std::{
    fs::File,
    io::{BufRead, BufReader},
    path::PathBuf,
};

use directories::ProjectDirs;

use crate::Session;

use super::SessionSource;

#[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()
    }
}

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)
    }
}