walk: Add a cache for DirEntry metadata
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tavian Barnes · committed by David Peter · parent 02e9850 · Browse files · 6 files·+67 added−24 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+67 added−24 removed
- tests:+15 added−1 removed
- other:+52 added−23 removed
Provenance
- Commit
7b5b3ec- Tree
b9dbfcd- Author
Tavian Barnes <tavianator@tavianator.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
02e9850
6 files changed+67 added−24 removed
modified:src/filetypes.rs+1 added-1 removed
35 unmodified lines36 || (!self.pipes && filesystem::is_pipe(*entry_type))37 || (self.executables_only38 && !entry39 .metadata()40- .map(|m| filesystem::is_executable(&m))40+ .map(|m| filesystem::is_executable(m))41 .unwrap_or(false))42 || (self.empty_only && !filesystem::is_empty(entry))43 || !(entry_type.is_file()44 || entry_type.is_dir()8 unmodified linesmodified:src/walk.rs+42 added-22 removed
11 unmodified lines12 13 use anyhow::{anyhow, Result};14 use ignore::overrides::OverrideBuilder;15 use ignore::{self, WalkBuilder};16+use once_cell::unsync::OnceCell;17 use regex::bytes::Regex;18 19 use crate::config::Config;20 use crate::error::print_error;274 unmodified lines295 }296 })297 }298 298-pub enum DirEntry {299+enum DirEntryInner {300 Normal(ignore::DirEntry),301 BrokenSymlink(PathBuf),302 }303 304+pub struct DirEntry {305+ inner: DirEntryInner,306+ metadata: OnceCell<Option<Metadata>>,307+}308+309 impl DirEntry {310+ fn normal(e: ignore::DirEntry) -> Self {311+ Self {312+ inner: DirEntryInner::Normal(e),313+ metadata: OnceCell::new(),314+ }315+ }316+317+ fn broken_symlink(path: PathBuf) -> Self {318+ Self {319+ inner: DirEntryInner::BrokenSymlink(path),320+ metadata: OnceCell::new(),321+ }322+ }323+324 pub fn path(&self) -> &Path {305- match self {306- DirEntry::Normal(e) => e.path(),307- DirEntry::BrokenSymlink(pathbuf) => pathbuf.as_path(),325+ match &self.inner {326+ DirEntryInner::Normal(e) => e.path(),327+ DirEntryInner::BrokenSymlink(pathbuf) => pathbuf.as_path(),328 }329 }330 331 pub fn file_type(&self) -> Option<FileType> {312- match self {313- DirEntry::Normal(e) => e.file_type(),314- DirEntry::BrokenSymlink(pathbuf) => {315- pathbuf.symlink_metadata().map(|m| m.file_type()).ok()316- }332+ match &self.inner {333+ DirEntryInner::Normal(e) => e.file_type(),334+ DirEntryInner::BrokenSymlink(_) => self.metadata().map(|m| m.file_type()),335 }336 }337 320- pub fn metadata(&self) -> Option<Metadata> {321- match self {322- DirEntry::Normal(e) => e.metadata().ok(),323- DirEntry::BrokenSymlink(_) => None,324- }338+ pub fn metadata(&self) -> Option<&Metadata> {339+ self.metadata340+ .get_or_init(|| match &self.inner {341+ DirEntryInner::Normal(e) => e.metadata().ok(),342+ DirEntryInner::BrokenSymlink(path) => path.symlink_metadata().ok(),343+ })344+ .as_ref()345 }346 347 pub fn depth(&self) -> Option<usize> {328- match self {329- DirEntry::Normal(e) => Some(e.depth()),330- DirEntry::BrokenSymlink(_) => None,348+ match &self.inner {349+ DirEntryInner::Normal(e) => Some(e.depth()),350+ DirEntryInner::BrokenSymlink(_) => None,351 }352 }353 }354 19 unmodified lines374 Ok(ref e) if e.depth() == 0 => {375 // Skip the root directory entry.376 return ignore::WalkState::Continue;377 }358- Ok(e) => DirEntry::Normal(e),378+ Ok(e) => DirEntry::normal(e),379 Err(ignore::Error::WithPath {380 path,381 err: inner_err,382 }) => match inner_err.as_ref() {3 unmodified lines386 .symlink_metadata()387 .ok()388 .map_or(false, |m| m.file_type().is_symlink()) =>389 {370- DirEntry::BrokenSymlink(path)390+ DirEntry::broken_symlink(path)391 }392 _ => {393 return match tx_thread.send(WorkerResult::Error(ignore::Error::WithPath {394 path,60 unmodified lines455 456 #[cfg(unix)]457 {458 if let Some(ref owner_constraint) = config.owner_constraint {439- if let Ok(ref metadata) = entry_path.metadata() {459+ if let Some(metadata) = entry.metadata() {460 if !owner_constraint.matches(metadata) {461 return ignore::WalkState::Continue;462 }463 } else {4 unmodified lines468 469 // Filter out unwanted sizes if it is a file and we have been given size constraints.470 if !config.size_constraints.is_empty() {471 if entry_path.is_file() {452- if let Ok(metadata) = entry_path.metadata() {472+ if let Some(metadata) = entry.metadata() {473 let file_size = metadata.len();474 if config475 .size_constraints476 .iter()11 unmodified lines488 489 // Filter out unwanted modification times490 if !config.time_constraints.is_empty() {491 let mut matched = false;472- if let Ok(metadata) = entry_path.metadata() {492+ if let Some(metadata) = entry.metadata() {493 if let Ok(modified) = metadata.modified() {494 matched = config495 .time_constraints496 .iter()23 unmodified linesmodified:tests/tests.rs+15 added-1 removed
1650 unmodified lines1651 fs::File::create(&path).expect("creation failed");1652 filetime::set_file_times(&path, ft, ft).expect("time modification failed");1653 }1654 1655+#[cfg(test)]1656+fn remove_symlink<P: AsRef<Path>>(path: P) {1657+ #[cfg(unix)]1658+ fs::remove_file(path).expect("remove symlink");1659+1660+ // On Windows, symlinks remember whether they point to files or directories, so try both1661+ #[cfg(windows)]1662+ fs::remove_file(path.as_ref())1663+ .or_else(|_| fs::remove_dir(path.as_ref()))1664+ .expect("remove symlink");1665+}1666+1667 #[test]1668 fn test_modified_relative() {1669 let te = TestEnv::new(&[], &[]);1670+ remove_symlink(te.test_root().join("symlink"));1671 create_file_with_modified(te.test_root().join("foo_0_now"), 0);1672 create_file_with_modified(te.test_root().join("bar_1_min"), 60);1673 create_file_with_modified(te.test_root().join("foo_10_min"), 600);1674 create_file_with_modified(te.test_root().join("bar_1_h"), 60 * 60);29 unmodified lines1704 filetime::set_file_times(path, ft, ft).expect("time modification failde");1705 }1706 1707 #[test]1695-fn test_modified_asolute() {1708+fn test_modified_absolute() {1709 let te = TestEnv::new(&[], &["15mar2018", "30dec2017"]);1710+ remove_symlink(te.test_root().join("symlink"));1711 change_file_modified(te.test_root().join("15mar2018"), "2018-03-15T12:00:00Z");1712 change_file_modified(te.test_root().join("30dec2017"), "2017-12-30T23:59:00Z");1713 1714 te.assert_output(189 unmodified linesmodified:Cargo.lock+1 added
175 unmodified lines176 "libc",177 "lscolors",178 "normpath",179 "num_cpus",180+ "once_cell",181 "regex",182 "regex-syntax",183 "tempdir",184 "users",434 unmodified linesmodified:Cargo.toml+1 added
47 unmodified lines48495051525354555621 unmodified lines47 unmodified linesanyhow = "1.0"dirs-next = "2.0"normpath = "0.3"chrono = "0.4"once_cell = "1.8.0"
[dependencies.clap]version = "2.31.3"features = ["suggestions", "color", "wrap_help"]21 unmodified linesmodified:CHANGELOG.md+7 added
1 # Upcoming release2 3+## Performance improvements4+5+- File metadata is now cached between the different filters that require it (e.g. `--owner`,6+ `--size`), reducing the number of `stat` syscalls when multiple filters are used; see #8637+8 ## Features9 - Don't buffer command output from `--exec` when using a single thread. See #52210 11 - Add new `-q, --quiet` flag, see #303 (@Asha20)7 unmodified lines19 - fd doesn't show substituted drive on Windows, see #36520 - Properly handle write errors to devices that are full, see #73721 - Use local time zone for time functions (`--change-newer-than`, `--change-older-than`), see #631 (@jacobmischka)22 - Support `--list-details` on more platforms (like BusyBox), see #78323+- The filters `--owner`, `--size`, and `--changed-{within,before}` now apply to symbolic links24+ themselves, rather than the link target, except when `--follow` is specified; see #86325 26 ## Changes27 28 - Apply custom `--path-separator` to commands run with `--exec(-batch)` and `--list-details`, see #697 (@aswild)509 unmodified lines