Skip to content
Myr

Compute depth for broken symlinks so --min-depth keeps them

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

When following links, a broken symlink is surfaced by the walker as an error that carries no depth, so fd stored it with an unknown depth and the --min-depth filter dropped it for any minimum value. Record the depth when the entry is created by counting the path components relative to the matching search root, which is what the issue discussion suggested. Broken symlinks are now filtered by depth like any other entry. Fixes #1017

authored by hexbinoct · committed by hexbinoct · parent ee20f42 · Browse files · 4 files+73 added−13 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+73 added−13 removed

  • tests:+37 added−0 removed
  • other:+36 added−13 removed

4 files+73 added−13 removed

modified:src/dir_entry.rs+11 added-9 removed
9 unmodified lines
1011#[derive(Debug)]12enum DirEntryInner {13 Normal(ignore::DirEntry),14 // Broken symlinks are surfaced by the walker as errors that carry no depth,15 // so we record the depth (relative to the search root) at creation time.14 BrokenSymlink(PathBuf),16 BrokenSymlink(PathBuf, usize),17}1819#[derive(Debug)]20pub struct DirEntry {
11 unmodified lines
32 style: OnceCell::new(),33 }34 }3534 pub fn broken_symlink(path: PathBuf) -> Self {36 pub fn broken_symlink(path: PathBuf, depth: usize) -> Self {37 Self {36 inner: DirEntryInner::BrokenSymlink(path),38 inner: DirEntryInner::BrokenSymlink(path, depth),39 metadata: OnceCell::new(),40 style: OnceCell::new(),41 }42 }4344 pub fn path(&self) -> &Path {45 match &self.inner {46 DirEntryInner::Normal(e) => e.path(),45 DirEntryInner::BrokenSymlink(pathbuf) => pathbuf.as_path(),47 DirEntryInner::BrokenSymlink(pathbuf, _) => pathbuf.as_path(),48 }49 }5051 pub fn into_path(self) -> PathBuf {52 match self.inner {53 DirEntryInner::Normal(e) => e.into_path(),52 DirEntryInner::BrokenSymlink(p) => p,54 DirEntryInner::BrokenSymlink(p, _) => p,55 }56 }5758 /// Returns the path as it should be presented to the user.
24 unmodified lines
8384 pub fn file_type(&self) -> Option<FileType> {85 match &self.inner {86 DirEntryInner::Normal(e) => e.file_type(),85 DirEntryInner::BrokenSymlink(_) => self.metadata().map(|m| m.file_type()),87 DirEntryInner::BrokenSymlink(..) => self.metadata().map(|m| m.file_type()),88 }89 }9091 pub fn metadata(&self) -> Option<&Metadata> {92 self.metadata93 .get_or_init(|| match &self.inner {94 DirEntryInner::Normal(e) => e.metadata().ok(),93 DirEntryInner::BrokenSymlink(path) => path.symlink_metadata().ok(),95 DirEntryInner::BrokenSymlink(path, _) => path.symlink_metadata().ok(),96 })97 .as_ref()98 }99100 pub fn depth(&self) -> Option<usize> {101 match &self.inner {102 DirEntryInner::Normal(e) => Some(e.depth()),101 DirEntryInner::BrokenSymlink(_) => None,103 DirEntryInner::BrokenSymlink(_, depth) => Some(*depth),104 }105 }106107 pub fn style(&self, ls_colors: &LsColors) -> Option<&Style> {
37 unmodified lines
145146 fn file_name(&self) -> OsString {147 let name = match &self.inner {148 DirEntryInner::Normal(e) => e.file_name(),147 DirEntryInner::BrokenSymlink(path) => {149 DirEntryInner::BrokenSymlink(path, _) => {150 // Path::file_name() only works if the last component is Normal,151 // but we want it for all component types, so we open code it.152 // Copied from LsColors::style_for_path_with_metadata().153 path.components()
38 unmodified lines
modified:src/walk.rs+24 added-4 removed
1use std::borrow::Cow;2use std::ffi::OsStr;3use std::io::{self, Write};4use std::mem;5use std::path::PathBuf;5use std::path::{Path, PathBuf};6use std::sync::atomic::{AtomicBool, Ordering};7use std::sync::{Arc, Mutex, MutexGuard};8use std::thread;9use std::time::{Duration, Instant};
429 unmodified lines
439 }440 }441442 /// Spawn the sender threads.443 fn spawn_senders(&self, walker: WalkParallel, tx: Sender<Batch>) {443 fn spawn_senders(&self, walker: WalkParallel, roots: &[PathBuf], tx: Sender<Batch>) {444 walker.run(|| {445 let patterns = &self.patterns;446 let config = &self.config;447 let quit_flag = self.quit_flag.as_ref();
46 unmodified lines
494 .symlink_metadata()495 .ok()496 .is_some_and(|m| m.file_type().is_symlink()) =>497 {498 let depth = depth_relative_to_roots(&path, roots);498 DirEntry::broken_symlink(path)499 DirEntry::broken_symlink(path, depth)500 }501 Err(err) => {502 return match tx.send(WorkerResult::Error(err)) {503 Ok(_) => WalkState::Continue,
136 unmodified lines
640 // Spawn the receiver thread(s)641 let receiver = scope.spawn(|| self.receive(rx));642643 // Spawn the sender threads.643 self.spawn_senders(walker, tx);644 self.spawn_senders(walker, paths, tx);645646 receiver.join().unwrap()647 });648
4 unmodified lines
653 }654 }655}656657/// Compute the depth of `path` relative to the search root it was found under.658///659/// `ignore::DirEntry::depth()` provides this for normal entries, but broken660/// symlinks are surfaced as errors that carry no depth, so we derive it from the661/// path components instead (see issue #1017). The matching root is the longest662/// search root (by component count) that `path` starts with; if none matches we663/// fall back to the full component count, which keeps the entry visible rather664/// than silently dropping it.665fn depth_relative_to_roots(path: &Path, roots: &[PathBuf]) -> usize {666 let components = path.components().count();667 let root_components = roots668 .iter()669 .filter(|root| path.starts_with(root))670 .map(|root| root.components().count())671 .max()672 .unwrap_or(0);673 components.saturating_sub(root_components)674}675676fn search_str_for_entry<'a>(677 entry_path: &'a std::path::Path,678 full_path_base: Option<&std::path::Path>,679) -> Cow<'a, OsStr> {
85 unmodified lines
modified:tests/tests.rs+37 added
1206 unmodified lines
1207 one/two/three/directory_foo/",1208 );1209}12101211/// Minimum depth with a broken symlink (regression test for #1017)1212///1213/// A broken symlink, surfaced while following links, has no depth reported by1214/// the walker, so --min-depth used to drop it unconditionally.1215#[test]1216fn test_min_depth_broken_symlink() {1217 let mut te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);1218 te.create_broken_symlink("one/two/broken_symlink")1219 .expect("Failed to create broken symlink.");12201221 // The broken symlink sits at depth 3, so it is kept up to that depth.1222 te.assert_output(1223 &[1224 "--follow",1225 "--type",1226 "symlink",1227 "--min-depth",1228 "3",1229 "broken_symlink",1230 ],1231 "one/two/broken_symlink",1232 );12331234 // A --min-depth beyond its actual depth must exclude it.1235 te.assert_output(1236 &[1237 "--follow",1238 "--type",1239 "symlink",1240 "--min-depth",1241 "4",1242 "broken_symlink",1243 ],1244 "",1245 );1246}12471248/// Exact depth (--exact-depth)1249#[test]1250fn test_exact_depth() {1251 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);
1664 unmodified lines
modified:CHANGELOG.md+1 added
7 unmodified lines
8- Sanitize control characters and bidirectional override characters in filenames9 when output goes to a terminal, to prevent terminal escape-sequence injection.10 Also reject a placeholder as the executable for `--exec-batch`, while still11 allowing it for `--exec`.12- Fix broken symlinks being incorrectly filtered out by `--min-depth` when following links (`--follow`), because their depth was not computed; see #1017 (@hexbinoct).13- Handle invalid working directories gracefully when using `--full-path`, see #1900 (@Xavrir).14- Fire the "search pattern contains a path separator" diagnostic for any pattern containing `/`, not just patterns that happen to name an existing directory. Preserves the legacy Windows behaviour that also flags native `\` separators when the pattern resolves to a real directory. See #1873.15- Also fire the "search pattern contains a path separator" diagnostic for `--and` patterns, not only the primary positional pattern. `--and` patterns are matched against the file name just like the primary pattern, so a path separator in them silently returned zero results. See #1873.16- Fix bug where passing "-" as a directory argument didn't actually search that directory, see #849 (@Sean-Kenneth-Doherty).
853 unmodified lines