Compare commits
3 commits
6f95c04eb6
...
76d75cabd9
Author | SHA1 | Date | |
---|---|---|---|
76d75cabd9 | |||
d2ee798f25 | |||
be7a6febcb |
17 changed files with 528 additions and 296 deletions
43
README.md
43
README.md
|
@ -1,37 +1,28 @@
|
|||
## kxio
|
||||
|
||||
[![status-badge](https://ci.kemitix.net/api/badges/53/status.svg)](https://ci.kemitix.net/repos/53)
|
||||
|
||||
Provides injectable Filesystem and Network resources to make code more testable.
|
||||
|
||||
### FileSystem
|
||||
|
||||
There are two FileSystem implementation: [filesystem] and [fs].
|
||||
|
||||
- [filesystem] is the legacy implementation and will be removed in a future version.
|
||||
- [fs] is the current version and is intended to stand-in for and extend the [std::fs] module from the Standard Library.
|
||||
|
||||
#### std::fs alternatives
|
||||
|
||||
| To Do | [std::fs] | [kxio::fs::FileSystem] | |
|
||||
| ----- | ---------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| [ ] | canonicalize | path_canonicalize | Returns the canonical, absolute form of a path with all intermediate components normalized and symbolic links resolved. |
|
||||
| [ ] | copy | file_copy | Copies the contents of one file to another. This function will also copy the permission bits of the original file to the destination file. |
|
||||
| [ ] | create_dir | dir_create | Creates a new, empty directory at the provided path |
|
||||
| [ ] | create_dir_all | dir_create_all | Recursively create a directory and all of its parent components if they are missing. |
|
||||
| [ ] | hard_link | link_create | Creates a new hard link on the filesystem. |
|
||||
| [ ] | metadata | path_metadata | Given a path, query the file system to get information about a file, directory, etc. |
|
||||
| [ ] | read | file_read | Read the entire contents of a file into a bytes vector. |
|
||||
| [ ] | read_dir | dir_read | Returns an iterator over the entries within a directory. |
|
||||
| [ ] | read_link | link_read | Reads a symbolic link, returning the file that the link points to. |
|
||||
| [x] | read_to_string | file_read_to_string | Read the entire contents of a file into a string. |
|
||||
| [ ] | remove_dir | dir_remove | Removes an empty directory. |
|
||||
| [ ] | remove_dir_all | dir_remove_all | Removes a directory at this path, after removing all its contents. Use carefully! |
|
||||
| [ ] | remove_file | file_remove | Removes a file from the filesystem. |
|
||||
| [ ] | rename | path_rename | Rename a file or directory to a new name, replacing the original file if to already exists. |
|
||||
| [ ] | set_permissions | path_set_permissions | Changes the permissions found on a file or a directory. |
|
||||
| [ ] | symlink_metadata | link_metadata | Query the metadata about a file without following symlinks. |
|
||||
| [x] | write | file_write | Write a slice as the entire contents of a file. |
|
||||
| [ ] | canonicalize | path(path).canonicalize() | Returns the canonical, absolute form of a path with all intermediate components normalized and symbolic links resolved. |
|
||||
| [ ] | copy | file(path).copy(target) | Copies the contents of one file to another. This function will also copy the permission bits of the original file to the destination file. |
|
||||
| [x] | create_dir | dir(path).create() | Creates a new, empty directory at the provided path |
|
||||
| [x] | create_dir_all | dir(path).create_all() | Recursively create a directory and all of its parent components if they are missing. |
|
||||
| [ ] | hard_link | link(path)create() | Creates a new hard link on the filesystem. |
|
||||
| [ ] | metadata | path(path).metadata() | Given a path, query the file system to get information about a file, directory, etc. |
|
||||
| [ ] | read | file(path).reader().bytes() | Read the entire contents of a file into a bytes vector. |
|
||||
| [x] | read_dir | dir(path).read() | Returns an iterator over the entries within a directory. |
|
||||
| [ ] | read_link | link(path).read() | Reads a symbolic link, returning the file that the link points to. |
|
||||
| [x] | read_to_string | file(path).reader().to_string() | Read the entire contents of a file into a string. |
|
||||
| [ ] | remove_dir | dir(path).remove() | Removes an empty directory. |
|
||||
| [ ] | remove_dir_all | dir(path).remove_all() | Removes a directory at this path, after removing all its contents. Use carefully! |
|
||||
| [ ] | remove_file | file(path).remove() | Removes a file from the filesystem. |
|
||||
| [ ] | rename | path(path).rename() | Rename a file or directory to a new name, replacing the original file if to already exists. |
|
||||
| [ ] | set_permissions | path(path).set_permissions() | Changes the permissions found on a file or a directory. |
|
||||
| [ ] | symlink_metadata | link(path).metadata() | Query the metadata about a file without following symlinks. |
|
||||
| [x] | write | file(path).write() | Write a slice as the entire contents of a file. |
|
||||
|
||||
### Network
|
||||
|
||||
|
|
2
justfile
2
justfile
|
@ -1,8 +1,10 @@
|
|||
build:
|
||||
cargo fmt
|
||||
cargo fmt --check
|
||||
cargo hack --feature-powerset clippy
|
||||
cargo hack --feature-powerset build
|
||||
cargo hack --feature-powerset test
|
||||
cargo doc
|
||||
|
||||
install-hooks:
|
||||
@echo "Installing git hooks"
|
||||
|
|
90
src/fs/dir.rs
Normal file
90
src/fs/dir.rs
Normal file
|
@ -0,0 +1,90 @@
|
|||
//
|
||||
use crate::fs::{DirItem, DirItemIterator, Result};
|
||||
|
||||
use super::{
|
||||
path::{DirG, PathReal},
|
||||
FileG, PathG,
|
||||
};
|
||||
|
||||
impl<'base, 'path> PathReal<'base, 'path, DirG> {
|
||||
/// Creates a new, empty directory at the path
|
||||
///
|
||||
/// Wrapper for [std::fs::create_dir]
|
||||
///
|
||||
/// ```
|
||||
/// # fn try_main() -> kxio::fs::Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo");
|
||||
/// let dir = fs.dir(&path);
|
||||
/// dir.create()?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn create(&self) -> Result<()> {
|
||||
self.check_error()?;
|
||||
std::fs::create_dir(self.as_pathbuf()).map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Recursively create a directory and all of its parent components if they are missing.
|
||||
///
|
||||
/// Wrapper for [std::fs::create_dir_all]
|
||||
///
|
||||
/// ```
|
||||
/// # fn try_main() -> kxio::fs::Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo").join("bar");
|
||||
/// let dir = fs.dir(&path);
|
||||
/// dir.create_all()?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn create_all(&self) -> Result<()> {
|
||||
self.check_error()?;
|
||||
std::fs::create_dir_all(self.as_pathbuf()).map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Returns an iterator over the entries within a directory.
|
||||
///
|
||||
/// Wrapper for [std::fs::read_dir]
|
||||
///
|
||||
/// ```
|
||||
/// # fn try_main() -> kxio::fs::Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo").join("bar");
|
||||
/// let dir = fs.dir(&path);
|
||||
/// for entry in dir.read()? { /* ... */ }
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn read(&self) -> Result<Box<dyn Iterator<Item = Result<DirItem>>>> {
|
||||
self.check_error()?;
|
||||
let read_dir = std::fs::read_dir(self.as_pathbuf())?;
|
||||
Ok(Box::new(DirItemIterator::new(read_dir)))
|
||||
}
|
||||
}
|
||||
impl<'base, 'path> TryFrom<PathReal<'base, 'path, PathG>> for PathReal<'base, 'path, FileG> {
|
||||
type Error = crate::fs::Error;
|
||||
|
||||
fn try_from(path: PathReal<'base, 'path, PathG>) -> std::result::Result<Self, Self::Error> {
|
||||
match path.as_file() {
|
||||
Ok(Some(dir)) => Ok(dir.clone()),
|
||||
Ok(None) => Err(crate::fs::Error::NotADirectory {
|
||||
path: path.as_pathbuf(),
|
||||
}),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'base, 'path> TryFrom<PathReal<'base, 'path, PathG>> for PathReal<'base, 'path, DirG> {
|
||||
type Error = crate::fs::Error;
|
||||
|
||||
fn try_from(path: PathReal<'base, 'path, PathG>) -> std::result::Result<Self, Self::Error> {
|
||||
match path.as_dir() {
|
||||
Ok(Some(dir)) => Ok(dir.clone()),
|
||||
Ok(None) => Err(crate::fs::Error::NotADirectory {
|
||||
path: path.as_pathbuf(),
|
||||
}),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,8 +1,10 @@
|
|||
//
|
||||
use std::{
|
||||
fs::{DirEntry, ReadDir},
|
||||
path::PathBuf,
|
||||
};
|
||||
|
||||
/// Represents an item in a directory
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum DirItem {
|
||||
File(PathBuf),
|
||||
|
@ -12,6 +14,7 @@ pub enum DirItem {
|
|||
Unsupported(PathBuf),
|
||||
}
|
||||
|
||||
/// An iterator for items in a directory.
|
||||
#[derive(Debug, derive_more::Constructor)]
|
||||
pub struct DirItemIterator(ReadDir);
|
||||
impl Iterator for DirItemIterator {
|
||||
|
|
43
src/fs/file.rs
Normal file
43
src/fs/file.rs
Normal file
|
@ -0,0 +1,43 @@
|
|||
//
|
||||
use crate::fs::Result;
|
||||
|
||||
use super::{
|
||||
path::{FileG, PathReal},
|
||||
reader::Reader,
|
||||
};
|
||||
|
||||
impl<'base, 'path> PathReal<'base, 'path, FileG> {
|
||||
/// Returns a [Reader] for the file.
|
||||
///
|
||||
/// ```
|
||||
/// # fn try_main() -> kxio::fs::Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo").join("bar");
|
||||
/// let file = fs.file(&path);
|
||||
/// let reader = file.reader()?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn reader(&self) -> Result<Reader> {
|
||||
self.check_error()?;
|
||||
Reader::new(&self.as_pathbuf())
|
||||
}
|
||||
|
||||
/// Writes a slice as the entire contents of a file.
|
||||
///
|
||||
/// Wrapper for [std::fs::write]
|
||||
///
|
||||
/// ```
|
||||
/// # fn try_main() -> kxio::fs::Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo").join("bar");
|
||||
/// let file = fs.file(&path);
|
||||
/// file.write("new file contents")?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn write<C: AsRef<[u8]>>(&self, contents: C) -> Result<()> {
|
||||
self.check_error()?;
|
||||
std::fs::write(self.as_pathbuf(), contents).map_err(Into::into)
|
||||
}
|
||||
}
|
|
@ -1,18 +1,48 @@
|
|||
/// Provides an injectable reference to part of the filesystem.
|
||||
///
|
||||
/// Create a new `FileSystem` to access a directory using `kxio::fs::new(path)`.
|
||||
/// Create a new `TempFileSystem` to access a temporary directory using `kxio::fs::temp()?`;
|
||||
///
|
||||
/// `TempFileSystem` derefs automaticalyl to `FileSystem` so can be used anywhere
|
||||
/// you would use `FileSystem`.
|
||||
use std::path::PathBuf;
|
||||
|
||||
mod dir;
|
||||
mod dir_item;
|
||||
mod real;
|
||||
mod file;
|
||||
mod path;
|
||||
mod reader;
|
||||
mod result;
|
||||
mod system;
|
||||
mod temp;
|
||||
|
||||
pub use dir_item::DirItem;
|
||||
pub use dir_item::DirItemIterator;
|
||||
pub use dir_item::{DirItem, DirItemIterator};
|
||||
pub use path::*;
|
||||
pub use reader::Reader;
|
||||
pub use result::{Error, Result};
|
||||
pub use system::FileSystem;
|
||||
|
||||
pub const fn new(base: PathBuf) -> real::FileSystem {
|
||||
real::FileSystem::new(base)
|
||||
/// Creates a new `FileSystem` for the path.
|
||||
///
|
||||
/// This will create a `FileSystem` that provides access to the
|
||||
/// filesystem under the given path.
|
||||
///
|
||||
/// Any attempt to access outside this base will result in a
|
||||
/// `error::Error::PathTraversal` error when attempting the
|
||||
/// opertation.
|
||||
pub const fn new(base: PathBuf) -> FileSystem {
|
||||
FileSystem::new(base)
|
||||
}
|
||||
|
||||
/// Creates a new `TempFileSystem` for a temporary directory.
|
||||
///
|
||||
/// The `TempFileSystem` provides a `Deref` to a `FileSystem` for
|
||||
/// the temporary directory.
|
||||
///
|
||||
/// When the `TempFileSystem` is dropped, the temporary directory
|
||||
/// is deleted.
|
||||
///
|
||||
/// Returns an error if the temporary directory cannot be created.
|
||||
pub fn temp() -> Result<temp::TempFileSystem> {
|
||||
temp::TempFileSystem::new()
|
||||
}
|
||||
|
|
205
src/fs/path.rs
Normal file
205
src/fs/path.rs
Normal file
|
@ -0,0 +1,205 @@
|
|||
//
|
||||
use std::{
|
||||
marker::PhantomData,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use crate::fs::{Error, Result};
|
||||
|
||||
pub trait PathType {}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PathG;
|
||||
impl PathType for PathG {}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FileG;
|
||||
impl PathType for FileG {}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DirG;
|
||||
impl PathType for DirG {}
|
||||
|
||||
/// Represents a path in the filesystem.
|
||||
///
|
||||
/// It can be a simple path, or it can be a file or a directory.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PathReal<'base, 'path, T: PathType> {
|
||||
base: &'base Path,
|
||||
path: &'path Path,
|
||||
_phanton: PhantomData<T>,
|
||||
pub(super) error: Option<Error>,
|
||||
}
|
||||
impl<'base, 'path, T: PathType> PathReal<'base, 'path, T> {
|
||||
pub(super) fn new(base: &'base Path, path: &'path Path) -> Self {
|
||||
Self {
|
||||
base,
|
||||
path,
|
||||
_phanton: PhantomData::<T>,
|
||||
error: PathReal::<T>::validate(base, path),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a [PathBuf] for the path.
|
||||
///
|
||||
/// ```
|
||||
/// # use kxio::fs::Result;
|
||||
/// # fn main() -> Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo");
|
||||
/// let path = fs.path(&path);
|
||||
/// let pathbuf = path.as_pathbuf();
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn as_pathbuf(&self) -> PathBuf {
|
||||
self.base.join(self.path)
|
||||
}
|
||||
|
||||
pub(super) fn put(&mut self, error: Error) {
|
||||
if self.error.is_none() {
|
||||
self.error.replace(error);
|
||||
}
|
||||
}
|
||||
|
||||
fn validate(base: &Path, path: &Path) -> Option<Error> {
|
||||
match PathReal::<PathG>::clean_path(path) {
|
||||
Err(error) => Some(error),
|
||||
Ok(path) => {
|
||||
if !path.starts_with(base) {
|
||||
return Some(Error::PathTraversal {
|
||||
base: base.to_path_buf(),
|
||||
path,
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn clean_path(path: &Path) -> Result<PathBuf> {
|
||||
// let path = path.as_ref();
|
||||
use path_clean::PathClean;
|
||||
let abs_path = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir().expect("current_dir").join(path)
|
||||
}
|
||||
.clean();
|
||||
Ok(abs_path)
|
||||
}
|
||||
|
||||
pub(super) fn check_error(&self) -> Result<()> {
|
||||
if let Some(error) = &self.error {
|
||||
Err(error.clone())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if the path exists.
|
||||
///
|
||||
/// N.B. If you have the path used to create the file or directory, you
|
||||
/// should use [std::path::Path::exists] instead.
|
||||
///
|
||||
/// ```
|
||||
/// # use kxio::fs::Result;
|
||||
/// # fn main() -> Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo");
|
||||
/// let dir = fs.dir(&path);
|
||||
/// # dir.create()?;
|
||||
/// if dir.exists()? { /* ... */ }
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn exists(&self) -> Result<bool> {
|
||||
self.check_error()?;
|
||||
Ok(self.as_pathbuf().exists())
|
||||
}
|
||||
|
||||
/// Returns true if the path is a directory.
|
||||
///
|
||||
/// ```
|
||||
/// # use kxio::fs::Result;
|
||||
/// # fn main() -> Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo");
|
||||
/// # fs.dir(&path).create()?;
|
||||
/// if path.is_dir() { /* ... */ }
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn is_dir(&self) -> Result<bool> {
|
||||
self.check_error()?;
|
||||
Ok(self.as_pathbuf().is_dir())
|
||||
}
|
||||
|
||||
/// Returns true if the path is a file.
|
||||
///
|
||||
/// ```
|
||||
/// # use kxio::fs::Result;
|
||||
/// # fn main() -> Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo");
|
||||
/// # fs.dir(&path).create()?;
|
||||
/// if path.is_file() { /* ... */ }
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn is_file(&self) -> Result<bool> {
|
||||
self.check_error()?;
|
||||
Ok(self.as_pathbuf().is_file())
|
||||
}
|
||||
|
||||
/// Returns the path as a directory if it exists and is a directory, otherwise
|
||||
/// it will return None.
|
||||
///
|
||||
/// ```
|
||||
/// # use kxio::fs::Result;
|
||||
/// # fn main() -> Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo");
|
||||
/// # fs.dir(&path).create()?;
|
||||
/// let file = fs.path(&path);
|
||||
/// if let Ok(Some(dir)) = file.as_dir() { /* ... */ }
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn as_dir(&self) -> Result<Option<PathReal<'base, 'path, DirG>>> {
|
||||
self.check_error()?;
|
||||
if self.as_pathbuf().is_dir() {
|
||||
Ok(Some(PathReal::new(self.base, self.path)))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the path as a file if it exists and is a file, otherwise
|
||||
/// it will return None.
|
||||
///
|
||||
/// ```
|
||||
/// # use kxio::fs::Result;
|
||||
/// # fn main() -> Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo");
|
||||
/// # fs.dir(&path).create()?;
|
||||
/// let file = fs.path(&path);
|
||||
/// if let Ok(Some(file)) = file.as_file() { /* ... */ }
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn as_file(&self) -> Result<Option<PathReal<'base, 'path, FileG>>> {
|
||||
self.check_error()?;
|
||||
if self.as_pathbuf().is_file() {
|
||||
Ok(Some(PathReal::new(self.base, self.path)))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<PathReal<'_, '_, PathG>> for PathBuf {
|
||||
fn from(path: PathReal<PathG>) -> Self {
|
||||
path.base.join(path.path)
|
||||
}
|
||||
}
|
71
src/fs/reader.rs
Normal file
71
src/fs/reader.rs
Normal file
|
@ -0,0 +1,71 @@
|
|||
//
|
||||
use std::{fmt::Display, path::Path, str::Lines};
|
||||
|
||||
use crate::fs::Result;
|
||||
|
||||
/// A reader for a file.
|
||||
pub struct Reader {
|
||||
contents: String,
|
||||
}
|
||||
impl Reader {
|
||||
pub(super) fn new(path: &Path) -> Result<Self> {
|
||||
let contents = std::fs::read_to_string(path)?;
|
||||
Ok(Self { contents })
|
||||
}
|
||||
|
||||
/// Returns the contents of the file as a string.
|
||||
///
|
||||
/// ```
|
||||
/// # use kxio::fs::Result;
|
||||
/// # fn main() -> Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo");
|
||||
/// let file = fs.file(&path);
|
||||
/// # file.write("new file contents")?;
|
||||
/// let contents = file.reader()?.contents();
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn contents(&self) -> &str {
|
||||
&self.contents
|
||||
}
|
||||
|
||||
/// Returns the contents of the file as a string.
|
||||
///
|
||||
/// ```
|
||||
/// # use kxio::fs::Result;
|
||||
/// # fn main() -> Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo");
|
||||
/// let file = fs.file(&path);
|
||||
/// # file.write("new file contents")?;
|
||||
/// let contents = file.reader()?.as_str();
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.contents
|
||||
}
|
||||
|
||||
/// Returns an iterator over the lines in the file.
|
||||
///
|
||||
/// ```
|
||||
/// # use kxio::fs::Result;
|
||||
/// # fn main() -> Result<()> {
|
||||
/// let fs = kxio::fs::temp()?;
|
||||
/// let path = fs.base().join("foo");
|
||||
/// let file = fs.file(&path);
|
||||
/// # file.write("new file contents")?;
|
||||
/// let lines = file.reader()?.lines();
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn lines(&self) -> Lines<'_> {
|
||||
self.contents.lines()
|
||||
}
|
||||
}
|
||||
impl Display for Reader {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.contents)
|
||||
}
|
||||
}
|
|
@ -1,64 +0,0 @@
|
|||
//
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::fs::{DirItem, DirItemIterator, Error, Result};
|
||||
|
||||
use super::path::PathReal;
|
||||
|
||||
pub struct DirReal<'base, 'path> {
|
||||
path: PathReal<'base, 'path>,
|
||||
}
|
||||
impl<'base, 'path> DirReal<'base, 'path> {
|
||||
pub(super) fn new(base: &'base Path, path: &'path Path) -> Self {
|
||||
let mut path = PathReal::new(base, path);
|
||||
if path.error.is_none() {
|
||||
if let Ok(exists) = path.exists() {
|
||||
if exists {
|
||||
if let Ok(is_dir) = path.is_dir() {
|
||||
if !is_dir {
|
||||
path.put(Error::NotADirectory {
|
||||
path: path.full_path(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Self { path }
|
||||
}
|
||||
|
||||
pub fn path(&self) -> PathBuf {
|
||||
self.path.full_path()
|
||||
}
|
||||
|
||||
pub fn create(&mut self) -> Result<()> {
|
||||
self.path.check_error()?;
|
||||
std::fs::create_dir(self.path.full_path()).map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn create_all(&mut self) -> Result<()> {
|
||||
self.path.check_error()?;
|
||||
std::fs::create_dir_all(self.path.full_path()).map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn read(&mut self) -> Result<Box<dyn Iterator<Item = Result<DirItem>>>> {
|
||||
self.path.check_error()?;
|
||||
let read_dir = std::fs::read_dir(self.path.full_path())?;
|
||||
Ok(Box::new(DirItemIterator::new(read_dir)))
|
||||
}
|
||||
|
||||
pub fn exists(&mut self) -> Result<bool> {
|
||||
self.path.check_error()?;
|
||||
self.path.exists()
|
||||
}
|
||||
|
||||
pub fn is_dir(&mut self) -> Result<bool> {
|
||||
self.path.check_error()?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn is_file(&mut self) -> Result<bool> {
|
||||
self.path.check_error()?;
|
||||
Ok(false)
|
||||
}
|
||||
}
|
|
@ -1,46 +0,0 @@
|
|||
//
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::fs::Result;
|
||||
|
||||
use super::{path::PathReal, reader::ReaderReal};
|
||||
|
||||
pub struct FileReal<'base, 'path> {
|
||||
path: PathReal<'base, 'path>,
|
||||
}
|
||||
impl<'base, 'path> FileReal<'base, 'path> {
|
||||
pub(super) fn new(base: &'base Path, path: &'path Path) -> Self {
|
||||
Self {
|
||||
path: PathReal::new(base, path),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path(&self) -> PathBuf {
|
||||
self.path.full_path()
|
||||
}
|
||||
|
||||
pub fn reader(&mut self) -> Result<ReaderReal> {
|
||||
self.path.check_error()?;
|
||||
ReaderReal::new(&self.path.full_path())
|
||||
}
|
||||
|
||||
pub fn write(&mut self, contents: &str) -> Result<()> {
|
||||
self.path.check_error()?;
|
||||
std::fs::write(self.path.full_path(), contents).map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn exists(&mut self) -> Result<bool> {
|
||||
self.path.check_error()?;
|
||||
self.path.exists()
|
||||
}
|
||||
|
||||
pub fn is_dir(&mut self) -> Result<bool> {
|
||||
self.path.check_error()?;
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub fn is_file(&mut self) -> Result<bool> {
|
||||
self.path.check_error()?;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
|
@ -1,8 +0,0 @@
|
|||
//
|
||||
mod dir;
|
||||
mod file;
|
||||
mod path;
|
||||
mod reader;
|
||||
mod system;
|
||||
|
||||
pub use system::FileSystem;
|
|
@ -1,102 +0,0 @@
|
|||
//
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::fs::{Error, Result};
|
||||
|
||||
use super::{dir::DirReal, file::FileReal};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PathReal<'base, 'path> {
|
||||
base: &'base Path,
|
||||
path: &'path Path,
|
||||
pub(super) error: Option<Error>,
|
||||
}
|
||||
impl<'base, 'path> PathReal<'base, 'path> {
|
||||
pub(super) fn full_path(&self) -> PathBuf {
|
||||
self.base.join(self.path)
|
||||
}
|
||||
pub(super) fn put(&mut self, error: Error) {
|
||||
if self.error.is_none() {
|
||||
self.error.replace(error);
|
||||
}
|
||||
}
|
||||
fn validate(base: &Path, path: &Path) -> Option<Error> {
|
||||
match PathReal::clean_path(path) {
|
||||
Err(error) => Some(error),
|
||||
Ok(path) => {
|
||||
if !path.starts_with(base) {
|
||||
return Some(Error::PathTraversal {
|
||||
base: base.to_path_buf(),
|
||||
path,
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn clean_path(path: &Path) -> Result<PathBuf> {
|
||||
// let path = path.as_ref();
|
||||
use path_clean::PathClean;
|
||||
let abs_path = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir().expect("current_dir").join(path)
|
||||
}
|
||||
.clean();
|
||||
Ok(abs_path)
|
||||
}
|
||||
|
||||
pub(super) fn new(base: &'base Path, path: &'path Path) -> Self {
|
||||
Self {
|
||||
base,
|
||||
path,
|
||||
error: PathReal::validate(base, path),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exists(&mut self) -> Result<bool> {
|
||||
self.check_error()?;
|
||||
Ok(self.full_path().exists())
|
||||
}
|
||||
|
||||
pub(super) fn check_error(&mut self) -> Result<()> {
|
||||
if let Some(error) = self.error.take() {
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_dir(&mut self) -> Result<bool> {
|
||||
self.check_error()?;
|
||||
Ok(self.full_path().is_dir())
|
||||
}
|
||||
|
||||
pub fn is_file(&mut self) -> Result<bool> {
|
||||
self.check_error()?;
|
||||
Ok(self.full_path().is_file())
|
||||
}
|
||||
|
||||
pub fn as_dir(&mut self) -> Result<Option<DirReal<'base, 'path>>> {
|
||||
self.check_error()?;
|
||||
if self.full_path().is_dir() {
|
||||
Ok(Some(DirReal::new(self.base, self.path)))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_file(&mut self) -> Result<Option<FileReal<'base, 'path>>> {
|
||||
self.check_error()?;
|
||||
if self.full_path().is_file() {
|
||||
Ok(Some(FileReal::new(self.base, self.path)))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<PathReal<'_, '_>> for PathBuf {
|
||||
fn from(path: PathReal) -> Self {
|
||||
path.base.join(path.path)
|
||||
}
|
||||
}
|
|
@ -1,27 +0,0 @@
|
|||
//
|
||||
use std::{fmt::Display, path::Path, str::Lines};
|
||||
|
||||
use crate::fs::Result;
|
||||
|
||||
pub struct ReaderReal {
|
||||
contents: String,
|
||||
}
|
||||
impl ReaderReal {
|
||||
pub(super) fn new(path: &Path) -> Result<Self> {
|
||||
let contents = std::fs::read_to_string(path)?;
|
||||
Ok(Self { contents })
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.contents
|
||||
}
|
||||
|
||||
pub fn lines(&self) -> Lines<'_> {
|
||||
self.contents.lines()
|
||||
}
|
||||
}
|
||||
impl Display for ReaderReal {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.contents)
|
||||
}
|
||||
}
|
|
@ -3,10 +3,17 @@ use std::path::PathBuf;
|
|||
|
||||
use derive_more::From;
|
||||
|
||||
/// Represents a error accessing the file system.
|
||||
///
|
||||
/// Any failure is related to `std::io`, a Path Traversal
|
||||
/// (i.e. trying to escape the base of the `FileSystem`),
|
||||
/// or attempting to use a file as a directory or /vise versa/.
|
||||
#[derive(Debug, From, derive_more::Display)]
|
||||
pub enum Error {
|
||||
Io(std::io::Error),
|
||||
|
||||
IoString(String),
|
||||
|
||||
#[display("Path access attempted outside of base ({base:?}): {path:?}")]
|
||||
PathTraversal {
|
||||
base: PathBuf,
|
||||
|
@ -19,5 +26,23 @@ pub enum Error {
|
|||
},
|
||||
}
|
||||
impl std::error::Error for Error {}
|
||||
impl Clone for Error {
|
||||
fn clone(&self) -> Self {
|
||||
match self {
|
||||
Error::Io(err) => Error::IoString(err.to_string()),
|
||||
Error::IoString(err) => Error::IoString(err.clone()),
|
||||
Error::PathTraversal { base, path } => Error::PathTraversal {
|
||||
base: base.clone(),
|
||||
path: path.clone(),
|
||||
},
|
||||
Error::NotADirectory { path } => Error::NotADirectory { path: path.clone() },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a success or a failure.
|
||||
///
|
||||
/// Any failure is related to `std::io`, a Path Traversal
|
||||
/// (i.e. trying to escape the base of the `FileSystem`),
|
||||
/// or attempting to use a file as a directory or /vise versa/.
|
||||
pub type Result<T> = core::result::Result<T, Error>;
|
||||
|
|
|
@ -3,8 +3,9 @@ use std::path::{Path, PathBuf};
|
|||
|
||||
use crate::fs::{Error, Result};
|
||||
|
||||
use super::{dir::DirReal, file::FileReal, path::PathReal};
|
||||
use super::path::{DirG, FileG, PathG, PathReal};
|
||||
|
||||
/// Represents to base of a section of a file system.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FileSystem {
|
||||
base: PathBuf,
|
||||
|
@ -13,6 +14,7 @@ impl FileSystem {
|
|||
pub const fn new(base: PathBuf) -> Self {
|
||||
Self { base }
|
||||
}
|
||||
|
||||
pub fn base(&self) -> &Path {
|
||||
&self.base
|
||||
}
|
||||
|
@ -23,15 +25,32 @@ impl FileSystem {
|
|||
Ok(path_of)
|
||||
}
|
||||
|
||||
pub fn dir<'base, 'path>(&'base self, path: &'path Path) -> DirReal<'base, 'path> {
|
||||
DirReal::new(self.base(), path)
|
||||
/// Access the path as a directory.
|
||||
pub fn dir<'base, 'path>(&'base self, path: &'path Path) -> PathReal<'base, 'path, DirG> {
|
||||
let mut dir = PathReal::new(self.base(), path);
|
||||
|
||||
if dir.error.is_none() {
|
||||
if let Ok(exists) = dir.exists() {
|
||||
if exists {
|
||||
if let Ok(is_dir) = dir.is_dir() {
|
||||
if !is_dir {
|
||||
dir.put(Error::NotADirectory {
|
||||
path: dir.as_pathbuf(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dir
|
||||
}
|
||||
|
||||
pub fn file<'base, 'path>(&'base self, path: &'path Path) -> FileReal<'base, 'path> {
|
||||
FileReal::new(self.base(), path)
|
||||
pub fn file<'base, 'path>(&'base self, path: &'path Path) -> PathReal<'base, 'path, FileG> {
|
||||
PathReal::new(self.base(), path)
|
||||
}
|
||||
|
||||
pub fn path<'base, 'path>(&'base self, path: &'path Path) -> PathReal<'base, 'path> {
|
||||
pub fn path<'base, 'path>(&'base self, path: &'path Path) -> PathReal<'base, 'path, PathG> {
|
||||
PathReal::new(self.base(), path)
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@ use std::sync::{Arc, Mutex};
|
|||
|
||||
use tempfile::TempDir;
|
||||
|
||||
use super::real::FileSystem;
|
||||
use super::FileSystem;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TempFileSystem {
|
||||
|
|
22
tests/fs.rs
22
tests/fs.rs
|
@ -40,12 +40,12 @@ mod path {
|
|||
let fs = fs::temp().expect("temp fs");
|
||||
|
||||
let path = fs.base().join("foo");
|
||||
let mut dir = fs.dir(&path);
|
||||
let dir = fs.dir(&path);
|
||||
dir.create().expect("create");
|
||||
|
||||
let_assert!(Ok(Some(as_dir)) = fs.path(&path).as_dir());
|
||||
|
||||
assert_eq!(dir.path(), as_dir.path());
|
||||
assert_eq!(dir.as_pathbuf(), as_dir.as_pathbuf());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
@ -55,12 +55,12 @@ mod path {
|
|||
let fs = fs::temp().expect("temp fs");
|
||||
|
||||
let path = fs.base().join("foo");
|
||||
let mut file = fs.file(&path);
|
||||
let file = fs.file(&path);
|
||||
file.write("contents").expect("create");
|
||||
|
||||
let_assert!(Ok(Some(mut as_file)) = fs.path(&path).as_file());
|
||||
let_assert!(Ok(Some(as_file)) = fs.path(&path).as_file());
|
||||
|
||||
assert_eq!(file.path(), as_file.path());
|
||||
assert_eq!(file.as_pathbuf(), as_file.as_pathbuf());
|
||||
assert_eq!(as_file.reader().expect("reader").to_string(), "contents");
|
||||
|
||||
Ok(())
|
||||
|
@ -70,7 +70,7 @@ mod path {
|
|||
let fs = fs::temp().expect("temp fs");
|
||||
|
||||
let path = fs.base().join("foo");
|
||||
let mut dir = fs.dir(&path);
|
||||
let dir = fs.dir(&path);
|
||||
dir.create().expect("create");
|
||||
|
||||
let_assert!(Ok(None) = fs.path(&path).as_file());
|
||||
|
@ -82,7 +82,7 @@ mod path {
|
|||
let fs = fs::temp().expect("temp fs");
|
||||
|
||||
let path = fs.base().join("foo");
|
||||
let mut file = fs.file(&path);
|
||||
let file = fs.file(&path);
|
||||
file.write("contents").expect("create");
|
||||
|
||||
let_assert!(Ok(None) = fs.path(&path).as_dir());
|
||||
|
@ -100,12 +100,12 @@ mod file {
|
|||
let fs = fs::temp().expect("temp fs");
|
||||
let pathbuf = fs.base().join("foo");
|
||||
|
||||
let mut file = fs.file(&pathbuf);
|
||||
let file = fs.file(&pathbuf);
|
||||
file.write("content").expect("write");
|
||||
let c = file.reader().expect("reader").to_string();
|
||||
assert_eq!(c, "content");
|
||||
|
||||
let mut path = fs.path(&pathbuf);
|
||||
let path = fs.path(&pathbuf);
|
||||
let exists = path.exists().expect("exists");
|
||||
assert!(exists);
|
||||
|
||||
|
@ -120,7 +120,7 @@ mod file {
|
|||
let fs = fs::temp().expect("temp fs");
|
||||
|
||||
let path = fs.base().join("foo");
|
||||
let mut file = fs.file(&path);
|
||||
let file = fs.file(&path);
|
||||
file.write("line 1\nline 2").expect("write");
|
||||
|
||||
let reader = file.reader().expect("reader");
|
||||
|
@ -174,7 +174,7 @@ mod dir_create_all {
|
|||
|
||||
fs.dir(&pathbuf).create_all().expect("create_all");
|
||||
|
||||
let mut path = fs.path(&pathbuf);
|
||||
let path = fs.path(&pathbuf);
|
||||
let exists = path.exists().expect("exists");
|
||||
assert!(exists, "path exists");
|
||||
|
||||
|
|
Loading…
Reference in a new issue