-
-
Notifications
You must be signed in to change notification settings - Fork 634
/
Copy pathmod.rs
137 lines (119 loc) · 2.67 KB
/
mod.rs
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
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use async_trait::async_trait;
use eyre::{Result, bail};
use memchr::Memchr;
use crate::history::History;
pub mod bash;
pub mod csv_history;
pub mod fish;
pub mod nu;
pub mod nu_histdb;
pub mod replxx;
pub mod resh;
pub mod xonsh;
pub mod xonsh_sqlite;
pub mod zsh;
pub mod zsh_histdb;
#[async_trait]
pub trait Importer: Sized {
const NAME: &'static str;
async fn new() -> Result<Self>;
async fn entries(&mut self) -> Result<usize>;
async fn load(self, loader: &mut impl Loader) -> Result<()>;
}
#[async_trait]
pub trait Loader: Sync + Send {
async fn push(&mut self, hist: History) -> eyre::Result<()>;
}
fn unix_byte_lines(input: &[u8]) -> impl Iterator<Item = &[u8]> {
UnixByteLines {
iter: memchr::memchr_iter(b'\n', input),
bytes: input,
i: 0,
}
}
struct UnixByteLines<'a> {
iter: Memchr<'a>,
bytes: &'a [u8],
i: usize,
}
impl<'a> Iterator for UnixByteLines<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
let j = self.iter.next()?;
let out = &self.bytes[self.i..j];
self.i = j + 1;
Some(out)
}
fn count(self) -> usize
where
Self: Sized,
{
self.iter.count()
}
}
fn count_lines(input: &[u8]) -> usize {
unix_byte_lines(input).count()
}
fn get_histpath<D>(def: D) -> Result<PathBuf>
where
D: FnOnce() -> Result<PathBuf>,
{
if let Ok(p) = std::env::var("HISTFILE") {
Ok(PathBuf::from(p))
} else {
def()
}
}
fn get_histfile_path<D>(def: D) -> Result<PathBuf>
where
D: FnOnce() -> Result<PathBuf>,
{
get_histpath(def).and_then(is_file)
}
fn get_histdir_path<D>(def: D) -> Result<PathBuf>
where
D: FnOnce() -> Result<PathBuf>,
{
get_histpath(def).and_then(is_dir)
}
fn read_to_end(path: PathBuf) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
let mut f = File::open(path)?;
f.read_to_end(&mut bytes)?;
Ok(bytes)
}
fn is_file(p: PathBuf) -> Result<PathBuf> {
if p.is_file() {
Ok(p)
} else {
bail!("Could not find history file {:?}. Try setting $HISTFILE", p)
}
}
fn is_dir(p: PathBuf) -> Result<PathBuf> {
if p.is_dir() {
Ok(p)
} else {
bail!(
"Could not find history directory {:?}. Try setting $HISTFILE",
p
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Default)]
pub struct TestLoader {
pub buf: Vec<History>,
}
#[async_trait]
impl Loader for TestLoader {
async fn push(&mut self, hist: History) -> Result<()> {
self.buf.push(hist);
Ok(())
}
}
}