use std::path::{Component, Path, PathBuf};
use super::implementation;
#[cfg(not(target_arch = "wasm32"))]
pub type Error = std::io::Error;
#[cfg(target_arch = "wasm32")]
#[derive(Debug)]
pub struct Error(wasm_bindgen::JsValue);
#[cfg(target_arch = "wasm32")]
impl From<wasm_bindgen::JsValue> for Error {
fn from(value: wasm_bindgen::JsValue) -> Self {
Self(value)
}
}
#[cfg(target_arch = "wasm32")]
impl std::fmt::Display for Error {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(message) = self.0.as_string() {
formatter.write_str(&message)
} else {
write!(formatter, "filesystem backend error: {:?}", self.0)
}
}
}
#[cfg(target_arch = "wasm32")]
impl std::error::Error for Error {}
#[cfg(target_arch = "wasm32")]
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Self(wasm_bindgen::JsValue::from_str(&error.to_string()))
}
}
pub type Result<T> = std::result::Result<T, Error>;
fn invalid_path_error(message: &str) -> Error {
#[cfg(not(target_arch = "wasm32"))]
{
implementation::invalid_path_error(message)
}
#[cfg(target_arch = "wasm32")]
{
implementation::invalid_path_error(message).into()
}
}
macro_rules! implementation_result {
($operation:expr) => {{
#[cfg(not(target_arch = "wasm32"))]
{
$operation
}
#[cfg(target_arch = "wasm32")]
{
$operation.map_err(Into::into)
}
}};
}
macro_rules! define_resource_handle {
($(#[$documentation:meta])* $name:ident($inner:ty) {
from_inner $visibility:vis,
drop $drop:expr;
}) => {
$(#[$documentation])*
pub struct $name {
inner: Option<$inner>,
}
impl std::fmt::Debug for $name {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct(stringify!($name)).finish_non_exhaustive()
}
}
impl $name {
$visibility fn from_inner(inner: $inner) -> Self {
Self { inner: Some(inner) }
}
}
impl Drop for $name {
fn drop(&mut self) {
if let Some(inner) = self.inner.take() {
let _ = ($drop)(inner);
}
}
}
};
}
macro_rules! define_bool_accessors {
($($(#[$documentation:meta])* $field:ident;)*) => {
$(
$(#[$documentation])*
pub fn $field(&self) -> bool {
self.$field
}
)*
};
}
macro_rules! define_bool_option_setters {
($($(#[$documentation:meta])* $field:ident;)*) => {
$(
$(#[$documentation])*
pub fn $field(&mut self, $field: bool) -> &mut Self {
self.$field = $field;
self
}
)*
};
}
macro_rules! define_wasm_sync_wrappers {
($($(#[$documentation:meta])* $name:ident($($argument:ident: $argument_type:ty),*) -> $output:ty = $implementation:ident;)*) => {
$(
#[cfg(target_arch = "wasm32")]
$(#[$documentation])*
pub fn $name($($argument: $argument_type),*) -> Result<$output> {
implementation_result!(crate::wasm_api::$implementation($($argument),*))
}
)*
};
}
macro_rules! define_wasm_async_wrappers {
($($(#[$documentation:meta])* $name:ident($($argument:ident: $argument_type:ty),*) -> $output:ty = $implementation:ident;)*) => {
$(
#[cfg(target_arch = "wasm32")]
$(#[$documentation])*
pub async fn $name($($argument: $argument_type),*) -> Result<$output> {
implementation_result!(crate::wasm_api::$implementation($($argument),*).await)
}
)*
};
}
macro_rules! define_wasm_value_wrappers {
($($(#[$documentation:meta])* $name:ident() -> $output:ty = $implementation:ident;)*) => {
$(
#[cfg(target_arch = "wasm32")]
$(#[$documentation])*
pub fn $name() -> $output {
crate::wasm_api::$implementation()
}
)*
};
}
macro_rules! define_file_handle_api {
($( $(#[$documentation:meta])* $operation:ident => $sync_operation:ident
($($argument:ident: $argument_type:ty),*) -> $output:ty {
async { $async_body:expr }
sync { $sync_body:expr }
}; )*) => {
$(
$(#[$documentation])*
pub async fn $operation($($argument: $argument_type),*) -> Result<$output> {
$async_body.await
}
$(#[$documentation])*
#[doc = ""]
#[doc = concat!("Synchronously performs `", stringify!($operation), "`.")]
pub fn $sync_operation($($argument: $argument_type),*) -> Result<$output> {
$sync_body
}
)*
};
}
macro_rules! define_file_methods {
(
async_mutable {
$( $(#[$async_documentation:meta])* $async_method:ident($($async_argument:ident: $async_argument_type:ty),*) -> $async_output:ty = $async_implementation:ident; )*
}
sync_mutable {
$( $(#[$sync_documentation:meta])* $sync_method:ident($($sync_argument:ident: $sync_argument_type:ty),*) -> $sync_output:ty = $sync_implementation:ident; )*
}
async_shared {
$( $(#[$async_shared_documentation:meta])* $async_shared_method:ident($($async_shared_argument:ident: $async_shared_argument_type:ty),*) -> $async_shared_output:ty = $async_shared_implementation:ident; )*
}
sync_shared {
$( $(#[$sync_shared_documentation:meta])* $sync_shared_method:ident($($sync_shared_argument:ident: $sync_shared_argument_type:ty),*) -> $sync_shared_output:ty = $sync_shared_implementation:ident; )*
}
) => {
$(
$(#[$async_documentation])*
pub async fn $async_method(&mut self, $($async_argument: $async_argument_type),*) -> Result<$async_output> {
implementation_result!(implementation::$async_implementation(self.inner_mut()? $(, $async_argument)*).await)
}
)*
$(
#[doc = concat!("Synchronous filesystem operation `", stringify!($sync_method), "`.")]
$(#[$sync_documentation])*
pub fn $sync_method(&mut self, $($sync_argument: $sync_argument_type),*) -> Result<$sync_output> {
implementation_result!(implementation::$sync_implementation(self.inner_mut()? $(, $sync_argument)*))
}
)*
$(
$(#[$async_shared_documentation])*
pub async fn $async_shared_method(&self, $($async_shared_argument: $async_shared_argument_type),*) -> Result<$async_shared_output> {
let inner = self.inner.as_ref().ok_or_else(|| {
invalid_path_error("operation attempted on a closed file")
})?;
implementation_result!(implementation::$async_shared_implementation(inner $(, $async_shared_argument)*).await)
}
)*
$(
#[doc = concat!("Synchronous filesystem operation `", stringify!($sync_shared_method), "`.")]
$(#[$sync_shared_documentation])*
pub fn $sync_shared_method(&self, $($sync_shared_argument: $sync_shared_argument_type),*) -> Result<$sync_shared_output> {
let inner = self.inner.as_ref().ok_or_else(|| {
invalid_path_error("operation attempted on a closed file")
})?;
implementation_result!(implementation::$sync_shared_implementation(inner $(, $sync_shared_argument)*))
}
)*
};
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Directory {
path: String,
}
define_resource_handle! {
Dir(implementation::Dir) {
from_inner pub(crate),
drop |inner| implementation::dir_close_sync(&inner);
}
}
impl Dir {
pub fn read_sync(&mut self) -> Result<Option<Dirent>> {
let inner = self
.inner
.as_mut()
.ok_or_else(|| invalid_path_error("directory is closed"))?;
implementation_result!(implementation::dir_read_sync(inner))
}
pub async fn read(&mut self) -> Result<Option<Dirent>> {
let inner = self
.inner
.as_mut()
.ok_or_else(|| invalid_path_error("directory is closed"))?;
implementation_result!(implementation::dir_read(inner).await)
}
pub fn close_sync(&mut self) -> Result<()> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| invalid_path_error("directory is closed"))?;
implementation::dir_close_sync(inner)?;
self.inner.take();
Ok(())
}
pub async fn close(&mut self) -> Result<()> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| invalid_path_error("directory is closed"))?;
implementation::dir_close(inner).await?;
self.inner.take();
Ok(())
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Dirent {
name: String,
is_file: bool,
is_dir: bool,
is_symlink: bool,
}
impl Dirent {
pub(crate) fn from_parts(name: String, is_file: bool, is_dir: bool, is_symlink: bool) -> Self {
Self {
name,
is_file,
is_dir,
is_symlink,
}
}
pub fn name(&self) -> &str {
&self.name
}
define_bool_accessors! {
is_file;
is_dir;
is_symlink;
}
}
define_resource_handle! {
Watcher(implementation::Watcher) {
from_inner,
drop |inner| implementation::watch_close(&inner);
}
}
impl Watcher {
pub fn close(&mut self) -> Result<()> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| invalid_path_error("watcher is closed"))?;
implementation::watch_close(inner)?;
self.inner.take();
Ok(())
}
}
#[derive(Clone, Copy, Debug)]
pub struct WatchOptions {
pub recursive: bool,
pub persistent: bool,
}
impl Default for WatchOptions {
fn default() -> Self {
Self {
recursive: false,
persistent: true,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct WatchFileOptions {
pub interval: std::time::Duration,
pub persistent: bool,
}
#[derive(Clone, Copy, Debug)]
pub struct ReadStreamOptions {
pub start: u64,
pub end: Option<u64>,
pub chunk_size: usize,
}
impl Default for ReadStreamOptions {
fn default() -> Self {
Self {
start: 0,
end: None,
chunk_size: 64 * 1024,
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct WriteStreamOptions {
pub start: Option<u64>,
}
define_resource_handle! {
ReadStream(implementation::ReadStream) {
from_inner,
drop |inner| implementation::read_stream_destroy(&inner);
}
}
impl ReadStream {
pub async fn read(&mut self) -> Result<Option<Vec<u8>>> {
let inner = self
.inner
.as_mut()
.ok_or_else(|| invalid_path_error("read stream is destroyed"))?;
implementation_result!(implementation::stream_read(inner).await)
}
pub fn destroy(&mut self) -> Result<()> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| invalid_path_error("read stream is destroyed"))?;
implementation::read_stream_destroy(inner)?;
self.inner.take();
Ok(())
}
}
define_resource_handle! {
WriteStream(implementation::WriteStream) {
from_inner,
drop |inner| implementation::write_stream_destroy(&inner);
}
}
impl WriteStream {
pub async fn write(&mut self, bytes: &[u8]) -> Result<()> {
let inner = self
.inner
.as_mut()
.ok_or_else(|| invalid_path_error("write stream is closed"))?;
implementation_result!(implementation::stream_write(inner, bytes).await)
}
pub async fn end(&mut self) -> Result<()> {
let inner = self
.inner
.as_mut()
.ok_or_else(|| invalid_path_error("write stream is closed"))?;
implementation::stream_end(inner).await?;
self.inner.take();
Ok(())
}
pub fn destroy(&mut self) -> Result<()> {
let inner = self
.inner
.as_ref()
.ok_or_else(|| invalid_path_error("write stream is closed"))?;
implementation::write_stream_destroy(inner)?;
self.inner.take();
Ok(())
}
}
impl Default for WatchFileOptions {
fn default() -> Self {
Self {
interval: std::time::Duration::from_millis(5007),
persistent: true,
}
}
}
#[derive(Debug)]
pub struct TempDir {
pub(crate) path: String,
}
impl TempDir {
pub fn path(&self) -> &str {
&self.path
}
pub fn keep(mut self) -> String {
std::mem::take(&mut self.path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
if !self.path.is_empty() {
let _ = implementation::rm_sync(&self.path, true, true);
}
}
}
impl Directory {
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref().to_str().ok_or_else(|| {
implementation::invalid_path_error("directory path is not valid UTF-8")
})?;
Ok(Self {
path: path.to_owned(),
})
}
pub fn as_path(&self) -> &str {
&self.path
}
fn resolve(&self, relative_path: &str) -> Result<String> {
let relative = Path::new(relative_path);
if relative_path.contains('\\')
|| relative.is_absolute()
|| relative.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
})
{
return Err(invalid_path_error(
"directory operations require a relative path that stays inside the directory",
));
}
let path = PathBuf::from(&self.path).join(relative);
path.to_str()
.map(str::to_owned)
.ok_or_else(|| invalid_path_error("resolved path is not valid UTF-8"))
}
fn symlink_paths(&self, target: &str, link: &str) -> Result<(String, String)> {
let link = self.resolve(link)?;
let relative_link = Path::new(link.as_str());
let root = Path::new(&self.path);
let mut depth = relative_link
.strip_prefix(root)
.map_err(|_| invalid_path_error("link is outside the directory"))?
.parent()
.map_or(0, |parent| {
parent
.components()
.filter(|c| matches!(c, Component::Normal(_)))
.count()
});
if target.contains('\\') || Path::new(target).is_absolute() {
return Err(invalid_path_error(
"symbolic link target must stay inside the directory",
));
}
for component in Path::new(target).components() {
match component {
Component::Normal(_) => depth += 1,
Component::ParentDir if depth > 0 => depth -= 1,
Component::CurDir => (),
_ => {
return Err(invalid_path_error(
"symbolic link target must stay inside the directory",
));
}
}
}
Ok((target.to_owned(), link))
}
pub fn symlink_sync(&self, target: &str, link: &str) -> Result<()> {
let (target, link) = self.symlink_paths(target, link)?;
implementation_result!(implementation::symlink_sync(&target, &link))
}
pub async fn symlink(&self, target: &str, link: &str) -> Result<()> {
let (target, link) = self.symlink_paths(target, link)?;
implementation_result!(implementation::symlink(&target, &link).await)
}
pub fn watch(
&self,
path: &str,
listener: impl FnMut(&str, &str) + Send + 'static,
) -> Result<Watcher> {
self.watch_with_options(path, WatchOptions::default(), listener)
}
pub fn watch_with_options(
&self,
path: &str,
options: WatchOptions,
listener: impl FnMut(&str, &str) + Send + 'static,
) -> Result<Watcher> {
fs::watch_with_options(&self.resolve(path)?, options, listener)
}
pub fn watch_file(
&self,
path: &str,
listener: impl FnMut(Metadata, Metadata) + Send + 'static,
) -> Result<u64> {
self.watch_file_with_options(path, WatchFileOptions::default(), listener)
}
pub fn watch_file_with_options(
&self,
path: &str,
options: WatchFileOptions,
listener: impl FnMut(Metadata, Metadata) + Send + 'static,
) -> Result<u64> {
fs::watch_file_with_options(&self.resolve(path)?, options, listener)
}
pub fn unwatch_file(&self, path: &str) -> Result<()> {
fs::unwatch_file(&self.resolve(path)?)
}
pub fn unwatch_file_listener(&self, path: &str, id: u64) -> Result<()> {
fs::unwatch_file_listener(&self.resolve(path)?, id)
}
pub fn create_read_stream(&self, path: &str) -> Result<ReadStream> {
self.create_read_stream_with_options(path, ReadStreamOptions::default())
}
pub fn create_read_stream_with_options(
&self,
path: &str,
options: ReadStreamOptions,
) -> Result<ReadStream> {
fs::create_read_stream_with_options(&self.resolve(path)?, options)
}
pub fn create_write_stream(&self, path: &str) -> Result<WriteStream> {
self.create_write_stream_with_options(path, WriteStreamOptions::default())
}
pub fn create_write_stream_with_options(
&self,
path: &str,
options: WriteStreamOptions,
) -> Result<WriteStream> {
fs::create_write_stream_with_options(&self.resolve(path)?, options)
}
}
struct RootFileSystem;
#[derive(Clone, Debug, Default)]
pub struct OpenOptions {
pub(crate) read: bool,
pub(crate) write: bool,
pub(crate) append: bool,
pub(crate) truncate: bool,
pub(crate) create: bool,
pub(crate) create_new: bool,
}
impl OpenOptions {
pub fn new() -> Self {
Self::default()
}
define_bool_option_setters! {
read;
write;
append;
truncate;
create;
create_new;
}
}
define_resource_handle! {
File(implementation::File) {
from_inner,
drop implementation::close_sync;
}
}
impl File {
fn inner_mut(&mut self) -> Result<&mut implementation::File> {
self.inner
.as_mut()
.ok_or_else(|| invalid_path_error("operation attempted on a closed file"))
}
fn take_inner(&mut self) -> Result<implementation::File> {
self.inner
.take()
.ok_or_else(|| invalid_path_error("operation attempted on a closed file"))
}
define_file_methods! {
async_mutable {
read(buffer: &mut [u8]) -> usize = read;
write(buffer: &[u8]) -> usize = write;
read_vectored(buffers: &mut [std::io::IoSliceMut<'_>]) -> usize = readv;
write_vectored(buffers: &[std::io::IoSlice<'_>]) -> usize = writev;
sync_all() -> () = fsync;
sync_data() -> () = fdatasync;
set_len(size: u64) -> () = ftruncate;
}
sync_mutable {
read_sync(buffer: &mut [u8]) -> usize = read_sync;
write_sync(buffer: &[u8]) -> usize = write_sync;
read_vectored_sync(buffers: &mut [std::io::IoSliceMut<'_>]) -> usize = readv_sync;
write_vectored_sync(buffers: &[std::io::IoSlice<'_>]) -> usize = writev_sync;
sync_all_sync() -> () = fsync_sync;
sync_data_sync() -> () = fdatasync_sync;
set_len_sync(size: u64) -> () = ftruncate_sync;
}
async_shared {
metadata() -> Metadata = fstat;
fchmod(mode: u32) -> () = fchmod;
fchown(uid: u32, gid: u32) -> () = fchown;
futimes(atime: std::time::SystemTime, mtime: std::time::SystemTime) -> () = futimes;
}
sync_shared {
metadata_sync() -> Metadata = fstat_sync;
fchmod_sync(mode: u32) -> () = fchmod_sync;
fchown_sync(uid: u32, gid: u32) -> () = fchown_sync;
futimes_sync(atime: std::time::SystemTime, mtime: std::time::SystemTime) -> () = futimes_sync;
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Metadata {
len: u64,
is_file: bool,
is_dir: bool,
is_symlink: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub struct StatFs {
pub block_size: u64,
pub blocks: f64,
pub blocks_free: f64,
pub blocks_available: f64,
pub files: f64,
pub files_free: f64,
}
impl Metadata {
pub(crate) fn from_parts(len: u64, is_file: bool, is_dir: bool, is_symlink: bool) -> Self {
Self {
len,
is_file,
is_dir,
is_symlink,
}
}
pub fn len(&self) -> u64 {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
define_bool_accessors! {
is_file;
is_dir;
is_symlink;
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Blob {
bytes: Vec<u8>,
}
impl Blob {
fn new(bytes: Vec<u8>) -> Self {
Self { bytes }
}
pub fn size(&self) -> usize {
self.bytes.len()
}
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
pub fn into_bytes(self) -> Vec<u8> {
self.bytes
}
}
macro_rules! define_file_api {
(
operations {
$( $(#[$documentation:meta])* $operation:ident([$($path:ident),+ $(,)?] $(, $arg:ident : $arg_type:ty)* $(,)?) -> $output:ty; )*
}
async_operations {
$( $(#[$async_documentation:meta])* $operation_async:ident([$($async_path:ident),+ $(,)?] $(, $async_arg:ident : $async_arg_type:ty)* $(,)?) -> $async_output:ty => $sync_operation:ident; )*
}
) => {
#[allow(async_fn_in_trait)]
pub trait FileOps {
fn resolve_path(&self, path: &str) -> Result<String>;
async fn open(&self, path: &str, options: &OpenOptions) -> Result<File> {
let path = self.resolve_path(path)?;
let inner = implementation::open(&path, options).await?;
Ok(File::from_inner(inner))
}
fn open_sync(&self, path: &str, options: &OpenOptions) -> Result<File> {
let path = self.resolve_path(path)?;
let inner = implementation::open_sync(&path, options)?;
Ok(File::from_inner(inner))
}
$(
$(#[$documentation])*
fn $operation(&self, $($path: &str),* $(, $arg: $arg_type)*) -> Result<$output> {
$(let $path = self.resolve_path($path)?;)*
#[cfg(not(target_arch = "wasm32"))]
{
implementation::$operation($(&$path,)* $($arg),*)
}
#[cfg(target_arch = "wasm32")]
{
implementation::$operation($(&$path,)* $($arg),*).map_err(Into::into)
}
}
)*
$(
$(#[$async_documentation])*
async fn $operation_async(&self, $($async_path: &str),* $(, $async_arg: $async_arg_type)*) -> Result<$async_output> {
$(let $async_path = self.resolve_path($async_path)?;)*
implementation_result!(implementation::$operation_async($(&$async_path,)* $($async_arg),*).await)
}
$(#[$async_documentation])*
#[doc = ""]
#[doc = concat!("Synchronously performs `", stringify!($operation_async), "`.")]
fn $sync_operation(&self, $($async_path: &str),* $(, $async_arg: $async_arg_type)*) -> Result<$async_output> {
$(let $async_path = self.resolve_path($async_path)?;)*
implementation_result!(implementation::$sync_operation($(&$async_path,)* $($async_arg),*))
}
)*
}
impl Directory {
pub async fn open(&self, path: &str, options: &OpenOptions) -> Result<File> {
FileOps::open(self, path, options).await
}
pub fn open_sync(&self, path: &str, options: &OpenOptions) -> Result<File> {
FileOps::open_sync(self, path, options)
}
pub async fn open_as_blob(&self, path: &str) -> Result<Blob> {
let path = self.resolve(path)?;
open_as_blob_path(&path).await
}
$(
$(#[$documentation])*
pub fn $operation(&self, $($path: &str),* $(, $arg: $arg_type)*) -> Result<$output> {
FileOps::$operation(self, $($path,)* $($arg),*)
}
)*
$(
$(#[$async_documentation])*
pub async fn $operation_async(&self, $($async_path: &str),* $(, $async_arg: $async_arg_type)*) -> Result<$async_output> {
FileOps::$operation_async(self, $($async_path,)* $($async_arg),*).await
}
$(#[$async_documentation])*
#[doc = ""]
#[doc = concat!("Synchronously performs `", stringify!($operation_async), "`.")]
pub fn $sync_operation(&self, $($async_path: &str),* $(, $async_arg: $async_arg_type)*) -> Result<$async_output> {
FileOps::$sync_operation(self, $($async_path,)* $($async_arg),*)
}
)*
}
pub mod fs {
use super::{
Blob, Dir, File, FileOps, Metadata, OpenOptions, Result, RootFileSystem, StatFs, TempDir, Watcher, WatchOptions, WatchFileOptions, ReadStream, ReadStreamOptions, WriteStream, WriteStreamOptions,
};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsValue;
use crate::implementation;
pub const F_OK: u32 = 0;
pub const R_OK: u32 = 4;
pub const W_OK: u32 = 2;
pub const X_OK: u32 = 1;
pub fn watch(path: &str, listener: impl FnMut(&str, &str) + Send + 'static) -> Result<Watcher> {
watch_with_options(path, WatchOptions::default(), listener)
}
pub fn watch_with_options(path: &str, options: WatchOptions, listener: impl FnMut(&str, &str) + Send + 'static) -> Result<Watcher> {
let inner = implementation::watch(path, options, Box::new(listener)).map_err(super::Error::from)?;
Ok(Watcher::from_inner(inner))
}
pub fn watch_file(path: &str, listener: impl FnMut(Metadata, Metadata) + Send + 'static) -> Result<u64> {
watch_file_with_options(path, WatchFileOptions::default(), listener)
}
pub fn watch_file_with_options(path: &str, options: WatchFileOptions, listener: impl FnMut(Metadata, Metadata) + Send + 'static) -> Result<u64> {
implementation::watch_file(path, options, Box::new(listener)).map_err(Into::into)
}
pub fn unwatch_file(path: &str) -> Result<()> {
implementation::unwatch_file(path, None).map_err(Into::into)
}
pub fn unwatch_file_listener(path: &str, id: u64) -> Result<()> {
implementation::unwatch_file(path, Some(id)).map_err(Into::into)
}
pub fn create_read_stream(path: &str) -> Result<ReadStream> {
create_read_stream_with_options(path, ReadStreamOptions::default())
}
pub fn create_read_stream_with_options(path: &str, options: ReadStreamOptions) -> Result<ReadStream> {
implementation::create_read_stream(path, options).map(ReadStream::from_inner).map_err(Into::into)
}
pub fn create_write_stream(path: &str) -> Result<WriteStream> {
create_write_stream_with_options(path, WriteStreamOptions::default())
}
pub fn create_write_stream_with_options(path: &str, options: WriteStreamOptions) -> Result<WriteStream> {
implementation::create_write_stream(path, options).map(WriteStream::from_inner).map_err(Into::into)
}
define_wasm_async_wrappers! {
configure(configuration: &JsValue) -> () = configure;
configure_single(configuration: &JsValue) -> () = configure_single;
resolve_mount_config(configuration: &JsValue) -> JsValue = resolve_mount_config;
resolve_remote_mount(channel: &JsValue, configuration: &JsValue) -> JsValue = resolve_remote_mount;
sync() -> () = sync;
wait_online(worker: &JsValue) -> () = wait_online;
}
define_wasm_sync_wrappers! {
configure_sync(configuration: &JsValue) -> () = configure_sync;
configure_single_sync(configuration: &JsValue) -> () = configure_single_sync;
configure_file_system(filesystem: &JsValue, configuration: &JsValue) -> () = configure_file_system;
resolve_mount_config_sync(configuration: &JsValue) -> JsValue = resolve_mount_config_sync;
mount(mount_point: &str, filesystem: &JsValue) -> () = mount;
umount(mount_point: &str) -> () = umount;
attach_fs(channel: &JsValue, filesystem: &JsValue) -> () = attach_fs;
detach_fs(channel: &JsValue, filesystem: &JsValue) -> () = detach_fs;
}
define_wasm_value_wrappers! {
mounts() -> JsValue = mounts;
core_fs() -> JsValue = zenfs_fs;
promises() -> JsValue = promises;
default_fs() -> JsValue = default_fs;
vfs() -> JsValue = vfs;
version() -> JsValue = version;
constants() -> JsValue = constants;
}
pub fn glob_to_regex(pattern: &str) -> Result<String> {
implementation_result!(implementation::glob_to_regex(pattern))
}
pub fn normalize_path(path: &str) -> Result<String> {
implementation_result!(implementation::normalize_path(path))
}
pub async fn open(path: &str, options: &OpenOptions) -> Result<File> {
FileOps::open(&RootFileSystem, path, options).await
}
pub fn open_sync(path: &str, options: &OpenOptions) -> Result<File> {
FileOps::open_sync(&RootFileSystem, path, options)
}
pub async fn open_as_blob(path: &str) -> Result<Blob> {
super::open_as_blob_path(path).await
}
pub async fn symlink(target: &str, link: &str) -> Result<()> {
implementation_result!(implementation::symlink(target, link).await)
}
pub fn symlink_sync(target: &str, link: &str) -> Result<()> {
implementation_result!(implementation::symlink_sync(target, link))
}
$(
$(#[$documentation])*
pub fn $operation($($path: &str),* $(, $arg: $arg_type)*) -> Result<$output> {
FileOps::$operation(&RootFileSystem, $($path,)* $($arg),*)
}
)*
$(
$(#[$async_documentation])*
pub async fn $operation_async($($async_path: &str),* $(, $async_arg: $async_arg_type)*) -> Result<$async_output> {
FileOps::$operation_async(&RootFileSystem, $($async_path,)* $($async_arg),*).await
}
$(#[$async_documentation])*
#[doc = ""]
#[doc = concat!("Synchronously performs `", stringify!($operation_async), "`.")]
pub fn $sync_operation($($async_path: &str),* $(, $async_arg: $async_arg_type)*) -> Result<$async_output> {
FileOps::$sync_operation(&RootFileSystem, $($async_path,)* $($async_arg),*)
}
)*
define_file_handle_api! {
fchmod => fchmod_sync(file: &File, mode: u32) -> () {
async { file.fchmod(mode) }
sync { file.fchmod_sync(mode) }
};
fchown => fchown_sync(file: &File, uid: u32, gid: u32) -> () {
async { file.fchown(uid, gid) }
sync { file.fchown_sync(uid, gid) }
};
futimes => futimes_sync(file: &File, atime: std::time::SystemTime, mtime: std::time::SystemTime) -> () {
async { file.futimes(atime, mtime) }
sync { file.futimes_sync(atime, mtime) }
};
close => close_sync(file: File) -> () {
async { super::close_file(file) }
sync { super::close_file_sync(file) }
};
read => read_sync(file: &mut File, buffer: &mut [u8]) -> usize {
async { file.read(buffer) }
sync { file.read_sync(buffer) }
};
write => write_sync(file: &mut File, buffer: &[u8]) -> usize {
async { file.write(buffer) }
sync { file.write_sync(buffer) }
};
readv => readv_sync(file: &mut File, buffers: &mut [std::io::IoSliceMut<'_>]) -> usize {
async { file.read_vectored(buffers) }
sync { file.read_vectored_sync(buffers) }
};
writev => writev_sync(file: &mut File, buffers: &[std::io::IoSlice<'_>]) -> usize {
async { file.write_vectored(buffers) }
sync { file.write_vectored_sync(buffers) }
};
fstat => fstat_sync(file: &File) -> Metadata {
async { file.metadata() }
sync { file.metadata_sync() }
};
fsync => fsync_sync(file: &mut File) -> () {
async { file.sync_all() }
sync { file.sync_all_sync() }
};
fdatasync => fdatasync_sync(file: &mut File) -> () {
async { file.sync_data() }
sync { file.sync_data_sync() }
};
ftruncate => ftruncate_sync(file: &mut File, size: u64) -> () {
async { file.set_len(size) }
sync { file.set_len_sync(size) }
};
}
}
};
}
define_file_api! {
operations {
append_text([path], contents: &str) -> ();
read_text([path]) -> String;
write_text([path], contents: &str) -> ();
create_dir([path]) -> ();
create_dir_all([path]) -> ();
read_dir([path]) -> Vec<String>;
mkdtemp_disposable_sync([prefix]) -> TempDir;
remove_file([path]) -> ();
}
async_operations {
access([path], mode: u32) -> () => access_sync;
append_file([path], contents: &[u8]) -> () => append_file_sync;
exists([path]) -> bool => exists_sync;
read_file([path]) -> Vec<u8> => read_file_sync;
write_file([path], contents: &[u8]) -> () => write_file_sync;
copy_file([from, to]) -> () => copy_file_sync;
cp([from, to]) -> () => cp_sync;
rename([from, to]) -> () => rename_sync;
mkdir([path], recursive: bool) -> () => mkdir_sync;
mkdtemp([prefix]) -> String => mkdtemp_sync;
opendir([path]) -> Dir => opendir_sync;
readdir([path]) -> Vec<String> => readdir_sync;
rmdir([path]) -> () => rmdir_sync;
rm([path], recursive: bool, force: bool) -> () => rm_sync;
realpath([path]) -> String => realpath_sync;
glob([path]) -> Vec<String> => glob_sync;
stat([path]) -> Metadata => stat_sync;
lstat([path]) -> Metadata => lstat_sync;
statfs([path]) -> StatFs => statfs_sync;
chmod([path], mode: u32) -> () => chmod_sync;
lchmod([path], mode: u32) -> () => lchmod_sync;
chown([path], uid: u32, gid: u32) -> () => chown_sync;
lchown([path], uid: u32, gid: u32) -> () => lchown_sync;
utimes([path], atime: std::time::SystemTime, mtime: std::time::SystemTime) -> () => utimes_sync;
lutimes([path], atime: std::time::SystemTime, mtime: std::time::SystemTime) -> () => lutimes_sync;
link([original, link]) -> () => link_sync;
readlink([path]) -> String => readlink_sync;
unlink([path]) -> () => unlink_sync;
truncate([path], len: u64) -> () => truncate_sync;
}
}
fn close_file_sync(mut file: File) -> Result<()> {
let inner = file.take_inner()?;
implementation::close_sync(inner)?;
Ok(())
}
async fn close_file(mut file: File) -> Result<()> {
let inner = file
.inner
.as_mut()
.ok_or_else(|| invalid_path_error("operation attempted on a closed file"))?;
implementation::close(inner).await?;
let _inner = file.inner.take();
Ok(())
}
async fn open_as_blob_path(path: &str) -> Result<Blob> {
let bytes = implementation::open_as_blob(path).await?;
Ok(Blob::new(bytes))
}
impl FileOps for Directory {
fn resolve_path(&self, path: &str) -> Result<String> {
self.resolve(path)
}
}
impl FileOps for RootFileSystem {
fn resolve_path(&self, path: &str) -> Result<String> {
Ok(path.to_owned())
}
}
pub fn app_dir(name: &str) -> Result<Directory> {
let path = implementation::app_dir(name)?;
Ok(Directory { path })
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn streams_read_in_chunks_and_finish_or_destroy_writes() {
futures_lite::future::block_on(async {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
let mut output = dir.create_write_stream("data").unwrap();
output.write(b"abcdef").await.unwrap();
output.write(b"gh").await.unwrap();
output.end().await.unwrap();
assert!(output.write(b"no").await.is_err());
assert_eq!(dir.read_text("data").unwrap(), "abcdefgh");
let mut input = dir
.create_read_stream_with_options(
"data",
ReadStreamOptions {
start: 2,
end: Some(6),
chunk_size: 2,
},
)
.unwrap();
assert_eq!(input.read().await.unwrap(), Some(b"cd".to_vec()));
assert_eq!(input.read().await.unwrap(), Some(b"ef".to_vec()));
assert_eq!(input.read().await.unwrap(), Some(b"g".to_vec()));
assert_eq!(input.read().await.unwrap(), None);
input.destroy().unwrap();
assert!(input.read().await.is_err());
let mut replace = dir.create_write_stream("data").unwrap();
replace.write(b"!").await.unwrap();
replace.end().await.unwrap();
assert_eq!(dir.read_text("data").unwrap(), "!");
let mut positioned = dir
.create_write_stream_with_options(
"positioned",
WriteStreamOptions { start: Some(2) },
)
.unwrap();
positioned.write(b"x").await.unwrap();
positioned.end().await.unwrap();
assert_eq!(dir.read_file_sync("positioned").unwrap(), b"\0\0x");
let mut abandoned = dir.create_write_stream("abandoned").unwrap();
abandoned.destroy().unwrap();
assert!(abandoned.write(b"no").await.is_err());
assert!(
dir.create_read_stream_with_options(
"data",
ReadStreamOptions {
chunk_size: 0,
..Default::default()
}
)
.is_err()
);
assert!(
dir.create_read_stream_with_options(
"data",
ReadStreamOptions {
start: 3,
end: Some(2),
..Default::default()
}
)
.is_err()
);
assert!(dir.create_read_stream("../escape").is_err());
let path = temp.path().join("data");
let mut root_stream = fs::create_read_stream(path.to_str().unwrap()).unwrap();
assert_eq!(root_stream.read().await.unwrap(), Some(b"!".to_vec()));
});
}
#[test]
fn watch_reports_events_and_closes() {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
let (tx, rx) = std::sync::mpsc::channel();
let mut watcher = dir
.watch(".", move |event, name| {
let _ = tx.send((event.to_owned(), name.to_owned()));
})
.unwrap();
dir.write_text("created", "hello").unwrap();
let (event, name) = rx.recv_timeout(std::time::Duration::from_secs(3)).unwrap();
assert!(matches!(event.as_str(), "change" | "rename"));
assert_eq!(name, "created");
watcher.close().unwrap();
assert!(watcher.close().is_err());
assert!(dir.watch("../escape", |_, _| {}).is_err());
}
#[test]
fn watch_file_listeners_can_be_removed_individually_or_together() {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
dir.write_text("file", "a").unwrap();
let options = WatchFileOptions {
interval: std::time::Duration::from_millis(20),
..Default::default()
};
let (first_tx, first_rx) = std::sync::mpsc::channel();
let first = dir
.watch_file_with_options("file", options, move |curr, prev| {
let _ = first_tx.send((curr.len(), prev.len()));
})
.unwrap();
let (second_tx, second_rx) = std::sync::mpsc::channel();
let second = dir
.watch_file_with_options("file", options, move |curr, prev| {
let _ = second_tx.send((curr.len(), prev.len()));
})
.unwrap();
dir.write_text("file", "longer").unwrap();
assert_eq!(
first_rx
.recv_timeout(std::time::Duration::from_secs(3))
.unwrap(),
(6, 1)
);
assert_eq!(
second_rx
.recv_timeout(std::time::Duration::from_secs(3))
.unwrap(),
(6, 1)
);
dir.unwatch_file_listener("file", first).unwrap();
dir.write_text("file", "even longer").unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
loop {
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
let (current_len, _) = second_rx.recv_timeout(remaining).unwrap();
if current_len == 11 {
break;
}
}
assert!(
first_rx
.recv_timeout(std::time::Duration::from_millis(100))
.is_err()
);
dir.unwatch_file("file").unwrap();
dir.unwatch_file_listener("file", second).unwrap();
assert!(dir.unwatch_file("../escape").is_err());
}
#[test]
fn hard_links_rename_and_unlink_work_on_fs_and_directory() {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
dir.write_text("source", "original").unwrap();
dir.link_sync("source", "hard").unwrap();
dir.write_text("hard", "updated").unwrap();
assert_eq!(dir.read_text("source").unwrap(), "updated");
dir.rename_sync("hard", "moved").unwrap();
dir.unlink_sync("source").unwrap();
assert_eq!(dir.read_text("moved").unwrap(), "updated");
dir.unlink_sync("moved").unwrap();
assert_eq!(
dir.unlink_sync("moved").unwrap_err().kind(),
std::io::ErrorKind::NotFound
);
assert_eq!(
dir.link_sync("../outside", "bad").unwrap_err().kind(),
std::io::ErrorKind::InvalidInput
);
let original = temp.path().join("original");
let copy = temp.path().join("copy");
fs::write_text(original.to_str().unwrap(), "data").unwrap();
fs::link_sync(original.to_str().unwrap(), copy.to_str().unwrap()).unwrap();
fs::unlink_sync(original.to_str().unwrap()).unwrap();
assert_eq!(fs::read_text(copy.to_str().unwrap()).unwrap(), "data");
}
#[cfg(unix)]
#[test]
fn symlinks_keep_relative_targets_and_unlink_does_not_remove_them() {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
dir.create_dir("nested").unwrap();
dir.write_text("source", "contents").unwrap();
dir.symlink_sync("../source", "nested/link").unwrap();
assert_eq!(dir.readlink_sync("nested/link").unwrap(), "../source");
assert_eq!(dir.read_text("nested/link").unwrap(), "contents");
dir.unlink_sync("nested/link").unwrap();
assert_eq!(dir.read_text("source").unwrap(), "contents");
dir.symlink_sync("../missing", "nested/dangling").unwrap();
assert_eq!(dir.readlink_sync("nested/dangling").unwrap(), "../missing");
assert_eq!(
dir.symlink_sync("../../outside", "nested/escape")
.unwrap_err()
.kind(),
std::io::ErrorKind::InvalidInput
);
assert_eq!(
dir.symlink_sync("source", "../outside").unwrap_err().kind(),
std::io::ErrorKind::InvalidInput
);
let path = temp.path().join("raw-link");
fs::symlink_sync("source", path.to_str().unwrap()).unwrap();
assert_eq!(fs::readlink_sync(path.to_str().unwrap()).unwrap(), "source");
}
#[test]
fn async_link_operations_work() {
futures_lite::future::block_on(async {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
dir.write_text("source", "value").unwrap();
dir.link("source", "hard").await.unwrap();
dir.rename("hard", "renamed").await.unwrap();
dir.unlink("source").await.unwrap();
assert_eq!(dir.read_text("renamed").unwrap(), "value");
#[cfg(unix)]
{
dir.symlink("renamed", "symbolic").await.unwrap();
assert_eq!(dir.readlink("symbolic").await.unwrap(), "renamed");
dir.unlink("symbolic").await.unwrap();
}
dir.unlink("renamed").await.unwrap();
});
}
#[cfg(unix)]
#[test]
fn metadata_stat_and_times_cover_path_and_descriptor_variants() {
use std::time::{Duration, UNIX_EPOCH};
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
dir.write_text("file", "hello").unwrap();
assert_eq!(dir.stat_sync("file").unwrap().len(), 5);
assert!(dir.lstat_sync("file").unwrap().is_file());
assert!(dir.statfs_sync("file").unwrap().block_size > 0);
let atime = UNIX_EPOCH + Duration::from_secs(1_600_000_000);
let mtime = atime + Duration::from_secs(100);
dir.utimes_sync("file", atime, mtime).unwrap();
let path = temp.path().join("file");
assert_eq!(std::fs::metadata(&path).unwrap().modified().unwrap(), mtime);
let mut options = OpenOptions::new();
options.read(true);
let file = dir.open_sync("file", &options).unwrap();
fs::futimes_sync(&file, atime, atime).unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().modified().unwrap(), atime);
assert_eq!(
dir.stat_sync("../file").unwrap_err().kind(),
std::io::ErrorKind::InvalidInput
);
#[cfg(unix)]
{
use std::os::unix::fs::{PermissionsExt, symlink};
let link = temp.path().join("link");
symlink("file", &link).unwrap();
assert!(dir.lstat_sync("link").unwrap().is_symlink());
assert!(dir.stat_sync("link").unwrap().is_file());
dir.lutimes_sync("link", atime, mtime).unwrap();
assert_eq!(
std::fs::symlink_metadata(&link)
.unwrap()
.modified()
.unwrap(),
mtime
);
dir.chmod_sync("file", 0o640).unwrap();
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o640
);
fs::fchmod_sync(&file, 0o600).unwrap();
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
let uid = unsafe { libc::geteuid() };
let gid = unsafe { libc::getegid() };
dir.chown_sync("file", uid, gid).unwrap();
dir.lchown_sync("link", uid, gid).unwrap();
fs::fchown_sync(&file, uid, gid).unwrap();
let _ = dir.lchmod_sync("link", 0o777);
assert_eq!(
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
0o600
);
}
}
#[cfg(unix)]
#[test]
fn async_metadata_operations_work() {
futures_lite::future::block_on(async {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
dir.write_text("file", "hi").unwrap();
assert_eq!(dir.stat("file").await.unwrap().len(), 2);
assert!(dir.lstat("file").await.unwrap().is_file());
assert!(dir.statfs("file").await.unwrap().blocks > 0.0);
let time = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_600_000_000);
dir.utimes("file", time, time).await.unwrap();
#[cfg(unix)]
{
std::os::unix::fs::symlink("file", temp.path().join("link")).unwrap();
dir.lutimes("link", time, time).await.unwrap();
dir.chmod("file", 0o600).await.unwrap();
let uid = unsafe { libc::geteuid() };
let gid = unsafe { libc::getegid() };
dir.chown("file", uid, gid).await.unwrap();
dir.lchown("link", uid, gid).await.unwrap();
let _ = dir.lchmod("link", 0o777).await;
}
let mut options = OpenOptions::new();
options.read(true);
let file = dir.open("file", &options).await.unwrap();
file.futimes(time, time).await.unwrap();
#[cfg(unix)]
{
file.fchmod(0o600).await.unwrap();
file.fchown(unsafe { libc::geteuid() }, unsafe { libc::getegid() })
.await
.unwrap();
}
});
}
#[test]
fn directory_apis_cover_creation_listing_removal_and_paths() {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
dir.mkdir_sync("nested/deep", true).unwrap();
assert_eq!(dir.readdir_sync("nested").unwrap(), vec!["deep"]);
let mut opened = dir.opendir_sync("nested").unwrap();
let entry = opened.read_sync().unwrap().unwrap();
assert_eq!(entry.name(), "deep");
assert!(entry.is_dir());
assert_eq!(opened.read_sync().unwrap(), None);
opened.close_sync().unwrap();
assert!(opened.read_sync().is_err());
assert_eq!(
dir.realpath_sync("nested/deep").unwrap(),
temp.path().join("nested/deep").to_str().unwrap()
);
assert_eq!(
dir.glob_sync("nested/*").unwrap(),
vec![
temp.path()
.join("nested/deep")
.to_str()
.unwrap()
.trim_start_matches('/')
]
);
assert_eq!(
dir.mkdir_sync("nested", false).unwrap_err().kind(),
std::io::ErrorKind::AlreadyExists
);
dir.rmdir_sync("nested/deep").unwrap();
dir.rm_sync("nested", true, false).unwrap();
dir.rm_sync("nested", false, true).unwrap();
assert_eq!(
dir.rm_sync("missing", false, false).unwrap_err().kind(),
std::io::ErrorKind::NotFound
);
assert_eq!(
dir.rm_sync("../outside", true, true).unwrap_err().kind(),
std::io::ErrorKind::InvalidInput
);
assert_eq!(fs::normalize_path("/a/./b/../c").unwrap(), "/a/c");
assert_eq!(fs::glob_to_regex("*.txt").unwrap(), "^[^/]*\\.txt$");
}
#[test]
fn temporary_directories_are_unique_and_disposable() {
let temp = tempdir().unwrap();
let prefix = temp.path().join("example-");
let prefix = prefix.to_str().unwrap();
let first = fs::mkdtemp_sync(prefix).unwrap();
let second = fs::mkdtemp_sync(prefix).unwrap();
assert_ne!(first, second);
assert!(Path::new(&first).is_dir());
let disposable = fs::mkdtemp_disposable_sync(prefix).unwrap();
let disposable_path = disposable.path().to_owned();
assert!(Path::new(&disposable_path).is_dir());
drop(disposable);
assert!(!Path::new(&disposable_path).exists());
}
#[test]
fn async_directory_operations_work() {
futures_lite::future::block_on(async {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
dir.mkdir("nested", false).await.unwrap();
assert_eq!(dir.readdir(".").await.unwrap(), vec!["nested"]);
let mut opened = dir.opendir(".").await.unwrap();
let entry = opened.read().await.unwrap().unwrap();
assert_eq!(entry.name(), "nested");
assert!(entry.is_dir());
assert_eq!(opened.read().await.unwrap(), None);
opened.close().await.unwrap();
assert_eq!(dir.glob("nest*").await.unwrap().len(), 1);
assert!(dir.realpath("nested").await.unwrap().ends_with("nested"));
let prefix = temp.path().join("tmp-");
let created = fs::mkdtemp(prefix.to_str().unwrap()).await.unwrap();
assert!(Path::new(&created).is_dir());
dir.rmdir("nested").await.unwrap();
fs::rm(&created, true, false).await.unwrap();
});
}
#[test]
fn directory_and_fs_share_file_operations() {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
let full_path = temp.path().join("hello.txt");
let full_path = full_path.to_str().unwrap();
dir.write_text("hello.txt", "from directory").unwrap();
assert_eq!(fs::read_text(full_path).unwrap(), "from directory");
fs::write_text(full_path, "from fs").unwrap();
assert_eq!(dir.read_text("hello.txt").unwrap(), "from fs");
}
#[test]
fn append_text_creates_and_appends_to_files() {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
let full_path = temp.path().join("hello.txt");
let full_path = full_path.to_str().unwrap();
dir.append_text("hello.txt", "from directory").unwrap();
fs::append_text(full_path, " and fs").unwrap();
assert_eq!(dir.read_text("hello.txt").unwrap(), "from directory and fs");
}
#[test]
fn rename_is_available_on_fs_and_directory() {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
dir.write_text("before.txt", "from directory").unwrap();
dir.rename_sync("before.txt", "after.txt").unwrap();
assert!(!dir.exists_sync("before.txt").unwrap());
assert_eq!(dir.read_text("after.txt").unwrap(), "from directory");
let root_before = temp.path().join("after.txt");
let root_after = temp.path().join("root-renamed.txt");
fs::rename_sync(root_before.to_str().unwrap(), root_after.to_str().unwrap()).unwrap();
assert!(!root_before.exists());
assert!(root_after.exists());
}
#[test]
fn copy_file_is_available_on_fs_and_directory() {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
dir.write_text("source.txt", "from directory").unwrap();
dir.copy_file_sync("source.txt", "copy.txt").unwrap();
assert_eq!(dir.read_text("copy.txt").unwrap(), "from directory");
let root_source = temp.path().join("copy.txt");
let root_copy = temp.path().join("root-copy.txt");
fs::copy_file_sync(root_source.to_str().unwrap(), root_copy.to_str().unwrap()).unwrap();
assert_eq!(
fs::read_text(root_copy.to_str().unwrap()).unwrap(),
"from directory"
);
}
#[test]
fn directory_rejects_paths_that_escape_its_root() {
let temp = tempdir().unwrap();
let dir = Directory::new(temp.path()).unwrap();
assert_eq!(
dir.write_text("../outside.txt", "nope").unwrap_err().kind(),
std::io::ErrorKind::InvalidInput
);
assert_eq!(
dir.rename_sync("inside.txt", "../outside.txt")
.unwrap_err()
.kind(),
std::io::ErrorKind::InvalidInput
);
assert_eq!(
dir.copy_file_sync("inside.txt", "../outside.txt")
.unwrap_err()
.kind(),
std::io::ErrorKind::InvalidInput
);
}
}