Skip to main content

morphir_workspace/
path.rs

1use serde::{Deserialize, Deserializer, Serialize};
2use thiserror::Error;
3
4use crate::diagnostic::WORKSPACE_PATH_NOT_CONFINED;
5
6/// A canonical slash-separated path confined beneath a named mount.
7///
8/// The value `.` denotes the mount root. All other values contain only
9/// non-empty path components and cannot contain `.` or `..` components.
10#[derive(Clone, Debug, Serialize, PartialEq, Eq, PartialOrd, Ord)]
11#[serde(transparent)]
12pub struct RelativePath(String);
13
14impl RelativePath {
15    /// Parses a canonical path relative to a named mount.
16    pub fn parse(path: impl Into<String>) -> Result<Self, RelativePathError> {
17        let path = path.into();
18
19        if is_confined(&path) {
20            Ok(Self(path))
21        } else {
22            Err(RelativePathError::NotConfined { path })
23        }
24    }
25
26    /// Returns the canonical mount root.
27    #[must_use]
28    pub fn root() -> Self {
29        Self(".".to_owned())
30    }
31
32    /// Joins another canonical relative path without normalizing escapes.
33    pub fn join(&self, path: impl AsRef<str>) -> Result<Self, RelativePathError> {
34        let path = Self::parse(path.as_ref())?;
35
36        match (self.as_str(), path.as_str()) {
37            (".", _) => Ok(path),
38            (_, ".") => Ok(self.clone()),
39            (base, child) => Self::parse(format!("{base}/{child}")),
40        }
41    }
42
43    /// Returns the canonical parent, keeping the mount root at `.`.
44    #[must_use]
45    pub fn parent(&self) -> Self {
46        match self.0.rsplit_once('/') {
47            Some((parent, _)) => Self(parent.to_owned()),
48            None => Self::root(),
49        }
50    }
51
52    /// Returns this path's canonical wire representation.
53    #[must_use]
54    pub fn as_str(&self) -> &str {
55        &self.0
56    }
57}
58
59impl<'de> Deserialize<'de> for RelativePath {
60    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
61    where
62        D: Deserializer<'de>,
63    {
64        let path = String::deserialize(deserializer)?;
65        Self::parse(path).map_err(serde::de::Error::custom)
66    }
67}
68
69/// An error returned when a path is not confined to its named mount.
70#[derive(Clone, Debug, Error, PartialEq, Eq)]
71pub enum RelativePathError {
72    /// The supplied path was not a canonical, confined relative path.
73    #[error("{WORKSPACE_PATH_NOT_CONFINED}: path `{path}` is not confined to its mount")]
74    NotConfined {
75        /// The rejected path.
76        path: String,
77    },
78}
79
80fn is_confined(path: &str) -> bool {
81    if path == "." {
82        return true;
83    }
84
85    if path.is_empty()
86        || path.starts_with('/')
87        || path.contains('\\')
88        || has_windows_drive_prefix(path)
89    {
90        return false;
91    }
92
93    path.split('/')
94        .all(|component| !component.is_empty() && component != "." && component != "..")
95}
96
97fn has_windows_drive_prefix(path: &str) -> bool {
98    let bytes = path.as_bytes();
99    bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'
100}