Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f36b137

Browse files
committedMay 21, 2021
Auto merge of rust-lang#85060 - ChrisDenton:win-file-exists, r=yaahc
Windows implementation of feature `path_try_exists` Draft of a Windows implementation of `try_exists` (rust-lang#83186). The first commit reorganizes the code so I would be interested to get some feedback on if this is a good idea or not. It moves the `Path::try_exists` function to `fs::exists`. leaving the former as a wrapper for the latter. This makes it easier to provide platform specific implementations and matches the `fs::metadata` function. The other commit implements a Windows specific variant of `exists`. I'm still figuring out my approach so this is very much a first draft. Eventually this will need some more eyes from knowledgable Windows people.
2 parents 6f5a198 + 86dbc06 commit f36b137

File tree

9 files changed

+72
-8
lines changed

9 files changed

+72
-8
lines changed
 

‎library/std/src/fs.rs

+26
Original file line numberDiff line numberDiff line change
@@ -2208,3 +2208,29 @@ impl AsInnerMut<fs_imp::DirBuilder> for DirBuilder {
22082208
&mut self.inner
22092209
}
22102210
}
2211+
2212+
/// Returns `Ok(true)` if the path points at an existing entity.
2213+
///
2214+
/// This function will traverse symbolic links to query information about the
2215+
/// destination file. In case of broken symbolic links this will return `Ok(false)`.
2216+
///
2217+
/// As opposed to the `exists()` method, this one doesn't silently ignore errors
2218+
/// unrelated to the path not existing. (E.g. it will return `Err(_)` in case of permission
2219+
/// denied on some of the parent directories.)
2220+
///
2221+
/// # Examples
2222+
///
2223+
/// ```no_run
2224+
/// #![feature(path_try_exists)]
2225+
/// use std::fs;
2226+
///
2227+
/// assert!(!fs::try_exists("does_not_exist.txt").expect("Can't check existence of file does_not_exist.txt"));
2228+
/// assert!(fs::try_exists("/root/secret_file.txt").is_err());
2229+
/// ```
2230+
// FIXME: stabilization should modify documentation of `exists()` to recommend this method
2231+
// instead.
2232+
#[unstable(feature = "path_try_exists", issue = "83186")]
2233+
#[inline]
2234+
pub fn try_exists<P: AsRef<Path>>(path: P) -> io::Result<bool> {
2235+
fs_imp::try_exists(path.as_ref())
2236+
}

‎library/std/src/path.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -2507,11 +2507,7 @@ impl Path {
25072507
#[unstable(feature = "path_try_exists", issue = "83186")]
25082508
#[inline]
25092509
pub fn try_exists(&self) -> io::Result<bool> {
2510-
match fs::metadata(self) {
2511-
Ok(_) => Ok(true),
2512-
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
2513-
Err(error) => Err(error),
2514-
}
2510+
fs::try_exists(self)
25152511
}
25162512

25172513
/// Returns `true` if the path exists on disk and is pointing at a regular file.

‎library/std/src/sys/hermit/fs.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use crate::sys::time::SystemTime;
1212
use crate::sys::unsupported;
1313
use crate::sys_common::os_str_bytes::OsStrExt;
1414

15-
pub use crate::sys_common::fs::copy;
15+
pub use crate::sys_common::fs::{copy, try_exists};
1616
//pub use crate::sys_common::fs::remove_dir_all;
1717

1818
fn cstr(path: &Path) -> io::Result<CString> {

‎library/std/src/sys/unix/fs.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ use libc::{
4848
dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, readdir64_r, stat64,
4949
};
5050

51-
pub use crate::sys_common::fs::remove_dir_all;
51+
pub use crate::sys_common::fs::{remove_dir_all, try_exists};
5252

5353
pub struct File(FileDesc);
5454

‎library/std/src/sys/unsupported/fs.rs

+4
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,10 @@ pub fn remove_dir_all(_path: &Path) -> io::Result<()> {
275275
unsupported()
276276
}
277277

278+
pub fn try_exists(_path: &Path) -> io::Result<bool> {
279+
unsupported()
280+
}
281+
278282
pub fn readlink(_p: &Path) -> io::Result<PathBuf> {
279283
unsupported()
280284
}

‎library/std/src/sys/wasi/fs.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use crate::sys::time::SystemTime;
1414
use crate::sys::unsupported;
1515
use crate::sys_common::FromInner;
1616

17-
pub use crate::sys_common::fs::remove_dir_all;
17+
pub use crate::sys_common::fs::{remove_dir_all, try_exists};
1818

1919
pub struct File {
2020
fd: WasiFd,

‎library/std/src/sys/windows/c.rs

+1
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ pub const ERROR_INVALID_HANDLE: DWORD = 6;
173173
pub const ERROR_NOT_ENOUGH_MEMORY: DWORD = 8;
174174
pub const ERROR_OUTOFMEMORY: DWORD = 14;
175175
pub const ERROR_NO_MORE_FILES: DWORD = 18;
176+
pub const ERROR_SHARING_VIOLATION: u32 = 32;
176177
pub const ERROR_HANDLE_EOF: DWORD = 38;
177178
pub const ERROR_FILE_EXISTS: DWORD = 80;
178179
pub const ERROR_INVALID_PARAMETER: DWORD = 87;

‎library/std/src/sys/windows/fs.rs

+29
Original file line numberDiff line numberDiff line change
@@ -944,3 +944,32 @@ fn symlink_junction_inner(original: &Path, junction: &Path) -> io::Result<()> {
944944
.map(drop)
945945
}
946946
}
947+
948+
// Try to see if a file exists but, unlike `exists`, report I/O errors.
949+
pub fn try_exists(path: &Path) -> io::Result<bool> {
950+
// Open the file to ensure any symlinks are followed to their target.
951+
let mut opts = OpenOptions::new();
952+
// No read, write, etc access rights are needed.
953+
opts.access_mode(0);
954+
// Backup semantics enables opening directories as well as files.
955+
opts.custom_flags(c::FILE_FLAG_BACKUP_SEMANTICS);
956+
match File::open(path, &opts) {
957+
Err(e) => match e.kind() {
958+
// The file definitely does not exist
959+
io::ErrorKind::NotFound => Ok(false),
960+
961+
// `ERROR_SHARING_VIOLATION` means that the file has been locked by
962+
// another process. This is often temporary so we simply report it
963+
// as the file existing.
964+
io::ErrorKind::Other if e.raw_os_error() == Some(c::ERROR_SHARING_VIOLATION as i32) => {
965+
Ok(true)
966+
}
967+
// Other errors such as `ERROR_ACCESS_DENIED` may indicate that the
968+
// file exists. However, these types of errors are usually more
969+
// permanent so we report them here.
970+
_ => Err(e),
971+
},
972+
// The file was opened successfully therefore it must exist,
973+
Ok(_) => Ok(true),
974+
}
975+
}

‎library/std/src/sys_common/fs.rs

+8
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,11 @@ fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
4141
}
4242
fs::remove_dir(path)
4343
}
44+
45+
pub fn try_exists(path: &Path) -> io::Result<bool> {
46+
match fs::metadata(path) {
47+
Ok(_) => Ok(true),
48+
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
49+
Err(error) => Err(error),
50+
}
51+
}

0 commit comments

Comments
 (0)
Failed to load comments.