Skip to content

Commit 62d38da

Browse files
authored
Rollup merge of #81822 - Kixunil:path_try_exists, r=kennytm
Added `try_exists()` method to `std::path::Path` This method is similar to the existing `exists()` method, except it doesn't silently ignore the errors, leading to less error-prone code. This change intentionally does NOT touch the documentation of `exists()` nor recommend people to use this method while it's unstable. Such changes are reserved for stabilization to prevent confusing people. Apart from that it avoids conflicts with #80979. `@joshtriplett` requested this PR in [internals discussion](https://internals.rust-lang.org/t/the-api-of-path-exists-encourages-broken-code/13817/25?u=kixunil)
2 parents f24ce9b + 4330268 commit 62d38da

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

library/std/src/path.rs

+30
Original file line numberDiff line numberDiff line change
@@ -2472,6 +2472,36 @@ impl Path {
24722472
fs::metadata(self).is_ok()
24732473
}
24742474

2475+
/// Returns `Ok(true)` if the path points at an existing entity.
2476+
///
2477+
/// This function will traverse symbolic links to query information about the
2478+
/// destination file. In case of broken symbolic links this will return `Ok(false)`.
2479+
///
2480+
/// As opposed to the `exists()` method, this one doesn't silently ignore errors
2481+
/// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2482+
/// denied on some of the parent directories.)
2483+
///
2484+
/// # Examples
2485+
///
2486+
/// ```no_run
2487+
/// #![feature(path_try_exists)]
2488+
///
2489+
/// use std::path::Path;
2490+
/// assert!(!Path::new("does_not_exist.txt").try_exists().expect("Can't check existence of file does_not_exist.txt"));
2491+
/// assert!(Path::new("/root/secret_file.txt").try_exists().is_err());
2492+
/// ```
2493+
// FIXME: stabilization should modify documentation of `exists()` to recommend this method
2494+
// instead.
2495+
#[unstable(feature = "path_try_exists", issue = "83186")]
2496+
#[inline]
2497+
pub fn try_exists(&self) -> io::Result<bool> {
2498+
match fs::metadata(self) {
2499+
Ok(_) => Ok(true),
2500+
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
2501+
Err(error) => Err(error),
2502+
}
2503+
}
2504+
24752505
/// Returns `true` if the path exists on disk and is pointing at a regular file.
24762506
///
24772507
/// This function will traverse symbolic links to query information about the

0 commit comments

Comments
 (0)