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 let plain = text.split('/').all(|part| {
25 !part.is_empty() && part != "." && part != ".." && !part.contains(['\\', ':', '\0'])
26 });
27 if plain {
28 Ok(Self(text))
29 } else {
30 Err(Invalid::Path(text))
31 }
32 }
33
34 #[must_use]
36 pub fn as_str(&self) -> &str {
37 &self.0
38 }
39
40 pub fn parts(&self) -> impl Iterator<Item = &str> {
42 self.0.split('/')
43 }
44
45 #[must_use]
48 pub fn join(&self, relative: &str) -> Option<Self> {
49 let mut parts: Vec<&str> = self.parts().collect();
50 parts.pop();
51 for part in relative.split('/') {
52 match part {
53 "" | "." => {}
54 ".." => {
55 parts.pop()?;
56 }
57 name => parts.push(name),
58 }
59 }
60 Self::new(parts.join("/")).ok()
61 }
62}
63
64impl FromStr for FilePath {
65 type Err = Invalid;
66
67 fn from_str(text: &str) -> Result<Self, Self::Err> {
68 Self::new(text)
69 }
70}
71
72impl TryFrom<String> for FilePath {
73 type Error = Invalid;
74
75 fn try_from(text: String) -> Result<Self, Self::Error> {
76 Self::new(text)
77 }
78}
79
80impl From<FilePath> for String {
81 fn from(path: FilePath) -> Self {
82 path.0
83 }
84}
85
86impl fmt::Display for FilePath {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 f.write_str(&self.0)
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 fn path(text: &str) -> FilePath {
97 FilePath::new(text).expect(text)
98 }
99
100 #[test]
101 fn a_path_is_plain_names() {
102 let file = path("dist/mermaid.js");
103 assert_eq!(file.as_str(), "dist/mermaid.js");
104 assert_eq!(file.parts().collect::<Vec<_>>(), ["dist", "mermaid.js"]);
105 assert_eq!(file.to_string(), "dist/mermaid.js");
106 assert_eq!("a.js".parse::<FilePath>(), Ok(path("a.js")));
107 }
108
109 #[test]
110 fn a_path_that_could_leave_the_pack_is_refused() {
111 for text in [
112 "",
113 "/a.js",
114 "a//b.js",
115 "./a.js",
116 "a/../b.js",
117 "..",
118 "a\\b.js",
119 "C:/a.js",
120 "a\0b",
121 ] {
122 assert_eq!(
123 FilePath::new(text),
124 Err(Invalid::Path(text.to_owned())),
125 "{text:?}"
126 );
127 }
128 assert!(
129 Invalid::Path("x".to_owned())
130 .to_string()
131 .contains("isn't a file's path")
132 );
133 }
134
135 #[test]
136 fn a_relative_path_resolves_against_the_files_folder() {
137 let kit = path("kit.comp.md");
138 assert_eq!(
139 kit.join("./parts/chip.comp.md"),
140 Some(path("parts/chip.comp.md"))
141 );
142 assert_eq!(
143 path("docs/a.comp.md").join("../ui/b.jsx"),
144 Some(path("ui/b.jsx"))
145 );
146 assert_eq!(
147 path("docs/a.comp.md").join("./x/../y.comp.md"),
148 Some(path("docs/y.comp.md"))
149 );
150 assert_eq!(kit.join("../x.comp.md"), None, "it leaves the pack");
151 assert_eq!(kit.join("./"), None, "it names a folder");
152 }
153
154 #[test]
155 fn a_path_is_a_string_in_json() {
156 let file: FilePath = serde_json::from_str(r#""dist/a.js""#).expect("a path");
157 assert_eq!(
158 serde_json::to_string(&file).expect("JSON"),
159 r#""dist/a.js""#
160 );
161 assert!(serde_json::from_str::<FilePath>(r#""../a.js""#).is_err());
162 assert_eq!(String::from(file), "dist/a.js");
163 assert_eq!(FilePath::try_from("a.js".to_owned()), Ok(path("a.js")));
164 }
165}