From 958aac71e9130b4f61e2e829dafe1b3ee16caa66 Mon Sep 17 00:00:00 2001 From: gennyble Date: Sat, 12 Oct 2024 04:31:35 -0500 Subject: little bit a Filesystem::reverse_resolve --- src/fs.rs | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/fs.rs b/src/fs.rs index 831aa86..e47889b 100755 --- a/src/fs.rs +++ b/src/fs.rs @@ -1,6 +1,6 @@ use camino::{Utf8Path, Utf8PathBuf}; use core::fmt; -use std::{io, ops::Deref, str::FromStr}; +use std::{fmt, io, ops::Deref, str::FromStr}; use crate::RuntimeError; @@ -154,6 +154,46 @@ impl Filesystem { } } + /// Resolve a file system path to a webpath. + /// + /// Paths are not checked to see if they exist and are not checked to be within the webroot. + /// + /// Paths attempt to resolve to the simplest form. For example, if the path is [`ROOT_INDEX`] + /// it will come out as `/` and if it is a dirfile, it will come out as a directory. + /// + /// **FOOTGUN** currently assumes every path is a file... + pub fn reverse_resolve>(&self, path: P) -> Result { + let path = path.as_ref(); + let relpath = match path.strip_prefix(&self.webroot) { + Ok(relpath) => relpath, + Err(_e) => { + if path.is_relative() { + path + } else { + //FIXME: gen- This error is not strictly correct, but it'll do for now. + // 2024-10-12 + return Err(RuntimeError::PathTooLow { + path: path.to_string(), + }); + } + } + }; + + if relpath == "" || relpath == ROOT_INDEX { + return Ok(Webpath { + webcanon: Utf8PathBuf::new(), + is_dir: true, + }); + } + + todo!(); + + Ok(Webpath { + webcanon: relpath.into(), + is_dir: false, + }) + } + pub fn metadata>(path: P) -> Result { path.as_ref() .metadata() @@ -248,4 +288,23 @@ mod test { format!("{TESTROOT}/one/one.html") ); } + + #[test] + fn filesystem_reverse_resolves_index() { + let fs = Filesystem::new(TESTROOT); + + assert_eq!(fs.reverse_resolve(TESTROOT).unwrap(), webpath!("/")); + assert_eq!( + fs.reverse_resolve(format!("{TESTROOT}/{ROOT_INDEX}")) + .unwrap(), + webpath!("/") + ) + } + + #[test] + fn filesystem_reverse_resolves_directories() { + let fs = Filesystem::new(TESTROOT); + + assert_eq!(fs.reverse_resolve("test/").unwrap(), webpath!("test/")) + } } -- cgit 1.4.1-3-g733a5