use std::{
fs,
io::{self, IoSlice, IoSliceMut},
path::{Path, PathBuf},
time::SystemTime,
};
use futures_lite::{
future::block_on,
io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt},
stream::StreamExt,
};
use super::api::{
Dirent, Metadata, OpenOptions, ReadStreamOptions, StatFs, WatchFileOptions, WatchOptions,
WriteStreamOptions,
};
pub(crate) use super::common::{
access_sync, app_dir, append_file_sync, append_text, copy_file_sync, cp_sync, create_dir,
create_dir_all, exists_sync, glob_to_regex, invalid_path_error, link_sync, lstat_sync,
metadata_parts, mkdir_sync, mkdtemp_disposable_sync, mkdtemp_sync, normalize_path, path_string,
read_dir, read_file_sync, read_text, readdir_sync, readlink_sync, realpath_sync, remove_file,
rename_sync, rm_sync, rmdir_sync, stat_sync, symlink_sync, truncate_sync, unlink_sync,
write_file_sync, write_text,
};
pub struct ReadStream {
file: async_fs::File,
chunk_size: usize,
remaining: Option<u64>,
}
pub fn create_read_stream(path: &str, options: ReadStreamOptions) -> io::Result<ReadStream> {
if options.chunk_size == 0 || options.chunk_size > u32::MAX as usize {
return Err(invalid_path_error(
"stream chunk size must be between 1 and u32::MAX",
));
}
if options.end.is_some_and(|end| end < options.start) {
return Err(invalid_path_error("stream end must not be before start"));
}
let mut file = async_fs::File::from(fs::File::open(path)?);
if options.start != 0 {
block_on(file.seek(io::SeekFrom::Start(options.start)))?;
}
Ok(ReadStream {
file,
chunk_size: options.chunk_size,
remaining: options
.end
.map(|end| end.saturating_sub(options.start).saturating_add(1)),
})
}
pub async fn stream_read(stream: &mut ReadStream) -> io::Result<Option<Vec<u8>>> {
let size = stream.remaining.map_or(stream.chunk_size, |remaining| {
stream
.chunk_size
.min(usize::try_from(remaining).unwrap_or(usize::MAX))
});
if size == 0 {
return Ok(None);
}
let mut bytes = vec![0; size];
let read = stream.file.read(&mut bytes).await?;
if read == 0 {
return Ok(None);
}
bytes.truncate(read);
if let Some(remaining) = &mut stream.remaining {
*remaining -= read as u64;
}
Ok(Some(bytes))
}
pub fn read_stream_destroy(_stream: &ReadStream) -> io::Result<()> {
Ok(())
}
pub struct WriteStream {
file: async_fs::File,
}
pub fn create_write_stream(path: &str, options: WriteStreamOptions) -> io::Result<WriteStream> {
let mut open = fs::OpenOptions::new();
open.write(true).create(true).truncate(true);
let mut file = async_fs::File::from(open.open(path)?);
if let Some(start) = options.start {
block_on(file.seek(io::SeekFrom::Start(start)))?;
}
Ok(WriteStream { file })
}
pub async fn stream_write(stream: &mut WriteStream, bytes: &[u8]) -> io::Result<()> {
stream.file.write_all(bytes).await
}
pub async fn stream_end(stream: &mut WriteStream) -> io::Result<()> {
stream.file.close().await
}
pub fn write_stream_destroy(_stream: &WriteStream) -> io::Result<()> {
Ok(())
}
pub struct Watcher(std::sync::Mutex<Option<notify::RecommendedWatcher>>);
type WatchListener = Box<dyn FnMut(&str, &str) + Send>;
pub fn watch(
path: &str,
options: WatchOptions,
mut listener: WatchListener,
) -> io::Result<Watcher> {
use notify::Watcher as _;
let watched = PathBuf::from(path);
let mut watcher = notify::recommended_watcher(move |event: notify::Result<notify::Event>| {
let Ok(event) = event else {
return;
};
let kind = match event.kind {
notify::EventKind::Create(_)
| notify::EventKind::Remove(_)
| notify::EventKind::Modify(notify::event::ModifyKind::Name(_)) => "rename",
notify::EventKind::Modify(_) => "change",
_ => return,
};
for changed in event.paths {
let name = changed
.file_name()
.and_then(|name| name.to_str())
.or_else(|| watched.file_name().and_then(|name| name.to_str()))
.unwrap_or("");
listener(kind, name);
}
})
.map_err(io::Error::other)?;
watcher
.watch(
Path::new(path),
if options.recursive {
notify::RecursiveMode::Recursive
} else {
notify::RecursiveMode::NonRecursive
},
)
.map_err(io::Error::other)?;
Ok(Watcher(std::sync::Mutex::new(Some(watcher))))
}
pub fn watch_close(watcher: &Watcher) -> io::Result<()> {
watcher
.0
.lock()
.map_err(|_| io::Error::other("watcher lock was poisoned"))?
.take();
Ok(())
}
struct FileWatch {
id: u64,
stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
thread: std::thread::Thread,
}
fn file_watches() -> &'static std::sync::Mutex<std::collections::HashMap<String, Vec<FileWatch>>> {
static WATCHES: std::sync::OnceLock<
std::sync::Mutex<std::collections::HashMap<String, Vec<FileWatch>>>,
> = std::sync::OnceLock::new();
WATCHES.get_or_init(Default::default)
}
fn watch_snapshot(path: &str) -> io::Result<Option<fs::Metadata>> {
match fs::metadata(path) {
Ok(metadata) => Ok(Some(metadata)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error),
}
}
fn watched_metadata(metadata: Option<&fs::Metadata>) -> Metadata {
metadata
.cloned()
.map(metadata_parts)
.unwrap_or_else(|| Metadata::from_parts(0, false, false, false))
}
fn snapshot_changed(before: Option<&fs::Metadata>, after: Option<&fs::Metadata>) -> bool {
match (before, after) {
(None, None) => false,
(Some(a), Some(b)) => {
a.len() != b.len()
|| a.modified().ok() != b.modified().ok()
|| a.accessed().ok() != b.accessed().ok()
|| a.permissions().readonly() != b.permissions().readonly()
}
_ => true,
}
}
pub fn watch_file(
path: &str,
options: WatchFileOptions,
mut listener: Box<dyn FnMut(Metadata, Metadata) + Send>,
) -> io::Result<u64> {
use std::sync::{
Arc,
atomic::{AtomicBool, AtomicU64, Ordering},
};
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
if options.interval.is_zero() {
return Err(invalid_path_error("watch interval must be positive"));
}
let mut before = watch_snapshot(path)?;
let stop = Arc::new(AtomicBool::new(false));
let cancel = Arc::clone(&stop);
let path_owned = path.to_owned();
let handle = std::thread::Builder::new()
.name("renfs-watch-file".to_owned())
.spawn(move || {
loop {
std::thread::park_timeout(options.interval);
if cancel.load(Ordering::Acquire) {
break;
}
let Ok(after) = watch_snapshot(&path_owned) else {
continue;
};
if snapshot_changed(before.as_ref(), after.as_ref()) {
listener(
watched_metadata(after.as_ref()),
watched_metadata(before.as_ref()),
);
}
before = after;
}
})?;
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let watch = FileWatch {
id,
stop,
thread: handle.thread().clone(),
};
file_watches()
.lock()
.map_err(|_| io::Error::other("file watcher lock was poisoned"))?
.entry(path.to_owned())
.or_default()
.push(watch);
Ok(id)
}
pub fn unwatch_file(path: &str, id: Option<u64>) -> io::Result<()> {
let mut watches = file_watches()
.lock()
.map_err(|_| io::Error::other("file watcher lock was poisoned"))?;
if let Some(list) = watches.get_mut(path) {
list.retain(|watch| {
if id.is_none_or(|id| id == watch.id) {
watch.stop.store(true, std::sync::atomic::Ordering::Release);
watch.thread.unpark();
false
} else {
true
}
});
if list.is_empty() {
watches.remove(path);
}
}
Ok(())
}
pub type File = async_fs::File;
pub type Dir = async_fs::ReadDir;
#[cfg(test)]
fn app_dir_in(base: &Path, name: &str) -> io::Result<String> {
let name_path = Path::new(name);
if name.contains('/')
|| name.contains('\\')
|| !matches!(
name_path.components().next(),
Some(std::path::Component::Normal(_))
)
|| name_path.components().count() != 1
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"application name must be a single path component",
));
}
let path = base.join(name_path);
fs::create_dir_all(&path)?;
path.into_os_string().into_string().map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
"application data directory path is not valid UTF-8",
)
})
}
pub async fn exists(path: &str) -> io::Result<bool> {
match async_fs::metadata(path).await {
Ok(_) => Ok(true),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error),
}
}
pub async fn access(path: &str, mode: u32) -> io::Result<()> {
super::common::check_access(&async_fs::metadata(path).await?, mode)
}
pub async fn append_file(path: &str, contents: &[u8]) -> io::Result<()> {
let mut options = async_fs::OpenOptions::new();
options.create(true).append(true);
options.open(path).await?.write_all(contents).await
}
pub async fn read_file(path: &str) -> io::Result<Vec<u8>> {
async_fs::read(path).await
}
pub async fn write_file(path: &str, contents: &[u8]) -> io::Result<()> {
async_fs::write(path, contents).await
}
pub async fn copy_file(from: &str, to: &str) -> io::Result<()> {
async_fs::copy(from, to).await.map(|_| ())
}
fn create_symlink(from: &Path, to: &Path) -> io::Result<()> {
let target = fs::read_link(from)?;
#[cfg(unix)]
{
std::os::unix::fs::symlink(target, to)
}
#[cfg(windows)]
{
if fs::metadata(from)?.is_dir() {
std::os::windows::fs::symlink_dir(target, to)
} else {
std::os::windows::fs::symlink_file(target, to)
}
}
#[cfg(not(any(unix, windows)))]
{
let _ = (target, to);
Err(io::Error::new(
io::ErrorKind::Unsupported,
"copying symbolic links is unsupported on this platform",
))
}
}
pub async fn cp(from: &str, to: &str) -> io::Result<()> {
let mut pending = vec![(PathBuf::from(from), PathBuf::from(to))];
let mut directory_permissions = Vec::new();
while let Some((source, destination)) = pending.pop() {
let metadata = async_fs::symlink_metadata(&source).await?;
if metadata.is_dir() {
async_fs::create_dir_all(&destination).await?;
let mut entries = async_fs::read_dir(&source).await?;
while let Some(entry) = entries.next().await {
let entry = entry?;
pending.push((entry.path(), destination.join(entry.file_name())));
}
directory_permissions.push((destination, metadata.permissions()));
} else if metadata.file_type().is_symlink() {
create_symlink(&source, &destination)?;
} else if metadata.is_file() {
async_fs::copy(&source, &destination).await?;
} else {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"copying this filesystem entry type is unsupported",
));
}
}
for (path, permissions) in directory_permissions.into_iter().rev() {
async_fs::set_permissions(path, permissions).await?;
}
Ok(())
}
pub fn open_sync(path: &str, options: &OpenOptions) -> io::Result<File> {
let mut open_options = fs::OpenOptions::new();
open_options
.read(options.read)
.write(options.write)
.append(options.append)
.truncate(options.truncate)
.create(options.create)
.create_new(options.create_new);
open_options.open(path).map(File::from)
}
pub async fn open(path: &str, options: &OpenOptions) -> io::Result<File> {
let mut open_options = async_fs::OpenOptions::new();
open_options
.read(options.read)
.write(options.write)
.append(options.append)
.truncate(options.truncate)
.create(options.create)
.create_new(options.create_new);
open_options.open(path).await
}
pub async fn open_as_blob(path: &str) -> io::Result<Vec<u8>> {
async_fs::read(path).await
}
pub fn close_sync(file: File) -> io::Result<()> {
drop(file);
Ok(())
}
pub async fn close(file: &mut File) -> io::Result<()> {
file.close().await
}
pub fn read_sync(file: &mut File, buffer: &mut [u8]) -> io::Result<usize> {
block_on(AsyncReadExt::read(file, buffer))
}
pub async fn read(file: &mut File, buffer: &mut [u8]) -> io::Result<usize> {
file.read(buffer).await
}
pub fn write_sync(file: &mut File, buffer: &[u8]) -> io::Result<usize> {
block_on(AsyncWriteExt::write(file, buffer))
}
pub async fn write(file: &mut File, buffer: &[u8]) -> io::Result<usize> {
file.write(buffer).await
}
pub fn readv_sync(file: &mut File, buffers: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
block_on(async {
let mut read = 0;
for buffer in buffers {
if buffer.is_empty() {
continue;
}
let count = file.read(&mut buffer[..]).await?;
read += count;
if count < buffer.len() {
break;
}
}
Ok(read)
})
}
pub async fn readv(file: &mut File, buffers: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
let mut read = 0;
for buffer in buffers {
if buffer.is_empty() {
continue;
}
let count = file.read(&mut buffer[..]).await?;
read += count;
if count < buffer.len() {
break;
}
}
Ok(read)
}
pub fn writev_sync(file: &mut File, buffers: &[IoSlice<'_>]) -> io::Result<usize> {
block_on(async {
let mut written = 0;
for buffer in buffers {
if buffer.is_empty() {
continue;
}
let count = file.write(buffer).await?;
written += count;
if count < buffer.len() {
break;
}
}
Ok(written)
})
}
pub async fn writev(file: &mut File, buffers: &[IoSlice<'_>]) -> io::Result<usize> {
let mut written = 0;
for buffer in buffers {
if buffer.is_empty() {
continue;
}
let count = file.write(buffer).await?;
written += count;
if count < buffer.len() {
break;
}
}
Ok(written)
}
pub fn fstat_sync(file: &File) -> io::Result<Metadata> {
let metadata = block_on(file.metadata())?;
Ok(metadata_parts(metadata))
}
pub async fn fstat(file: &File) -> io::Result<Metadata> {
Ok(metadata_parts(file.metadata().await?))
}
pub async fn stat(path: &str) -> io::Result<Metadata> {
async_fs::metadata(path).await.map(metadata_parts)
}
pub async fn lstat(path: &str) -> io::Result<Metadata> {
async_fs::symlink_metadata(path).await.map(metadata_parts)
}
#[cfg(unix)]
fn c_path(path: &str) -> io::Result<std::ffi::CString> {
std::ffi::CString::new(path.as_bytes())
.map_err(|_| invalid_path_error("path contains a NUL byte"))
}
#[cfg(unix)]
pub fn statfs_sync(path: &str) -> io::Result<StatFs> {
let path = c_path(path)?;
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(path.as_ptr(), &mut stat) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(StatFs {
block_size: stat.f_bsize as u64,
blocks: stat.f_blocks as f64,
blocks_free: stat.f_bfree as f64,
blocks_available: stat.f_bavail as f64,
files: stat.f_files as f64,
files_free: stat.f_ffree as f64,
})
}
#[cfg(not(unix))]
pub fn statfs_sync(_path: &str) -> io::Result<StatFs> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"statfs is unsupported on this platform",
))
}
pub async fn statfs(path: &str) -> io::Result<StatFs> {
statfs_sync(path)
}
#[cfg(unix)]
fn permissions(mode: u32) -> fs::Permissions {
use std::os::unix::fs::PermissionsExt;
fs::Permissions::from_mode(mode)
}
#[cfg(not(unix))]
fn permissions(mode: u32, mut permissions: fs::Permissions) -> fs::Permissions {
permissions.set_readonly(mode & 0o222 == 0);
permissions
}
pub fn chmod_sync(path: &str, mode: u32) -> io::Result<()> {
#[cfg(unix)]
{
fs::set_permissions(path, permissions(mode))
}
#[cfg(not(unix))]
{
let permissions = permissions(mode, fs::metadata(path)?.permissions());
fs::set_permissions(path, permissions)
}
}
pub async fn chmod(path: &str, mode: u32) -> io::Result<()> {
#[cfg(unix)]
{
async_fs::set_permissions(path, permissions(mode)).await
}
#[cfg(not(unix))]
{
let current = async_fs::metadata(path).await?.permissions();
async_fs::set_permissions(path, permissions(mode, current)).await
}
}
pub fn fchmod_sync(file: &File, mode: u32) -> io::Result<()> {
#[cfg(unix)]
{
block_on(file.set_permissions(permissions(mode)))
}
#[cfg(not(unix))]
{
let current = block_on(file.metadata())?.permissions();
block_on(file.set_permissions(permissions(mode, current)))
}
}
pub async fn fchmod(file: &File, mode: u32) -> io::Result<()> {
#[cfg(unix)]
{
file.set_permissions(permissions(mode)).await
}
#[cfg(not(unix))]
{
let current = file.metadata().await?.permissions();
file.set_permissions(permissions(mode, current)).await
}
}
#[cfg(unix)]
pub fn lchmod_sync(path: &str, mode: u32) -> io::Result<()> {
let path = c_path(path)?;
if unsafe {
libc::fchmodat(
libc::AT_FDCWD,
path.as_ptr(),
mode as libc::mode_t,
libc::AT_SYMLINK_NOFOLLOW,
)
} == 0
{
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(unix))]
pub fn lchmod_sync(_path: &str, _mode: u32) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"lchmod is unsupported on this platform",
))
}
pub async fn lchmod(path: &str, mode: u32) -> io::Result<()> {
lchmod_sync(path, mode)
}
#[cfg(unix)]
fn set_owner(path: &str, uid: u32, gid: u32, flags: libc::c_int) -> io::Result<()> {
let path = c_path(path)?;
if unsafe { libc::fchownat(libc::AT_FDCWD, path.as_ptr(), uid, gid, flags) } == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(unix)]
pub fn chown_sync(path: &str, uid: u32, gid: u32) -> io::Result<()> {
set_owner(path, uid, gid, 0)
}
#[cfg(unix)]
pub fn lchown_sync(path: &str, uid: u32, gid: u32) -> io::Result<()> {
set_owner(path, uid, gid, libc::AT_SYMLINK_NOFOLLOW)
}
#[cfg(not(unix))]
pub fn chown_sync(_path: &str, _uid: u32, _gid: u32) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"chown is unsupported on this platform",
))
}
#[cfg(not(unix))]
pub fn lchown_sync(_path: &str, _uid: u32, _gid: u32) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"lchown is unsupported on this platform",
))
}
pub async fn chown(path: &str, uid: u32, gid: u32) -> io::Result<()> {
chown_sync(path, uid, gid)
}
pub async fn lchown(path: &str, uid: u32, gid: u32) -> io::Result<()> {
lchown_sync(path, uid, gid)
}
#[cfg(unix)]
pub fn fchown_sync(file: &File, uid: u32, gid: u32) -> io::Result<()> {
use std::os::fd::AsRawFd;
if unsafe { libc::fchown(file.as_raw_fd(), uid, gid) } == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(unix))]
pub fn fchown_sync(_file: &File, _uid: u32, _gid: u32) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"fchown is unsupported on this platform",
))
}
pub async fn fchown(file: &File, uid: u32, gid: u32) -> io::Result<()> {
fchown_sync(file, uid, gid)
}
fn file_times(atime: SystemTime, mtime: SystemTime) -> (filetime::FileTime, filetime::FileTime) {
(
filetime::FileTime::from_system_time(atime),
filetime::FileTime::from_system_time(mtime),
)
}
pub fn utimes_sync(path: &str, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
let (atime, mtime) = file_times(atime, mtime);
filetime::set_file_times(path, atime, mtime)
}
pub async fn utimes(path: &str, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
utimes_sync(path, atime, mtime)
}
pub fn lutimes_sync(path: &str, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
let (atime, mtime) = file_times(atime, mtime);
filetime::set_symlink_file_times(path, atime, mtime)
}
pub async fn lutimes(path: &str, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
lutimes_sync(path, atime, mtime)
}
#[cfg(unix)]
pub fn futimes_sync(file: &File, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
use std::os::fd::AsRawFd;
let (atime, mtime) = file_times(atime, mtime);
let times = [
libc::timespec {
tv_sec: atime.unix_seconds() as _,
tv_nsec: atime.nanoseconds() as _,
},
libc::timespec {
tv_sec: mtime.unix_seconds() as _,
tv_nsec: mtime.nanoseconds() as _,
},
];
if unsafe { libc::futimens(file.as_raw_fd(), times.as_ptr()) } == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(not(unix))]
pub fn futimes_sync(_file: &File, _atime: SystemTime, _mtime: SystemTime) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"futimes is unsupported on this platform",
))
}
pub async fn futimes(file: &File, atime: SystemTime, mtime: SystemTime) -> io::Result<()> {
futimes_sync(file, atime, mtime)
}
pub fn fsync_sync(file: &File) -> io::Result<()> {
block_on(file.sync_all())
}
pub async fn fsync(file: &File) -> io::Result<()> {
file.sync_all().await
}
pub fn fdatasync_sync(file: &File) -> io::Result<()> {
block_on(file.sync_data())
}
pub async fn fdatasync(file: &File) -> io::Result<()> {
file.sync_data().await
}
pub fn ftruncate_sync(file: &File, size: u64) -> io::Result<()> {
block_on(file.set_len(size))
}
pub async fn ftruncate(file: &File, size: u64) -> io::Result<()> {
file.set_len(size).await
}
pub async fn truncate(path: &str, len: u64) -> io::Result<()> {
let mut options = async_fs::OpenOptions::new();
options.write(true);
options.open(path).await?.set_len(len).await
}
pub async fn mkdir(path: &str, recursive: bool) -> io::Result<()> {
if recursive {
async_fs::create_dir_all(path).await
} else {
async_fs::create_dir(path).await
}
}
pub async fn mkdtemp(prefix: &str) -> io::Result<String> {
mkdtemp_sync(prefix)
}
pub async fn readdir(path: &str) -> io::Result<Vec<String>> {
let mut entries = async_fs::read_dir(path).await?;
let mut names = Vec::new();
while let Some(entry) = entries.next().await {
names.push(entry?.file_name().into_string().map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
"directory entry name is not valid UTF-8",
)
})?);
}
Ok(names)
}
pub fn opendir_sync(path: &str) -> io::Result<super::api::Dir> {
block_on(async_fs::read_dir(path)).map(super::api::Dir::from_inner)
}
pub async fn opendir(path: &str) -> io::Result<super::api::Dir> {
async_fs::read_dir(path)
.await
.map(super::api::Dir::from_inner)
}
async fn dirent(entry: async_fs::DirEntry) -> io::Result<Dirent> {
let name = entry.file_name().into_string().map_err(|_| {
io::Error::new(
io::ErrorKind::InvalidData,
"directory entry name is not valid UTF-8",
)
})?;
let kind = entry.file_type().await?;
Ok(Dirent::from_parts(
name,
kind.is_file(),
kind.is_dir(),
kind.is_symlink(),
))
}
pub fn dir_read_sync(dir: &mut Dir) -> io::Result<Option<Dirent>> {
block_on(dir_read(dir))
}
pub async fn dir_read(dir: &mut Dir) -> io::Result<Option<Dirent>> {
match dir.next().await.transpose()? {
Some(entry) => dirent(entry).await.map(Some),
None => Ok(None),
}
}
pub fn dir_close_sync(_dir: &Dir) -> io::Result<()> {
Ok(())
}
pub async fn dir_close(_dir: &Dir) -> io::Result<()> {
Ok(())
}
pub async fn rmdir(path: &str) -> io::Result<()> {
async_fs::remove_dir(path).await
}
pub async fn rm(path: &str, recursive: bool, force: bool) -> io::Result<()> {
let result = match async_fs::symlink_metadata(path).await {
Ok(metadata) if metadata.is_dir() => {
if recursive {
async_fs::remove_dir_all(path).await
} else {
async_fs::remove_dir(path).await
}
}
Ok(_) => async_fs::remove_file(path).await,
Err(error) => Err(error),
};
if force
&& result
.as_ref()
.is_err_and(|error| error.kind() == io::ErrorKind::NotFound)
{
Ok(())
} else {
result
}
}
pub async fn realpath(path: &str) -> io::Result<String> {
path_string(async_fs::canonicalize(path).await?)
}
pub fn glob_sync(pattern: &str) -> io::Result<Vec<String>> {
glob::glob(pattern)
.map_err(|error| invalid_path_error(&error.to_string()))?
.map(|entry| {
let path = path_string(entry.map_err(io::Error::other)?)?;
Ok(if Path::new(pattern).is_absolute() {
path.trim_start_matches('/').to_owned()
} else {
path
})
})
.collect()
}
pub async fn glob(pattern: &str) -> io::Result<Vec<String>> {
glob_sync(pattern)
}
pub async fn rename(from: &str, to: &str) -> io::Result<()> {
async_fs::rename(from, to).await
}
pub async fn link(original: &str, link: &str) -> io::Result<()> {
async_fs::hard_link(original, link).await
}
pub async fn symlink(target: &str, link: &str) -> io::Result<()> {
symlink_sync(target, link)
}
pub async fn readlink(path: &str) -> io::Result<String> {
path_string(async_fs::read_link(path).await?)
}
pub async fn unlink(path: &str) -> io::Result<()> {
async_fs::remove_file(path).await
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn app_dir_creates_a_named_directory_under_the_data_directory() {
let temp = tempdir().unwrap();
let path = app_dir_in(temp.path(), "example-app").unwrap();
assert_eq!(path, temp.path().join("example-app").to_str().unwrap());
assert!(Path::new(&path).is_dir());
}
#[test]
fn app_dir_rejects_path_components() {
let temp = tempdir().unwrap();
assert_eq!(
app_dir_in(temp.path(), "../outside").unwrap_err().kind(),
io::ErrorKind::InvalidInput
);
assert_eq!(
app_dir_in(temp.path(), "").unwrap_err().kind(),
io::ErrorKind::InvalidInput
);
}
}
#[cfg(test)]
#[path = "implementation_tests.rs"]
mod shared_tests;