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
extern crate fragment;
use self::fragment::matching;
use walkdir::{DirEntry, Error, WalkDir};
use std::path::PathBuf;
use std::clone::Clone;
pub struct Index {
path: PathBuf,
entries: Vec<IndexedPath>,
}
#[derive(Debug, PartialEq)]
pub struct IndexedPath(PathBuf);
impl ToString for IndexedPath {
fn to_string(&self) -> String {
self.0.to_string_lossy().into_owned()
}
}
impl Clone for IndexedPath {
fn clone(&self) -> Self {
IndexedPath(self.0.clone())
}
fn clone_from(&mut self, source: &Self) {
self.0 = source.0.clone()
}
}
impl Index {
pub fn new(path: PathBuf) -> Index {
Index {
path: path,
entries: Vec::new(),
}
}
pub fn populate(&mut self) {
let prefix_length = match self.path.to_str() {
Some(path) => path.len() + 1,
None => return,
};
for entry in WalkDir::new(&self.path) {
match relative_entry_path(entry, prefix_length) {
Some(entry_path) => self.entries.push(IndexedPath(PathBuf::from(entry_path))),
_ => (),
}
}
}
pub fn find(&self, term: &str, limit: usize) -> Vec<PathBuf> {
matching::find(term, &self.entries, limit)
.into_iter()
.map(|r| {
let IndexedPath(other_thing) = r.clone();
other_thing
})
.collect()
}
}
fn relative_entry_path(entry: Result<DirEntry, Error>, prefix_length: usize) -> Option<String> {
match entry {
Ok(e) => {
match e.path().metadata() {
Ok(metadata) => {
if metadata.is_file() {
match e.path().to_str() {
Some(path) => Some(path[prefix_length..].to_string()),
_ => None,
}
} else {
None
}
}
_ => None,
}
}
_ => None,
}
}
#[cfg(test)]
mod tests {
extern crate fragment;
use super::{Index, IndexedPath};
use std::path::PathBuf;
#[test]
fn populate_adds_all_files_to_entries() {
let path = PathBuf::from("tests/sample");
let mut index = Index::new(path);
let expected_entries = vec![IndexedPath(PathBuf::from("directory/nested_file")),
IndexedPath(PathBuf::from("root_file"))];
index.populate();
assert_eq!(index.entries, expected_entries);
}
#[test]
fn find_defers_to_matching_module() {
let path = PathBuf::from("tests/sample");
let mut index = Index::new(path);
index.populate();
let term = "root";
let limit = 5;
let results: Vec<String> = index.find(term, limit)
.iter()
.map(|r| r.to_string_lossy().into_owned())
.collect();
assert_eq!(results, vec!["root_file".to_string()]);
}
}