Skip to content
Myr

Merge pull request #2039 from hexbinoct/fix/min-depth-broken-symlink

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

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

authored by Thayne McCombs · committed by GitHub · parents 2797c4a, b3a8ff6 · Browse files · 5 files+247 added−28 removed
This commit

State

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

Diff stats

5 files+247 added−28 removed

  • tests:+201 added−0 removed
  • other:+46 added−28 removed

5 files+247 added−28 removed

modified:src/dir_entry.rs+11 added-9 removed
9 unmodified lines
1011#[derive(Debug)]12enum DirEntryInner {13 Normal(ignore::DirEntry),14 BrokenSymlink(PathBuf),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}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: Option<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 { path, .. } => path.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 { path, .. } => path,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, .. } => *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+33 added-18 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};
472 unmodified lines
482 }483 }484 let entry = match entry {485 Ok(e) => DirEntry::normal(e),486 Err(ignore::Error::WithPath {487 path,488 err: inner_err,489 }) if inner_err490 .io_error()491 .is_some_and(|io_error| io_error.kind() == io::ErrorKind::NotFound)492 && path493 .symlink_metadata()494 .ok()495 .is_some_and(|m| m.file_type().is_symlink()) =>496 {497 DirEntry::broken_symlink(path)498 }486 Err(err) => {487 // The depth has to be read off the error before it is488 // taken apart, since it is recorded on an inner variant.489 let depth = err.depth();490 match err {491 ignore::Error::WithPath {492 path,493 err: inner_err,494 } if is_broken_symlink(&path, &inner_err) => {495 DirEntry::broken_symlink(path, depth)496 }497 err => {500 return match tx.send(WorkerResult::Error(err)) {501 Ok(_) => WalkState::Continue,502 Err(_) => WalkState::Quit,503 };498 return match tx.send(WorkerResult::Error(err)) {499 Ok(_) => WalkState::Continue,500 Err(_) => WalkState::Quit,501 };502 }503 }504 }505 };506507 if let Some(min_depth) = config.min_depth
143 unmodified lines
651 }652 }653}654655/// Whether a walk error is really a broken symlink rather than a failure worth656/// reporting.657///658/// A symlink whose target is missing is surfaced by the walker as a NotFound659/// error against the link's own path, so it never arrives as an entry. fd still660/// wants to match and print it (see issue #1017), which means recovering it here.661fn is_broken_symlink(path: &Path, err: &ignore::Error) -> bool {662 err.io_error()663 .is_some_and(|io_error| io_error.kind() == io::ErrorKind::NotFound)664 && path665 .symlink_metadata()666 .ok()667 .is_some_and(|m| m.file_type().is_symlink())668}669670fn search_str_for_entry<'a>(671 entry_path: &'a std::path::Path,672 full_path_base: Option<&std::path::Path>,673) -> Cow<'a, OsStr> {
85 unmodified lines
modified:tests/tests.rs+201 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/// Minimum depth with a broken symlink combined with --absolute-path (#1017)1249///1250/// With --absolute-path the search root is made absolute before walking, so the1251/// broken symlink's depth must still be computed relative to that root rather1252/// than from the absolute path's full component count.1253#[test]1254fn test_min_depth_broken_symlink_absolute_path() {1255 let (mut te, abs_path) = get_test_env_with_abs_path(DEFAULT_DIRS, DEFAULT_FILES);1256 te.create_broken_symlink("one/two/broken_symlink")1257 .expect("Failed to create broken symlink.");12581259 // The broken symlink sits at depth 3 relative to the (absolute) root.1260 te.assert_output(1261 &[1262 "--follow",1263 "--absolute-path",1264 "--type",1265 "symlink",1266 "--min-depth",1267 "3",1268 "broken_symlink",1269 ],1270 &format!("{abs_path}/one/two/broken_symlink"),1271 );12721273 // A --min-depth beyond its actual depth must exclude it.1274 te.assert_output(1275 &[1276 "--follow",1277 "--absolute-path",1278 "--type",1279 "symlink",1280 "--min-depth",1281 "4",1282 "broken_symlink",1283 ],1284 "",1285 );1286}12871288/// 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]1297fn 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.");13011302 // 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 );13161317 // 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}13331334/// 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` directory1338/// (`symlink -> one/two`), so it is reachable at depth 2 as well as depth 3.1339#[test]1340fn test_max_depth_broken_symlink() {1341 let mut te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);1342 te.create_broken_symlink("one/two/broken_symlink")1343 .expect("Failed to create broken symlink.");13441345 // --max-depth 3 keeps both routes to the broken symlink.1346 te.assert_output(1347 &[1348 "--follow",1349 "--type",1350 "symlink",1351 "--max-depth",1352 "3",1353 "broken_symlink",1354 ],1355 "one/two/broken_symlink1356 symlink/broken_symlink",1357 );13581359 // A --max-depth below either route must exclude it.1360 te.assert_output(1361 &[1362 "--follow",1363 "--type",1364 "symlink",1365 "--max-depth",1366 "1",1367 "broken_symlink",1368 ],1369 "",1370 );1371}13721373/// Exact depth with a broken symlink (#1017)1374///1375/// A broken symlink must be kept only at its exact depth. It is reachable at1376/// depth 3 (`one/two/broken_symlink`) and, through the followed `symlink`1377/// directory, at depth 2 (`symlink/broken_symlink`).1378#[test]1379fn test_exact_depth_broken_symlink() {1380 let mut te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);1381 te.create_broken_symlink("one/two/broken_symlink")1382 .expect("Failed to create broken symlink.");13831384 // Only the depth-3 route matches --exact-depth 3.1385 te.assert_output(1386 &[1387 "--follow",1388 "--type",1389 "symlink",1390 "--exact-depth",1391 "3",1392 "broken_symlink",1393 ],1394 "one/two/broken_symlink",1395 );13961397 // Only the depth-2 route (via the followed symlink) matches --exact-depth 2,1398 // which confirms the depth is computed relative to the search root.1399 te.assert_output(1400 &[1401 "--follow",1402 "--type",1403 "symlink",1404 "--exact-depth",1405 "2",1406 "broken_symlink",1407 ],1408 "symlink/broken_symlink",1409 );1410}14111412/// Exact depth (--exact-depth)1413#[test]1414fn test_exact_depth() {1415 let te = TestEnv::new(DEFAULT_DIRS, DEFAULT_FILES);
1724 unmodified lines
modified:Cargo.toml+1 added-1 removed
modified:CHANGELOG.md+1 added
17 unmodified lines
18- Sanitize control characters and bidirectional override characters in filenames19 when output goes to a terminal, to prevent terminal escape-sequence injection.20 Also reject a placeholder as the executable for `--exec-batch`, while still21 allowing it for `--exec`.22- Fix broken symlinks being incorrectly filtered out by `--min-depth` when following links (`--follow`), because their depth was not computed; see #1017 (@hexbinoct).23- Handle invalid working directories gracefully when using `--full-path`, see #1900 (@Xavrir).24- 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.25- 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.26- Fix bug where passing "-" as a directory argument didn't actually search that directory, see #849 (@Sean-Kenneth-Doherty).
853 unmodified lines