Skip to content
Myr

ignore: add incremental checking

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This adds a new increment checker for ignore files, overrides and file type selection. This effectively makes it possible to check individual file paths as to whether they are ignored or not by any ignore file in the directory tree (including parent gitignores). This is particularly useful in the context of implementing a file watcher, where one wants to make a decision about whether a newly added file should be included *without* doing a full re-traversal of the directory tree. This implementation reuses pretty much all of the existing gitignore logic without making any changes to it.

authored by Andrew Gallant · committed by Andrew Gallant · parent c55818f · Browse files · 4 files+1355 added−10 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+1355 added−10 removed

  • other:+1355 added−10 removed

4 files+1355 added−10 removed

modified:crates/ignore/src/dir.rs+7 added-2 removed
495 unmodified lines
496 /// Returns a match indicating whether the given file path should be497 /// ignored or not.498 ///499 /// The match contains information about its origin.500 fn matched<'a, P: AsRef<Path>>(500 pub(crate) fn matched<'a, P: AsRef<Path>>(501 &'a self,502 path: P,503 is_dir: bool,504 ) -> Match<IgnoreMatch<'a>> {
39 unmodified lines
544 }545546 /// Performs matching only on the ignore files for this directory and547 /// all parent directories.548 fn matched_ignore<'a>(548 pub(crate) fn matched_ignore<'a>(549 &'a self,550 path: &Path,551 is_dir: bool,552 ) -> Match<IgnoreMatch<'a>> {
367 unmodified lines
920 self.opts.hidden = yes;921 self922 }923924 /// Whether ignoring hidden files is enabled or not.925 pub(crate) fn is_hidden(&self) -> bool {926 self.opts.hidden927 }928929 /// Enables reading `.ignore` files.930 ///931 /// `.ignore` files have the same semantics as `gitignore` files and are932 /// supported by search tools such as ripgrep and The Silver Searcher.
681 unmodified lines
added:crates/ignore/src/incremental.rs+1286 added
1use std::{2 collections::HashMap,3 path::{Path, PathBuf},4 sync::OnceLock,5};67use crate::{8 Error, Match, PartialErrorBuilder, dir::Ignore, pathutil::is_hidden_path,9};1011/// A cached matcher for checking paths against hierarchical ignore files.12///13/// An `IncrementalIgnore` is built from a [`crate::WalkBuilder`]. Unlike a14/// recursive walk, it can check individual paths while still respecting the15/// ignore files in every relevant parent directory. Matchers for directories16/// are compiled on first use and then retained for later queries.17/// Each matcher corresponds to exactly one root configured on the builder,18/// and paths passed to it are interpreted relative to that root.19/// A matcher for the special `-` root representing standard input is inert20/// and always returns a non-match.21///22/// The matcher checks path-based filters in the same precedence order as23/// a traversal. This includes glob overrides, `.ignore`, `.gitignore`,24/// `.git/info/exclude`, global and explicitly added ignore files, custom25/// ignore file names and file type selections. It does not apply filters that26/// require a directory entry or other traversal state, such as custom entry27/// predicates. Hidden-file detection, minimum and maximum depth limits and the28/// maximum file size are applied.29///30/// A matcher is a snapshot at directory granularity. Once the ignore files in31/// a directory have been loaded, edits to those files are not observed. Build32/// a new matcher to reload them.33///34/// # Warning35///36/// The incremental path checking here necessarily needs to do a lot more work37/// per path matched. Callers should _not_ use this to run directory traversal.38/// This is intended to avoid the work of re-traversing an entire directory39/// tree when only a few changes are detected. (For example, in response to40/// file additions or deletions.)41///42/// # Example43///44/// ```rust,no_run45/// use ignore::WalkBuilder;46///47/// let mut builder = WalkBuilder::new(".");48/// builder.add_custom_ignore_filename(".rgignore");49/// let mut matchers = builder.build_matchers();50/// let matcher = &mut matchers[0];51///52/// if matcher.matched("src/generated.rs", false).is_ignore() {53/// println!("ignored");54/// }55/// ```56#[derive(Clone, Debug)]57pub struct IncrementalIgnore {58 /// The root exactly as it was given to `WalkBuilder`.59 root: PathBuf,60 /// The normalized root used only by the opt-in normalization routine.61 normalized_root: OnceLock<Option<PathBuf>>,62 /// The matcher for the configured root directory, loaded on first use.63 ignore: RootIgnore,64 /// Directory paths relative to `root`, excluding the root itself.65 dirs: HashMap<PathBuf, CachedDir>,66 /// Options for additional filtering beyond gitignore.67 options: IncrementalIgnoreOptions,68}6970/// The options for a matcher, mostly meant to duplicate as much as we can from71/// `WalkParallel`.72#[derive(Clone, Debug)]73pub(crate) struct IncrementalIgnoreOptions {74 pub(crate) min_depth: Option<usize>,75 pub(crate) max_depth: Option<usize>,76 pub(crate) max_filesize: Option<u64>,77 pub(crate) hidden: bool,78 pub(crate) follow_links: bool,79}8081#[derive(Clone, Debug)]82enum RootIgnore {83 Unloaded(Ignore),84 Loaded(Ignore),85 NotDirectory,86 Stdin,87}8889/// Cached traversal state for a directory relative to the configured root.90///91/// The presence of an entry means that the directory and every ancestor92/// between it and the root have already been checked.93#[derive(Clone, Debug)]94enum CachedDir {95 /// The directory may be descended into. The matcher includes the ignore96 /// rules loaded through this directory and is therefore the matcher to use97 /// for its children.98 Allowed(Ignore),99 /// The directory may not be descended into because it was ignored by a100 /// path rule or hidden-file filtering. Every descendant is consequently101 /// ignored, and ignore files inside this directory are not loaded.102 Ignored,103}104105impl IncrementalIgnore {106 pub(crate) fn new(107 root: PathBuf,108 ignore: Ignore,109 options: IncrementalIgnoreOptions,110 ) -> IncrementalIgnore {111 // File traversal special cases `-` to search stdin, so we recognize112 // it here for completeness too. In particular, we really want113 // `WalkBuilder::build_matchers` to return a matcher for every root,114 // even when it's a simple file (handled automatically) or when it's115 // stdin (necessarily special cased).116 //117 // If callers need to search a file or directory named `-`, then they118 // can use `./-`. As is the case for file traversal too.119 let ignore = if root == Path::new("-") {120 RootIgnore::Stdin121 } else {122 RootIgnore::Unloaded(ignore)123 };124 IncrementalIgnore {125 root,126 normalized_root: OnceLock::new(),127 ignore,128 dirs: HashMap::new(),129 options,130 }131 }132133 /// Return the root that paths matched by this matcher are relative to.134 pub fn root(&self) -> &Path {135 &self.root136 }137138 /// Normalize `path` and return it relative to this matcher's root.139 ///140 /// This returns `None` when `path` cannot be made absolute or141 /// when it is known to be outside this matcher's root. Unlike142 /// [`IncrementalIgnore::matched`], this performs absolute path conversion,143 /// lexical normalization and allocation. It is intended as an opt-in144 /// convenience for callers that do not already have root-relative paths.145 ///146 /// Note that `.` is interpreted relative to the process level current147 /// working directory. It is _not_ interpreted relative to the root of148 /// this matcher.149 ///150 /// Note also that this may reject paths that only differ in casing. For151 /// example, if the root path for this matcher is `/FOO` but the provided152 /// path is `/foo/bar`, then this may return `None`. Callers must ensure153 /// casing is consistent between the path provided and the root path for154 /// this matcher.155 pub fn normalize<P: AsRef<Path>>(&self, path: P) -> Option<PathBuf> {156 if matches!(self.ignore, RootIgnore::Stdin) {157 return None;158 }159 let path = normalize_absolute(path.as_ref())?;160 let root = self161 .normalized_root162 .get_or_init(|| normalize_absolute(&self.root))163 .as_ref()?;164 path.strip_prefix(root).ok().map(Path::to_path_buf)165 }166167 /// Match a root-relative path against ignore files in its directory and168 /// all relevant parent directories.169 ///170 /// `is_dir` should be true when `path` should be matched as a directory.171 ///172 /// For the return value, use [`IncrementalMatch::is_ignore`],173 /// [`IncrementalMatch::is_whitelist`] or [`IncrementalMatch::is_none`] to174 /// inspect it.175 ///176 /// Matchers for previously unseen directories are loaded and cached during177 /// this call. Errors encountered while loading ignore files are logged. To178 /// receive those errors, use [`IncrementalIgnore::matched_with_errors`].179 ///180 /// `path` must be relative to this matcher's root and must not contain a181 /// parent directory (`..`) component. Behavior is unspecified when these182 /// preconditions are violated. Callers with an absolute path or with a183 /// path containing `.` or `..` may use [`IncrementalIgnore::normalize`]184 /// to get a path satisfying these preconditions. In all cases, a relative185 /// path is *assumed* to be relative to the root of this ignore matcher.186 ///187 /// In general, it is intended that callers doing recursive directory188 /// traversal on the root of this matcher may provide relative paths to189 /// this routine *without* calling [`IncrementalIgnore::normalize`].190 ///191 /// The empty path represents the explicitly configured root and also192 /// returns non-match, consistent with recursive traversal where a root is193 /// always treated as being at depth zero.194 pub fn matched<P: AsRef<Path>>(195 &mut self,196 path: P,197 is_dir: bool,198 ) -> IncrementalMatch {199 let (matched, err) = self.matched_with_errors(path, is_dir);200 if let Some(err) = err {201 log::debug!("error while loading ignore files: {err}");202 }203 matched204 }205206 /// Match a root-relative path and return errors encountered while loading207 /// ignore files.208 ///209 /// This is equivalent to [`IncrementalIgnore::matched`], except that210 /// it returns any errors from newly loaded ignore files. Loading can211 /// partially succeed, so valid rules are always applied to the returned212 /// match even when an error is present.213 pub fn matched_with_errors<P: AsRef<Path>>(214 &mut self,215 path: P,216 is_dir: bool,217 ) -> (IncrementalMatch, Option<Error>) {218 let mut errs = PartialErrorBuilder::default();219 let matched =220 self.matched_with_errors_impl(path.as_ref(), is_dir, &mut errs);221 (matched, errs.into_error_option())222 }223224 fn matched_with_errors_impl(225 &mut self,226 relative: &Path,227 is_dir: bool,228 errs: &mut PartialErrorBuilder,229 ) -> IncrementalMatch {230 // We short-circuit here when our matcher corresponds to `Stdin` in231 // order to always return a non-match. This is somewhat redundant with232 // `root_ignore()` which does this too, but we do it here so that it233 // always happens, e.g., before depth filtering.234 if relative.is_absolute() || matches!(self.ignore, RootIgnore::Stdin) {235 return IncrementalMatch::none(is_dir);236 }237238 let (mut satisfies_min, mut edge_max) = (true, false);239 if self.options.min_depth.is_some() || self.options.max_depth.is_some()240 {241 let depth = relative242 .components()243 .filter_map(|component| match component {244 std::path::Component::CurDir => None,245 component => Some(component),246 })247 .count();248 satisfies_min =249 self.options.min_depth.is_none_or(|min| depth >= min);250 let satisfies_max =251 self.options.max_depth.is_none_or(|max| depth <= max);252 edge_max = self.options.max_depth.is_some_and(|max| depth == max);253 // When we have a file that isn't past our min depth, we can give254 // up right away.255 if !is_dir && !satisfies_min {256 return IncrementalMatch::ignore().not_within_depth();257 }258 // Same for *anything* that exceeds our max depth.259 if !satisfies_max {260 return IncrementalMatch::ignore().not_within_depth();261 }262 }263264 // When the path is invalid in some way, we bail out early to avoid265 // potentially doing a stat call below.266 let (mut mat, valid) = self267 .matched_with_errors_ignore(relative, is_dir, errs)268 .map(|mat| (mat, true))269 .unwrap_or_else(|| (IncrementalMatch::none(is_dir), false));270271 if !is_dir272 && !mat.is_ignore()273 && valid274 && let Some(max_filesize) = self.options.max_filesize275 {276 let path = self.root().join(relative);277 let result = if self.options.follow_links {278 path.metadata()279 } else {280 path.symlink_metadata()281 };282 match result {283 Ok(md) if md.len() > max_filesize => {284 return IncrementalMatch::ignore();285 }286 Ok(_) => {}287 Err(err) => {288 // Record the error but otherwise fall through289 let err = Error::from(err);290 errs.push(err.with_path(path));291 }292 }293 }294295 // We still need to tag our `mat` if it doesn't pass the depth filter,296 // or if it's a directory on the edge of a depth filter. This can only297 // happen when the path is reported as a directory. Otherwise regular298 // files are always handled above.299 if is_dir {300 if !satisfies_min {301 mat = mat.not_within_depth();302 }303 if edge_max {304 mat = mat.no_descent();305 }306 }307 mat308 }309310 fn matched_with_errors_ignore(311 &mut self,312 relative: &Path,313 is_dir: bool,314 errs: &mut PartialErrorBuilder,315 ) -> Option<IncrementalMatch> {316 let mut components = relative317 .components()318 .filter_map(|component| match component {319 std::path::Component::CurDir => None,320 component => Some(component),321 })322 .peekable();323 components.peek()?;324325 // If the exact parent is cached, then all of its ancestors have326 // already been checked. An allowed cache entry is the matcher to use327 // for children of that directory, while an ignored cache entry is328 // terminal for every descendant. In the usual case, this avoids both329 // walking every component and allocating a relative directory path.330 //331 // Only try the fast path when the final component is a normal path332 // component. Invalid paths are handled by the component walk below.333 let has_normal_final_component =334 relative.components().next_back().is_some_and(|component| {335 matches!(component, std::path::Component::Normal(_))336 });337 if has_normal_final_component && let Some(parent) = relative.parent() {338 match self.dirs.get(parent) {339 Some(CachedDir::Allowed(ignore)) => {340 return Some(self.match_path(ignore, relative, is_dir));341 }342 Some(CachedDir::Ignored) => {343 return Some(IncrementalMatch::ignore());344 }345 None => {}346 }347 }348349 let mut ignore = self.root_ignore(errs)?;350 let mut dir = PathBuf::new();351 while let Some(component) = components.next() {352 match component {353 std::path::Component::ParentDir354 | std::path::Component::RootDir355 | std::path::Component::Prefix(_) => {356 return None;357 }358 std::path::Component::CurDir => continue,359 std::path::Component::Normal(_) => {}360 }361 if components.peek().is_none() {362 break;363 }364 dir.push(component.as_os_str());365 match self.dirs.get(&dir) {366 Some(CachedDir::Allowed(cached)) => {367 ignore = cached.clone();368 continue;369 }370 Some(CachedDir::Ignored) => {371 return Some(IncrementalMatch::ignore());372 }373 None => {}374 }375376 let path = self.root.join(&dir);377 let mat = ignore.matched(&path, true);378 let is_hidden =379 self.options.hidden && mat.is_none() && is_hidden_path(&path);380 if mat.is_ignore() || is_hidden {381 self.dirs.insert(dir.clone(), CachedDir::Ignored);382 return Some(IncrementalMatch::ignore());383 }384 let (child, err) = ignore.add_child(&path);385 errs.maybe_push(err);386 self.dirs.insert(dir.clone(), CachedDir::Allowed(child.clone()));387 ignore = child;388 }389390 Some(self.match_path(&ignore, relative, is_dir))391 }392393 fn match_path(394 &self,395 ignore: &Ignore,396 relative: &Path,397 is_dir: bool,398 ) -> IncrementalMatch {399 let path = self.root.join(relative);400 let mut mat = IncrementalMatch::from_match(401 ignore.matched(&path, is_dir).map(|_| ()),402 is_dir,403 );404 // Whether a file is hidden or not has low precedence in filtering. We405 // only check it if we haven't matched anything above. This permits406 // callers to whitelist hidden files or directories.407 if self.options.hidden && mat.is_none() && is_hidden_path(&path) {408 mat = IncrementalMatch::ignore();409 }410 mat411 }412413 fn root_ignore(414 &mut self,415 errs: &mut PartialErrorBuilder,416 ) -> Option<Ignore> {417 let ignore = match self.ignore {418 RootIgnore::Unloaded(ref ignore) => ignore.clone(),419 RootIgnore::Loaded(ref ignore) => return Some(ignore.clone()),420 RootIgnore::NotDirectory | RootIgnore::Stdin => return None,421 };422 if !self.root.is_dir() {423 self.ignore = RootIgnore::NotDirectory;424 return None;425 }426427 let (parents, err) = ignore.add_parents(&self.root);428 errs.maybe_push(err);429 let (root, err) = parents.add_child(&self.root);430 errs.maybe_push(err);431 self.ignore = RootIgnore::Loaded(root.clone());432 Some(root)433 }434}435436/// The result of an incremental match.437///438/// This is similar to [`Match`] in that it reports whether a file path should439/// be ignored, whitelisted or didn't match anything at all. It also has extra440/// data, such as whether a directory matched but should not be descended into.441///442/// Generally speaking, callers that only care about specific files can stick443/// to the `is_none()`, `is_ignore()` or `is_whitelist()` predicates. Directory444/// entries are more complicated because we sometimes want to yield directories445/// to descend into, but not actually visit (e.g., for the minimum depth446/// filter). Or, we may want to yield a directory to visit but not descend into447/// (e.g., for the maximum depth filter).448#[derive(Clone, Debug)]449pub struct IncrementalMatch {450 mat: Match<()>,451 should_descend: bool,452 is_within_depth: bool,453}454455impl IncrementalMatch {456 fn none(is_dir: bool) -> IncrementalMatch {457 IncrementalMatch {458 mat: Match::None,459 should_descend: is_dir,460 is_within_depth: true,461 }462 }463464 fn ignore() -> IncrementalMatch {465 IncrementalMatch {466 mat: Match::Ignore(()),467 should_descend: false,468 is_within_depth: true,469 }470 }471472 fn from_match(mat: Match<()>, is_dir: bool) -> IncrementalMatch {473 let should_descend = is_dir && !mat.is_ignore();474 IncrementalMatch { mat, should_descend, is_within_depth: true }475 }476477 fn no_descent(self) -> IncrementalMatch {478 IncrementalMatch { should_descend: false, ..self }479 }480481 fn not_within_depth(self) -> IncrementalMatch {482 IncrementalMatch { is_within_depth: false, ..self }483 }484485 /// Returns true if the match result didn't match anything.486 pub fn is_none(&self) -> bool {487 self.mat.is_none()488 }489490 /// Returns true if the match result implies the path should be ignored.491 pub fn is_ignore(&self) -> bool {492 self.mat.is_ignore()493 }494495 /// Returns true if the match result implies the path should be496 /// whitelisted.497 pub fn is_whitelist(&self) -> bool {498 self.mat.is_whitelist()499 }500501 /// Returns true only when this match corresponds to a directory *and*502 /// whether the caller should look inside this directory for additional503 /// results.504 ///505 /// It is possible for a match to report `false` for506 /// [`IncrementalMatch::is_ignore`] _and_ `false` for507 /// [`IncrementalMatch::should_descend`]. This can occur, for example, when508 /// a maximum depth setting allows a directory through, but where none of509 /// its children entries should be visited.510 ///511 /// This is always `false` for a file path that does *not* correspond to a512 /// directory.513 pub fn should_descend(&self) -> bool {514 self.should_descend515 }516517 /// Returns true only when this result corresponds to an entry that is518 /// within the depth filter.519 ///520 /// This is `false` when a path corresponds to a directory and is less than521 /// the minimum depth. In this case, callers should continue looking inside522 /// that directory.523 ///524 /// This is always `true` for a match corresponding to a file path that525 /// isn't a directory.526 pub fn is_within_depth(&self) -> bool {527 self.is_within_depth528 }529530 /// Inverts the match so that `Ignore` becomes `Whitelist` and531 /// `Whitelist` becomes `Ignore`. A non-match remains the same.532 pub fn invert(self) -> IncrementalMatch {533 IncrementalMatch { mat: self.mat.invert(), ..self }534 }535}536537/// Return a lexically normalized absolute representation of `path`.538///539/// This collapses `.` and `..`, but intentionally does not canonicalize or540/// resolve symlinks. Ignore rules apply to the lexical path, and resolving a541/// symlink below a root could move the result outside of that root.542fn normalize_absolute(path: &Path) -> Option<PathBuf> {543 let absolute = std::path::absolute(path).ok()?;544 let mut normalized = PathBuf::new();545 for component in absolute.components() {546 match component {547 std::path::Component::CurDir => {}548 std::path::Component::ParentDir => {549 normalized.pop();550 }551 _ => normalized.push(component.as_os_str()),552 }553 }554 Some(normalized)555}556557#[cfg(test)]558mod tests {559 use std::{560 fs::{self, File},561 io::Write,562 path::{Path, PathBuf},563 };564565 use crate::{566 IncrementalIgnore, IncrementalMatch, WalkBuilder,567 overrides::OverrideBuilder, tests::TempDir, types::TypesBuilder,568 };569570 use super::CachedDir;571572 fn wfile<P: AsRef<Path>>(path: P, contents: &str) {573 let mut file = File::create(path).unwrap();574 file.write_all(contents.as_bytes()).unwrap();575 }576577 fn mkdirp<P: AsRef<Path>>(path: P) {578 fs::create_dir_all(path).unwrap();579 }580581 fn tmpdir() -> TempDir {582 TempDir::new().unwrap()583 }584585 fn builder<P: AsRef<Path>>(path: P) -> WalkBuilder {586 let mut builder = WalkBuilder::new(path);587 builder.git_global(false);588 builder589 }590591 fn one_matcher(builder: &WalkBuilder) -> IncrementalIgnore {592 let mut matchers = builder.build_matchers();593 assert_eq!(matchers.len(), 1);594 matchers.pop().unwrap()595 }596597 fn builders<I: IntoIterator<Item = P>, P: AsRef<Path>>(598 paths: I,599 ) -> WalkBuilder {600 let mut builder = WalkBuilder::from_iter(paths);601 builder.git_global(false);602 builder603 }604605 fn matchers(builder: &WalkBuilder) -> Vec<IncrementalIgnore> {606 builder.build_matchers()607 }608609 fn matchedf<P: AsRef<Path>>(610 matcher: &mut IncrementalIgnore,611 path: P,612 ) -> IncrementalMatch {613 let (matched, err) = matcher.matched_with_errors(path, false);614 assert!(err.is_none(), "unexpected matcher error: {err:?}");615 matched616 }617618 fn matchedd<P: AsRef<Path>>(619 matcher: &mut IncrementalIgnore,620 path: P,621 ) -> IncrementalMatch {622 let (matched, err) = matcher.matched_with_errors(path, true);623 assert!(err.is_none(), "unexpected matcher error: {err:?}");624 matched625 }626627 // Test that multiple parent ignore files, when nested, are respected.628 #[test]629 fn nested_parent_gitignores() {630 let td = tmpdir();631 let root = td.path().join("project/work");632 mkdirp(td.path().join(".git"));633 mkdirp(root.join("src"));634 wfile(td.path().join(".gitignore"), "*.tmp\n");635 wfile(td.path().join("project/.gitignore"), "!keep.tmp\nnested.log\n");636637 let mut m = one_matcher(&builder(&root));638 assert_eq!(m.root(), root);639 assert!(matchedf(&mut m, "src/drop.tmp").is_ignore());640 assert!(matchedf(&mut m, "src/keep.tmp").is_whitelist());641 assert!(matchedf(&mut m, "src/nested.log").is_ignore());642 assert!(matchedf(&mut m, "src/ok.rs").is_none());643 }644645 // Test that an anchored rule in a child directory is matched relative to646 // that directory, not relative to the configured root.647 #[test]648 fn anchored_child_rule_uses_child_root() {649 let td = tmpdir();650 let root = td.path().join("root");651 mkdirp(root.join("a"));652 wfile(root.join("a/.ignore"), "/foo\n");653654 let mut m = one_matcher(&builder(&root));655 assert!(matchedf(&mut m, "a/foo").is_ignore());656 assert!(matchedf(&mut m, "a/b/foo").is_none());657 }658659 // Test that a leading `./` impacts how the rules are matched.660 #[cfg(not(windows))]661 #[test]662 fn leading_dot_slash_impacts_matching() {663 let td = tmpdir();664 let root = td.path().join("root");665 mkdirp(root.join("a"));666 wfile(root.join(".ignore"), "/foo\n");667 wfile(root.join("a/.ignore"), "/foo\n");668669 let mut m = one_matcher(&builder(&root));670 assert!(matchedf(&mut m, "foo").is_ignore());671 assert!(matchedf(&mut m, "./foo").is_none());672 assert!(matchedf(&mut m, "a/allowed").is_none());673 assert!(matchedf(&mut m, "a/foo").is_ignore());674 assert!(matchedf(&mut m, "./a/foo").is_none());675 }676677 // Test that custom ignore files are respected.678 #[test]679 fn parent_ignore_and_custom_ignore() {680 let td = tmpdir();681 let root = td.path().join("project/work");682 mkdirp(root.join("src"));683 wfile(td.path().join(".ignore"), "*.cache\n");684 wfile(td.path().join(".rgignore"), "*.svg\n");685 wfile(td.path().join("project/.ignore"), "!keep.cache\n");686 wfile(td.path().join("project/.rgignore"), "!keep.svg\n");687688 let mut builder = builder(&root);689 builder.add_custom_ignore_filename(".rgignore");690 let mut m = one_matcher(&builder);691 assert!(matchedf(&mut m, "src/drop.cache").is_ignore());692 assert!(matchedf(&mut m, "src/keep.cache").is_whitelist());693 assert!(matchedf(&mut m, "src/drop.svg").is_ignore());694 assert!(matchedf(&mut m, "src/keep.svg").is_whitelist());695 }696697 // Test that glob overrides take precedence over ignore files.698 #[test]699 fn glob_overrides_are_applied() {700 let td = tmpdir();701 wfile(td.path().join(".ignore"), "keep.rs\n!drop.rs\n");702703 let mut overrides = OverrideBuilder::new(td.path());704 overrides.add("keep.rs").unwrap();705 overrides.add("!drop.rs").unwrap();706 let mut b = builder(td.path());707 b.overrides(overrides.build().unwrap());708 let mut m = one_matcher(&b);709710 assert!(matchedf(&mut m, "keep.rs").is_whitelist());711 assert!(matchedf(&mut m, "drop.rs").is_ignore());712 }713714 // Test that an override-ignored directory prevents matching rules below715 // it, just as it prevents a traversal from descending into the directory.716 #[test]717 fn glob_overrides_apply_to_ancestors() {718 let td = tmpdir();719 mkdirp(td.path().join("blocked"));720 wfile(td.path().join("blocked/.ignore"), "!keep.rs\n");721722 let mut overrides = OverrideBuilder::new(td.path());723 overrides.add("!blocked/").unwrap();724 let mut b = builder(td.path());725 b.overrides(overrides.build().unwrap());726 let mut m = one_matcher(&b);727728 assert!(matchedf(&mut m, "blocked/keep.rs").is_ignore());729 }730731 // Test that file type selections are applied to files, but not732 // directories.733 #[test]734 fn file_types_are_applied() {735 let td = tmpdir();736 mkdirp(td.path().join("src"));737738 let mut types = TypesBuilder::new();739 types.add("rust", "*.rs").unwrap();740 types.select("rust");741 let mut b = builder(td.path());742 b.types(types.build().unwrap());743 let mut m = one_matcher(&b);744745 assert!(matchedd(&mut m, "src").is_none());746 assert!(matchedf(&mut m, "src/lib.rs").is_whitelist());747 assert!(matchedf(&mut m, "README.md").is_ignore());748 }749750 #[test]751 fn directly_ignored_directory_is_not_descended() {752 let td = tmpdir();753 mkdirp(td.path().join(".git"));754 mkdirp(td.path().join("blocked"));755 wfile(td.path().join(".gitignore"), "blocked/\n");756757 let mut m = one_matcher(&builder(td.path()));758 let dir = matchedd(&mut m, "blocked");759 assert!(dir.is_ignore());760 assert!(!dir.should_descend());761 }762763 // Test that when a directory is ignored, anything below it always ignored764 // even when there are explicit whitelist rules. This matches directory765 // traversal semantics.766 #[test]767 fn ignored_ancestor_wins() {768 let td = tmpdir();769 mkdirp(td.path().join(".git"));770 mkdirp(td.path().join("blocked"));771 mkdirp(td.path().join("open"));772 // This is the key line: since the entire `blocked` directory is773 // ignored, a proper file traversal won't ever descend into it. So774 // `blocked/keep.rs` should be ignored even if there are ignore rules775 // "beneath" it that whitelist it.776 wfile(td.path().join(".gitignore"), "blocked/\n!blocked/keep.rs\n");777 wfile(td.path().join("blocked/.gitignore"), "!keep.rs\n");778779 let mut m = one_matcher(&builder(td.path()));780 assert!(matchedf(&mut m, "blocked/keep.rs").is_ignore());781 assert!(matchedf(&mut m, "blocked/other.rs").is_ignore());782 assert!(matchedf(&mut m, "open/keep.rs").is_none());783 }784785 // Test that we respect git boundaries. And that we don't respect git786 // boundaries when not configured to do so.787 #[test]788 fn respects_git_repository_boundaries() {789 let td = tmpdir();790 let root = td.path().join("repo/src");791 mkdirp(td.path().join("repo/.git"));792 mkdirp(&root);793 wfile(td.path().join(".gitignore"), "outside-rule\n");794 wfile(td.path().join(".ignore"), "tool-rule\n");795 wfile(td.path().join("repo/.gitignore"), "inside-rule\n");796797 let mut m = one_matcher(&builder(&root));798 assert!(matchedf(&mut m, "inside-rule").is_ignore());799 assert!(matchedf(&mut m, "outside-rule").is_none());800 assert!(matchedf(&mut m, "tool-rule").is_ignore());801802 let mut no_git_required = builder(&root);803 no_git_required.require_git(false);804 let mut m = one_matcher(&no_git_required);805 assert!(matchedf(&mut m, "outside-rule").is_ignore());806 }807808 // Test that when a gitignore matcher in a parent directory is created, we809 // reuse that matcher from memory even if it's changed on disk.810 #[test]811 fn compiled_matchers_are_reused() {812 let td = tmpdir();813 mkdirp(td.path().join("a"));814 wfile(td.path().join("a/.ignore"), "*.tmp\n");815816 let mut m = one_matcher(&builder(td.path()));817 assert!(matchedf(&mut m, "a/first.tmp").is_ignore());818819 // Below demonstrates that this new ignore file contents820 // aren't actually picked up because it was already loaded.821 wfile(td.path().join("a/.ignore"), "!*.tmp\n*.rs\n");822 assert!(matchedf(&mut m, "a/first.tmp").is_ignore());823 assert!(matchedf(&mut m, "a/second.tmp").is_ignore());824 assert!(matchedf(&mut m, "a/keep.rs").is_none());825 // To get the new ignore file, we need to rebuild the matcher.826 let mut m = one_matcher(&builder(td.path()));827 assert!(matchedf(&mut m, "a/first.tmp").is_whitelist());828 assert!(matchedf(&mut m, "a/second.tmp").is_whitelist());829 assert!(matchedf(&mut m, "a/keep.rs").is_ignore());830 }831832 #[test]833 fn cached_allowed_parent_matches_children() {834 let td = tmpdir();835 mkdirp(td.path().join("a/b"));836 wfile(td.path().join("a/b/.ignore"), "ignored\n");837838 let mut m = one_matcher(&builder(td.path()));839 assert!(matchedf(&mut m, "a/b/allowed").is_none());840 assert!(matches!(841 m.dirs.get(Path::new("a/b")),842 Some(CachedDir::Allowed(_))843 ));844 assert!(matchedf(&mut m, "a/b/ignored").is_ignore());845 }846847 #[test]848 fn cached_ignored_parent_matches_children() {849 let td = tmpdir();850 mkdirp(td.path().join("blocked"));851 wfile(td.path().join(".ignore"), "blocked/\n");852853 let mut m = one_matcher(&builder(td.path()));854 assert!(matchedf(&mut m, "blocked/first").is_ignore());855 assert!(matches!(856 m.dirs.get(Path::new("blocked")),857 Some(CachedDir::Ignored)858 ));859 assert!(matchedf(&mut m, "blocked/second").is_ignore());860 }861862 #[test]863 fn cached_parent_matcher_is_used_for_directory() {864 let td = tmpdir();865 mkdirp(td.path().join("a/b"));866 wfile(td.path().join("a/b/.ignore"), "**\n");867868 let mut m = one_matcher(&builder(td.path()));869 assert!(matchedf(&mut m, "a/b/file").is_ignore());870 assert!(matches!(871 m.dirs.get(Path::new("a/b")),872 Some(CachedDir::Allowed(_))873 ));874 let dir = matchedd(&mut m, "a/b");875 assert!(dir.is_none());876 assert!(dir.should_descend());877 }878879 // Like `compiled_matchers_are_reused`, but with multiple roots.880 #[test]881 fn compiled_multi_matchers_are_reused() {882 let td = tmpdir();883 mkdirp(td.path().join("a/b/c"));884885 wfile(td.path().join("a/.ignore"), "*.tmp\n");886 let mut mats = matchers(&builders([887 td.path().join("a/b"),888 td.path().join("a/b/c"),889 ]));890 assert!(matchedf(&mut mats[0], "first.tmp").is_ignore());891 assert!(matchedf(&mut mats[0], "c/first.tmp").is_ignore());892893 // Even though we haven't used the second matcher, it should still894 // reuse the `a/.ignore` above. If it didn't, then `a/b/c/first.tmp`895 // below would be whitelisted.896 wfile(td.path().join("a/.ignore"), "!*.tmp\n");897 assert!(matchedf(&mut mats[1], "first.tmp").is_ignore());898 }899900 #[test]901 fn compiled_multi_child_matchers_are_not_reused() {902 let td = tmpdir();903 mkdirp(td.path().join("a/b/c/d/e"));904905 wfile(td.path().join("a/b/c/d/e/.ignore"), "*.tmp\n");906 let mut mats = matchers(&builders([907 td.path().join("a/b"),908 td.path().join("a/b/c"),909 ]));910 // Some sanity checking first.911 assert!(matchedf(&mut mats[0], "c/first.tmp").is_none());912 assert!(matchedf(&mut mats[0], "c/d/first.tmp").is_none());913 assert!(matchedf(&mut mats[0], "c/d/e/first.tmp").is_ignore());914915 // Now write a new ignore file at the same location as above916 // and check that the other matcher still uses the "stale" data.917 wfile(td.path().join("a/b/c/d/e/.ignore"), "!*.tmp\n");918 assert!(matchedf(&mut mats[1], "first.tmp").is_none());919 assert!(matchedf(&mut mats[1], "d/first.tmp").is_none());920 // This is the punch line: because we didn't load `mats[1]` before921 // changing the ignore file, it loads it here and thus this path gets922 // whitelisted.923 assert!(matchedf(&mut mats[1], "d/e/first.tmp").is_whitelist());924 // ... but `mats[0]` still uses the stale gitignore matcher cached in925 // memory!926 assert!(matchedf(&mut mats[0], "c/d/e/first.tmp").is_ignore());927928 // If we rebuilder the matcher... then we force reloading and they're929 // now consistent with one another.930 let mut mats = matchers(&builders([931 td.path().join("a/b"),932 td.path().join("a/b/c"),933 ]));934 assert!(matchedf(&mut mats[0], "c/d/e/first.tmp").is_whitelist());935 assert!(matchedf(&mut mats[1], "d/e/first.tmp").is_whitelist());936 }937938 // Tests that even when there is an error with a glob pattern, we still939 // respect other glob patterns that are valid.940 #[test]941 fn partial_errors_keep_valid_rules() {942 let td = tmpdir();943 let root = td.path().join("work");944 mkdirp(&root);945 wfile(td.path().join(".ignore"), "{bad\n*.tmp\n");946947 let mut builder = builder(&root);948 builder.git_ignore(false).git_exclude(false);949 let mut m = one_matcher(&builder);950 let (matched, err) = m.matched_with_errors("drop.tmp", false);951 assert!(err.is_some());952 assert!(matched.is_ignore());953 }954955 // Tests that parent rules are not respected if the matcher is configured956 // not to do so.957 #[test]958 fn parent_loading_can_be_disabled() {959 let td = tmpdir();960 let root = td.path().join("work");961 mkdirp(&root);962 wfile(td.path().join(".ignore"), "parent-rule\n");963 wfile(root.join(".ignore"), "root-rule\n");964965 let mut b = builder(&root);966 b.parents(false);967 let mut m = one_matcher(&b);968 assert!(matchedf(&mut m, "parent-rule").is_none());969 assert!(matchedf(&mut m, "root-rule").is_ignore());970971 // Sanity check that without `parents(false)`, the parent rule is972 // respected.973 let mut m = one_matcher(&builder(&root));974 assert!(matchedf(&mut m, "parent-rule").is_ignore());975 assert!(matchedf(&mut m, "root-rule").is_ignore());976 }977978 // Tests that we can normalize a file path that isn't already in "normal"979 // relative form, and then use that to match on ignore files.980 #[test]981 fn paths_are_relative_to_the_root() {982 let td = tmpdir();983 let root = td.path().join("root");984 let outside = td.path().join("outside");985 mkdirp(&root);986 mkdirp(&outside);987 wfile(root.join(".ignore"), "file\n");988989 let mut m = one_matcher(&builder(&root));990 assert!(matchedd(&mut m, "").is_none());991 assert!(matchedd(&mut m, ".").is_none());992 assert!(matchedf(&mut m, "file").is_ignore());993 // Doesn't work because it isn't relative to the root. It's absolute.994 assert!(matchedf(&mut m, root.join("file")).is_none());995 // Also doesn't work because while it's relative, it contains `..`.996 assert!(matchedf(&mut m, "dir/../file").is_none());997998 let norm = m.normalize(root.join("dir/../file")).unwrap();999 assert_eq!(norm, Path::new("file"));1000 assert!(matchedf(&mut m, "file").is_ignore());10011002 // Doesn't normalize because its an absolute path outside of our root.1003 assert_eq!(m.normalize(outside.join("file")), None);1004 }10051006 // Tests that two matchers in two different directories correctly interpret1007 // the same parent gitignore file.1008 #[test]1009 fn multiple_roots_keep_their_own_context() {1010 let td = tmpdir();1011 let root_a = td.path().join("a");1012 let root_b = td.path().join("b");1013 mkdirp(td.path().join(".git"));1014 mkdirp(&root_a);1015 mkdirp(&root_b);1016 wfile(td.path().join(".gitignore"), "/a/*.tmp\n/b/*.log\n");10171018 let mut builder =1019 builders([root_a.as_path(), Path::new("-"), root_b.as_path()]);1020 builder.git_global(false);1021 let mut ms = matchers(&builder);1022 assert_eq!(ms.len(), 3);1023 assert_eq!(ms[0].root(), root_a);1024 assert_eq!(ms[1].root(), Path::new("-"));1025 assert_eq!(ms[2].root(), root_b);1026 assert!(matchedf(&mut ms[0], "drop.tmp").is_ignore());1027 assert!(matchedf(&mut ms[0], "keep.log").is_none());1028 assert!(matchedf(&mut ms[1], "anything").is_none());1029 assert_eq!(ms[1].normalize("anything"), None);1030 assert!(matchedf(&mut ms[2], "keep.tmp").is_none());1031 assert!(matchedf(&mut ms[2], "drop.log").is_ignore());1032 }10331034 // Tests that only the exact `-` root represents standard input.1035 #[test]1036 fn dot_dash_root_is_not_stdin() {1037 let m = one_matcher(&builder("./-"));1038 assert_eq!(m.root(), Path::new("./-"));1039 assert_eq!(m.normalize("./-/file"), Some(PathBuf::from("file")));1040 }10411042 #[test]1043 fn stdin_is_inert_with_depth_limits() {1044 let mut b = builder("-");1045 b.min_depth(Some(2));1046 let mut m = one_matcher(&b);1047 let mat = matchedf(&mut m, "file");1048 assert!(mat.is_none());1049 assert!(mat.is_within_depth());10501051 let mut b = builder("-");1052 b.max_depth(Some(0));1053 let mut m = one_matcher(&b);1054 let mat = matchedd(&mut m, "dir");1055 assert!(mat.is_none());1056 assert!(mat.is_within_depth());1057 assert!(mat.should_descend());1058 }10591060 // Tests that ignore matching works lexically, and doesn't accidentally1061 // resolve symbolic links.1062 #[cfg(unix)]1063 #[test]1064 fn symlink_path_stays_under_lexical_root() {1065 use std::os::unix::fs::symlink;10661067 let td = tmpdir();1068 let root = td.path().join("root");1069 let outside = td.path().join("outside");1070 mkdirp(&root);1071 mkdirp(&outside);1072 wfile(root.join(".ignore"), "link\n");1073 wfile(outside.join("target"), "");1074 symlink(outside.join("target"), root.join("link")).unwrap();10751076 let mut m = one_matcher(&builder(&root));1077 assert!(matchedf(&mut m, "link").is_ignore());1078 }10791080 #[test]1081 fn depth_limits() {1082 let td = tmpdir();1083 mkdirp(td.path().join("a/b/c/d"));10841085 let mut b = builder(td.path());1086 b.min_depth(Some(2)).max_depth(Some(3));1087 let mut m = one_matcher(&b);10881089 let dir = matchedd(&mut m, "a");1090 assert!(!dir.is_within_depth());1091 assert!(dir.should_descend());1092 assert!(matchedf(&mut m, "file").is_ignore());10931094 let dir = matchedd(&mut m, "a/b");1095 assert!(dir.is_within_depth());1096 assert!(dir.should_descend());1097 assert!(!matchedf(&mut m, "a/file").is_ignore());10981099 let dir = matchedd(&mut m, "a/b/c");1100 assert!(dir.is_within_depth());1101 assert!(!dir.should_descend());1102 assert!(!matchedf(&mut m, "a/b/file").is_ignore());1103 assert!(matchedf(&mut m, "a/b/c/file").is_ignore());11041105 let dir = matchedd(&mut m, "a/b/c/d");1106 assert!(dir.is_ignore());1107 assert!(!dir.is_within_depth());1108 assert!(!dir.should_descend());1109 assert!(matchedf(&mut m, "a/b/c/d/file").is_ignore());1110 }11111112 #[test]1113 fn depth_limits_apply_to_root() {1114 let td = tmpdir();11151116 let mut b = builder(td.path());1117 b.min_depth(Some(1));1118 let mut m = one_matcher(&b);1119 for path in ["", "."] {1120 let root = matchedd(&mut m, path);1121 assert!(root.is_none());1122 assert!(!root.is_within_depth());1123 assert!(root.should_descend());1124 }11251126 let mut b = builder(td.path());1127 b.max_depth(Some(0));1128 let mut m = one_matcher(&b);1129 for path in ["", "."] {1130 let root = matchedd(&mut m, path);1131 assert!(root.is_none());1132 assert!(root.is_within_depth());1133 assert!(!root.should_descend());1134 }1135 }11361137 #[test]1138 fn max_filesize() {1139 let td = tmpdir();1140 mkdirp(td.path().join("dir"));1141 wfile(td.path().join("empty"), "");1142 wfile(td.path().join("at-limit"), "12345");1143 wfile(td.path().join("over-limit"), "123456");11441145 let mut b = builder(td.path());1146 b.max_filesize(Some(5));1147 let mut m = one_matcher(&b);11481149 assert!(matchedf(&mut m, "empty").is_none());1150 assert!(matchedf(&mut m, "at-limit").is_none());1151 assert!(matchedf(&mut m, "over-limit").is_ignore());11521153 let dir = matchedd(&mut m, "dir");1154 assert!(dir.is_none());1155 assert!(dir.should_descend());1156 }11571158 #[test]1159 fn max_filesize_does_not_stat_ignored_file() {1160 let td = tmpdir();1161 wfile(td.path().join(".ignore"), "ignored\n");11621163 let mut b = builder(td.path());1164 b.max_filesize(Some(0));1165 let mut m = one_matcher(&b);1166 let (mat, err) = m.matched_with_errors("ignored", false);1167 assert!(mat.is_ignore());1168 assert!(err.is_none(), "ignored missing file was statted: {err:?}");1169 }11701171 #[cfg(unix)]1172 #[test]1173 fn max_filesize_respects_follow_links() {1174 use std::os::unix::fs::symlink;11751176 let td = tmpdir();1177 wfile(1178 td.path().join("target"),1179 "target contents are much longer than the size limit",1180 );1181 symlink("target", td.path().join("link")).unwrap();11821183 let mut b = builder(td.path());1184 b.max_filesize(Some(10));1185 let mut m = one_matcher(&b);1186 assert!(matchedf(&mut m, "link").is_none());11871188 b.follow_links(true);1189 let mut m = one_matcher(&b);1190 assert!(matchedf(&mut m, "link").is_ignore());1191 }11921193 #[test]1194 fn hidden_files_and_directories() {1195 let td = tmpdir();1196 mkdirp(td.path().join(".hidden-dir"));1197 mkdirp(td.path().join("visible-dir"));1198 wfile(td.path().join(".hidden-file"), "");1199 wfile(td.path().join("visible-file"), "");12001201 let mut m = one_matcher(&builder(td.path()));1202 assert!(matchedf(&mut m, ".hidden-file").is_ignore());1203 let dir = matchedd(&mut m, ".hidden-dir");1204 assert!(dir.is_ignore());1205 assert!(!dir.should_descend());1206 assert!(matchedf(&mut m, "visible-file").is_none());1207 let dir = matchedd(&mut m, "visible-dir");1208 assert!(dir.is_none());1209 assert!(dir.should_descend());12101211 let mut b = builder(td.path());1212 b.hidden(false);1213 let mut m = one_matcher(&b);1214 assert!(matchedf(&mut m, ".hidden-file").is_none());1215 let dir = matchedd(&mut m, ".hidden-dir");1216 assert!(dir.is_none());1217 assert!(dir.should_descend());1218 }12191220 #[test]1221 fn gitignore_whitelist_overrides_hidden_filter() {1222 let td = tmpdir();1223 mkdirp(td.path().join(".git"));1224 mkdirp(td.path().join(".hidden-dir"));1225 wfile(td.path().join(".hidden-file"), "");1226 wfile(td.path().join(".gitignore"), "!.hidden-file\n!.hidden-dir/\n");12271228 let mut m = one_matcher(&builder(td.path()));1229 assert!(matchedf(&mut m, ".hidden-file").is_whitelist());1230 let dir = matchedd(&mut m, ".hidden-dir");1231 assert!(dir.is_whitelist());1232 assert!(dir.should_descend());1233 }12341235 #[test]1236 fn descendants_of_hidden_directories_are_ignored() {1237 let td = tmpdir();1238 mkdirp(td.path().join(".git"));1239 mkdirp(td.path().join(".hidden/nested"));1240 mkdirp(td.path().join("visible/.hidden"));1241 wfile(td.path().join(".hidden/file"), "");1242 wfile(td.path().join(".hidden/nested/file"), "");1243 wfile(td.path().join("visible/.hidden/file"), "");1244 wfile(td.path().join(".hidden/.gitignore"), "!file\n");12451246 let mut m = one_matcher(&builder(td.path()));1247 assert!(matchedf(&mut m, ".hidden/file").is_ignore());1248 assert!(matchedf(&mut m, ".hidden/nested/file").is_ignore());1249 assert!(matchedf(&mut m, "visible/.hidden/file").is_ignore());1250 }12511252 #[test]1253 fn whitelisted_hidden_directory_allows_descendants() {1254 let td = tmpdir();1255 mkdirp(td.path().join(".git"));1256 mkdirp(td.path().join(".hidden"));1257 wfile(td.path().join(".hidden/file"), "");1258 wfile(td.path().join(".gitignore"), "!.hidden/\n");12591260 let mut m = one_matcher(&builder(td.path()));1261 let dir = matchedd(&mut m, ".hidden");1262 assert!(dir.is_whitelist());1263 assert!(dir.should_descend());1264 assert!(matchedf(&mut m, ".hidden/file").is_none());1265 }12661267 #[test]1268 fn hidden_directories_outside_depth_limits() {1269 let td = tmpdir();1270 mkdirp(td.path().join("a/.hidden"));12711272 let mut b = builder(td.path());1273 b.min_depth(Some(3));1274 let mut m = one_matcher(&b);1275 let dir = matchedd(&mut m, "a/.hidden");1276 assert!(dir.is_ignore());1277 assert!(!dir.is_within_depth());12781279 let mut b = builder(td.path());1280 b.max_depth(Some(1));1281 let mut m = one_matcher(&b);1282 let dir = matchedd(&mut m, "a/.hidden");1283 assert!(dir.is_ignore());1284 assert!(!dir.is_within_depth());1285 }1286}
modified:crates/ignore/src/lib.rs+2 added
46 unmodified lines
47#![deny(missing_docs)]4849use std::path::{Path, PathBuf};5051pub use crate::incremental::{IncrementalIgnore, IncrementalMatch};52pub use crate::walk::{53 DirEntry, ParallelVisitor, ParallelVisitorBuilder, Walk, WalkBuilder,54 WalkParallel, WalkState,55};5657mod default_types;58mod dir;59pub mod gitignore;60mod incremental;61pub mod overrides;62mod pathutil;63pub mod types;64mod walk;
485 unmodified lines
modified:crates/ignore/src/walk.rs+60 added-8 removed
16 unmodified lines
17use crate::{18 Error, PartialErrorBuilder,19 dir::{Ignore, IgnoreBuilder},20 gitignore::GitignoreBuilder,21 incremental::{IncrementalIgnore, IncrementalIgnoreOptions},22 overrides::Override,23 types::Types,24};25
603 unmodified lines
629 }630 })631 .collect::<Vec<_>>()632 .into_iter();632 let ig_root = self633 .get_or_set_current_dir()634 .map(|cwd| self.ig_builder.build_with_cwd(Some(cwd.to_path_buf())))635 .unwrap_or_else(|| self.ig_builder.build());633 let ig_root = self.build_ignore();634 Walk {635 its,636 it: None,637 ig_root: ig_root.clone(),
3 unmodified lines
641 filter: self.filter.clone(),642 }643 }644645 /// Build matchers for checking paths against ignore files without646 /// recursively walking the configured roots.647 ///648 /// The returned matchers use the path-based filtering configuration649 /// on this builder, including glob overrides, file type selections,650 /// parent ignore files, `.ignore`, `.gitignore`, global Git651 /// ignore files, explicitly added ignore files and custom ignore652 /// file names. For example, ripgrep configures `.rgignore` via653 /// [`WalkBuilder::add_custom_ignore_filename`]. Minimum and maximum depth654 /// limits, maximum file size and hidden-file filtering are also applied.655 /// Other options that only control traversal or require a directory entry,656 /// such as custom entry predicates, are not applied.657 ///658 /// One matcher is returned for each configured path, in the same order as659 /// the paths were added to this builder. Each matcher accepts paths660 /// relative to its own [`IncrementalIgnore::root`]. The matcher for the661 /// special `-` path representing standard input always returns a non-match662 /// for all inputs.663 ///664 /// Ignore matchers are loaded lazily and cached by directory.665 /// Thus, the first query may read ignore files from the root and666 /// its parents, while later queries reuse the compiled matchers.667 /// Errors encountered while loading ignore files are returned by668 /// [`IncrementalIgnore::matched_with_errors`]. Once an ignore file has669 /// been loaded, changes to it are not observed. Build new matchers to670 /// reload changed ignore files.671 ///672 /// Matchers built together share the builder's base ignore configuration673 /// and compiled parent matchers.674 pub fn build_matchers(&self) -> Vec<IncrementalIgnore> {675 let ignore = self.build_ignore();676 let options = IncrementalIgnoreOptions {677 min_depth: self.min_depth,678 max_depth: self.max_depth,679 max_filesize: self.max_filesize,680 hidden: self.ig_builder.is_hidden(),681 follow_links: self.follow_links,682 };683 self.paths684 .iter()685 .map(move |path| {686 IncrementalIgnore::new(687 path.clone(),688 ignore.clone(),689 options.clone(),690 )691 })692 .collect()693 }694695 /// Build a new `WalkParallel` iterator.696 ///697 /// Note that this *doesn't* return something that implements `Iterator`.698 /// Instead, the returned value must be run with a closure. e.g.,699 /// `builder.build_parallel().run(|| |path| { println!("{path:?}"); WalkState::Continue })`.700 pub fn build_parallel(&self) -> WalkParallel {653 let ig_root = self654 .get_or_set_current_dir()655 .map(|cwd| self.ig_builder.build_with_cwd(Some(cwd.to_path_buf())))656 .unwrap_or_else(|| self.ig_builder.build());701 let ig_root = self.build_ignore();702 WalkParallel {703 paths: self.paths.clone().into_iter(),704 ig_root,705 max_depth: self.max_depth,
391 unmodified lines
1097 result1098 });1099 result.as_ref().ok().map(|path| &**path)1100 }11011102 /// Build the root ignore matcher shared by all consumers of this builder.1103 fn build_ignore(&self) -> Ignore {1104 self.get_or_set_current_dir()1105 .map(|cwd| self.ig_builder.build_with_cwd(Some(cwd.to_path_buf())))1106 .unwrap_or_else(|| self.ig_builder.build())1107 }1108}11091110/// Walk is a recursive directory iterator over file paths in one or more1111/// directories.
1601 unmodified lines