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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
|
use sqlite::{Connection, State};
use crate::BString;
use crate::date::DateTime;
use std::env::current_dir;
use std::i64;
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,
}
pub fn canonical_path(mut path: BString) -> BString {
while let Some(b'/') = path.last() {
path.pop();
}
if path.is_empty() {
path.push(b'/');
}
path
}
impl HistoryEntry {
pub fn new(cmd: BString) -> Self {
Self {
time: DateTime::now(),
loc: canonical_path(
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
// TODO maybe better behavior?
let _ = try_persist(entry);
}
pub struct HistoryQueryer {
db: Connection,
}
impl HistoryQueryer {
pub fn new() -> sqlite::Result<Self> {
Ok(Self { db: try_db()? })
}
pub fn query(
&self,
min_time: Option<DateTime>,
max_time: Option<DateTime>,
path_prefix: Option<&[u8]>,
path_strict: bool,
) -> sqlite::Result<impl Iterator<Item = HistoryEntry>> {
let mut query = String::from("SELECT id, ts, loc, cmd FROM history\n");
let mut has_cond = false;
let mut cond = |c| {
if has_cond {
query += "AND ";
} else {
query += "WHERE ";
}
query += c;
query += "\n";
has_cond = true;
};
let path_prefix = path_prefix.map(|p| canonical_path(p.to_vec()));
let mut upper = Vec::new();
if let Some(path_prefix) = &path_prefix {
if path_strict {
cond("loc = ?");
} else {
upper = path_prefix.to_vec();
if let Some(last) = upper.last_mut() {
*last = last.saturating_add(1);
} else {
upper.push(0xFF);
}
cond("loc >= ? AND loc < ?");
}
}
if min_time.is_some() {
cond("ts >= ?");
}
if max_time.is_some() {
cond("ts <= ?");
}
query += "ORDER BY id asc";
let mut stmt = self.db.prepare(&query)?;
let mut i = 1;
if let Some(path_prefix) = &path_prefix {
stmt.bind((i, path_prefix.as_slice()))?;
i += 1;
if !path_strict {
stmt.bind((i, upper.as_slice()))?;
i += 1;
}
}
if let Some(t) = min_time {
stmt.bind((i, t.unix() as i64))?;
i += 1;
}
if let Some(t) = max_time {
stmt.bind((i, t.unix() as i64))?;
i += 1;
}
let _ = i;
Ok(std::iter::from_fn(move || match stmt.next() {
Ok(State::Row) => {
let ts: i64 = stmt.read::<i64, _>(1).ok()?;
let loc: Vec<u8> = stmt.read::<Vec<u8>, _>(2).ok()?;
let cmd: Vec<u8> = stmt.read::<Vec<u8>, _>(3).ok()?;
let time = DateTime::from_unix(ts as u64);
Some(HistoryEntry { time, loc, cmd })
}
_ => None,
}))
}
}
pub fn local_history_filter(
hist: Vec<HistoryEntry>,
min_time: Option<DateTime>,
max_time: Option<DateTime>,
path_prefix: Option<&[u8]>,
path_strict: bool,
) -> impl Iterator<Item = HistoryEntry> {
let path_prefix = path_prefix.map(|p| canonical_path(p.to_vec()));
hist.into_iter().filter(move |entry| {
if let Some(t) = &min_time
&& t.unix() > entry.time.unix()
{
return false;
}
if let Some(t) = &max_time
&& t.unix() < entry.time.unix()
{
return false;
}
if let Some(path_prefix) = &path_prefix {
if path_strict {
let canon_path = canonical_path(entry.loc.clone());
return &canon_path == path_prefix;
} else {
if !entry.loc.starts_with(&path_prefix) {
return false;
}
}
}
true
})
}
|