1use std::path::Path;
13
14use gitpoulpi_core::domain::{SearchHit, SearchKind, SearchTarget};
15use gitpoulpi_core::fuzzy::{self, Anchor};
16use serde::Deserialize;
17
18const SECONDARY_PENALTY: i32 = 8_000;
21const SETTLED_PENALTY: i32 = 60;
23
24#[derive(Debug, Clone, Default, Deserialize)]
26pub struct CachedItem {
27 #[serde(default)]
28 pub number: u64,
29 #[serde(default)]
31 pub iid_label: String,
32 #[serde(default)]
33 pub title: String,
34 #[serde(default)]
35 pub author: String,
36 #[serde(default)]
38 pub source_branch: String,
39 #[serde(default)]
41 pub state: String,
42}
43
44#[derive(Debug, Clone, Default, Deserialize)]
46pub struct CachedItems {
47 #[serde(default)]
48 pub prs: Vec<CachedItem>,
49 #[serde(default)]
50 pub issues: Vec<CachedItem>,
51}
52
53pub fn load(path: &Path) -> CachedItems {
55 std::fs::read_to_string(path)
56 .ok()
57 .and_then(|raw| serde_json::from_str(&raw).ok())
58 .unwrap_or_default()
59}
60
61fn label_of(item: &CachedItem, fallback_mark: char) -> String {
62 let mark = if item.iid_label.is_empty() {
63 format!("{fallback_mark}{}", item.number)
64 } else {
65 item.iid_label.clone()
66 };
67 format!("{mark} {}", item.title)
68}
69
70fn hit(item: &CachedItem, kind: SearchKind, text_lower: &str) -> Option<SearchHit> {
71 let label = label_of(
72 item,
73 if kind == SearchKind::PullRequest {
74 '!'
75 } else {
76 '#'
77 },
78 );
79 let lower = label.to_lowercase();
80 let digits = text_lower.trim_start_matches(['#', '!']);
81 let by_number = (!digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()))
82 .then(|| {
83 let n = item.number.to_string();
84 if n == digits {
85 Some(40_000)
86 } else if n.starts_with(digits) {
87 Some(35_000 - n.len() as i32)
88 } else {
89 None
90 }
91 })
92 .flatten();
93 let primary = fuzzy::matched(&lower, text_lower, Anchor::Whole);
94 let branch_lower = item.source_branch.to_lowercase();
95 let author_lower = item.author.to_lowercase();
96 let secondary = [&author_lower, &branch_lower]
97 .into_iter()
98 .filter(|t| !t.is_empty())
99 .filter_map(|t| fuzzy::score_lower(t, text_lower, Anchor::Whole))
100 .max()
101 .map(|s| s - SECONDARY_PENALTY);
102 let (mut score, positions) = match (by_number, primary, secondary) {
103 (Some(n), Some(m), _) if m.score <= n => (n, Vec::new()),
104 (Some(n), None, _) => (n, Vec::new()),
105 (_, Some(m), Some(s)) if s > m.score => (s, Vec::new()),
106 (_, Some(m), _) => (m.score, m.positions),
107 (_, None, Some(s)) => (s, Vec::new()),
108 (None, None, None) => return None,
109 };
110 if matches!(item.state.as_str(), "merged" | "closed") {
111 score -= SETTLED_PENALTY;
112 }
113 let mut detail = item.author.clone();
114 if !item.source_branch.is_empty() {
115 if !detail.is_empty() {
116 detail.push_str(" \u{b7} ");
117 }
118 detail.push_str(&item.source_branch);
119 }
120 if matches!(item.state.as_str(), "merged" | "closed" | "draft") {
121 if !detail.is_empty() {
122 detail.push_str(" \u{b7} ");
123 }
124 detail.push_str(&item.state);
125 }
126 Some(SearchHit {
127 kind,
128 label,
129 detail,
130 target: match kind {
131 SearchKind::PullRequest => SearchTarget::PullRequest {
132 number: item.number,
133 },
134 _ => SearchTarget::Issue {
135 number: item.number,
136 },
137 },
138 score,
139 positions,
140 repo: None,
141 })
142}
143
144pub fn search(
148 items: &CachedItems,
149 kinds: &[SearchKind],
150 text: &str,
151 limit: usize,
152) -> Vec<SearchHit> {
153 let text_lower = text.trim().to_lowercase();
154 let wants = |k: SearchKind| kinds.is_empty() || kinds.contains(&k);
155 let mut hits: Vec<SearchHit> = Vec::new();
156 if wants(SearchKind::PullRequest) {
157 hits.extend(
158 items
159 .prs
160 .iter()
161 .filter_map(|i| hit(i, SearchKind::PullRequest, &text_lower)),
162 );
163 }
164 if wants(SearchKind::Issue) {
165 hits.extend(
166 items
167 .issues
168 .iter()
169 .filter_map(|i| hit(i, SearchKind::Issue, &text_lower)),
170 );
171 }
172 let number = |h: &SearchHit| match h.target {
173 SearchTarget::PullRequest { number } | SearchTarget::Issue { number } => number,
174 _ => 0,
175 };
176 hits.sort_by(|a, b| {
177 b.score
178 .cmp(&a.score)
179 .then_with(|| number(b).cmp(&number(a)))
180 });
181 if limit > 0 {
182 hits.truncate(limit);
183 }
184 hits
185}
186
187#[cfg(test)]
188mod tests {
189 use super::*;
190
191 fn items() -> CachedItems {
192 serde_json::from_str(
193 r##"{
194 "profile_id": "p", "unknown_field": [1, 2],
195 "prs": [
196 {"number": 12, "iid_label": "#12", "title": "Fix login redirect", "author": "ana",
197 "source_branch": "fix/login", "state": "open", "extra": 1},
198 {"number": 40, "iid_label": "!40", "title": "Bump deps", "author": "bob",
199 "source_branch": "chore/deps", "state": "merged"}
200 ],
201 "issues": [
202 {"number": 7, "iid_label": "#7", "title": "Login page is slow", "author": "cy",
203 "state": "open"}
204 ]
205 }"##,
206 )
207 .unwrap()
208 }
209
210 #[test]
211 fn a_title_matches_and_highlights_after_the_number() {
212 let hits = search(&items(), &[], "login", 10);
213 let kinds: Vec<_> = hits.iter().map(|h| h.kind).collect();
215 assert_eq!(kinds, [SearchKind::Issue, SearchKind::PullRequest]);
216 assert_eq!(hits[1].label, "#12 Fix login redirect");
217 assert_eq!(hits[1].positions, [8, 9, 10, 11, 12]);
219 assert_eq!(hits[1].detail, "ana \u{b7} fix/login");
220 }
221
222 #[test]
223 fn a_number_finds_its_item_first() {
224 let hits = search(&items(), &[], "12", 10);
225 assert_eq!(hits[0].target, SearchTarget::PullRequest { number: 12 });
226 let hits = search(&items(), &[], "!40", 10);
227 assert_eq!(hits[0].target, SearchTarget::PullRequest { number: 40 });
228 }
229
230 #[test]
231 fn author_and_branch_match_under_the_titles() {
232 let by_author = search(&items(), &[], "bob", 10);
233 assert_eq!(by_author.len(), 1);
234 assert_eq!(by_author[0].label, "!40 Bump deps");
235 assert!(by_author[0].positions.is_empty());
236 let by_branch = search(&items(), &[], "chore", 10);
237 assert_eq!(
238 by_branch[0].target,
239 SearchTarget::PullRequest { number: 40 }
240 );
241 }
242
243 #[test]
244 fn kinds_restrict_and_an_empty_query_lists_everything() {
245 let only_issues = search(&items(), &[SearchKind::Issue], "", 10);
246 assert_eq!(only_issues.len(), 1);
247 assert_eq!(search(&items(), &[], "", 10).len(), 3);
248 assert_eq!(search(&items(), &[], "", 2).len(), 2);
249 }
250
251 #[test]
252 fn a_missing_or_corrupt_cache_is_empty() {
253 let dir = tempfile::tempdir().unwrap();
254 assert!(load(&dir.path().join("nope.json")).prs.is_empty());
255 let bad = dir.path().join("hosting-cache.json");
256 std::fs::write(&bad, "{\"prs\": [{\"number\": 1,").unwrap();
257 let cache = load(&bad);
258 assert!(cache.prs.is_empty() && cache.issues.is_empty());
259 std::fs::write(
260 &bad,
261 serde_json::to_string(&serde_json::json!({"prs": 3})).unwrap(),
262 )
263 .unwrap();
264 assert!(load(&bad).prs.is_empty());
265 }
266}