devpage_core/folder/
served.rs1use std::path::{Path, PathBuf};
8
9#[derive(Debug, Clone, Default, PartialEq, Eq)]
15pub struct ServedFolder(PathBuf, String);
16
17impl ServedFolder {
18 pub fn new(path: &Path) -> std::io::Result<Self> {
21 path.canonicalize().map(Self::canonical)
22 }
23
24 pub fn canonical(path: PathBuf) -> Self {
26 Self(path, String::new())
27 }
28
29 pub fn mounted(self, mount: &str) -> Self {
32 debug_assert!(mount.is_empty() || (mount.starts_with('/') && !mount.ends_with('/')));
33 Self(self.0, mount.to_string())
34 }
35
36 pub fn mount(&self) -> &str {
38 &self.1
39 }
40
41 pub fn path(&self) -> &Path {
43 &self.0
44 }
45
46 pub fn inside(&self, path: &Path) -> Option<PathBuf> {
48 let real = path.canonicalize().ok()?;
49 real.starts_with(&self.0).then_some(real)
50 }
51
52 pub fn file(&self, path: &Path) -> Option<PathBuf> {
54 self.inside(path).filter(|real| real.is_file())
55 }
56
57 pub fn folder(&self, path: &Path) -> Option<PathBuf> {
59 self.inside(path).filter(|real| real.is_dir())
60 }
61
62 pub fn named(&self, path: &Path) -> Option<PathBuf> {
68 if let Some(file) = self.file(path) {
69 return Some(file);
70 }
71 let lexical = lexical(path);
72 let would_be = match (lexical.parent(), lexical.file_name()) {
73 (Some(parent), Some(name)) => parent
74 .canonicalize()
75 .map(|parent| parent.join(name))
76 .unwrap_or(lexical),
77 _ => lexical,
78 };
79 (self.contains(&would_be) && std::fs::symlink_metadata(&would_be).is_err())
80 .then_some(would_be)
81 }
82
83 pub fn at(&self, url_path: &str) -> Option<PathBuf> {
86 self.inside(&self.0.join(url_path.trim_start_matches('/')))
87 }
88
89 pub fn file_at(&self, url_path: &str) -> Option<PathBuf> {
91 self.at(url_path).filter(|real| real.is_file())
92 }
93
94 pub fn contains(&self, path: &Path) -> bool {
98 path.starts_with(&self.0)
99 }
100
101 pub fn relative<'a>(&self, path: &'a Path) -> Option<&'a Path> {
103 path.strip_prefix(&self.0).ok()
104 }
105
106 pub fn url(&self, file: &Path) -> Option<String> {
110 Some(format!("{}/{}", self.1, self.name(file)?))
111 }
112
113 pub fn name(&self, file: &Path) -> Option<String> {
117 Some(slashed(self.relative(file)?))
118 }
119}
120
121#[cfg(any(test, feature = "testing"))]
125pub fn symlink(target: &Path, link: &Path) -> std::io::Result<()> {
126 #[cfg(unix)]
127 return std::os::unix::fs::symlink(target, link);
128 #[cfg(windows)]
129 return if target.is_dir() {
130 std::os::windows::fs::symlink_dir(target, link)
131 } else {
132 std::os::windows::fs::symlink_file(target, link)
133 };
134}
135
136pub fn slashed(path: &Path) -> String {
139 path.components()
140 .map(|c| c.as_os_str().to_string_lossy())
141 .collect::<Vec<_>>()
142 .join("/")
143}
144
145pub(crate) fn lexical(path: &Path) -> PathBuf {
149 use std::path::Component;
150 let mut out = PathBuf::new();
151 for component in path.components() {
152 match component {
153 Component::CurDir => {}
154 Component::ParentDir => {
155 out.pop();
156 }
157 other => out.push(other),
158 }
159 }
160 out
161}
162
163impl AsRef<Path> for ServedFolder {
164 fn as_ref(&self) -> &Path {
165 &self.0
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 fn fixture(name: &str) -> (PathBuf, ServedFolder) {
176 let top =
177 std::env::temp_dir().join(format!("devpage-served-{name}-{}", std::process::id()));
178 let _ = std::fs::remove_dir_all(&top);
179 std::fs::create_dir_all(top.join("served/docs")).unwrap();
180 std::fs::write(top.join("outside.txt"), "secret").unwrap();
181 std::fs::write(top.join("served/docs/a.md"), "# A").unwrap();
182 symlink(&top.join("outside.txt"), &top.join("served/link-out")).unwrap();
183 let served = ServedFolder::new(&top.join("served")).unwrap();
184 (top.canonicalize().unwrap(), served)
185 }
186
187 #[test]
190 fn names_and_addresses_join_with_slashes() {
191 let (top, served) = fixture("slashes");
192 let a = served
193 .file(&top.join("served").join("docs").join("a.md"))
194 .unwrap();
195 assert_eq!(served.name(&a).as_deref(), Some("docs/a.md"));
196 assert_eq!(served.url(&a).as_deref(), Some("/docs/a.md"));
197 std::fs::remove_dir_all(&top).ok();
198 }
199
200 #[test]
201 fn resolves_files_and_folders_inside() {
202 let (top, served) = fixture("inside");
203 let a = top.join("served/docs/a.md");
204 assert_eq!(
205 served.file(&top.join("served/docs/../docs/a.md")),
206 Some(a.clone())
207 );
208 assert_eq!(
209 served.folder(&top.join("served/docs")),
210 Some(top.join("served/docs"))
211 );
212 assert_eq!(
213 served.file(&top.join("served/docs")),
214 None,
215 "a folder is no file"
216 );
217 assert_eq!(served.folder(&a), None, "a file is no folder");
218 assert_eq!(served.at("/docs/a.md"), Some(a.clone()));
219 assert_eq!(served.file_at("/docs/a.md"), Some(a.clone()));
220 assert_eq!(served.file_at("/docs"), None, "a folder is no file");
221 assert_eq!(served.url(&a).as_deref(), Some("/docs/a.md"));
222 assert_eq!(served.name(&a).as_deref(), Some("docs/a.md"));
223 assert_eq!(served.relative(&a), Some(Path::new("docs/a.md")));
224 }
225
226 #[test]
227 fn a_mounted_folder_addresses_its_files_under_the_mount() {
228 let (top, served) = fixture("mounted");
229 let a = top.join("served/docs/a.md");
230 let mounted = served.clone().mounted("/d/x/v/2");
231 assert_eq!(mounted.url(&a).as_deref(), Some("/d/x/v/2/docs/a.md"));
232 assert_eq!(
233 mounted.name(&a).as_deref(),
234 Some("docs/a.md"),
235 "a name is the same anywhere"
236 );
237 assert_eq!(mounted.mount(), "/d/x/v/2");
238 assert_eq!(ServedFolder::new(&top.join("served")).unwrap(), served);
240 }
241
242 #[test]
243 fn refuses_what_climbs_out_or_links_out() {
244 let (top, served) = fixture("outside");
245 assert_eq!(served.at("/../outside.txt"), None);
246 assert_eq!(served.file_at("/../outside.txt"), None);
247 assert_eq!(served.file(&top.join("served/../outside.txt")), None);
248 assert_eq!(served.at("/link-out"), None);
249 assert_eq!(served.file(&top.join("served/link-out")), None);
250 assert_eq!(served.inside(&top.join("served/missing.md")), None);
251 assert!(!served.contains(&top.join("outside.txt")));
252 assert_eq!(served.relative(&top.join("outside.txt")), None);
253 assert_eq!(served.name(&top.join("outside.txt")), None);
255 assert_eq!(served.url(&top.join("outside.txt")), None);
256 assert_eq!(
257 served.clone().mounted("/d/x").url(&top.join("outside.txt")),
258 None
259 );
260 }
261
262 #[test]
263 fn a_deleted_file_is_still_inside_by_its_path() {
264 let (top, served) = fixture("deleted");
265 let gone = top.join("served/docs/gone.md");
266 assert!(served.contains(&gone));
267 assert_eq!(served.inside(&gone), None, "it no longer resolves");
268 }
269}