oxinav-core 0.5.0

Core logic for OxiNav: file operations, pane state, archives and viewing, with no UI dependency
Documentation
//! Searching file contents: what a query means and what a hit holds.
//!
//! The rules live here so they can be tested without touching disk; the
//! searching itself goes through `Filesystem::search`, which the real
//! filesystem implements with ripgrep's library crates.

use crate::error::OxiNavError;
use crate::pane::Pane;
use std::path::PathBuf;

/// The most hits a search reports. Past this the pattern is too broad for a
/// list to help, and the search stops. Safe to tune.
pub const MAX_HITS: usize = 1_000;

/// The most characters of a matching line shown in the results. Safe to
/// tune.
pub const MAX_SNIPPET: usize = 200;

/// What to search for, and which files to look in.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchQuery {
    /// A regular expression, as ripgrep reads one.
    pub pattern: String,
    pub case_insensitive: bool,
    /// Search dot-prefixed files and directories too.
    pub include_hidden: bool,
    /// Only search files whose names match this glob (`pane::matches_filter`).
    pub name_glob: Option<String>,
}

impl SearchQuery {
    /// A query for `pattern`, scoped the way `pane` is showing things: its
    /// hidden-file setting and its name filter. `None` for a blank pattern.
    ///
    /// Case follows ripgrep's smart case: insensitive unless the pattern has
    /// an uppercase letter of its own. An escaped letter (`\S`, `\W`) is a
    /// character class, not a letter to match, so it does not count.
    pub fn new(pattern: &str, pane: &Pane) -> Option<Self> {
        if pattern.trim().is_empty() {
            return None;
        }
        Some(Self {
            pattern: pattern.to_string(),
            case_insensitive: !has_literal_uppercase(pattern),
            include_hidden: pane.show_hidden,
            name_glob: pane.filter.clone(),
        })
    }
}

/// Whether ripgrep's regex engine accepts `query`'s pattern, so a mistake
/// can be reported where it was typed rather than after a search starts.
pub fn check_pattern(query: &SearchQuery) -> Result<(), OxiNavError> {
    grep_regex::RegexMatcherBuilder::new()
        .case_insensitive(query.case_insensitive)
        .line_terminator(Some(b'\n'))
        .build(&query.pattern)
        .map(|_| ())
        .map_err(|error| OxiNavError::InvalidPattern(pattern_error(&error.to_string())))
}

/// The regex crate's parse error, reduced to its one-line reason. The full
/// message quotes the pattern back inside a wrapper the user never typed
/// (`(?:foo()`), with a caret under it, which reads worse than the reason.
pub fn pattern_error(message: &str) -> String {
    message
        .lines()
        .rev()
        .find_map(|line| line.trim().strip_prefix("error: "))
        .unwrap_or(message)
        .to_string()
}

fn has_literal_uppercase(pattern: &str) -> bool {
    let mut escaped = false;
    for c in pattern.chars() {
        if escaped {
            escaped = false;
        } else if c == '\\' {
            escaped = true;
        } else if c.is_uppercase() {
            return true;
        }
    }
    false
}

/// One matching line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchHit {
    pub path: PathBuf,
    /// 1-based, as editors and `rg` count.
    pub line: u64,
    /// The line, shortened for display by [`snippet`].
    pub text: String,
}

/// How a search ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchEnd {
    /// Every file was searched.
    Finished,
    /// Cancelled before the end; the hits so far stand.
    Stopped,
    /// More than [`MAX_HITS`] matched, so the search stopped there.
    Capped,
}

/// A matching line as the results list shows it: without its line ending or
/// leading indentation, and cut to [`MAX_SNIPPET`] characters.
pub fn snippet(line: &str) -> String {
    let line = line.trim_start().trim_end_matches(['\n', '\r']);
    match line.char_indices().nth(MAX_SNIPPET) {
        Some((cut, _)) => format!("{}\u{2026}", &line[..cut]),
        None => line.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn pane(show_hidden: bool, filter: Option<&str>) -> Pane {
        let mut pane = Pane::new(PathBuf::from("/proj"));
        pane.show_hidden = show_hidden;
        pane.filter = filter.map(str::to_string);
        pane
    }

    #[test]
    fn blank_patterns_are_not_queries() {
        assert_eq!(SearchQuery::new("", &pane(false, None)), None);
        assert_eq!(SearchQuery::new("   ", &pane(false, None)), None);
    }

    #[test]
    fn smart_case_follows_uppercase_letters() {
        let query = |p| SearchQuery::new(p, &pane(false, None)).unwrap();
        assert!(query("todo").case_insensitive);
        assert!(!query("Todo").case_insensitive);
        assert!(!query("fn Main").case_insensitive);
        // Escapes are classes, not letters.
        assert!(query(r"\Sfoo\W").case_insensitive);
        assert!(!query(r"\SFoo").case_insensitive);
    }

    #[test]
    fn scope_comes_from_the_pane() {
        let query = SearchQuery::new("x", &pane(true, Some("*.rs"))).unwrap();
        assert!(query.include_hidden);
        assert_eq!(query.name_glob.as_deref(), Some("*.rs"));

        let query = SearchQuery::new("x", &pane(false, None)).unwrap();
        assert!(!query.include_hidden);
        assert_eq!(query.name_glob, None);
    }

    #[test]
    fn invalid_patterns_are_caught_before_searching() {
        let query = |p| SearchQuery::new(p, &pane(false, None)).unwrap();
        assert!(check_pattern(&query(r"fn\s+main")).is_ok());
        assert!(matches!(
            check_pattern(&query("foo(")),
            Err(OxiNavError::InvalidPattern(_))
        ));
    }

    #[test]
    fn pattern_errors_are_reduced_to_their_reason() {
        let full = "regex parse error:\n    (?:foo()\n    ^\nerror: unclosed group";
        assert_eq!(pattern_error(full), "unclosed group");
        assert_eq!(pattern_error("something else"), "something else");
    }

    #[test]
    fn snippets_lose_indentation_and_line_endings() {
        assert_eq!(snippet("    let x = 1;\r\n"), "let x = 1;");
    }

    #[test]
    fn long_snippets_are_cut_on_a_character_boundary() {
        let line = "é".repeat(MAX_SNIPPET + 10);
        let cut = snippet(&line);
        assert_eq!(cut.chars().count(), MAX_SNIPPET + 1);
        assert!(cut.ends_with('\u{2026}'));
        assert_eq!(snippet(&"é".repeat(MAX_SNIPPET)), "é".repeat(MAX_SNIPPET));
    }
}