Skip to content
Myr

ignore: fetch directory entry metadata in batches

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

On Windows probing the existence of each ignore file is very heavy. Windows prefers fetching metadata in batches (FindFirstFileExW/FindNextFileW, which translates to std::sys::fs::read_dir) Now, in ignore::Work::read_dir, we read the entire directory at once, then use the result to determine the existense of ignore files. The result is saved and visited later. This avoids stat'ing file paths that don't exist. Note that this also helps with Linux workloads too. For example, on the <https://github.com/NightMachinary/r_HPfanfiction> repository: ``` $ hyperfine "rg-base 'with regexes,'" "rg-test 'with regexes,'" Benchmark 1: rg-base 'with regexes,' Time (mean ± σ): 483.1 ms ± 6.4 ms [User: 2493.1 ms, System: 3192.9 ms] Range (min … max): 474.8 ms … 496.0 ms 10 runs Benchmark 2: rg-test 'with regexes,' Time (mean ± σ): 350.4 ms ± 5.2 ms [User: 1652.6 ms, System: 2324.5 ms] Range (min … max): 341.6 ms … 358.5 ms 10 runs Summary rg-test 'with regexes,' ran 1.38 ± 0.03 times faster than rg-base 'with regexes,' ``` Fixes #3293, Closes #3410

authored by Yujiang Wang · committed by Andrew Gallant · parent 653d7f5 · Browse files · 3 files+171 added−30 removed
This commit

State

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

Diff stats

3 files+171 added−30 removed

  • other:+171 added−30 removed

3 files+171 added−30 removed

modified:crates/ignore/src/dir.rs+116 added-11 removed
14 unmodified lines
1516use std::{17 collections::HashMap,18 ffi::{OsStr, OsString},19 fs::{File, FileType},19 fs::{self, File, FileType},20 io::{self, BufRead},21 path::{Path, PathBuf},22 sync::{Arc, RwLock, Weak},23};
254 unmodified lines
278 err,279 )280 }281282 /// Like add_child, but uses successful read_dir entries to reduce283 /// probing when discovering ignore files.284 pub(crate) fn add_child_with_entries<P: AsRef<Path>>(285 &self,286 dir: P,287 entries: &[fs::DirEntry],288 ) -> (Ignore, Option<Error>) {289 let files = self.collect_ignore_files(entries);290 let (ig, err) = self.add_child_path_with_found_ignore_files(291 dir.as_ref(),292 Some(&files),293 );294 (295 Ignore {296 inner: Arc::new(ig),297 absolute_base: self.absolute_base.clone(),298 },299 err,300 )301 }302303 /// Like add_child, but takes a full path and returns an IgnoreInner.304 fn add_child_path(&self, dir: &Path) -> (IgnoreInner, Option<Error>) {305 self.add_child_path_with_found_ignore_files(dir, None)306 }307308 fn collect_ignore_files(309 &self,310 entries: &[fs::DirEntry],311 ) -> IgnoreFilesFound {312 let custom_ignore_filenames = &self.inner.custom_ignore_filenames;313 let mut files = IgnoreFilesFound {314 has_ignore: false,315 has_git_ignore: false,316 has_git_dir: false,317 has_jj_dir: false,318 custom_ignore_files: vec![false; custom_ignore_filenames.len()],319 };320 for entry in entries {321 let file_name = entry.file_name();322 if file_name == OsStr::new(".ignore") {323 files.has_ignore = true;324 } else if file_name == OsStr::new(".gitignore") {325 files.has_git_ignore = true;326 } else if file_name == OsStr::new(".git") {327 files.has_git_dir = true;328 } else if file_name == OsStr::new(".jj") {329 files.has_jj_dir = true;330 }331 for (i, name) in custom_ignore_filenames.iter().enumerate() {332 if file_name == name.as_os_str() {333 files.custom_ignore_files[i] = true;334 }335 }336 }337 files338 }339340 fn add_child_path_with_found_ignore_files(341 &self,342 dir: &Path,343 ignore_files_list: Option<&IgnoreFilesFound>,344 ) -> (IgnoreInner, Option<Error>) {345 let check_vcs_dir = self.inner.opts.require_git346 && (self.inner.opts.git_ignore || self.inner.opts.git_exclude);286 let git_type = if check_vcs_dir {347 let git_type = if check_vcs_dir348 && ignore_files_list.is_none_or(|i| i.has_git_dir)349 {350 dir.join(".git").metadata().ok().map(|md| md.file_type())351 } else {352 None353 };291 let has_git =292 check_vcs_dir && (git_type.is_some() || dir.join(".jj").exists());354 let has_jj = check_vcs_dir355 && ignore_files_list.is_none_or(|i| i.has_jj_dir)356 && dir.join(".jj").exists();357 let has_git = check_vcs_dir && (git_type.is_some() || has_jj);358359 let mut errs = PartialErrorBuilder::default();295 let custom_ig_matcher =296 if self.inner.custom_ignore_filenames.is_empty() {360 let custom_ig_matcher = if self361 .inner362 .custom_ignore_filenames363 .is_empty()364 {365 Gitignore::empty()366 } else {367 let custom_ignore_names: Vec<&OsString> = match ignore_files_list {368 None => self.inner.custom_ignore_filenames.iter().collect(),369 Some(m) => self370 .inner371 .custom_ignore_filenames372 .iter()373 .zip(m.custom_ignore_files.iter())374 .filter(|&(_, &matched)| matched)375 .map(|(name, _)| name)376 .collect(),377 };378 if custom_ignore_names.is_empty() {379 Gitignore::empty()380 } else {381 let (m, err) = create_gitignore(382 &dir,383 &dir,302 &self.inner.custom_ignore_filenames,384 &custom_ignore_names,385 self.inner.opts.ignore_case_insensitive,386 );387 errs.maybe_push(err);388 m389 }307 };308 let ig_matcher = if !self.inner.opts.ignore {390 };391 let ig_matcher = if !self.inner.opts.ignore392 || !ignore_files_list.is_none_or(|i| i.has_ignore)393 {394 Gitignore::empty()395 } else {396 let (m, err) = create_gitignore(397 &dir,
3 unmodified lines
401 );402 errs.maybe_push(err);403 m404 };320 let gi_matcher = if !self.inner.opts.git_ignore {405 let gi_matcher = if !self.inner.opts.git_ignore406 || !ignore_files_list.is_none_or(|i| i.has_git_ignore)407 {408 Gitignore::empty()409 } else {410 let (m, err) = create_gitignore(411 &dir,
4 unmodified lines
416 errs.maybe_push(err);417 m418 };419333 let gi_exclude_matcher = if !self.inner.opts.git_exclude {420 let gi_exclude_matcher = if !self.inner.opts.git_exclude421 || !ignore_files_list.is_none_or(|i| i.has_git_dir)422 {423 Gitignore::empty()424 } else {425 match resolve_git_commondir(dir, git_type) {426 Ok(git_dir) => {
268 unmodified lines
695 self.absolute_base.as_ref().map(|p| &***p)696 }697}698699/// State for tracking what kinds of files ripgrep is interested in for a700/// given directory.701///702/// This is computed over the entire set of files in a directory instead of703/// trying to stat each file individually. If a file is present, it's only then704/// that we stat it for more information, instead of relying on the stat to705/// determine its existence.706#[derive(Debug)]707struct IgnoreFilesFound {708 has_ignore: bool,709 has_git_ignore: bool,710 has_git_dir: bool,711 has_jj_dir: bool,712 custom_ignore_files: Vec<bool>,713}714715#[derive(Clone, Copy)]716pub(crate) struct IgnoreRef<'a> {717 inner: &'a IgnoreInner,718}
890 unmodified lines
modified:crates/ignore/src/walk.rs+48 added-17 removed
1465 unmodified lines
1466 /// number should be considered.1467 root_device: Option<u64>,1468}14691470#[derive(Default)]1471struct ReadDirResult {1472 entries: Vec<fs::DirEntry>,1473 errors: Vec<Error>,1474}14751476impl Work {1477 /// Returns true if and only if this work item is a directory.1478 fn is_dir(&self) -> bool {1479 self.dent.is_dir()
18 unmodified lines
1498 self.ignore = ig;1499 err1500 }15011502 /// Adds ignore rules for this directory without reading its contents.1503 fn add_ignore(&mut self) {1504 let (ig, err) = self.ignore.add_child(self.dent.path());1505 self.ignore = ig;1506 self.dent.err = err;1507 }15081509 /// Reads the directory contents of this work item and adds ignore1510 /// rules for this directory.1511 ///1512 /// If there was a problem with reading the directory contents, then1513 /// an error is returned. If there was a problem reading the ignore1514 /// rules for this directory, then the error is attached to this1515 /// work item's directory entry.1503 fn read_dir(&mut self) -> Result<fs::ReadDir, Error> {1516 fn read_dir(&mut self) -> Result<ReadDirResult, Error> {1517 let readdir = match fs::read_dir(self.dent.path()) {1518 Ok(readdir) => readdir,1519 Err(err) => {1520 let err = Error::from(err)
1 unmodified line
1522 .with_depth(self.dent.depth());1523 return Err(err);1524 }1525 };1513 let (ig, err) = self.ignore.add_child(self.dent.path());1526 // Actually descend into the directory and read its contents1527 let mut result = ReadDirResult::default();1528 for entry in readdir {1529 match entry {1530 Ok(entry) => result.entries.push(entry),1531 Err(err) => result.errors.push(1532 Error::from(err)1533 .with_path(self.dent.path())1534 .with_depth(self.dent.depth() + 1),1535 ),1536 }1537 }1538 let (ig, err) = self1539 .ignore1540 .add_child_with_entries(self.dent.path(), &result.entries);1541 self.ignore = ig;1542 self.dent.err = err;1516 Ok(readdir)1543 Ok(result)1544 }1545}15461547/// A work-stealing stack.
161 unmodified lines
1709 // as we may receive an `Err` value e.g. in the case when we do not1710 // have sufficient read permissions to list the directory.1711 // In that case we still want to provide the closure with a valid1712 // entry before passing the error value.1686 let readdir = work.read_dir();1713 let depth = work.dent.depth();1714 let readdir = if descend && self.max_depth.is_none_or(|m| depth < m) {1715 Some(work.read_dir())1716 } else {1717 work.add_ignore();1718 None1719 };1720 if should_visit {1721 let state = self.visitor.visit(Ok(work.dent));1722 if !state.is_continue() {1723 return state;
3 unmodified lines
1727 return WalkState::Skip;1728 }17291730 let readdir = match readdir {1731 Some(readdir) => readdir,1732 None => return WalkState::Skip,1733 };1734 let readdir = match readdir {1735 Ok(readdir) => readdir,1736 Err(err) => {1737 return self.visitor.visit(Err(err));1738 }1739 };17401705 if self.max_depth.map_or(false, |max| depth >= max) {1706 return WalkState::Skip;1707 }1708 for result in readdir {1741 for result in readdir.entries {1742 let state = self.generate_work(1743 &work.ignore,1744 depth + 1,1745 work.root_device,
2 unmodified lines
1748 if state.is_quit() {1749 return state;1750 }1751 }1752 for err in readdir.errors {1753 let state = self.visitor.visit(Err(err));1754 if state.is_quit() {1755 return state;1756 }1757 }1758 WalkState::Continue1759 }17601761 /// Decides whether to submit the given directory entry as a file to
13 unmodified lines
1775 &mut self,1776 ig: &Ignore,1777 depth: usize,1778 root_device: Option<u64>,1740 result: Result<fs::DirEntry, io::Error>,1779 fs_dent: fs::DirEntry,1780 ) -> WalkState {1742 let fs_dent = match result {1743 Ok(fs_dent) => fs_dent,1744 Err(err) => {1745 return self1746 .visitor1747 .visit(Err(Error::from(err).with_depth(depth)));1748 }1749 };1781 let mut dent = match DirEntryRaw::from_entry(depth, &fs_dent) {1782 Ok(dent) => DirEntry::new_raw(dent, None),1783 Err(err) => {1784 return self.visitor.visit(Err(err));
745 unmodified lines
modified:CHANGELOG.md+7 added-2 removed
1TBD2===3Unreleased changes. Release notes have not yet been written.45Performance improvements:67* [PERF #3293](https://github.com/BurntSushi/ripgrep/issues/3293):8 Improves directory traversal time on very large corpora.910Bug fixes:1112* [BUG #3212](https://github.com/BurntSushi/ripgrep/pull/3212):13 Don't check for the existence of `.jj` when `--no-ignore` is used.14151115.1.012======1615.1.0 (2025-10-22)17===================18This is a small release that fixes a bug with how ripgrep handles line19buffering. This might manifest as ripgrep printing output later than you20expect or not working correctly with `tail -f` (even if you're using the21`--line-buffered` flag).
1829 unmodified lines