Skip to main content

tilo_resource/
absolute_path.rs

1//! [`AbsolutePath`] — the one type an action takes a file or folder on this
2//! device as.
3//!
4//! A relative path names a different place depending on where the app's
5//! process happens to run, so an app that wrote to one would scatter files
6//! into its working directory. An argument of this type is refused when it
7//! is decoded, before any app sees it: every effect taking a path refuses a
8//! relative one the same way, with the same message.
9
10use std::fmt;
11use std::path::{Path, PathBuf};
12
13use serde::{Deserialize, Deserializer, Serialize};
14use serde_json::{Value, json};
15
16/// An absolute path on this device. It cannot be made from a relative one.
17#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
18#[serde(transparent)]
19pub struct AbsolutePath(PathBuf);
20
21/// Why a path was refused: it was relative.
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct RelativePath(pub PathBuf);
24
25impl fmt::Display for RelativePath {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        write!(
28            f,
29            "the path must be absolute, not relative to where the app runs: {}",
30            self.0.display()
31        )
32    }
33}
34
35impl std::error::Error for RelativePath {}
36
37impl From<RelativePath> for String {
38    fn from(error: RelativePath) -> Self {
39        error.to_string()
40    }
41}
42
43impl AbsolutePath {
44    /// `path`, refused when it is relative.
45    ///
46    /// # Errors
47    ///
48    /// [`RelativePath`] when `path` is not absolute.
49    pub fn new(path: impl Into<PathBuf>) -> Result<Self, RelativePath> {
50        let path = path.into();
51        if path.is_absolute() {
52            Ok(Self(path))
53        } else {
54            Err(RelativePath(path))
55        }
56    }
57
58    /// The path.
59    #[must_use]
60    pub fn as_path(&self) -> &Path {
61        &self.0
62    }
63
64    /// The path, owned.
65    #[must_use]
66    pub fn into_path_buf(self) -> PathBuf {
67        self.0
68    }
69
70    /// The path as text, lossily for one that is not UTF-8.
71    #[must_use]
72    pub fn to_string_lossy(&self) -> String {
73        self.0.to_string_lossy().into_owned()
74    }
75}
76
77impl std::ops::Deref for AbsolutePath {
78    type Target = Path;
79
80    fn deref(&self) -> &Path {
81        &self.0
82    }
83}
84
85impl AsRef<Path> for AbsolutePath {
86    fn as_ref(&self) -> &Path {
87        &self.0
88    }
89}
90
91impl From<AbsolutePath> for PathBuf {
92    fn from(path: AbsolutePath) -> Self {
93        path.0
94    }
95}
96
97impl TryFrom<PathBuf> for AbsolutePath {
98    type Error = RelativePath;
99
100    fn try_from(path: PathBuf) -> Result<Self, RelativePath> {
101        Self::new(path)
102    }
103}
104
105impl TryFrom<&Path> for AbsolutePath {
106    type Error = RelativePath;
107
108    fn try_from(path: &Path) -> Result<Self, RelativePath> {
109        Self::new(path)
110    }
111}
112
113impl TryFrom<String> for AbsolutePath {
114    type Error = RelativePath;
115
116    fn try_from(path: String) -> Result<Self, RelativePath> {
117        Self::new(path)
118    }
119}
120
121impl TryFrom<&str> for AbsolutePath {
122    type Error = RelativePath;
123
124    fn try_from(path: &str) -> Result<Self, RelativePath> {
125        Self::new(path)
126    }
127}
128
129impl std::str::FromStr for AbsolutePath {
130    type Err = RelativePath;
131
132    fn from_str(path: &str) -> Result<Self, RelativePath> {
133        Self::new(path)
134    }
135}
136
137impl fmt::Display for AbsolutePath {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        self.0.display().fmt(f)
140    }
141}
142
143impl<'de> Deserialize<'de> for AbsolutePath {
144    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
145        Self::new(PathBuf::deserialize(deserializer)?).map_err(serde::de::Error::custom)
146    }
147}
148
149impl crate::JsonSchema for AbsolutePath {
150    fn json_schema() -> Value {
151        json!({"type": "string", "description": "An absolute path on this device"})
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    #[test]
160    fn a_relative_path_is_refused_when_decoded() {
161        let error = serde_json::from_value::<AbsolutePath>(json!("notes/out.txt")).unwrap_err();
162        assert!(
163            error.to_string().contains("must be absolute"),
164            "got {error}"
165        );
166        assert!(serde_json::from_value::<AbsolutePath>(json!("")).is_err());
167        let path = serde_json::from_value::<AbsolutePath>(json!("/home/you/out.txt")).unwrap();
168        assert_eq!(path.as_path(), Path::new("/home/you/out.txt"));
169        assert_eq!(
170            serde_json::to_value(&path).unwrap(),
171            json!("/home/you/out.txt")
172        );
173    }
174}