forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

code_search.rs484 lines, 19.0 KiBHistoryRawDownload
1//! Page: code search at `/{owner}/{repo}/search`. Runs `git grep` at one commit (`ref`, default the
2//! default branch) and groups the hits by file. Each line links to the blob view at `#L<n>`. In
3//! plain-text mode the matching text is wrapped in `<mark>`; regex mode shows the lines unhighlighted.
4//! `case=1` makes the match case-sensitive; `path` is a git pathspec glob that limits the search.
5
6use forge_git::browse;
7use forge_git::search::{GrepHit, GrepOptions, GrepResult, grep};
8use topcoat::Result;
9use topcoat::context::{Cx, context};
10use topcoat::router::error::not_found;
11use topcoat::router::{page, path_param, query_params};
12use topcoat::view::{View, view};
13
14use crate::i18n::{
15 self,
16 code::{self as g, K},
17};
18use crate::pages::code_live::branch_live_url;
19use crate::pages::commits::blocking;
20use crate::pages::repo::repo_head;
21use crate::pages::repo_ctx::load_repo;
22use crate::state::AppState;
23use crate::views::{empty_state, repo_href, shell};
24
25path_param!(owner);
26path_param!(repo);
27
28#[query_params(error = bad_request)]
29struct SearchQuery {
30 q: Option<String>,
31 r#ref: Option<String>,
32 case: Option<String>,
33 regex: Option<String>,
34 path: Option<String>,
35}
36
37/// A piece of a result line. `hit` marks the query occurrence to highlight.
38struct Segment {
39 text: String,
40 hit: bool,
41}
42
43/// One result line, ready to render.
44struct LineRow {
45 num: String,
46 href: String,
47 segments: Vec<Segment>,
48}
49
50/// The hits of one file, in git's order.
51struct FileGroup {
52 path: String,
53 href: String,
54 lines: Vec<LineRow>,
55}
56
57/// Splits `line` around the occurrences of `query`. Matching compares ASCII case-insensitively
58/// unless `match_case`. Only whole-byte matches are taken, so every slice stays on a char boundary.
59fn segments(line: &str, query: &str, match_case: bool) -> Vec<Segment> {
60 let (hay, needle) = (line.as_bytes(), query.as_bytes());
61 let mut out = Vec::new();
62 let mut last = 0;
63 let mut i = 0;
64 while !needle.is_empty() && i + needle.len() <= hay.len() {
65 let window = &hay[i..i + needle.len()];
66 let same = if match_case {
67 window == needle
68 } else {
69 window.eq_ignore_ascii_case(needle)
70 };
71 if same {
72 let end = i + needle.len();
73 if last < i {
74 out.push(Segment {
75 text: line.get(last..i).unwrap_or_default().to_owned(),
76 hit: false,
77 });
78 }
79 out.push(Segment {
80 text: line.get(i..end).unwrap_or_default().to_owned(),
81 hit: true,
82 });
83 i = end;
84 last = end;
85 } else {
86 i += 1;
87 }
88 }
89 if last < line.len() {
90 out.push(Segment {
91 text: line.get(last..).unwrap_or_default().to_owned(),
92 hit: false,
93 });
94 }
95 out
96}
97
98/// Groups consecutive hits of the same file, keeping git's order.
99fn group_hits(
100 hits: &[GrepHit],
101 owner: &str,
102 repo: &str,
103 ref_name: &str,
104 query: Option<(&str, bool)>,
105) -> Vec<FileGroup> {
106 let mut groups: Vec<FileGroup> = Vec::new();
107 for hit in hits {
108 let blob = repo_href(owner, repo, "blob", &format!("{ref_name}/{}", hit.path));
109 let segs = match query {
110 Some((q, match_case)) => segments(&hit.line, q, match_case),
111 None => vec![Segment {
112 text: hit.line.clone(),
113 hit: false,
114 }],
115 };
116 let row = LineRow {
117 num: hit.line_no.to_string(),
118 href: format!("{blob}#L{}", hit.line_no),
119 segments: segs,
120 };
121 match groups.last_mut() {
122 Some(group) if group.path == hit.path => group.lines.push(row),
123 _ => groups.push(FileGroup {
124 href: blob,
125 path: hit.path.clone(),
126 lines: vec![row],
127 }),
128 }
129 }
130 groups
131}
132
133#[page("/{owner}/{repo}/search")]
134async fn search_page(cx: &Cx) -> Result<impl View> {
135 let owner = owner(cx);
136 let name = repo(cx);
137 let query = query_params::<SearchQuery>(cx)?;
138
139 let ctx = load_repo(cx, owner, name).await?;
140 let state = context::<AppState>(cx);
141 let repo_name = ctx.repo.name.clone();
142 let owner_name = ctx.repo.owner_name.clone();
143 let lang = i18n::lang(cx, ctx.viewer.as_ref().map(|(user, _)| user));
144
145 let typed_ref = query.r#ref.clone().unwrap_or_default().trim().to_owned();
146 let repo_dir = ctx.path.clone();
147 // The commit to search (None for an empty repo), and the ref name shown and used in links.
148 let (commit, ref_name) = if typed_ref.is_empty() {
149 let branch = ctx.repo.default_branch.clone();
150 let commit = blocking(move || browse::default_branch_commit(&repo_dir, &branch)).await?;
151 (commit, ctx.repo.default_branch.clone())
152 } else {
153 let name = typed_ref.clone();
154 let Some(commit) = blocking(move || browse::resolve_commit(&repo_dir, &name)).await? else {
155 return Err(not_found().into());
156 };
157 (Some(commit), typed_ref.clone())
158 };
159
160 let q = query.q.clone().unwrap_or_default();
161 let match_case = query.case.as_deref() == Some("1");
162 let regex = query.regex.as_deref() == Some("1");
163 let path_glob = query.path.clone().unwrap_or_default().trim().to_owned();
164
165 let mut notice: Option<String> = None;
166 let mut result: Option<GrepResult> = None;
167 if let Some(commit) = commit.as_deref().filter(|_| !q.trim().is_empty()) {
168 let opts = GrepOptions {
169 fixed: !regex,
170 ignore_case: !match_case,
171 path_glob: (!path_glob.is_empty()).then(|| path_glob.clone()),
172 ..GrepOptions::default()
173 };
174 match grep(&state.git, &ctx.path, commit, &q, opts).await {
175 Ok(found) => result = Some(found),
176 Err(forge_git::Error::InvalidInput(msg)) => notice = Some(msg),
177 Err(_) => {
178 notice = Some(g::t(lang, K::SearchFailed).to_owned());
179 }
180 }
181 }
182
183 let searched = result.is_some();
184 let empty_repo = commit.is_none();
185 let no_query = q.trim().is_empty();
186 let truncated = result.as_ref().is_some_and(|r| r.truncated);
187 let hits = result.as_ref().map(|r| r.hits.as_slice()).unwrap_or(&[]);
188 let highlight = (!regex).then_some((q.as_str(), match_case));
189 let groups = group_hits(hits, &owner_name, &repo_name, &ref_name, highlight);
190 let match_count = hits.len();
191 let file_count = groups.len();
192 let shown = match_count.to_string();
193 let summary = g::match_summary(lang, match_count, file_count);
194 let empty_message = g::empty_repo_message(lang, &ctx.repo.default_branch);
195 let has_results = !groups.is_empty();
196 let action = repo_href(&owner_name, &repo_name, "search", "");
197 let title = format!(
198 "{owner_name}/{repo_name} \u{b7} {}",
199 g::t(lang, K::SearchWord)
200 );
201 let ref_value = typed_ref;
202 let path_value = path_glob;
203 let ref_label = ref_name.clone();
204
205 let mut header = ctx.head(state, "code").await?;
206 // Results of a branch go stale when it moves: the header's stream follows that branch's head.
207 header.live = branch_live_url(&owner_name, &repo_name, &ref_name);
208 Ok(view! {
209 shell(title: title.as_str(), viewer: ctx.viewer.as_ref(),
210 repo_head(head: header)
211 <form method="get" action=(action.as_str()) class="sheet search-form" role="search">
212 <div class="sheet-tools">
213 <div class="plain-search">
214 <input type="search" name="q" value=(q.as_str()) data-live-search="" autocomplete="off" placeholder=(g::t(lang, K::SearchCodePlaceholder)) aria-label=(g::t(lang, K::SearchCodePlaceholder))>
215 <button type="submit" class="sr-only">(g::t(lang, K::SearchButton))</button>
216 </div>
217 </div>
218 <section class="sec">
219 <div class="fields">
220 <div class="field">
221 <label for="search-ref">(g::t(lang, K::RefField))</label>
222 // Not live: a half-typed branch name is a 404 page. It searches on leaving the field.
223 <input id="search-ref" type="text" name="ref" value=(ref_value.as_str()) placeholder=(ctx.repo.default_branch.as_str()) data-autosubmit=(true)>
224 </div>
225 <div class="field">
226 <label for="search-path">(g::t(lang, K::PathField))</label>
227 <input id="search-path" type="text" name="path" value=(path_value.as_str()) data-live-search="">
228 </div>
229 <label class="switch">
230 <input type="checkbox" name="case" value="1" checked=(match_case) data-autosubmit=(true)>
231 <span>(g::t(lang, K::MatchCase))</span>
232 </label>
233 <label class="switch">
234 <input type="checkbox" name="regex" value="1" checked=(regex) data-autosubmit=(true)>
235 <span>(g::t(lang, K::RegexOption))</span>
236 </label>
237 </div>
238 </section>
239 if empty_repo {
240 <p class="state">(empty_message.as_str())</p>
241 } else if no_query {
242 <p class="state">(g::t(lang, K::SearchFilesAt)) <code>(ref_label.as_str())</code> "."</p>
243 }
244 if let Some(msg) = notice {
245 <p class="state" role="alert">(msg.as_str())</p>
246 }
247 if !no_query && !empty_repo {
248 if has_results {
249 <p class="hint">(summary.as_str())
250 if truncated {
251 (g::t(lang, K::ShowingFirst)) (shown.as_str()) (g::t(lang, K::ShowingFirstEnd))
252 }
253 </p>
254 for group in groups.iter() {
255 <section class="sec search-file">
256 <h2><a href=(group.href.as_str())>(group.path.as_str())</a></h2>
257 <ul class="search-hits">
258 for line in group.lines.iter() {
259 <li>
260 <a class="ln" href=(line.href.as_str())>(line.num.as_str())</a>
261 <code class="search-line">
262 for seg in line.segments.iter() {
263 if seg.hit {
264 <mark>(seg.text.as_str())</mark>
265 } else {
266 (seg.text.as_str())
267 }
268 }
269 </code>
270 </li>
271 }
272 </ul>
273 </section>
274 }
275 } else if searched {
276 empty_state(title: g::t(lang, K::NoMatches))
277 }
278 }
279 </form>
280 )
281 })
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 fn texts(segs: &[Segment]) -> Vec<(String, bool)> {
289 segs.iter().map(|s| (s.text.clone(), s.hit)).collect()
290 }
291
292 #[test]
293 fn segments_split_around_each_hit() {
294 let segs = segments("Hello hello HELLO", "hello", false);
295 assert_eq!(
296 texts(&segs),
297 vec![
298 ("Hello".to_owned(), true),
299 (" ".to_owned(), false),
300 ("hello".to_owned(), true),
301 (" ".to_owned(), false),
302 ("HELLO".to_owned(), true),
303 ],
304 "every case-insensitive hit is marked"
305 );
306 let segs = segments("Hello hello", "hello", true);
307 assert_eq!(
308 texts(&segs),
309 vec![("Hello ".to_owned(), false), ("hello".to_owned(), true)],
310 "case-sensitive match skips other case"
311 );
312 // Non-ASCII text is never split inside a character.
313 let segs = segments("café CAFÉ", "é", false);
314 assert_eq!(
315 segs.iter().filter(|s| s.hit).count(),
316 1,
317 "unicode is not split inside a character"
318 );
319 assert_eq!(
320 segments("no match here", "zzz", false).len(),
321 1,
322 "no match is one plain segment"
323 );
324 }
325}
326
327#[cfg(test)]
328mod route_tests {
329 use std::path::Path;
330 use std::process::Command;
331
332 use forge_core::Visibility;
333 use forge_git::repo::{init_bare, repo_path};
334 use topcoat::router::request::Request;
335 use topcoat::router::{Body, Router, to_bytes};
336
337 use crate::state::AppState;
338
339 async fn app(dir: &Path) -> (Router, AppState) {
340 let state = crate::test_support::test_state(dir).await;
341 (crate::test_support::app_router(state.clone()), state)
342 }
343
344 fn git(dir: &Path, args: &[&str]) {
345 let status = Command::new("git")
346 .current_dir(dir)
347 .env("GIT_CONFIG_NOSYSTEM", "1")
348 .args([
349 "-c",
350 "user.name=Test",
351 "-c",
352 "user.email=test@example.com",
353 "-c",
354 "commit.gpgsign=false",
355 ])
356 .args(args)
357 .status()
358 .expect("git runs");
359 assert!(status.success(), "git {args:?} failed");
360 }
361
362 /// `tahinli/demo` (public) and `tahinli/secret` (private), both with content on `main`, plus
363 /// `tahinli/empty` (public, no commits).
364 async fn fixture(dir: &Path) -> (Router, AppState) {
365 let (router, state) = app(dir).await;
366 let tahinli = state
367 .store
368 .create_user("tahinli", None, "x", false)
369 .await
370 .unwrap();
371 let demo = state
372 .store
373 .create_repo(
374 &tahinli.id,
375 "demo",
376 "A demo repo",
377 Visibility::Public,
378 "main",
379 )
380 .await
381 .unwrap();
382 let secret = state
383 .store
384 .create_repo(&tahinli.id, "secret", "", Visibility::Private, "main")
385 .await
386 .unwrap();
387 let empty = state
388 .store
389 .create_repo(&tahinli.id, "empty", "", Visibility::Public, "main")
390 .await
391 .unwrap();
392 for repo in [&demo, &secret, &empty] {
393 let path = repo_path(&state.config.data_dir, &repo.id).unwrap();
394 init_bare(&state.git, &path, "main").await.unwrap();
395 }
396
397 let work = dir.join("work");
398 std::fs::create_dir_all(work.join("src")).unwrap();
399 std::fs::write(work.join("README.md"), "# Demo\n\nHello from the README.\n").unwrap();
400 std::fs::write(
401 work.join("src/main.rs"),
402 "fn main() {\n println!(\"hi\");\n}\n",
403 )
404 .unwrap();
405 git(&work, &["init", "-q", "-b", "main"]);
406 git(&work, &["add", "-A"]);
407 git(&work, &["commit", "-q", "-m", "first commit"]);
408 for repo in [&demo, &secret] {
409 let path = repo_path(&state.config.data_dir, &repo.id).unwrap();
410 git(&work, &["push", "-q", path.to_str().unwrap(), "main:main"]);
411 }
412 (router, state)
413 }
414
415 async fn get(router: &Router, uri: &str) -> (u16, String) {
416 let req = Request::builder()
417 .method("GET")
418 .uri(uri)
419 .body(Body::empty())
420 .unwrap();
421 let res = router.handle(req).await;
422 let status = res.status().as_u16();
423 let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
424 (status, String::from_utf8_lossy(&bytes).into_owned())
425 }
426
427 /// Every search scenario reads one shared, read-only fixture: results and links, case,
428 /// regex and path options, failure messages, a private repo, an unknown ref and the Turkish page.
429 #[tokio::test]
430 async fn search_pages_over_one_fixture() {
431 let dir = tempfile::tempdir().unwrap();
432 let (router, _) = fixture(dir.path()).await;
433
434 // Results group by file, link to the matching line and highlight the match.
435 let (status, body) = get(&router, "/tahinli/demo/search?q=hello").await;
436 assert_eq!(status, 200, "results");
437 assert!(body.contains("README.md"), "file listed");
438 assert!(
439 body.contains("/tahinli/demo/blob/main/README.md#L3"),
440 "line links to the blob view"
441 );
442 assert!(body.contains("<mark>Hello</mark>"), "match highlighted");
443 assert!(body.contains("1 match in 1 file"), "summary shown");
444 assert!(!body.contains("src/main.rs"), "non-matching file absent");
445
446 // Case-sensitive miss, regex hit without highlights, and a path glob that excludes src.
447 let (_, body) = get(&router, "/tahinli/demo/search?q=HELLO&case=1").await;
448 assert!(body.contains("No matches."), "case-sensitive miss");
449 let (_, body) = get(&router, "/tahinli/demo/search?q=h.llo&regex=1").await;
450 assert!(body.contains("README.md"), "regex hit");
451 assert!(!body.contains("<mark>"), "regex mode does not highlight");
452 let (_, body) = get(&router, "/tahinli/demo/search?q=println&path=README.md").await;
453 assert!(body.contains("No matches."), "path glob excludes src");
454
455 // A bad regex, an empty repo and an unknown ref each show their message or status.
456 let (status, body) = get(&router, "/tahinli/demo/search?q=(&regex=1").await;
457 assert_eq!(status, 200, "bad regex");
458 assert!(body.contains("could not run"), "git failure shown");
459 let (status, body) = get(&router, "/tahinli/empty/search?q=hello").await;
460 assert_eq!(status, 200, "empty repo");
461 assert!(body.contains("no commits"), "empty repo message");
462 let (status, _) = get(&router, "/tahinli/demo/search?q=hello&ref=nope-branch").await;
463 assert_eq!(status, 404, "unknown ref");
464
465 // A private repo is 404 for anonymous viewers and leaks no content.
466 let (status, body) = get(&router, "/tahinli/secret/search?q=hello").await;
467 assert_eq!(status, 404, "private repo");
468 assert!(!body.contains("README.md"), "private repo leaks no files");
469
470 // A Turkish viewer gets the Turkish page.
471 let req = Request::builder()
472 .method("GET")
473 .uri("/tahinli/demo/search?q=hello")
474 .header("accept-language", "tr")
475 .body(Body::empty())
476 .unwrap();
477 let res = router.handle(req).await;
478 let bytes = to_bytes(res.into_body(), usize::MAX).await.unwrap();
479 let body = String::from_utf8_lossy(&bytes).into_owned();
480 assert!(body.contains("· arama"), "Turkish page title");
481 assert!(body.contains("Kodda ara"), "Turkish search placeholder");
482 assert!(body.contains("1 eşleşme, 1 dosyada"), "Turkish summary");
483 }
484}