Skip to content
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
97 changes: 97 additions & 0 deletions library/std/src/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1546,6 +1546,8 @@ impl crate::io::IoHandle for File {}
impl Dir {
/// Attempts to open a directory at `path` in read-only mode.
///
/// This function opens a directory. To open a file instead, see [`File::open`].
///
/// # Errors
///
/// This function will return an error if `path` does not point to an existing directory.
Expand Down Expand Up @@ -1573,6 +1575,9 @@ impl Dir {

/// Attempts to open a file in read-only mode relative to this directory.
///
/// This function interprets `path` relative to the directory provided by `self`. To open a file
/// relative to the current working directory, or at an absolute path, see [`File::open`].
///
/// # Errors
///
/// This function will return an error if `path` does not point to an existing file.
Expand All @@ -1598,6 +1603,98 @@ impl Dir {
.open_file(path.as_ref(), &OpenOptions::new().read(true).0)
.map(|f| File { inner: f })
}

/// Attempts to open a file according to `opts` relative to this directory.
///
/// This function interprets `path` relative to the directory provided by `self`. To open a file
/// relative to the current working directory, or at an absolute path, see [`File::open`].
///
/// # Errors
///
/// This function will return an error if `path` does not point to an existing file.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::{fs::{Dir, OpenOptions}, io::{self, Write}};
///
/// fn main() -> io::Result<()> {
/// let dir = Dir::open("foo")?;
/// let mut opts = OpenOptions::new();
/// opts.read(true).write(true);
/// let mut f = dir.open_file_with("bar.txt", &opts)?;
/// f.write_all(b"Hello, world!")?;
/// let contents = io::read_to_string(f)?;
/// assert_eq!(contents, "Hello, world!");
/// Ok(())
/// }
/// ```
#[unstable(feature = "dirfd", issue = "120426")]
pub fn open_file_with<P: AsRef<Path>>(&self, path: P, opts: &OpenOptions) -> io::Result<File> {
self.inner.open_file(path.as_ref(), &opts.0).map(|f| File { inner: f })
}

/// Attempts to remove a file relative to this directory.
///
/// This function interprets `path` relative to the directory provided by `self`. To remove a file
/// relative to the current working directory, or at an absolute path, see [`fs::remove_file`][remove_file].
///
/// # Errors
///
/// This function will return an error if `path` does not point to an existing file.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::fs::Dir;
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::open("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.as_ref())
}

/// Attempts to rename a file or directory relative to this directory to a new name, replacing
/// the destination file if present.
///
/// This function interprets `from` relative to the directory provided by `self` and `to` relative to the directory
/// provided by `to_dir`. To rename a file relative to the current working directory, or at an absolute path, see [`fs::rename`][rename].
///
/// # Errors
///
/// This function will return an error if `from` does not point to an existing file or directory.
/// Other errors may also be returned according to [`OpenOptions::open`].
///
/// # Examples
///
/// ```no_run
/// #![feature(dirfd)]
/// use std::fs::Dir;
///
/// fn main() -> std::io::Result<()> {
/// let dir = Dir::open("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.as_ref(), &to_dir.inner, to.as_ref())
}
}

impl AsInner<fs_imp::Dir> for Dir {
Expand Down
51 changes: 49 additions & 2 deletions library/std/src/fs/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use rand::RngCore;

#[cfg(not(miri))]
use super::Dir;
#[cfg(not(miri))]
use crate::fs::exists;
use crate::fs::{self, File, FileTimes, OpenOptions, TryLockError};
#[cfg(not(miri))]
use crate::io;
Expand Down Expand Up @@ -2544,8 +2546,7 @@ fn test_dir_smoke_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());
check!(f.write_all(b"bar"));
drop(f);
let dir = check!(Dir::open(tmpdir.path()));
let f = check!(dir.open_file("foo.txt"));
Expand All @@ -2555,3 +2556,49 @@ fn test_dir_read_file() {
let buf = check!(io::read_to_string(f));
assert_eq!("bar", &buf);
}

#[test]
// FIXME: libc calls fail on miri
#[cfg(not(miri))]
fn test_dir_write_file() {
let tmpdir = tmpdir();
let dir = check!(Dir::open(tmpdir.path()));
let mut f = check!(dir.open_file_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]
// FIXME: libc calls fail on miri
#[cfg(not(miri))]
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::open(tmpdir.path()));
check!(dir.remove_file("foo.txt"));
assert!(!matches!(exists(tmpdir.join("foo.txt")), Ok(true)));
}

#[test]
// FIXME: libc calls fail on miri
#[cfg(not(miri))]
fn test_dir_rename_file() {
let tmpdir = tmpdir();
let mut f = check!(File::create(tmpdir.join("foo.txt")));
check!(f.write_all(b"bar"));
drop(f);
let dir = check!(Dir::open(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);
}
9 changes: 9 additions & 0 deletions library/std/src/sys/fs/common.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![allow(dead_code)] // not used on all platforms

use crate::fs::{remove_file, rename};
use crate::io::{self, Error, ErrorKind};
use crate::path::{Path, PathBuf};
use crate::sys::fs::{File, OpenOptions};
Expand Down Expand Up @@ -72,6 +73,14 @@ impl Dir {
pub fn open_file(&self, path: &Path, opts: &OpenOptions) -> io::Result<File> {
File::open(&self.path.join(path), &opts)
}

pub fn remove_file(&self, path: &Path) -> io::Result<()> {
remove_file(self.path.join(path))
}

pub fn rename(&self, from: &Path, to_dir: &Self, to: &Path) -> io::Result<()> {
rename(self.path.join(from), to_dir.path.join(to))
}
}

impl fmt::Debug for Dir {
Expand Down
32 changes: 30 additions & 2 deletions library/std/src/sys/fs/unix/dir.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use libc::c_int;
use libc::{c_int, renameat, unlinkat};

cfg_select! {
not(
Expand Down Expand Up @@ -27,7 +27,7 @@ use crate::sys::fd::FileDesc;
use crate::sys::fs::OpenOptions;
use crate::sys::fs::unix::{File, debug_path_fd};
use crate::sys::helpers::run_path_with_cstr;
use crate::sys::{AsInner, FromInner, IntoInner, cvt_r};
use crate::sys::{AsInner, FromInner, IntoInner, cvt, cvt_r};
use crate::{fmt, fs, io};

pub struct Dir(OwnedFd);
Expand All @@ -41,6 +41,16 @@ impl Dir {
run_path_with_cstr(path.as_ref(), &|path| self.open_file_c(path, &opts))
}

pub fn remove_file(&self, path: &Path) -> io::Result<()> {
run_path_with_cstr(path, &|path| self.remove_c(path, false))
}

pub fn rename(&self, from: &Path, to_dir: &Self, to: &Path) -> io::Result<()> {
run_path_with_cstr(from, &|from| {
run_path_with_cstr(to, &|to| self.rename_c(from, to_dir, to))
})
}

pub fn open_with_c(path: &CStr, opts: &OpenOptions) -> io::Result<Self> {
let flags = libc::O_CLOEXEC
| libc::O_DIRECTORY
Expand All @@ -61,6 +71,24 @@ impl Dir {
})?;
Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
}

fn remove_c(&self, path: &CStr, remove_dir: bool) -> io::Result<()> {
cvt(unsafe {
unlinkat(
self.0.as_raw_fd(),
path.as_ptr(),
if remove_dir { libc::AT_REMOVEDIR } else { 0 },
)
})
.map(|_| ())
}

fn rename_c(&self, from: &CStr, to_dir: &Self, to: &CStr) -> io::Result<()> {
cvt(unsafe {
renameat(self.0.as_raw_fd(), from.as_ptr(), to_dir.0.as_raw_fd(), to.as_ptr())
})
.map(|_| ())
}
}

impl fmt::Debug for Dir {
Expand Down
Loading
Loading