From 23876c5420c20292966367659708a200c8668f96 Mon Sep 17 00:00:00 2001 From: gennyble Date: Thu, 22 Feb 2024 04:12:40 -0600 Subject: Minimum viable --- src/fs.rs | 52 ++++++++++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 24 deletions(-) (limited to 'src/fs.rs') diff --git a/src/fs.rs b/src/fs.rs index e13f405..d9b8810 100644 --- a/src/fs.rs +++ b/src/fs.rs @@ -1,6 +1,9 @@ use camino::{Utf8Path, Utf8PathBuf}; +use core::fmt; use std::{io, ops::Deref, str::FromStr}; +use crate::RuntimeError; + /// Webpath is the path we get from HTTP requests. It's garunteed to not fall /// below the webroot and will never start or end with a slash. #[derive(Clone, Debug, PartialEq)] @@ -60,9 +63,16 @@ impl PartialEq for Webpath { } } +impl fmt::Display for Webpath { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "/{}", self.webcanon) + } +} + const ROOT_INDEX: &str = "home.html"; const DIRFILE_EXT: &str = "html"; +#[derive(Clone, Debug)] pub struct Filesystem { webroot: Utf8PathBuf, } @@ -74,7 +84,8 @@ impl Filesystem { } } - fn resolve(&self, webpath: &Webpath) -> Result { + pub fn resolve(&self, webpath: &Webpath) -> Result { + println!("resolve = {webpath}"); if webpath.is_index() || webpath == ROOT_INDEX { return Ok(self.webroot.join(ROOT_INDEX)); } @@ -102,35 +113,28 @@ impl Filesystem { } } - fn metadata>(path: P) -> Result { + pub fn metadata>(path: P) -> Result { path.as_ref() .metadata() .map_err(|ioe| RuntimeError::from_io(ioe, path.as_ref().to_owned())) } -} -#[derive(Debug, snafu::Snafu)] -pub enum RuntimeError { - #[snafu(display("the path was not found: {path}"))] - NotFound { - source: io::Error, - path: Utf8PathBuf, - }, - #[snafu(display("io error: {path}: {source}"))] - UnknownIo { - source: io::Error, - path: Utf8PathBuf, - }, - #[snafu(display("path tried to go below webroot: {path}"))] - PathTooLow { path: String }, -} + pub async fn open>(path: P) -> Result { + tokio::fs::File::open(path.as_ref()) + .await + .map_err(|ioe| RuntimeError::from_io(ioe, path.as_ref().to_owned())) + } -impl RuntimeError { - pub fn from_io(source: io::Error, path: Utf8PathBuf) -> Self { - match source.kind() { - io::ErrorKind::NotFound => RuntimeError::NotFound { source, path }, - _ => RuntimeError::UnknownIo { source, path }, - } + pub async fn read>(path: P) -> Result, RuntimeError> { + tokio::fs::read(path.as_ref()) + .await + .map_err(|ioe| RuntimeError::from_io(ioe, path.as_ref().to_owned())) + } + + pub async fn read_to_string>(path: P) -> Result { + tokio::fs::read_to_string(path.as_ref()) + .await + .map_err(|ioe| RuntimeError::from_io(ioe, path.as_ref().to_owned())) } } -- cgit 1.4.1-3-g733a5