Skip to content

dirfd: preliminary unix and windows implementations #139514

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
259 changes: 259 additions & 0 deletions library/std/src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,30 @@ pub enum TryLockError {
WouldBlock,
}

#[unstable(feature = "dirfd", issue = "120426")]
/// An object providing access to a directory on the filesystem.
///
/// Files are automatically closed when they go out of scope. Errors detected
/// on closing are ignored by the implementation of `Drop`.
///
/// # Examples
///
/// Opens a directory and then a file inside it.
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::fs::Dir;
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::new("foo")?;
/// let file = dir.open("bar.txt")?;
/// Ok(())
/// }
/// ```
pub struct Dir {
inner: fs_imp::Dir,
}

/// Metadata information about a file.
///
/// This structure is returned from the [`metadata`] or
Expand Down Expand Up @@ -1402,6 +1426,241 @@ impl Seek for Arc<File> {
}
}

impl Dir {
/// Attempts to open a directory at `path` in read-only mode.
///
/// See [`new_with`] for more options.
///
/// # Errors
///
/// This function will return an error in these (and other) situations:
/// * The path doesn't exist
/// * The path doesn't specify a directory
/// * The process doesn't have permission to read the directory
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::{fs::Dir, io::Read};
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::new("foo")?;
/// let mut f = dir.open("bar.txt")?;
/// let mut data = vec![];
/// f.read_to_end(&mut data)?;
/// Ok(())
/// }
/// ```
///
/// [`new_with`]: Dir::new_with
#[unstable(feature = "dirfd", issue = "120426")]
pub fn new<P: AsRef<Path>>(path: P) -> io::Result<Self> {
Ok(Self { inner: fs_imp::Dir::new(path)? })
}

/// Attempts to open a directory at `path` with the options specified by `opts`.
///
/// # Errors
///
/// This function will return an error in these (and other) situations:
/// * The path doesn't exist
/// * The path doesn't specify a directory
/// * The process doesn't have permission to read/write (according to `opts`) the directory
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::fs::{Dir, OpenOptions};
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::new_with("foo", OpenOptions::new().write(true))?;
/// let mut f = dir.remove_file("bar.txt")?;
/// Ok(())
/// }
/// ```
#[unstable(feature = "dirfd", issue = "120426")]
pub fn new_with<P: AsRef<Path>>(path: P, opts: &OpenOptions) -> io::Result<Self> {
Ok(Self { inner: fs_imp::Dir::new_with(path, &opts.0)? })
}

/// Attempts to open a file in read-only mode relative to this directory.
///
/// # Errors
///
/// This function will return an error in these (and other) situations:
/// * The path doesn't exist
/// * The path doesn't specify a regular file
/// * The process doesn't have permission to read/write (according to `opts`) the directory
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::{fs::Dir, io::Read};
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::new("foo")?;
/// let mut f = dir.open("bar.txt")?;
/// let mut data = vec![];
/// f.read_to_end(&mut data)?;
/// Ok(())
/// }
/// ```
#[unstable(feature = "dirfd", issue = "120426")]
pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
self.inner.open(path).map(|f| File { inner: f })
}

/// Attempts to open a file relative to this directory with the options specified by `opts`.
///
/// # Errors
///
/// This function will return an error in these (and other) situations:
/// * The path doesn't exist
/// * The path doesn't specify a regular file
/// * The process doesn't have permission to read/write (according to `opts`) the directory
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::{fs::{Dir, OpenOptions}, io::Read};
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::new("foo")?;
/// let mut f = dir.open_with("bar.txt", OpenOptions::new().read(true))?;
/// let mut data = vec![];
/// f.read_to_end(&mut data)?;
/// Ok(())
/// }
/// ```
#[unstable(feature = "dirfd", issue = "120426")]
pub fn open_with<P: AsRef<Path>>(&self, path: P, opts: &OpenOptions) -> io::Result<File> {
self.inner.open_with(path, &opts.0).map(|f| File { inner: f })
}

/// Attempts to create a directory relative to this directory.
///
/// # Errors
///
/// This function will return an error in these (and other) situations:
/// * The path exists
/// * The process doesn't have permission to create the directory
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::{fs::{Dir, OpenOptions}, io::Read};
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::new("foo")?;
/// let mut f = dir.open_with("bar.txt", OpenOptions::new().read(true))?;
/// let mut data = vec![];
/// f.read_to_end(&mut data)?;
/// Ok(())
/// }
/// ```
#[unstable(feature = "dirfd", issue = "120426")]
pub fn create_dir<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
self.inner.create_dir(path)
}

/// Attempts to remove a file relative to this directory.
///
/// # Errors
///
/// This function will return an error in these (and other) situations:
/// * The path doesn't exist
/// * The path doesn't specify a regular file
/// * The process doesn't have permission to delete the file.
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::fs::Dir;
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::new("foo")?;
/// dir.remove_file("bar.txt")?;
/// Ok(())
/// }
/// ```
#[unstable(feature = "dirfd", issue = "120426")]
pub fn remove_file<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
self.inner.remove_file(path)
}

/// Attempts to remove a directory relative to this directory.
///
/// # Errors
///
/// This function will return an error in these (and other) situations:
/// * The path doesn't exist
/// * The path doesn't specify a directory
/// * The directory isn't empty
/// * The process doesn't have permission to delete the directory.
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::fs::Dir;
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::new("foo")?;
/// dir.remove_dir("baz")?;
/// Ok(())
/// }
/// ```
#[unstable(feature = "dirfd", issue = "120426")]
pub fn remove_dir<P: AsRef<Path>>(&self, path: P) -> io::Result<()> {
self.inner.remove_dir(path)
}

/// Attempts to rename a file or directory relative to this directory to a new name, replacing
/// the destination file if present.
///
/// # Errors
///
/// This function will return an error in these (and other) situations:
/// * The `from` path doesn't exist
/// * The `from` path doesn't specify a directory
/// * `self` and `to_dir` are on different mount points
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::fs::Dir;
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::new("foo")?;
/// dir.rename("bar.txt", &dir, "quux.txt")?;
/// Ok(())
/// }
/// ```
#[unstable(feature = "dirfd", issue = "120426")]
pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(
&self,
from: P,
to_dir: &Self,
to: Q,
) -> io::Result<()> {
self.inner.rename(from, &to_dir.inner, to)
}
}

#[unstable(feature = "dirfd", issue = "120426")]
impl fmt::Debug for Dir {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}

impl OpenOptions {
/// Creates a blank new set of options ready for configuration.
///
Expand Down
93 changes: 92 additions & 1 deletion library/std/src/fs/tests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use rand::RngCore;

use super::Dir;
#[cfg(any(
windows,
target_os = "freebsd",
Expand All @@ -17,7 +18,7 @@ use crate::char::MAX_LEN_UTF8;
target_vendor = "apple",
))]
use crate::fs::TryLockError;
use crate::fs::{self, File, FileTimes, OpenOptions};
use crate::fs::{self, File, FileTimes, OpenOptions, create_dir};
use crate::io::prelude::*;
use crate::io::{BorrowedBuf, ErrorKind, SeekFrom};
use crate::mem::MaybeUninit;
Expand Down Expand Up @@ -2024,3 +2025,93 @@ fn test_rename_junction() {
// Junction links are always absolute so we just check the file name is correct.
assert_eq!(fs::read_link(&dest).unwrap().file_name(), Some(not_exist.as_os_str()));
}

#[test]
fn test_dir_smoke_test() {
let tmpdir = tmpdir();
check!(Dir::new(tmpdir.path()));
}

#[test]
fn test_dir_read_file() {
let tmpdir = tmpdir();
let mut f = check!(File::create(tmpdir.join("foo.txt")));
check!(f.write(b"bar"));
check!(f.flush());
drop(f);
let dir = check!(Dir::new(tmpdir.path()));
let mut f = check!(dir.open("foo.txt"));
let mut buf = [0u8; 3];
check!(f.read_exact(&mut buf));
assert_eq!(b"bar", &buf);
}

#[test]
fn test_dir_write_file() {
let tmpdir = tmpdir();
let dir = check!(Dir::new(tmpdir.path()));
let mut f = check!(dir.open_with("foo.txt", &OpenOptions::new().write(true).create(true)));
check!(f.write(b"bar"));
check!(f.flush());
drop(f);
let mut f = check!(File::open(tmpdir.join("foo.txt")));
let mut buf = [0u8; 3];
check!(f.read_exact(&mut buf));
assert_eq!(b"bar", &buf);
}

#[test]
fn test_dir_remove_file() {
let tmpdir = tmpdir();
let mut f = check!(File::create(tmpdir.join("foo.txt")));
check!(f.write(b"bar"));
check!(f.flush());
drop(f);
let dir = check!(Dir::new(tmpdir.path()));
check!(dir.remove_file("foo.txt"));
let result = File::open(tmpdir.join("foo.txt"));
#[cfg(all(unix, not(target_os = "vxworks")))]
error!(result, "No such file or directory");
#[cfg(target_os = "vxworks")]
error!(result, "no such file or directory");
#[cfg(windows)]
error!(result, 2); // ERROR_FILE_NOT_FOUND
}

#[test]
fn test_dir_remove_dir() {
let tmpdir = tmpdir();
check!(create_dir(tmpdir.join("foo")));
let dir = check!(Dir::new(tmpdir.path()));
check!(dir.remove_dir("foo"));
let result = Dir::new(tmpdir.join("foo"));
#[cfg(all(unix, not(target_os = "vxworks")))]
error!(result, "No such file or directory");
#[cfg(target_os = "vxworks")]
error!(result, "no such file or directory");
#[cfg(windows)]
error!(result, 2); // ERROR_FILE_NOT_FOUND
}

#[test]
fn test_dir_rename_file() {
let tmpdir = tmpdir();
let mut f = check!(File::create(tmpdir.join("foo.txt")));
check!(f.write(b"bar"));
check!(f.flush());
drop(f);
let dir = check!(Dir::new(tmpdir.path()));
check!(dir.rename("foo.txt", &dir, "baz.txt"));
let mut f = check!(File::open(tmpdir.join("baz.txt")));
let mut buf = [0u8; 3];
check!(f.read_exact(&mut buf));
assert_eq!(b"bar", &buf);
}

#[test]
fn test_dir_create_dir() {
let tmpdir = tmpdir();
let dir = check!(Dir::new(tmpdir.path()));
check!(dir.create_dir("foo"));
check!(Dir::new(tmpdir.join("foo")));
}
2 changes: 1 addition & 1 deletion library/std/src/sys/fs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub fn with_native_path<T>(path: &Path, f: &dyn Fn(&Path) -> io::Result<T>) -> i
}

pub use imp::{
DirBuilder, DirEntry, File, FileAttr, FilePermissions, FileTimes, FileType, OpenOptions,
Dir, DirBuilder, DirEntry, File, FileAttr, FilePermissions, FileTimes, FileType, OpenOptions,
ReadDir,
};

Expand Down
Loading
Loading