Skip to content

Commit 66f7f7d

Browse files
committed
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.
1 parent 399b645 commit 66f7f7d

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
@@ -2468,6 +2468,36 @@ impl Path {
24682468
fs::metadata(self).is_ok()
24692469
}
24702470

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

0 commit comments

Comments
 (0)