Compare commits

...

2 commits

Author SHA1 Message Date
ece13d43a2 WIP: docs(fs): add some documentation
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2024-05-17 12:09:15 +01:00
d0aee99c83 feat(fs): add dir_read()
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
ci/woodpecker/cron/woodpecker Pipeline was successful
2024-05-17 12:08:56 +01:00
6 changed files with 220 additions and 4 deletions

View file

@ -1,6 +1,6 @@
[package] [package]
name = "kxio" name = "kxio"
version = "1.1.2" version = "1.2.0"
edition = "2021" edition = "2021"
authors = ["Paul Campbell <pcampbell@kemitix.net>"] authors = ["Paul Campbell <pcampbell@kemitix.net>"]
description = "Provides injectable Filesystem and Network resources to make code more testable" description = "Provides injectable Filesystem and Network resources to make code more testable"
@ -33,8 +33,12 @@ thiserror = "1.0"
tempfile = "3.10" tempfile = "3.10"
path-clean = "1.0" path-clean = "1.0"
# error handling # boilerplate
derive_more = { version = "1.0.0-beta.6", features = ["from", "display"] } derive_more = { version = "1.0.0-beta.6", features = [
"from",
"display",
"constructor",
] }
[dev-dependencies] [dev-dependencies]
# testing # testing

37
src/fs/dir_item.rs Normal file
View file

@ -0,0 +1,37 @@
use std::{
fs::{DirEntry, ReadDir},
path::PathBuf,
};
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum DirItem {
File(PathBuf),
Dir(PathBuf),
SymLink(PathBuf),
Fifo(PathBuf),
Unsupported(PathBuf),
}
#[derive(Debug, derive_more::Constructor)]
pub struct DirItemIterator(ReadDir);
impl Iterator for DirItemIterator {
type Item = super::Result<DirItem>;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(map_dir_item)
}
}
fn map_dir_item(item: std::io::Result<DirEntry>) -> super::Result<DirItem> {
let item = item?;
let file_type = item.file_type()?;
if file_type.is_dir() {
Ok(DirItem::Dir(item.path()))
} else if file_type.is_file() {
Ok(DirItem::File(item.path()))
} else if file_type.is_symlink() {
Ok(DirItem::SymLink(item.path()))
} else {
Ok(DirItem::Unsupported(item.path()))
}
}

View file

@ -1,18 +1,99 @@
use crate::fs::DirItem;
use super::Result; use super::Result;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
/// A handle for accessing the filesystem.
pub trait FileSystemLike { pub trait FileSystemLike {
/// Returns the base directory for the filesystem that this handle can access.
///
/// Many methods expect a [Path] paremeter. This [Path] must be within the base directory of the
/// handle. Call [FileSystemLike::base] to get this.
///
/// To construct a [Path] within the filesystem:
///
/// ```no_run
/// let fs = kxio::fs::new(std::env::current_dir()?);
/// let file_name = fs.base().join("foo");
/// ```
fn base(&self) -> &Path; fn base(&self) -> &Path;
/// Creates a directory at the path. The parent directory must already exists, if it doesn't
/// consider using [FileSystemLike::dir_create_all] instead.
///
/// ```no_run
/// let fs = kxio::fs::temp()?;
/// let dir_name = fs.base().join("subdir");
/// fs.dir_create(&dir_name)?;
/// ```
fn dir_create(&self, path: &Path) -> Result<()>; fn dir_create(&self, path: &Path) -> Result<()>;
/// Creates a directory and any missing parents as the path.
///
/// ```no_run
/// let fs = kxio::fs::temp()?;
/// let path_name = fs.base().join("subdir").join("child");
/// fs.dir_create_all(&path_name)?;
/// ```
fn dir_create_all(&self, path: &Path) -> Result<()>; fn dir_create_all(&self, path: &Path) -> Result<()>;
/// Reads the items in a directory and returns them as an iterator.
fn dir_read(&self, path: &Path) -> Result<Box<dyn Iterator<Item = Result<DirItem>>>>;
/// Reads a file into a [String]. Will attempt to read the whole file into memory in one go.
///
/// ```no_run
/// let fs = kxio::fs::new(std::env::current_dir()?);
/// let file_name = fs.base().join("existing_file.txt");
/// let file_contents = fs.file_read_to_string(&file_name)?;
/// ```
fn file_read_to_string(&self, path: &Path) -> Result<String>; fn file_read_to_string(&self, path: &Path) -> Result<String>;
/// Writes a string slice to a file.
///
/// ```no_run
/// let fs = kxio::fs::temp()?;
/// let file_name = fs.base().join("new_file");
/// let contents = "contents of new file";
/// fs.file_write(&file_name, contents)?;
/// ```
fn file_write(&self, path: &Path, contents: &str) -> Result<()>; fn file_write(&self, path: &Path, contents: &str) -> Result<()>;
/// Checks that the path exists.
///
/// ```no_run
/// let fs = kxio::fs::new(std::env::current_dir()?);
/// let path = fs.base().join("foo");
/// let exists: bool = fs.path_exists(&path)?;
/// ```
fn path_exists(&self, path: &Path) -> Result<bool>; fn path_exists(&self, path: &Path) -> Result<bool>;
/// Checks whether the path is a directory.
///
/// ```no_run
/// let fs = kxio::fs::new(std::env::current_dir()?);
/// let path = fs.base().join("foo");
/// let is_dir: bool = fs.path_is_dir(&path)?;
/// ```
fn path_is_dir(&self, path: &Path) -> Result<bool>; fn path_is_dir(&self, path: &Path) -> Result<bool>;
/// Checks whether the path is a file.
///
/// ```no_run
/// let fs = kxio::fs::new(std::env::current_dir()?);
/// let path = fs.base().join("foo");
/// let is_file: bool = fs.path_is_file(&path)?;
/// ```
fn path_is_file(&self, path: &Path) -> Result<bool>; fn path_is_file(&self, path: &Path) -> Result<bool>;
/// Creates a new [PathBuf] within the filesystem.
///
/// ```no_run
/// let fs = kxio::fs::temp()?;
/// let path_of = fs.path_of("subdir/file.txt")?;
/// let path = fs.base().join("subdir").join("file.txt");
/// assert_eq!(path_of, path);
/// ```
fn path_of(&self, path: PathBuf) -> Result<PathBuf>; fn path_of(&self, path: PathBuf) -> Result<PathBuf>;
} }

View file

@ -4,10 +4,14 @@ use derive_more::From;
use crate::fs::like::FileSystemLike; use crate::fs::like::FileSystemLike;
mod like; pub mod like;
mod real; mod real;
mod temp; mod temp;
mod dir_item;
pub use dir_item::DirItem;
pub use dir_item::DirItemIterator;
#[derive(Debug, From, derive_more::Display)] #[derive(Debug, From, derive_more::Display)]
pub enum Error { pub enum Error {
Io(std::io::Error), Io(std::io::Error),
@ -17,15 +21,38 @@ pub enum Error {
base: PathBuf, base: PathBuf,
path: PathBuf, path: PathBuf,
}, },
#[display("Path must be a directory: {path:?}")]
NotADirectory {
path: PathBuf,
},
} }
impl std::error::Error for Error {} impl std::error::Error for Error {}
pub type Result<T> = core::result::Result<T, Error>; pub type Result<T> = core::result::Result<T, Error>;
/// Creates a new handle for accessing the filesystem.
///
/// The base parameter is the root directory that all operations must be within.
pub const fn new(base: PathBuf) -> FileSystem { pub const fn new(base: PathBuf) -> FileSystem {
FileSystem::Real(real::new(base)) FileSystem::Real(real::new(base))
} }
/// Creates a new handle for accessing a temporary directory on the filesystem.
///
/// When this handle is dropped, the temporary directory is deleted.
///
/// Calling base on the handle will return the temporary directory.
///
/// # Example
///
/// This will create a temporary directory and create a file inside it called 'foo':
///
/// ```no_run
/// let fs = kxio::fs::temp()?;
/// let file_name = fs.base().join("foo");
/// fs.file_write(&file_name, "contents")?;
/// ```
pub fn temp() -> Result<FileSystem> { pub fn temp() -> Result<FileSystem> {
temp::new().map(FileSystem::Temp) temp::new().map(FileSystem::Temp)
} }

View file

@ -1,5 +1,7 @@
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crate::fs::{DirItem, DirItemIterator};
pub const fn new(base: PathBuf) -> RealFileSystem { pub const fn new(base: PathBuf) -> RealFileSystem {
RealFileSystem { base } RealFileSystem { base }
} }
@ -24,6 +26,20 @@ impl super::FileSystemLike for RealFileSystem {
std::fs::create_dir_all(path).map_err(Into::into) std::fs::create_dir_all(path).map_err(Into::into)
} }
fn dir_read(
&self,
path: &Path,
) -> super::Result<Box<dyn Iterator<Item = super::Result<DirItem>>>> {
self.validate(path)?;
if !self.path_is_dir(path)? {
return Err(super::Error::NotADirectory {
path: path.to_path_buf(),
});
}
let read_dir = std::fs::read_dir(path)?;
Ok(Box::new(DirItemIterator::new(read_dir)))
}
fn file_read_to_string(&self, path: &Path) -> super::Result<String> { fn file_read_to_string(&self, path: &Path) -> super::Result<String> {
self.validate(path)?; self.validate(path)?;
std::fs::read_to_string(path).map_err(Into::into) std::fs::read_to_string(path).map_err(Into::into)

View file

@ -107,6 +107,57 @@ mod dir_create_all {
} }
} }
mod dir_dir_read {
use crate::fs::DirItem;
use super::*;
#[test]
fn should_return_dir_items() -> TestResult {
let fs = fs::temp()?;
let file1 = fs.base().join("file-1");
let dir = fs.base().join("dir");
let file2 = dir.join("file-2");
fs.file_write(&file1, "file-1")?;
fs.dir_create(&dir)?;
fs.file_write(&file2, "file-2")?;
let items = fs
.dir_read(fs.base())?
.filter_map(|i| i.ok())
.collect::<Vec<_>>();
assert_eq!(items.len(), 2);
assert!(items.contains(&DirItem::File(file1)));
assert!(items.contains(&DirItem::Dir(dir)));
Ok(())
}
#[test]
fn should_fail_on_not_a_dir() -> TestResult {
let fs = fs::temp()?;
let path = fs.base().join("file");
fs.file_write(&path, "contents")?;
let_assert!(Err(fs::Error::NotADirectory { path: _path }) = fs.dir_read(&path));
Ok(())
}
#[test]
fn should_fail_on_path_traversal() -> TestResult {
let fs = fs::temp()?;
let path = fs.base().join("..").join("foo");
let_assert!(
Err(fs::Error::PathTraversal {
base: _base,
path: _path
}) = fs.dir_read(&path)
);
Ok(())
}
}
mod path_exists { mod path_exists {
use super::*; use super::*;
#[test] #[test]