/
lib.rs
215 lines (178 loc) · 6.01 KB
/
lib.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
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
use std::collections::HashMap;
use std::sync::Arc;
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
use matcher::{Bonus, MatchResult, MatcherBuilder};
use printer::truncate_item_output_text_v0;
use types::{ClapItem, MatchScope, SourceItem};
/// Pass a Vector of lines to Vim for setting them in Vim with one single API call.
type LinesInBatch = Vec<String>;
/// Each line's matched indices of LinesInBatch.
type MatchedIndicesInBatch = Vec<Vec<usize>>;
/// NOTE: TruncatedMap is ought to be HashMap<usize, String>,
/// but there is an issue when converting to call result to Vim Dict in python dynamic call,
/// therefore hereby has to use HashMap<String, String> instead.
type TruncatedMapInfo = HashMap<String, String>;
const DEFAULT_WINWIDTH: usize = 80;
#[derive(Debug, Clone)]
struct MatchContext {
winwidth: usize,
enable_icon: bool,
match_scope: MatchScope,
bonuses: Vec<Bonus>,
}
impl From<HashMap<String, String>> for MatchContext {
fn from(ctx: HashMap<String, String>) -> Self {
let winwidth = ctx
.get("winwidth")
.and_then(|x| x.parse::<usize>().ok())
.unwrap_or(DEFAULT_WINWIDTH);
let enable_icon = ctx
.get("enable_icon")
.map(|x| x.to_lowercase() == "true")
.unwrap_or(false);
let match_scope = ctx
.get("match_scope")
.map(Into::into)
.unwrap_or(MatchScope::Full);
let bonus_type = ctx.get("bonus_type").map(Into::into).unwrap_or(Bonus::None);
let mut bonuses = vec![bonus_type];
if let Some(language) = ctx.get("language") {
bonuses.push(Bonus::Language(language.into()));
}
Self {
winwidth,
enable_icon,
match_scope,
bonuses,
}
}
}
#[derive(Debug)]
struct LineWithIcon(String);
impl ClapItem for LineWithIcon {
fn raw_text(&self) -> &str {
self.0.as_str()
}
fn match_text(&self) -> &str {
&self.0[4..]
}
fn match_result_callback(&self, match_result: MatchResult) -> MatchResult {
let mut match_result = match_result;
match_result.indices.iter_mut().for_each(|x| {
*x += 4;
});
match_result
}
}
/// Filter the candidates synchorously given `query` and `candidates`.
///
/// `recent_files` and `context` are the full context for matching each item.
#[pyfunction]
fn fuzzy_match(
query: &str,
candidates: Vec<String>,
recent_files: Vec<String>,
context: HashMap<String, String>,
) -> PyResult<(MatchedIndicesInBatch, LinesInBatch, TruncatedMapInfo)> {
let MatchContext {
winwidth,
enable_icon,
match_scope,
mut bonuses,
} = context.into();
bonuses.push(Bonus::RecentFiles(recent_files.into()));
let matcher = MatcherBuilder::new()
.bonuses(bonuses)
.match_scope(match_scope)
.build(query.into());
let mut ranked = candidates
.into_iter()
.filter_map(|line: String| {
let item: Arc<dyn ClapItem> = if enable_icon {
Arc::new(LineWithIcon(line))
} else {
Arc::new(SourceItem::from(line))
};
matcher.match_item(item)
})
.collect::<Vec<_>>();
ranked.sort_unstable_by(|v1, v2| v2.cmp(v1));
// " " is 4 bytes, but the offset of highlight is 2.
// 2 = chars(icon)
let skipped = if enable_icon { Some(2) } else { None };
let truncated_map = truncate_item_output_text_v0(ranked.iter_mut(), winwidth, skipped);
let (lines, indices): (Vec<_>, Vec<_>) = ranked
.into_iter()
.map(|matched_item| {
(
matched_item.display_text().to_string(),
matched_item.indices,
)
})
.unzip();
Ok((
indices,
lines,
truncated_map
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect(),
))
}
/// This module is a python module implemented in Rust.
#[pymodule]
fn fuzzymatch_rs(_py: Python, m: &PyModule) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(fuzzy_match))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn py_and_rs_subscore_should_work() {
use matcher::substring::substr_indices as substr_scorer;
use pyo3::prelude::*;
use pyo3::types::PyModule;
use std::fs;
use types::CaseMatching;
let cur_dir = std::env::current_dir().unwrap();
let py_path = cur_dir.parent().unwrap().join("scorer.py");
let py_source_code = fs::read_to_string(py_path).unwrap();
pyo3::prepare_freethreaded_python();
let gil = Python::acquire_gil();
let py = gil.python();
let py_scorer = PyModule::from_code(py, &py_source_code, "scorer.py", "scorer").unwrap();
let test_cases = vec![
("su ou", "substr_scorer_should_work"),
("su ork", "substr_scorer_should_work"),
];
for (needle, haystack) in test_cases.into_iter() {
let py_result: (i32, Vec<usize>) = py_scorer
.getattr("substr_scorer")
.unwrap()
.call1((needle, haystack))
.unwrap()
.extract()
.map(|(score, positions): (f64, Vec<usize>)| (score as i32, positions))
.unwrap();
let rs_result = substr_scorer(haystack, needle, CaseMatching::Smart).unwrap();
assert_eq!(py_result, rs_result);
}
}
#[test]
fn test_skip_icon() {
let lines = vec![" .dependabot/config.yml".into(), " .editorconfig".into()];
let query = "con";
let context: HashMap<String, String> = vec![
("winwidth", "62"),
("enable_icon", "True"),
("match_scope", "Full"),
("bonus_type", "FileName"),
]
.into_iter()
.map(|(x, y)| (x.into(), y.into()))
.collect();
println!("ret: {:#?}", fuzzy_match(query, lines, vec![], context));
}
}