Skip to main content

compmd_pack/
file_path.rs

1//! A file's path in a pack: `/`-separated names that can't leave the pack's folder.
2
3use std::fmt;
4use std::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8use crate::invalid::Invalid;
9
10/// A file's path in a pack, `dist/mermaid.js`.
11#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
12#[serde(try_from = "String", into = "String")]
13pub struct FilePath(String);
14
15impl FilePath {
16    /// The path `text`, when it is one: `/`-separated names, none of them empty, `.` or `..`, with no `\` or `:` (a
17    /// Windows path of its own), so it can't name a file outside the pack.
18    ///
19    /// # Errors
20    ///
21    /// [`Invalid::Path`] when it isn't one.
22    pub fn new(text: impl Into<String>) -> Result<Self, Invalid> {
23        let text = text.into();
24        if text.split('/').all(is_name) {
25            Ok(Self(text))
26        } else {
27            Err(Invalid::Path(text))
28        }
29    }
30
31    /// The path as written.
32    #[must_use]
33    pub fn as_str(&self) -> &str {
34        &self.0
35    }
36
37    /// Its names, in order.
38    pub fn parts(&self) -> impl Iterator<Item = &str> {
39        self.0.split('/')
40    }
41
42    /// The file `relative` (`./card.comp.md`, `../ui/x.jsx`) names, seen from this file's folder; `None` when it
43    /// leaves the pack, or names its folder.
44    #[must_use]
45    pub fn join(&self, relative: &str) -> Option<Self> {
46        Self::new(self.joined_names(relative)?.join("/")).ok()
47    }
48
49    /// The folder `relative` (`./`, `../guide/`) names, seen from this file's folder: its `/`-separated path, empty
50    /// for the root folder; `None` when it leaves the root, or one of its names isn't a file's name.
51    ///
52    /// ```
53    /// # use compmd_pack::FilePath;
54    /// let post = FilePath::new("posts/harbour.comp.md").expect("a path");
55    /// assert_eq!(post.join_folder("../guide/").as_deref(), Some("guide"));
56    /// assert_eq!(post.join_folder("../").as_deref(), Some(""));
57    /// assert_eq!(post.join_folder("../../"), None);
58    /// ```
59    #[must_use]
60    pub fn join_folder(&self, relative: &str) -> Option<String> {
61        let names = self.joined_names(relative)?;
62        names
63            .iter()
64            .all(|name| is_name(name))
65            .then(|| names.join("/"))
66    }
67
68    /// The names of what `relative` names, seen from this file's folder; `None` when `..` leaves the root.
69    fn joined_names<'a>(&'a self, relative: &'a str) -> Option<Vec<&'a str>> {
70        let mut names: Vec<&str> = self.parts().collect();
71        names.pop();
72        for part in relative.split('/') {
73            match part {
74                "" | "." => {}
75                ".." => {
76                    names.pop()?;
77                }
78                name => names.push(name),
79            }
80        }
81        Some(names)
82    }
83}
84
85/// Whether `part` is a file's or a folder's name: not empty, `.` or `..`, with no `\` or `:` (a Windows path of its
86/// own) and no NUL.
87fn is_name(part: &str) -> bool {
88    !part.is_empty() && part != "." && part != ".." && !part.contains(['\\', ':', '\0'])
89}
90
91impl FromStr for FilePath {
92    type Err = Invalid;
93
94    fn from_str(text: &str) -> Result<Self, Self::Err> {
95        Self::new(text)
96    }
97}
98
99impl TryFrom<String> for FilePath {
100    type Error = Invalid;
101
102    fn try_from(text: String) -> Result<Self, Self::Error> {
103        Self::new(text)
104    }
105}
106
107impl From<FilePath> for String {
108    fn from(path: FilePath) -> Self {
109        path.0
110    }
111}
112
113impl fmt::Display for FilePath {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.write_str(&self.0)
116    }
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    fn path(text: &str) -> FilePath {
124        FilePath::new(text).expect(text)
125    }
126
127    #[test]
128    fn a_path_is_plain_names() {
129        let file = path("dist/mermaid.js");
130        assert_eq!(file.as_str(), "dist/mermaid.js");
131        assert_eq!(file.parts().collect::<Vec<_>>(), ["dist", "mermaid.js"]);
132        assert_eq!(file.to_string(), "dist/mermaid.js");
133        assert_eq!("a.js".parse::<FilePath>(), Ok(path("a.js")));
134    }
135
136    #[test]
137    fn a_path_that_could_leave_the_pack_is_refused() {
138        for text in [
139            "",
140            "/a.js",
141            "a//b.js",
142            "./a.js",
143            "a/../b.js",
144            "..",
145            "a\\b.js",
146            "C:/a.js",
147            "a\0b",
148        ] {
149            assert_eq!(
150                FilePath::new(text),
151                Err(Invalid::Path(text.to_owned())),
152                "{text:?}"
153            );
154        }
155        assert!(
156            Invalid::Path("x".to_owned())
157                .to_string()
158                .contains("isn't a file's path")
159        );
160    }
161
162    #[test]
163    fn a_relative_path_resolves_against_the_files_folder() {
164        let kit = path("kit.comp.md");
165        assert_eq!(
166            kit.join("./parts/chip.comp.md"),
167            Some(path("parts/chip.comp.md"))
168        );
169        assert_eq!(
170            path("docs/a.comp.md").join("../ui/b.jsx"),
171            Some(path("ui/b.jsx"))
172        );
173        assert_eq!(
174            path("docs/a.comp.md").join("./x/../y.comp.md"),
175            Some(path("docs/y.comp.md"))
176        );
177        assert_eq!(kit.join("../x.comp.md"), None, "it leaves the pack");
178        assert_eq!(kit.join("./"), None, "it names a folder");
179        assert_eq!(kit.join("./a\\b.js"), None, "a name with `\\`");
180    }
181
182    #[test]
183    fn a_relative_folder_resolves_against_the_files_folder() {
184        let post = path("posts/harbour.comp.md");
185        assert_eq!(post.join_folder("./").as_deref(), Some("posts"));
186        assert_eq!(post.join_folder(".").as_deref(), Some("posts"));
187        assert_eq!(post.join_folder("../guide/").as_deref(), Some("guide"));
188        assert_eq!(post.join_folder("..").as_deref(), Some(""));
189        assert_eq!(post.join_folder("../../"), None, "it leaves the root");
190        assert_eq!(post.join_folder("./a:b/"), None, "a name with `:`");
191    }
192
193    /// `join`'s laws, for any path and any relative path of names, `.`, `..` and empty parts.
194    mod join_laws {
195        use super::*;
196        use proptest::prelude::*;
197
198        /// A file's or a folder's name.
199        fn name() -> impl Strategy<Value = String> {
200            "[a-z0-9][a-z0-9._-]{0,7}"
201        }
202
203        /// A file's path, of one to four names.
204        fn file() -> impl Strategy<Value = FilePath> {
205            prop::collection::vec(name(), 1..5)
206                .prop_map(|names| FilePath::new(names.join("/")).expect("names make a path"))
207        }
208
209        /// A part of a relative path: a name, `.`, `..` or empty.
210        fn part() -> impl Strategy<Value = String> {
211            prop_oneof![
212                name(),
213                Just(".".into()),
214                Just("..".into()),
215                Just(String::new())
216            ]
217        }
218
219        proptest! {
220            #[test]
221            fn what_it_names_is_a_path_of_the_pack(base in file(), parts in prop::collection::vec(part(), 0..6)) {
222                if let Some(joined) = base.join(&parts.join("/")) {
223                    prop_assert_eq!(FilePath::new(joined.as_str()), Ok(joined.clone()));
224                }
225            }
226
227            #[test]
228            fn names_go_under_the_file_s_folder(base in file(), names in prop::collection::vec(name(), 1..4)) {
229                let mut expected: Vec<String> = base.parts().map(str::to_owned).collect();
230                expected.pop();
231                expected.extend(names.iter().cloned());
232                let joined = base.join(&format!("./{}", names.join("/")));
233                prop_assert_eq!(joined.map(String::from), Some(expected.join("/")));
234            }
235
236            #[test]
237            fn one_level_up_too_many_leaves_the_pack(base in file(), tail in name()) {
238                let up = "../".repeat(base.parts().count());
239                prop_assert_eq!(base.join(&format!("{up}{tail}")), None);
240            }
241
242            #[test]
243            fn a_name_then_up_again_is_where_it_started(base in file(), name in name(), rest in name()) {
244                prop_assert_eq!(base.join(&format!("{name}/../{rest}")), base.join(&rest));
245            }
246
247            #[test]
248            fn a_windows_name_never_joins(base in file(), first in name(), mark in prop_oneof![Just('\\'), Just(':'), Just('\0')], last in name()) {
249                prop_assert_eq!(base.join(&format!("./{first}{mark}{last}")), None);
250            }
251        }
252    }
253
254    #[test]
255    fn a_path_is_a_string_in_json() {
256        let file: FilePath = serde_json::from_str(r#""dist/a.js""#).expect("a path");
257        assert_eq!(
258            serde_json::to_string(&file).expect("JSON"),
259            r#""dist/a.js""#
260        );
261        assert!(serde_json::from_str::<FilePath>(r#""../a.js""#).is_err());
262        assert_eq!(String::from(file), "dist/a.js");
263        assert_eq!(FilePath::try_from("a.js".to_owned()), Ok(path("a.js")));
264    }
265}