refactor(fs): reorder trait methods

This commit is contained in:
Paul Campbell 2024-04-28 12:48:32 +01:00
parent 9c76ddc3e1
commit a77ed422eb
2 changed files with 16 additions and 12 deletions

View file

@ -4,9 +4,11 @@ use std::path::{Path, PathBuf};
pub trait FileSystemLike {
fn base(&self) -> &Path;
fn path_of(&self, path: PathBuf) -> Result<PathBuf>;
fn file_write(&self, path: &Path, contents: &str) -> 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_file(&self, path: &Path) -> Result<bool>;
fn path_of(&self, path: PathBuf) -> Result<PathBuf>;
}

View file

@ -12,10 +12,11 @@ impl super::FileSystemLike for RealFileSystem {
fn base(&self) -> &Path {
&self.base
}
fn path_of(&self, path: PathBuf) -> super::Result<PathBuf> {
let path_of = self.base.as_path().join(path);
self.validate(&path_of)?;
Ok(path_of)
fn file_read_to_string(&self, path: &Path) -> super::Result<String> {
self.validate(path)?;
std::fs::read_to_string(path).map_err(Into::into)
}
fn file_write(&self, path: &Path, contents: &str) -> super::Result<()> {
@ -23,9 +24,9 @@ impl super::FileSystemLike for RealFileSystem {
std::fs::write(path, contents).map_err(Into::into)
}
fn file_read_to_string(&self, path: &Path) -> super::Result<String> {
fn path_exists(&self, path: &Path) -> super::Result<bool> {
self.validate(path)?;
std::fs::read_to_string(path).map_err(Into::into)
Ok(path.exists())
}
fn path_is_file(&self, path: &Path) -> super::Result<bool> {
@ -33,14 +34,15 @@ impl super::FileSystemLike for RealFileSystem {
Ok(path.is_file())
}
fn path_exists(&self, path: &Path) -> super::Result<bool> {
self.validate(path)?;
Ok(path.exists())
fn path_of(&self, path: PathBuf) -> super::Result<PathBuf> {
let path_of = self.base.as_path().join(path);
self.validate(&path_of)?;
Ok(path_of)
}
}
impl RealFileSystem {
fn validate(&self, path: &std::path::Path) -> super::Result<()> {
fn validate(&self, path: &Path) -> super::Result<()> {
if !path.starts_with(&self.base) {
return Err(super::Error::PathTraversal {
base: self.base.clone(),