feat(fs): add dir_create and dir_create_all

Closes kemitix/kxio#25
This commit is contained in:
Paul Campbell 2024-04-28 14:30:23 +01:00
parent a77ed422eb
commit 12d55b98e5
4 changed files with 59 additions and 7 deletions

View file

@ -5,10 +5,14 @@ use std::path::{Path, PathBuf};
pub trait FileSystemLike {
fn base(&self) -> &Path;
fn dir_create(&self, path: &Path) -> Result<()>;
fn dir_create_all(&self, path: &Path) -> Result<()>;
fn file_read_to_string(&self, path: &Path) -> Result<String>;
fn file_write(&self, path: &Path, contents: &str) -> Result<()>;
fn path_exists(&self, path: &Path) -> Result<bool>;
fn path_is_dir(&self, path: &Path) -> Result<bool>;
fn path_is_file(&self, path: &Path) -> Result<bool>;
fn path_of(&self, path: PathBuf) -> Result<PathBuf>;
}

View file

@ -32,7 +32,6 @@ pub enum FileSystem {
Real(real::RealFileSystem),
Temp(temp::TempFileSystem),
}
impl std::ops::Deref for FileSystem {
type Target = dyn FileSystemLike;

View file

@ -13,6 +13,15 @@ impl super::FileSystemLike for RealFileSystem {
&self.base
}
fn dir_create(&self, path: &Path) -> super::Result<()> {
self.validate(path)?;
std::fs::create_dir(path).map_err(Into::into)
}
fn dir_create_all(&self, path: &Path) -> super::Result<()> {
self.validate(path)?;
std::fs::create_dir_all(path).map_err(Into::into)
}
fn file_read_to_string(&self, path: &Path) -> super::Result<String> {
self.validate(path)?;
@ -29,6 +38,11 @@ impl super::FileSystemLike for RealFileSystem {
Ok(path.exists())
}
fn path_is_dir(&self, path: &Path) -> super::Result<bool> {
self.validate(path)?;
Ok(path.is_dir())
}
fn path_is_file(&self, path: &Path) -> super::Result<bool> {
self.validate(path)?;
Ok(path.is_file())

View file

@ -6,15 +6,50 @@ type TestResult = Result<(), crate::fs::Error>;
#[test]
fn write_read_file_exists() -> TestResult {
let temp_fs = fs::temp()?;
let name: PathBuf = temp_fs.path_of("foo".into())?;
temp_fs.file_write(&name, "content")?;
let c = temp_fs.file_read_to_string(&name)?;
let fs = fs::temp()?;
let pathbuf: PathBuf = fs.path_of("foo".into())?;
fs.file_write(&pathbuf, "content")?;
let c = fs.file_read_to_string(&pathbuf)?;
assert_eq!(c, "content");
let exists = temp_fs.path_exists(&name)?;
let exists = fs.path_exists(&pathbuf)?;
assert!(exists);
let is_file = temp_fs.path_is_file(&name)?;
let is_file = fs.path_is_file(&pathbuf)?;
assert!(is_file);
Ok(())
}
#[test]
fn create_dir_should_create_a_dir() -> TestResult {
let fs = fs::temp()?;
let pathbuf = fs.path_of("subdir".into())?;
fs.dir_create(&pathbuf)?;
let exists = fs.path_exists(&pathbuf)?;
assert!(exists);
let is_dir = fs.path_is_dir(&pathbuf)?;
assert!(is_dir);
Ok(())
}
#[test]
fn create_dir_all_should_create_a_dir() -> TestResult {
let fs = fs::temp()?;
let pathbuf = fs.base().join("subdir").join("child");
fs.dir_create_all(&pathbuf)?;
let exists = fs.path_exists(&pathbuf)?;
assert!(exists, "path exists");
let is_dir = fs.path_is_dir(&pathbuf)?;
assert!(is_dir, "path is a directory");
Ok(())
}