Skip to main content

griz_core/find/
summary.rs

1//! File-level search results for callers that do not need individual spans.
2
3use 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/// A matching file, its match count, and the fingerprint searched.
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
10pub struct FileSummary {
11    /// File containing the matches.
12    pub path: PathBuf,
13    /// Matches in this file.
14    pub count: usize,
15    /// Fingerprint of the whole file when searched.
16    pub file_hash: String,
17}
18
19/// One page of matching files.
20#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
21pub struct FindFilesPage {
22    /// Matching files on this page.
23    pub file_matches: Vec<FileSummary>,
24    /// Matches across every file, including files outside this page.
25    pub total: usize,
26    /// Files with at least one match, including files outside this page.
27    pub files: usize,
28    /// Offset of the next file page, when there is one.
29    pub next: Option<usize>,
30}
31
32/// Searches with the same filters as `super::find`, paging by matching file.
33///
34/// `offset` and `limit` count files instead of individual matches.
35///
36/// # Errors
37/// Returns a message for an invalid query or a filesystem traversal/read failure.
38pub 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}