summaryrefslogtreecommitdiffstats
path: root/src/history.rs
blob: 863be8ec2f262820053e427f9f3abf766ef8b82e (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
56
57
58
59
60
use std::{
    fs::File,
    io::{BufRead, BufReader, Write},
    path::PathBuf,
};

use directories::ProjectDirs;

use crate::Session;

pub use error::Error;

mod error;

#[derive(Debug)]
pub struct History {
    pub file: File,
    pub entries: Vec<Session>,
}

impl History {
    pub fn open(history_file: PathBuf) -> Result<Self, std::io::Error> {
        let file = File::options().write(true).open(&history_file)?;

        let entries = BufReader::new(File::open(history_file)?)
            .lines()
            .flatten()
            .flat_map(|item| ron::from_str(&item))
            .collect();

        Ok(Self { file, entries })
    }

    pub fn default_path() -> Option<PathBuf> {
        ProjectDirs::from("", "", env!("CARGO_CRATE_NAME"))?
            .state_dir()?
            .join("history")
            .into()
    }
}

impl IntoIterator for History {
    type Item = Session;

    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.entries.into_iter()
    }
}

impl Write for History {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.file.write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.file.flush()
    }
}