ailloli_ui_fs/
uri.rs

1//! Normalized, serializable identifiers for local and remote filesystem entries.
2
3use std::fmt;
4use std::path::{Path, PathBuf};
5
6use crate::FileError;
7
8/// Version-one filesystem URI with a normalized scheme, optional authority, and path.
9///
10/// Paths use `/`, collapse repeated separators, and always start with `/`.
11/// This is deliberately a small VFS syntax rather than a complete RFC URI
12/// implementation: queries/fragments are unsupported, dot segments are not
13/// resolved, and only `%` and spaces are encoded/decoded by path helpers.
14/// Constructor methods establish these invariants, but derived deserialization
15/// stores the three fields verbatim and can therefore produce an unnormalized
16/// or otherwise invalid value. Only deserialize data from a trusted compatible
17/// producer when later code relies on normalized paths.
18///
19/// # Examples
20///
21/// ```
22/// use ailloli_ui_fs::FileUri;
23/// let uri = FileUri::parse("SFTP://host//srv/project")?;
24/// assert_eq!(uri.to_string(), "sftp://host/srv/project");
25/// # Ok::<(), ailloli_ui_fs::FileError>(())
26/// ```
27#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
28pub struct FileUri {
29    /// Usually normalized lowercase scheme; deserialization can bypass validation.
30    scheme: String,
31    /// Optional case-sensitive provider authority.
32    authority: Option<String>,
33    /// Usually normalized absolute path; deserialization can bypass validation.
34    path: String,
35}
36
37impl FileUri {
38    /// Parses and normalizes a version-one filesystem URI.
39    ///
40    /// Outer whitespace is trimmed and the scheme is lowercased. The input must
41    /// contain `://`, a non-empty target, and no literal `?` or `#`. Backslashes
42    /// in the path become `/` and repeated slashes collapse. Authority text and
43    /// existing percent escapes are otherwise retained verbatim.
44    ///
45    /// # Errors
46    ///
47    /// Returns [`FileError::InvalidUri`] for empty input, a missing/invalid
48    /// scheme or path, a missing path after an authority, or a query/fragment.
49    ///
50    /// # Examples
51    ///
52    /// ```
53    /// use ailloli_ui_fs::FileUri;
54    /// let uri = FileUri::parse(" file:///tmp/a%20b ")?;
55    /// assert_eq!(uri.path(), "/tmp/a%20b");
56    /// assert!(FileUri::parse("file:///tmp/a?raw=1").is_err());
57    /// # Ok::<(), ailloli_ui_fs::FileError>(())
58    /// ```
59    pub fn parse(input: impl AsRef<str>) -> Result<Self, FileError> {
60        let input = input.as_ref().trim();
61        if input.is_empty() {
62            return Err(FileError::InvalidUri("empty uri".into()));
63        }
64        if input.contains('?') || input.contains('#') {
65            return Err(FileError::InvalidUri(
66                "query and fragment are not supported in v1".into(),
67            ));
68        }
69        let Some((scheme, rest)) = input.split_once("://") else {
70            return Err(FileError::InvalidUri(input.into()));
71        };
72        let scheme = normalize_scheme(scheme)?;
73        let (authority, path) = split_authority_and_path(rest)?;
74        Ok(Self {
75            scheme,
76            authority,
77            path: normalize_path(path),
78        })
79    }
80
81    /// Converts an absolute local path into an authority-free `file` URI.
82    ///
83    /// The path must be valid UTF-8. Percent signs are encoded as `%25`, spaces
84    /// as `%20`, and platform separators normalize to `/`; other URI-reserved
85    /// characters are left verbatim. Relative paths are rejected.
86    ///
87    /// # Errors
88    ///
89    /// Returns [`FileError::InvalidUri`] for a relative or non-UTF-8 path.
90    ///
91    /// # Examples
92    ///
93    /// ```
94    /// use ailloli_ui_fs::FileUri;
95    /// let uri = FileUri::local("/tmp/a b")?;
96    /// assert_eq!(uri.to_string(), "file:///tmp/a%20b");
97    /// assert!(FileUri::local("relative/path").is_err());
98    /// # Ok::<(), ailloli_ui_fs::FileError>(())
99    /// ```
100    pub fn local(path: impl Into<PathBuf>) -> Result<Self, FileError> {
101        let path = path.into();
102        if !path.is_absolute() {
103            return Err(FileError::InvalidUri(format!(
104                "local file uri requires absolute path: {}",
105                path.display()
106            )));
107        }
108        let path = path_to_uri_path(&path)?;
109        Ok(Self {
110            scheme: "file".into(),
111            authority: None,
112            path,
113        })
114    }
115
116    /// Builds a URI from components using the crate's normalization rules.
117    ///
118    /// An empty authority becomes `None`. Relative path text is accepted and
119    /// receives a leading `/`; backslashes and repeated separators normalize.
120    /// Existing percent escapes, dot segments, `?`, and `#` are not validated.
121    ///
122    /// # Errors
123    ///
124    /// Returns [`FileError::InvalidUri`] only when the normalized scheme is
125    /// empty or contains a character outside ASCII alphanumeric, `+`, `-`, `.`.
126    ///
127    /// # Examples
128    ///
129    /// ```
130    /// use ailloli_ui_fs::FileUri;
131    /// let uri = FileUri::new("SFTP", Some("host"), "srv\\project")?;
132    /// assert_eq!(uri.to_string(), "sftp://host/srv/project");
133    /// # Ok::<(), ailloli_ui_fs::FileError>(())
134    /// ```
135    pub fn new(
136        scheme: impl Into<String>,
137        authority: Option<impl Into<String>>,
138        path: impl Into<String>,
139    ) -> Result<Self, FileError> {
140        let scheme = normalize_scheme(&scheme.into())?;
141        let authority = authority.map(Into::into).filter(|value| !value.is_empty());
142        let path = normalize_path(path.into());
143        if path.is_empty() || !path.starts_with('/') {
144            return Err(FileError::InvalidUri("uri path must be absolute".into()));
145        }
146        Ok(Self {
147            scheme,
148            authority,
149            path,
150        })
151    }
152
153    /// Returns the normalized lowercase scheme.
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use ailloli_ui_fs::FileUri;
159    /// assert_eq!(FileUri::parse("FILE:///")?.scheme(), "file");
160    /// # Ok::<(), ailloli_ui_fs::FileError>(())
161    /// ```
162    pub fn scheme(&self) -> &str {
163        &self.scheme
164    }
165
166    /// Returns the authority, or `None` for authority-free URIs.
167    ///
168    /// Authority comparison is case-sensitive and no host normalization occurs.
169    ///
170    /// # Examples
171    ///
172    /// ```
173    /// use ailloli_ui_fs::FileUri;
174    /// assert_eq!(FileUri::parse("sftp://host/home")?.authority(), Some("host"));
175    /// assert_eq!(FileUri::parse("file:///tmp")?.authority(), None);
176    /// # Ok::<(), ailloli_ui_fs::FileError>(())
177    /// ```
178    pub fn authority(&self) -> Option<&str> {
179        self.authority.as_deref()
180    }
181
182    /// Returns the normalized, absolute, still-percent-encoded path.
183    ///
184    /// # Examples
185    ///
186    /// ```
187    /// use ailloli_ui_fs::FileUri;
188    /// assert_eq!(FileUri::parse("file:////tmp//a")?.path(), "/tmp/a");
189    /// # Ok::<(), ailloli_ui_fs::FileError>(())
190    /// ```
191    pub fn path(&self) -> &str {
192        &self.path
193    }
194
195    /// Returns the final non-empty encoded path segment.
196    ///
197    /// Root returns `None`; a trailing slash is ignored. No allocation or
198    /// percent decoding occurs.
199    ///
200    /// # Examples
201    ///
202    /// ```
203    /// use ailloli_ui_fs::FileUri;
204    /// assert_eq!(FileUri::parse("file:///tmp/a%20b/")?.file_name(), Some("a%20b"));
205    /// assert_eq!(FileUri::parse("file:///")?.file_name(), None);
206    /// # Ok::<(), ailloli_ui_fs::FileError>(())
207    /// ```
208    pub fn file_name(&self) -> Option<&str> {
209        self.path.rsplit('/').find(|segment| !segment.is_empty())
210    }
211
212    /// Returns an allocated, partially percent-decoded final segment.
213    ///
214    /// Decoding replaces uppercase `%20` with spaces and `%25` with `%`, in
215    /// that order. Other escapes, lowercase forms, and malformed escapes remain
216    /// unchanged. Root returns `None`.
217    ///
218    /// # Examples
219    ///
220    /// ```
221    /// use ailloli_ui_fs::FileUri;
222    /// assert_eq!(FileUri::parse("file:///a%20b")?.file_name_decoded().as_deref(), Some("a b"));
223    /// # Ok::<(), ailloli_ui_fs::FileError>(())
224    /// ```
225    pub fn file_name_decoded(&self) -> Option<String> {
226        self.file_name().map(percent_decode_lossy)
227    }
228
229    /// Returns the normalized lexical parent while preserving scheme/authority.
230    ///
231    /// Files directly below root return the root URI; root itself returns
232    /// `None`. Dot segments are ordinary text and are not resolved.
233    ///
234    /// # Examples
235    ///
236    /// ```
237    /// use ailloli_ui_fs::FileUri;
238    /// let uri = FileUri::parse("file:///tmp/a")?;
239    /// assert_eq!(uri.parent().unwrap().to_string(), "file:///tmp");
240    /// # Ok::<(), ailloli_ui_fs::FileError>(())
241    /// ```
242    pub fn parent(&self) -> Option<Self> {
243        let trimmed = self.path.trim_end_matches('/');
244        let idx = trimmed.rfind('/')?;
245        if idx == 0 {
246            return Self::new(self.scheme.clone(), self.authority.clone(), "/").ok();
247        }
248        Self::new(self.scheme.clone(), self.authority.clone(), &trimmed[..idx]).ok()
249    }
250
251    /// Appends one trimmed child name and encodes percent signs and spaces.
252    ///
253    /// Empty names and names containing `/` or `\` are rejected. Other URI
254    /// delimiters and dot names are accepted verbatim, so a child containing
255    /// `?` or `#` may not round-trip through [`Self::parse`].
256    ///
257    /// # Errors
258    ///
259    /// Returns [`FileError::InvalidUri`] for an empty or multi-segment name, or
260    /// if rebuilding the URI fails.
261    ///
262    /// # Examples
263    ///
264    /// ```
265    /// use ailloli_ui_fs::FileUri;
266    /// let root = FileUri::parse("file:///tmp")?;
267    /// assert_eq!(root.join_child(" a b ")?.to_string(), "file:///tmp/a%20b");
268    /// assert!(root.join_child("a/b").is_err());
269    /// # Ok::<(), ailloli_ui_fs::FileError>(())
270    /// ```
271    pub fn join_child(&self, name: impl AsRef<str>) -> Result<Self, FileError> {
272        let name = name.as_ref().trim();
273        if name.is_empty() || name.contains('/') || name.contains('\\') {
274            return Err(FileError::InvalidUri(format!("invalid child name: {name}")));
275        }
276        let base = self.path.trim_end_matches('/');
277        Self::new(
278            self.scheme.clone(),
279            self.authority.clone(),
280            format!("{base}/{}", percent_encode_path(name)),
281        )
282    }
283
284    /// Replaces the final segment using [`Self::join_child`] name rules.
285    ///
286    /// # Errors
287    ///
288    /// Returns [`FileError::InvalidUri`] when this URI is root or the new name
289    /// is empty or contains a path separator.
290    ///
291    /// # Examples
292    ///
293    /// ```
294    /// use ailloli_ui_fs::FileUri;
295    /// let uri = FileUri::parse("file:///tmp/a")?;
296    /// assert_eq!(uri.with_file_name("b")?.to_string(), "file:///tmp/b");
297    /// assert!(FileUri::parse("file:///")?.with_file_name("b").is_err());
298    /// # Ok::<(), ailloli_ui_fs::FileError>(())
299    /// ```
300    pub fn with_file_name(&self, name: impl AsRef<str>) -> Result<Self, FileError> {
301        let Some(parent) = self.parent() else {
302            return Err(FileError::InvalidUri(format!("uri has no parent: {self}")));
303        };
304        parent.join_child(name)
305    }
306
307    /// Returns a decoded lexical path relative to `root` when compatible.
308    ///
309    /// Scheme and authority must match exactly, and `self` must equal or be
310    /// below the root on a path-segment boundary. Equal non-root paths return
311    /// `"."`; equal root or trailing-slash paths return an empty string due to
312    /// normalization semantics. The result uses the same limited decoding as
313    /// [`Self::file_name_decoded`].
314    ///
315    /// # Examples
316    ///
317    /// ```
318    /// use ailloli_ui_fs::FileUri;
319    /// let root = FileUri::parse("file:///tmp/work")?;
320    /// let child = FileUri::parse("file:///tmp/work/a%20b")?;
321    /// assert_eq!(child.relative_path_from(&root).as_deref(), Some("a b"));
322    /// assert_eq!(root.relative_path_from(&root).as_deref(), Some("."));
323    /// # Ok::<(), ailloli_ui_fs::FileError>(())
324    /// ```
325    pub fn relative_path_from(&self, root: &Self) -> Option<String> {
326        if self.scheme != root.scheme || self.authority != root.authority {
327            return None;
328        }
329        let root_path = root.path.trim_end_matches('/');
330        let path = self.path.as_str();
331        if path == root_path {
332            return Some(".".to_string());
333        }
334        let prefix = format!("{root_path}/");
335        let relative = path.strip_prefix(&prefix)?;
336        Some(percent_decode_lossy(relative))
337    }
338
339    /// Converts an authority-free or `localhost` `file` URI to a local path.
340    ///
341    /// Authority matching is case-sensitive. Percent decoding is intentionally
342    /// limited to uppercase `%20` and `%25`; no existence check is performed.
343    ///
344    /// # Errors
345    ///
346    /// Returns [`FileError::UnsupportedScheme`] for non-`file` schemes or a
347    /// non-empty authority other than exact `localhost`.
348    ///
349    /// # Examples
350    ///
351    /// ```
352    /// use ailloli_ui_fs::FileUri;
353    /// use std::path::PathBuf;
354    /// assert_eq!(FileUri::parse("file://localhost/tmp/a%20b")?.to_local_path()?, PathBuf::from("/tmp/a b"));
355    /// assert!(FileUri::parse("sftp://host/tmp")?.to_local_path().is_err());
356    /// # Ok::<(), ailloli_ui_fs::FileError>(())
357    /// ```
358    pub fn to_local_path(&self) -> Result<PathBuf, FileError> {
359        if self.scheme != "file" {
360            return Err(FileError::UnsupportedScheme(self.scheme.clone()));
361        }
362        if self
363            .authority
364            .as_deref()
365            .is_some_and(|value| value != "localhost")
366        {
367            return Err(FileError::UnsupportedScheme(format!(
368                "file authority {:?}",
369                self.authority
370            )));
371        }
372        Ok(PathBuf::from(percent_decode_lossy(&self.path)))
373    }
374}
375
376impl fmt::Display for FileUri {
377    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
378        write!(f, "{}://", self.scheme)?;
379        if let Some(authority) = &self.authority {
380            write!(f, "{authority}")?;
381        }
382        write!(f, "{}", self.path)
383    }
384}
385
386impl std::str::FromStr for FileUri {
387    type Err = FileError;
388
389    fn from_str(s: &str) -> Result<Self, Self::Err> {
390        Self::parse(s)
391    }
392}
393
394/// Trims/lowercases a scheme and accepts only ASCII alphanumeric, `+`, `-`, `.`.
395///
396/// # Errors
397///
398/// Returns [`FileError::InvalidUri`] when the trimmed scheme is empty or
399/// contains any other character.
400fn normalize_scheme(scheme: &str) -> Result<String, FileError> {
401    let scheme = scheme.trim().to_ascii_lowercase();
402    let valid = !scheme.is_empty()
403        && scheme
404            .chars()
405            .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '+' | '-' | '.'));
406    if valid {
407        Ok(scheme)
408    } else {
409        Err(FileError::InvalidUri(format!("invalid scheme: {scheme}")))
410    }
411}
412
413/// Splits the post-scheme target into optional authority and absolute path text.
414///
415/// # Errors
416///
417/// Returns [`FileError::InvalidUri`] for an empty target, a remote target with
418/// no slash-delimited path, or an empty authority.
419fn split_authority_and_path(rest: &str) -> Result<(Option<String>, String), FileError> {
420    if rest.is_empty() {
421        return Err(FileError::InvalidUri("uri target is empty".into()));
422    }
423    if rest.starts_with('/') {
424        return Ok((None, rest.to_string()));
425    }
426    let Some((authority, path)) = rest.split_once('/') else {
427        return Err(FileError::InvalidUri("uri path is empty".into()));
428    };
429    if authority.is_empty() {
430        return Err(FileError::InvalidUri("uri authority is empty".into()));
431    }
432    Ok((Some(authority.to_string()), format!("/{path}")))
433}
434
435/// Converts separators, collapses repeats, and ensures one leading slash.
436fn normalize_path(path: impl Into<String>) -> String {
437    let mut path = path.into().replace('\\', "/");
438    while path.contains("//") {
439        path = path.replace("//", "/");
440    }
441    if !path.starts_with('/') {
442        path.insert(0, '/');
443    }
444    path
445}
446
447/// Converts one UTF-8 platform path to the crate's minimally encoded URI path.
448///
449/// # Errors
450///
451/// Returns [`FileError::InvalidUri`] when `path` is not valid UTF-8.
452fn path_to_uri_path(path: &Path) -> Result<String, FileError> {
453    let Some(path) = path.to_str() else {
454        return Err(FileError::InvalidUri(
455            "local path is not valid UTF-8".into(),
456        ));
457    };
458    Ok(normalize_path(percent_encode_path(path)))
459}
460
461/// Encodes percent signs first and spaces second, leaving other characters unchanged.
462fn percent_encode_path(path: &str) -> String {
463    path.replace('%', "%25").replace(' ', "%20")
464}
465
466/// Decodes uppercase `%20` then `%25` without validating other escapes.
467fn percent_decode_lossy(path: &str) -> String {
468    path.replace("%20", " ").replace("%25", "%")
469}
470
471#[cfg(test)]
472mod tests {
473    //! Covers v1 parsing, invalid syntax, local conversion, and lexical path helpers.
474
475    use super::*;
476
477    #[test]
478    fn parses_file_and_remote_uris() {
479        let file = FileUri::parse("file:///tmp/a.rs").expect("file uri");
480        assert_eq!(file.scheme(), "file");
481        assert_eq!(file.authority(), None);
482        assert_eq!(file.path(), "/tmp/a.rs");
483        assert_eq!(file.to_string(), "file:///tmp/a.rs");
484
485        let sftp = FileUri::parse("sftp://host/var/www").expect("sftp uri");
486        assert_eq!(sftp.scheme(), "sftp");
487        assert_eq!(sftp.authority(), Some("host"));
488        assert_eq!(sftp.path(), "/var/www");
489
490        let ftp = FileUri::parse("ftp://host/path").expect("ftp uri");
491        assert_eq!(ftp.scheme(), "ftp");
492        assert_eq!(ftp.authority(), Some("host"));
493        assert_eq!(ftp.path(), "/path");
494    }
495
496    #[test]
497    fn rejects_invalid_v1_uris() {
498        assert!(matches!(FileUri::parse(""), Err(FileError::InvalidUri(_))));
499        assert!(matches!(
500            FileUri::parse("file:///tmp/a.rs?download=1"),
501            Err(FileError::InvalidUri(_))
502        ));
503        assert!(matches!(
504            FileUri::parse("file://"),
505            Err(FileError::InvalidUri(_))
506        ));
507        let root = FileUri::parse("file:///").expect("filesystem root");
508        assert_eq!(root.path(), "/");
509        assert_eq!(root.parent(), None);
510        assert_eq!(root.join_child("bin").unwrap().to_string(), "file:///bin");
511    }
512
513    #[test]
514    fn builds_local_file_uri() {
515        let uri = FileUri::local("/tmp/octav ui.rs").expect("local uri");
516        assert_eq!(uri.scheme(), "file");
517        assert_eq!(uri.path(), "/tmp/octav%20ui.rs");
518        assert_eq!(
519            uri.to_local_path().expect("path"),
520            PathBuf::from("/tmp/octav ui.rs")
521        );
522    }
523
524    #[test]
525    fn uri_parent_join_rename_and_relative_paths() {
526        let root = FileUri::parse("file:///tmp/octav%20ui").expect("root");
527        let file = root.join_child("main file.rs").expect("child");
528        assert_eq!(file.to_string(), "file:///tmp/octav%20ui/main%20file.rs");
529        assert_eq!(file.file_name_decoded().as_deref(), Some("main file.rs"));
530        assert_eq!(file.parent(), Some(root.clone()));
531        assert_eq!(
532            FileUri::parse("file:///bin").unwrap().parent(),
533            Some(FileUri::parse("file:///").unwrap())
534        );
535        assert_eq!(
536            file.with_file_name("lib.rs").expect("rename").to_string(),
537            "file:///tmp/octav%20ui/lib.rs"
538        );
539        assert_eq!(
540            file.relative_path_from(&root),
541            Some("main file.rs".to_string())
542        );
543        assert_eq!(root.relative_path_from(&root), Some(".".to_string()));
544        assert!(FileUri::parse("file:///tmp/other")
545            .expect("other")
546            .relative_path_from(&root)
547            .is_none());
548    }
549}