griz_core/find/
summary.rs1use super::{FindQuery, Matcher, content_hash, files, find_in_file, read_text, validate_within};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use std::path::{Path, PathBuf};
7
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
10pub struct FileSummary {
11 pub path: PathBuf,
13 pub count: usize,
15 pub file_hash: String,
17}
18
19#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
21pub struct FindFilesPage {
22 pub file_matches: Vec<FileSummary>,
24 pub total: usize,
26 pub files: usize,
28 pub next: Option<usize>,
30}
31
32pub fn find_files(query: &FindQuery) -> Result<FindFilesPage, String> {
39 let matcher = Matcher::new(query)?;
40 let paths = files(query)?;
41 validate_within(query, &paths)?;
42 let mut page = FindFilesPage::default();
43 for path in paths {
44 let Some(text) = read_text(&path)? else {
45 continue;
46 };
47 let Some(hits) = find_in_file(&matcher, query, &path, &text, (0, 0))? else {
48 continue;
49 };
50 collect(&mut page, query, &path, &text, hits.total);
51 }
52 let shown = query.offset.saturating_add(page.file_matches.len());
53 page.next = (shown < page.files).then_some(shown);
54 Ok(page)
55}
56
57fn collect(page: &mut FindFilesPage, query: &FindQuery, path: &Path, text: &str, count: usize) {
58 if count == 0 {
59 return;
60 }
61 page.files += 1;
62 page.total += count;
63 if page.files - 1 < query.offset || page.file_matches.len() >= query.limit {
64 return;
65 }
66 page.file_matches.push(FileSummary {
67 path: path.to_path_buf(),
68 count,
69 file_hash: content_hash(text),
70 });
71}