Take the broken symlink depth from the walker
Before adoption: this commit came in with the history the project adopted, so no landing records it.
The depth of a broken symlink was derived from its path by stripping the matching search root, because the walker did not report a depth on the errors that carry broken symlinks. ignore 0.4.28 fills that depth in, so read it from the error instead and drop the path arithmetic. The path based version could not express one case. When two search roots overlap, the walker visits the same broken symlink once per root at a different depth each time, and both visits carry the same path, so a single path derived answer had to serve both. Searching roots a and a/b with --min-depth 2 dropped a/b/blink even though a real file in its place was kept.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+83 added−56 removed
- tests:+46 added−0 removed
- other:+37 added−56 removed
Provenance
- Commit
b3a8ff6- Tree
7dc1d53- Author
hexbinoct <abubakarm@gmail.com>- Committer
hexbinoct <abubakarm@gmail.com>- Parent
68edfde
4 files changed+83 added−56 removed
modified:src/dir_entry.rs+5 added-5 removed
9 unmodified lines10 11 #[derive(Debug)]12 enum 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.16- BrokenSymlink { path: PathBuf, depth: usize },14+ // Broken symlinks reach us as walk errors rather than entries, so we carry15+ // over the depth the walker recorded on the error.16+ BrokenSymlink { path: PathBuf, depth: Option<usize> },17 }18 19 #[derive(Debug)]20 pub struct DirEntry {11 unmodified lines32 style: OnceCell::new(),33 }34 }35 36- pub fn broken_symlink(path: PathBuf, depth: usize) -> Self {36+ pub fn broken_symlink(path: PathBuf, depth: Option<usize>) -> Self {37 Self {38 inner: DirEntryInner::BrokenSymlink { path, depth },39 metadata: OnceCell::new(),40 style: OnceCell::new(),58 unmodified lines99 100 pub fn depth(&self) -> Option<usize> {101 match &self.inner {102 DirEntryInner::Normal(e) => Some(e.depth()),103- DirEntryInner::BrokenSymlink { depth, .. } => Some(*depth),103+ DirEntryInner::BrokenSymlink { depth, .. } => *depth,104 }105 }106 107 pub fn style(&self, ls_colors: &LsColors) -> Option<&Style> {84 unmodified linesmodified:src/walk.rs+31 added-50 removed
438 unmodified lines439 }440 }441 442 /// Spawn the sender threads.443- fn spawn_senders(&self, walker: WalkParallel, roots: &[PathBuf], tx: Sender<Batch>) {443+ fn spawn_senders(&self, walker: WalkParallel, 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();35 unmodified lines483 }484 }485 let entry = match entry {486 Ok(e) => DirEntry::normal(e),487- Err(ignore::Error::WithPath {488- path,489- err: inner_err,490- }) if inner_err491- .io_error()492- .is_some_and(|io_error| io_error.kind() == io::ErrorKind::NotFound)493- && path494- .symlink_metadata()495- .ok()496- .is_some_and(|m| m.file_type().is_symlink()) =>497- {498- let depth = depth_relative_to_roots(&path, roots);499- DirEntry::broken_symlink(path, depth)500- }487 Err(err) => {488+ // The depth has to be read off the error before it is489+ // taken apart, since it is recorded on an inner variant.490+ let depth = err.depth();491+ match err {492+ ignore::Error::WithPath {493+ path,494+ err: inner_err,495+ } if is_broken_symlink(&path, &inner_err) => {496+ DirEntry::broken_symlink(path, depth)497+ }498+ err => {502- return match tx.send(WorkerResult::Error(err)) {503- Ok(_) => WalkState::Continue,504- Err(_) => WalkState::Quit,505- };499+ return match tx.send(WorkerResult::Error(err)) {500+ Ok(_) => WalkState::Continue,501+ Err(_) => WalkState::Quit,502+ };503+ }504+ }505 }506 };507 508 if let Some(min_depth) = config.min_depth130 unmodified lines639 // Spawn the receiver thread(s)640 let receiver = scope.spawn(|| self.receive(rx));641 642 // Spawn the sender threads.644- self.spawn_senders(walker, paths, tx);643+ self.spawn_senders(walker, tx);644 645 receiver.join().unwrap()646 });647 4 unmodified lines652 }653 }654 }655 657-/// Compute the depth of `path` relative to the search root it was found under.656+/// Whether a walk error is really a broken symlink rather than a failure worth657+/// reporting.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 instead (see issue #1017). The walker reports every entry's path662-/// prefixed by the search root it was found under, so we strip the matching root663-/// and count the remaining components. Both the path and the roots are put into664-/// absolute form first, so the comparison is correct regardless of whether665-/// `--absolute-path` has already made the roots absolute (otherwise an absolute666-/// path would fail to match a relative root and the depth would be wrong). When667-/// more than one root is a prefix, the deepest (most specific) one wins. If none668-/// matches, which should not happen, we fall back to the full component count,669-/// keeping the entry visible rather than silently dropping it.670-fn depth_relative_to_roots(path: &Path, roots: &[PathBuf]) -> usize {671- // `Path::join` ignores the base when its argument is already absolute, so672- // this leaves absolute inputs untouched and anchors relative ones at the cwd.673- let cwd = std::env::current_dir().ok();674- let absolute = |p: &Path| -> PathBuf {675- match &cwd {676- Some(cwd) => cwd.join(p),677- None => p.to_path_buf(),678- }679- };680-681- let absolute_path = absolute(path);682- roots683- .iter()684- .filter_map(|root| absolute_path.strip_prefix(absolute(root)).ok())685- .map(|relative| relative.components().count())686- .min()687- .unwrap_or_else(|| path.components().count())659+/// A symlink whose target is missing is surfaced by the walker as a NotFound660+/// error against the link's own path, so it never arrives as an entry. fd still661+/// wants to match and print it (see issue #1017), which means recovering it here.662+fn is_broken_symlink(path: &Path, err: &ignore::Error) -> bool {663+ err.io_error()664+ .is_some_and(|io_error| io_error.kind() == io::ErrorKind::NotFound)665+ && path666+ .symlink_metadata()667+ .ok()668+ .is_some_and(|m| m.file_type().is_symlink())669 }670 671 fn search_str_for_entry<'a>(672 entry_path: &'a std::path::Path,87 unmodified linesmodified:tests/tests.rs+46 added
1283 unmodified lines1284 "",1285 );1286 }1287 1288+/// Minimum depth with a broken symlink under overlapping search roots (#1017)1289+///1290+/// When two search roots overlap, the walker visits the same broken symlink once1291+/// per root, at a different depth each time. Here `one/two/broken_symlink` is at1292+/// depth 2 under root `one` and at depth 1 under root `one/two`, so --min-depth 21293+/// must keep the entry the walker reached via `one` and drop the one it reached1294+/// via `one/two`. A depth derived from the entry's path cannot distinguish the1295+/// two visits, since both carry the same path.1296+#[test]1297+fn test_min_depth_broken_symlink_overlapping_roots() {1298+ let mut te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);1299+ te.create_broken_symlink("one/two/broken_symlink")1300+ .expect("Failed to create broken symlink.");1301+1302+ // Only the route through `one` reaches depth 2.1303+ te.assert_output(1304+ &[1305+ "--follow",1306+ "--type",1307+ "symlink",1308+ "--min-depth",1309+ "2",1310+ "broken_symlink",1311+ "one",1312+ "one/two",1313+ ],1314+ "one/two/broken_symlink",1315+ );1316+1317+ // Both routes clear --min-depth 1, so it is reported once per root.1318+ te.assert_output(1319+ &[1320+ "--follow",1321+ "--type",1322+ "symlink",1323+ "--min-depth",1324+ "1",1325+ "broken_symlink",1326+ "one",1327+ "one/two",1328+ ],1329+ "one/two/broken_symlink1330+ one/two/broken_symlink",1331+ );1332+}1333+1334 /// Maximum depth with a broken symlink (#1017)1335 ///1336 /// A broken symlink must be filtered by --max-depth like any other entry. The1337 /// default environment also exposes it through the followed `symlink` directory1742 unmodified linesmodified:Cargo.toml+1 added-1 removed
32 unmodified lines3334353637373839404174 unmodified lines32 unmodified lines[dependencies]aho-corasick = "1.1"nu-ansi-term = "0.50"argmax = "0.4.0"ignore = "0.4.25"ignore = "0.4.28"regex = "1.12.2"regex-syntax = "0.8"ctrlc = "3.5"globset = "0.4"74 unmodified lines