Skip to main content

tilo_paths/
location.rs

1//! Locations as portable values: an operating-system path, or a path inside a virtual
2//! storage root the platform's file layer serves.
3
4use std::fmt;
5use std::path::{Path, PathBuf};
6
7use crate::caps::{Feature, Unsupported, WEB_NATIVE_PATHS};
8
9/// Where something lives. Native targets give paths; the web gives virtual
10/// roots, and so does a native process that has no home directory, whose
11/// storage then lasts only as long as the process.
12#[derive(Clone, Debug, PartialEq, Eq, Hash)]
13pub enum Location {
14    Native(PathBuf),
15    Virtual(VirtualRoot, VPath),
16}
17
18impl Location {
19    /// The operating-system path, for code that must hand one to a native API; portable
20    /// code opens locations through the platform's file layer instead.
21    ///
22    /// # Errors
23    ///
24    /// [`Unsupported`] for a virtual location, which has no path.
25    pub fn native_path(&self) -> Result<&Path, Unsupported> {
26        match self {
27            Self::Native(path) => Ok(path),
28            Self::Virtual(root, _) => Err(Unsupported {
29                feature: Feature::NativePaths,
30                reason: match root {
31                    VirtualRoot::Opfs { .. } => WEB_NATIVE_PATHS,
32                    VirtualRoot::Memory => "Storage kept in memory has no file system path.",
33                },
34            }),
35        }
36    }
37
38    #[must_use]
39    pub fn join(&self, relative: &VPath) -> Self {
40        match self {
41            Self::Native(path) => Self::Native(
42                relative
43                    .components()
44                    .fold(path.clone(), |path, component| path.join(component)),
45            ),
46            Self::Virtual(root, path) => Self::Virtual(root.clone(), path.join(relative)),
47        }
48    }
49}
50
51impl fmt::Display for Location {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        match self {
54            Self::Native(path) => path.display().fmt(f),
55            Self::Virtual(VirtualRoot::Opfs { profile }, path) => {
56                write!(f, "opfs://{profile}/{path}")
57            }
58            Self::Virtual(VirtualRoot::Memory, path) => write!(f, "memory:///{path}"),
59        }
60    }
61}
62
63#[derive(Clone, Debug, PartialEq, Eq, Hash)]
64#[non_exhaustive]
65pub enum VirtualRoot {
66    /// The browser's origin-private file system, one tree per Tilo profile.
67    Opfs {
68        profile: String,
69    },
70    Memory,
71}
72
73/// A relative path inside a [`VirtualRoot`] or below a native location:
74/// `/`-separated components, none of them empty, `.` or `..`. The empty path
75/// is the root itself.
76#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
77pub struct VPath(String);
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub struct InvalidVPath {
81    pub reason: &'static str,
82}
83
84impl fmt::Display for InvalidVPath {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        write!(f, "invalid virtual path: {}", self.reason)
87    }
88}
89
90impl std::error::Error for InvalidVPath {}
91
92impl VPath {
93    #[must_use]
94    pub const fn root() -> Self {
95        Self(String::new())
96    }
97
98    pub fn new(path: &str) -> Result<Self, InvalidVPath> {
99        if path.is_empty() {
100            return Ok(Self::root());
101        }
102        for component in path.split('/') {
103            check_component(component)?;
104        }
105        Ok(Self(path.to_owned()))
106    }
107
108    pub(crate) fn from_components<'a>(components: impl IntoIterator<Item = &'a str>) -> Self {
109        let mut path = Self::root();
110        for component in components {
111            debug_assert!(check_component(component).is_ok(), "{component:?}");
112            path.push(component);
113        }
114        path
115    }
116
117    #[must_use]
118    pub fn as_str(&self) -> &str {
119        &self.0
120    }
121
122    #[must_use]
123    pub fn is_root(&self) -> bool {
124        self.0.is_empty()
125    }
126
127    pub fn components(&self) -> impl Iterator<Item = &str> {
128        self.0.split('/').filter(|component| !component.is_empty())
129    }
130
131    #[must_use]
132    pub fn join(&self, other: &Self) -> Self {
133        let mut joined = self.clone();
134        for component in other.components() {
135            joined.push(component);
136        }
137        joined
138    }
139
140    fn push(&mut self, component: &str) {
141        if !self.0.is_empty() {
142            self.0.push('/');
143        }
144        self.0.push_str(component);
145    }
146}
147
148impl fmt::Display for VPath {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        f.write_str(&self.0)
151    }
152}
153
154fn check_component(component: &str) -> Result<(), InvalidVPath> {
155    let reason = match component {
156        "" => "empty component (absolute path, or doubled or trailing `/`)",
157        "." | ".." => "`.` and `..` are not components",
158        _ if component.contains('\\') => "backslash in a component",
159        _ if component.contains('\0') => "NUL in a component",
160        _ => return Ok(()),
161    };
162    Err(InvalidVPath { reason })
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn vpaths_are_relative_and_normal() {
171        assert_eq!(VPath::new("").map(|path| path.is_root()), Ok(true));
172        assert_eq!(
173            VPath::new("notes/2026/a.md").map(|path| path.components().count()),
174            Ok(3)
175        );
176        for invalid in ["/abs", "a//b", "a/", "./a", "a/../b", "..", "a\\b", "a\0"] {
177            assert!(VPath::new(invalid).is_err(), "{invalid:?}");
178        }
179    }
180
181    #[test]
182    fn joining_keeps_the_root_and_appends_components() {
183        let base = VPath::new("so.tilo.notes/data").unwrap();
184        let child = VPath::new("drafts/a.md").unwrap();
185        assert_eq!(base.join(&child).as_str(), "so.tilo.notes/data/drafts/a.md");
186        assert_eq!(VPath::root().join(&child), child);
187        assert_eq!(base.join(&VPath::root()), base);
188
189        let native = Location::Native(PathBuf::from("/srv/app"));
190        assert_eq!(
191            native.join(&child),
192            Location::Native(PathBuf::from("/srv/app/drafts/a.md"))
193        );
194        let opfs = Location::Virtual(
195            VirtualRoot::Opfs {
196                profile: "default".into(),
197            },
198            base,
199        );
200        assert_eq!(
201            opfs.join(&child).to_string(),
202            "opfs://default/so.tilo.notes/data/drafts/a.md"
203        );
204    }
205
206    #[test]
207    fn only_native_locations_have_a_path() {
208        let native = Location::Native(PathBuf::from("/srv/app"));
209        assert_eq!(native.native_path(), Ok(Path::new("/srv/app")));
210        let memory = Location::Virtual(VirtualRoot::Memory, VPath::new("app/runtime").unwrap());
211        assert_eq!(memory.to_string(), "memory:///app/runtime");
212        assert_eq!(
213            memory.native_path().map_err(|error| error.feature),
214            Err(Feature::NativePaths)
215        );
216    }
217}