1use std::fmt;
4use std::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8use crate::invalid::Invalid;
9
10#[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 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 #[must_use]
33 pub fn as_str(&self) -> &str {
34 &self.0
35 }
36
37 pub fn parts(&self) -> impl Iterator<Item = &str> {
39 self.0.split('/')
40 }
41
42 #[must_use]
45 pub fn join(&self, relative: &str) -> Option<Self> {
46 Self::new(self.joined_names(relative)?.join("/")).ok()
47 }
48
49 #[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 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
85fn 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 mod join_laws {
195 use super::*;
196 use proptest::prelude::*;
197
198 fn name() -> impl Strategy<Value = String> {
200 "[a-z0-9][a-z0-9._-]{0,7}"
201 }
202
203 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 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}