Skip to content
Myr

haystack.rs

This file

Path

crates/core/haystack.rs

160 lines · 5.6 KiB · Rust

Last changed by

Not known.

History of this file

Take it

1/*!2Defines a builder for haystacks.34A "haystack" represents something we want to search. It encapsulates the logic5for whether a haystack ought to be searched or not, separate from the standard6ignore rules and other filtering logic.78Effectively, a haystack wraps a directory entry and adds some light application9level logic around it.10*/1112use std::path::Path;1314/// A builder for constructing things to search over.15#[derive(Clone, Debug)]16pub(crate) struct HaystackBuilder {17    strip_dot_prefix: bool,18}1920impl HaystackBuilder {21    /// Return a new haystack builder with a default configuration.22    pub(crate) fn new() -> HaystackBuilder {23        HaystackBuilder { strip_dot_prefix: false }24    }2526    /// Create a new haystack from a possibly missing directory entry.27    ///28    /// If the directory entry isn't present, then the corresponding error is29    /// logged if messages have been configured. Otherwise, if the directory30    /// entry is deemed searchable, then it is returned as a haystack.31    pub(crate) fn build_from_result(32        &self,33        result: Result<ignore::DirEntry, ignore::Error>,34    ) -> Option<Haystack> {35        match result {36            Ok(dent) => self.build(dent),37            Err(err) => {38                err_message!("{err}");39                None40            }41        }42    }4344    /// Create a new haystack using this builder's configuration.45    ///46    /// If a directory entry could not be created or should otherwise not be47    /// searched, then this returns `None` after emitting any relevant log48    /// messages.49    fn build(&self, dent: ignore::DirEntry) -> Option<Haystack> {50        let hay = Haystack { dent, strip_dot_prefix: self.strip_dot_prefix };51        if let Some(err) = hay.dent.error() {52            ignore_message!("{err}");53        }54        // If this entry was explicitly provided by an end user, then we always55        // want to search it.56        if hay.is_explicit() {57            return Some(hay);58        }59        // At this point, we only want to search something if it's explicitly a60        // file. This omits symlinks. (If ripgrep was configured to follow61        // symlinks, then they have already been followed by the directory62        // traversal.)63        if hay.is_file() {64            return Some(hay);65        }66        // We got nothing. Emit a debug message, but only if this isn't a67        // directory. Otherwise, emitting messages for directories is just68        // noisy.69        if !hay.is_dir() {70            log::debug!(71                "ignoring {}: failed to pass haystack filter: \72                 file type: {:?}, metadata: {:?}",73                hay.dent.path().display(),74                hay.dent.file_type(),75                hay.dent.metadata()76            );77        }78        None79    }8081    /// When enabled, if the haystack's file path starts with `./` then it is82    /// stripped.83    ///84    /// This is useful when implicitly searching the current working directory.85    pub(crate) fn strip_dot_prefix(86        &mut self,87        yes: bool,88    ) -> &mut HaystackBuilder {89        self.strip_dot_prefix = yes;90        self91    }92}9394/// A haystack is a thing we want to search.95///96/// Generally, a haystack is either a file or stdin.97#[derive(Clone, Debug)]98pub(crate) struct Haystack {99    dent: ignore::DirEntry,100    strip_dot_prefix: bool,101}102103impl Haystack {104    /// Return the file path corresponding to this haystack.105    ///106    /// If this haystack corresponds to stdin, then a special `<stdin>` path107    /// is returned instead.108    pub(crate) fn path(&self) -> &Path {109        if self.strip_dot_prefix && self.dent.path().starts_with("./") {110            self.dent.path().strip_prefix("./").unwrap()111        } else {112            self.dent.path()113        }114    }115116    /// Returns true if and only if this entry corresponds to stdin.117    pub(crate) fn is_stdin(&self) -> bool {118        self.dent.is_stdin()119    }120121    /// Returns true if and only if this entry corresponds to a haystack to122    /// search that was explicitly supplied by an end user.123    ///124    /// Generally, this corresponds to either stdin or an explicit file path125    /// argument. e.g., in `rg foo some-file ./some-dir/`, `some-file` is126    /// an explicit haystack, but, e.g., `./some-dir/some-other-file` is not.127    ///128    /// However, note that ripgrep does not see through shell globbing. e.g.,129    /// in `rg foo ./some-dir/*`, `./some-dir/some-other-file` will be treated130    /// as an explicit haystack.131    pub(crate) fn is_explicit(&self) -> bool {132        // stdin is obvious. When an entry has a depth of 0, that means it133        // was explicitly provided to our directory iterator, which means it134        // was in turn explicitly provided by the end user. The !is_dir check135        // means that we want to search files even if their symlinks, again,136        // because they were explicitly provided. (And we never want to try137        // to search a directory.)138        self.is_stdin() || (self.dent.depth() == 0 && !self.is_dir())139    }140141    /// Returns true if and only if this haystack points to a directory after142    /// following symbolic links.143    fn is_dir(&self) -> bool {144        let ft = match self.dent.file_type() {145            None => return false,146            Some(ft) => ft,147        };148        if ft.is_dir() {149            return true;150        }151        // If this is a symlink, then we want to follow it to determine152        // whether it's a directory or not.153        self.dent.path_is_symlink() && self.dent.path().is_dir()154    }155156    /// Returns true if and only if this haystack points to a file.157    fn is_file(&self) -> bool {158        self.dent.file_type().map_or(false, |ft| ft.is_file())159    }160}