aboutsummaryrefslogtreecommitdiffstats
path: root/src/history.rs
blob: 865d9495e7c2659db7398734956d2bbec375270f (plain) (blame)
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
use sqlite::Connection;

use crate::BString;
use crate::date::DateTime;
use std::env::current_dir;
use std::path::PathBuf;

fn db_file() -> PathBuf {
    crate::basedir::data_dir().join("history.db")
}

#[derive(Clone)]
pub struct HistoryEntry {
    /// time of execution
    pub time: DateTime,

    /// absolute path where the command was executed
    pub loc: BString,

    /// the command
    pub cmd: BString,
}

impl HistoryEntry {
    pub fn new(cmd: BString) -> Self {
        Self {
            time: DateTime::now(),
            loc: current_dir()
                .unwrap()
                .as_os_str()
                .as_encoded_bytes()
                .to_vec(),
            cmd,
        }
    }
}

fn try_db() -> sqlite::Result<Connection> {
    sqlite::open(db_file())
}

fn db() -> Connection {
    try_db().unwrap()
}

pub fn setup() {
    let db = db();

    db.execute(
        "
    CREATE TABLE IF NOT EXISTS history (
        id  INTEGER PRIMARY KEY AUTOINCREMENT,
        ts  INTEGER NOT NULL,
        loc BLOB NOT NULL,
        cmd BLOB NOT NULL
    )
    ",
    )
    .unwrap();

    db.execute("CREATE INDEX IF NOT EXISTS idx_history_ts ON history(ts)")
        .unwrap();
}

fn try_persist(entry: &HistoryEntry) -> sqlite::Result<()> {
    let db = try_db()?;
    let mut s = db.prepare("INSERT INTO history (ts, loc, cmd) VALUES (?, ?, ?)")?;
    s.bind((1, entry.time.unix() as i64))?;
    s.bind((2, entry.loc.as_slice()))?;
    s.bind((3, entry.cmd.as_slice()))?;
    s.next()?;
    Ok(())
}

pub fn persist(entry: &HistoryEntry) {
    // keep quiet in case db fails
    let _ = try_persist(entry);
}