1use std::ffi::{OsStr, OsString};
9use std::path::{Component, Path, PathBuf, Prefix};
10
11use crate::NameCase;
12use crate::env::fold;
13
14pub fn plain(path: &Path) -> Option<PathBuf> {
25 let mut parts = path.components().peekable();
26 let Some(Component::Prefix(prefix)) = parts.next() else {
27 return Some(path.to_owned());
28 };
29 let mut out = match prefix.kind() {
30 Prefix::VerbatimDisk(drive) if parts.peek() == Some(&Component::RootDir) => {
31 PathBuf::from(format!("{}:", char::from(drive)))
32 }
33 Prefix::VerbatimUNC(server, share) if !server.is_empty() && !share.is_empty() => {
34 let mut unc = OsString::from(r"\\");
35 unc.push(server);
36 unc.push(r"\");
37 unc.push(share);
38 PathBuf::from(unc)
39 }
40 Prefix::VerbatimDisk(_) | Prefix::VerbatimUNC(..) | Prefix::Verbatim(_) => return None,
41 Prefix::DeviceNS(_) | Prefix::Disk(_) | Prefix::UNC(..) => return Some(path.to_owned()),
42 };
43 for part in parts {
44 match part {
45 Component::RootDir => out.push(r"\"),
46 Component::Normal(name) if survives(name) => out.push(name),
47 _ => return None,
48 }
49 }
50 Some(out)
51}
52
53fn survives(name: &OsStr) -> bool {
56 let bytes = name.as_encoded_bytes();
57 if bytes.contains(&b'/') || bytes.ends_with(b".") || bytes.ends_with(b" ") {
58 return false;
59 }
60 let stem = bytes.split(|b| *b == b'.').next().unwrap_or(bytes);
62 let stem = stem.trim_ascii_end();
63 let device = |prefix: &[u8]| {
64 stem.len() == 4 && stem[..3].eq_ignore_ascii_case(prefix) && matches!(stem[3], b'1'..=b'9')
65 };
66 !([b"CON", b"PRN", b"AUX", b"NUL"]
67 .iter()
68 .any(|d| stem.eq_ignore_ascii_case(*d))
69 || device(b"COM")
70 || device(b"LPT"))
71}
72
73pub fn lexical(path: &Path) -> PathBuf {
75 let mut out = PathBuf::new();
76 for part in path.components() {
77 match part {
78 Component::CurDir => {}
79 Component::ParentDir => {
80 out.pop();
81 }
82 other => out.push(other),
83 }
84 }
85 out
86}
87
88#[derive(Clone, Debug)]
91pub struct Place {
92 real: PathBuf,
94 parts: Vec<String>,
96}
97
98impl Place {
99 pub fn of(path: &Path, case: NameCase) -> Place {
108 let (real, exact) = resolve(path);
109 let parts = real
110 .components()
111 .enumerate()
112 .map(|(i, component)| part(component, if i < exact { None } else { Some(case) }))
113 .collect();
114 Place { real, parts }
115 }
116
117 pub fn same(&self, other: &Place) -> bool {
119 self.parts == other.parts
120 }
121
122 pub fn within(&self, dir: &Place) -> bool {
124 self.relative(dir).is_some()
125 }
126
127 pub fn relative(&self, dir: &Place) -> Option<PathBuf> {
130 self.parts
131 .starts_with(&dir.parts)
132 .then(|| self.real.components().skip(dir.parts.len()).collect())
133 }
134
135 pub fn parent(&self) -> Option<Place> {
137 let real = self.real.parent()?.to_owned();
138 let parts = self.parts[..self.parts.len() - 1].to_vec();
139 Some(Place { real, parts })
140 }
141}
142
143pub fn same(a: &Path, b: &Path, case: NameCase) -> bool {
145 Place::of(a, case).same(&Place::of(b, case))
146}
147
148pub fn within(path: &Path, dir: &Path, case: NameCase) -> bool {
150 Place::of(path, case).within(&Place::of(dir, case))
151}
152
153pub fn relative(path: &Path, dir: &Path, case: NameCase) -> Option<PathBuf> {
155 Place::of(path, case).relative(&Place::of(dir, case))
156}
157
158fn resolve(path: &Path) -> (PathBuf, usize) {
161 let path = lexical(path);
162 if !path.is_absolute() {
163 return (path, 0);
164 }
165 let mut existing = path.as_path();
166 let mut rest = Vec::new();
167 loop {
168 if let Ok(canonical) = std::fs::canonicalize(existing) {
169 let exact = canonical.components().count();
170 let real = rest.iter().rev().fold(canonical, |p, part| p.join(part));
171 return (real, exact);
172 }
173 match (existing.parent(), existing.file_name()) {
174 (Some(parent), Some(name)) => {
175 rest.push(name.to_owned());
176 existing = parent;
177 }
178 _ => return (path, 0),
179 }
180 }
181}
182
183fn part(component: Component<'_>, case: Option<NameCase>) -> String {
188 let folded = |name: &OsStr| match case {
189 Some(case) => fold(name, case),
190 None => name.to_owned(),
191 };
192 let part = match component {
193 Component::Prefix(prefix) => match prefix.kind() {
194 Prefix::VerbatimDisk(d) | Prefix::Disk(d) => {
195 OsString::from(format!("{}:", char::from(d.to_ascii_uppercase())))
196 }
197 Prefix::VerbatimUNC(server, share) | Prefix::UNC(server, share) => {
198 let mut unc = OsString::from("//");
199 unc.push(server);
200 unc.push("/");
201 unc.push(share);
202 fold(&unc, NameCase::Insensitive)
203 }
204 _ => folded(prefix.as_os_str()),
205 },
206 Component::RootDir => OsString::new(),
207 other => folded(other.as_os_str()),
208 };
209 part.to_string_lossy().into_owned()
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 fn scratch(name: &str) -> PathBuf {
218 let dir = std::env::temp_dir().join(format!("cuno-paths-{}-{name}", std::process::id()));
219 let _ = std::fs::remove_dir_all(&dir);
220 std::fs::create_dir_all(&dir).unwrap();
221 dir
222 }
223
224 #[test]
226 fn case_is_ignored_only_where_the_file_system_ignores_it() {
227 let a = Path::new("/project/Src/Main.cpp");
228 let b = Path::new("/project/src/main.cpp");
229 assert!(same(a, b, NameCase::Insensitive));
230 assert!(!same(a, b, NameCase::Sensitive));
231 }
232
233 #[test]
237 fn dot_and_dot_dot_are_resolved_by_name() {
238 let case = NameCase::Sensitive;
239 assert!(same(
240 Path::new("/p/./src/../src/a.c"),
241 Path::new("/p/src/a.c"),
242 case
243 ));
244 assert!(within(Path::new("/p/src/../target"), Path::new("/p"), case));
245 assert!(!within(Path::new("/p/../q"), Path::new("/p"), case));
246 let relative_path = Path::new("no-such-dir/y/../z");
249 assert!(same(relative_path, Path::new("no-such-dir/z"), case));
250 assert!(within(relative_path, Path::new("no-such-dir/."), case));
251 assert!(!within(
252 Path::new("no-such-dir/y/out"),
253 Path::new("no-such-dir/z"),
254 case
255 ));
256 assert_eq!(resolve(Path::new("src/../src")).0, PathBuf::from("src"));
257 }
258
259 #[test]
262 fn within_takes_whole_names() {
263 let case = NameCase::Sensitive;
264 let dir = Path::new("/a/b");
265 assert!(within(Path::new("/a/b"), dir, case));
266 assert!(within(Path::new("/a/b/c"), dir, case));
267 assert!(!within(Path::new("/a/bc"), dir, case));
268 assert!(!within(Path::new("/a"), dir, case));
269 assert_eq!(
270 relative(Path::new("/a/b/c/d"), dir, case),
271 Some(PathBuf::from("c/d"))
272 );
273 assert_eq!(relative(Path::new("/a/b"), dir, case), Some(PathBuf::new()));
274 }
275
276 #[test]
282 fn a_path_not_there_yet_continues_from_the_part_that_is() {
283 let dir = scratch("tail");
284 let case = NameCase::host();
285 let missing = dir.join("not").join("yet");
286 let (real, _) = resolve(&missing);
287 assert!(real.ends_with("not/yet"));
288 assert!(real.starts_with(std::fs::canonicalize(&dir).unwrap()));
289 assert!(!same(&missing, &dir.join("not"), case));
290 assert!(within(&missing, &dir, case));
291 std::fs::remove_dir_all(&dir).unwrap();
292 }
293
294 #[cfg(windows)]
300 #[test]
301 fn a_verbatim_prefix_is_the_plain_one() {
302 let drive = (b'D'..=b'Z')
303 .map(char::from)
304 .find(|d| !Path::new(&format!("{d}:\\")).exists())
305 .expect("a free drive letter");
306 let verbatim = PathBuf::from(format!(r"\\?\{drive}:\nowhere"));
307 let plain = PathBuf::from(format!(r"{drive}:\nowhere"));
308 assert!(same(&verbatim, &plain, NameCase::Insensitive));
309 }
310
311 #[cfg(windows)]
317 #[test]
318 fn a_junction_is_where_it_leads() {
319 let dir = scratch("junction");
320 let target = dir.join("target");
321 let link = dir.join("link");
322 std::fs::create_dir(&target).unwrap();
323 let made = std::process::Command::new("cmd")
324 .args(["/C", "mklink", "/J"])
325 .arg(&link)
326 .arg(&target)
327 .output()
328 .unwrap();
329 assert!(made.status.success(), "{made:?}");
330 let case = NameCase::Insensitive;
331 assert!(same(&link, &target, case));
332 assert!(within(&link.join("debug"), &target, case));
333 assert!(!within(&link, &dir.join("elsewhere"), case));
334 std::fs::remove_dir(&link).unwrap();
335 std::fs::remove_dir_all(&dir).unwrap();
336 }
337
338 #[test]
345 fn existing_names_are_compared_as_the_file_system_spells_them() {
346 let dir = scratch("spelled");
347 let case = NameCase::Insensitive;
348 for name in ["tool_σ.cpp", "tool_ς.cpp"] {
349 std::fs::write(dir.join(name), "").unwrap();
350 }
351 assert!(!same(
352 &dir.join("tool_σ.cpp"),
353 &dir.join("tool_ς.cpp"),
354 case
355 ));
356 assert!(same(&dir.join("New/Out"), &dir.join("new/out"), case));
357 std::fs::remove_dir_all(&dir).unwrap();
358 }
359
360 #[cfg(windows)]
366 #[test]
367 fn a_share_is_one_share_however_it_is_written() {
368 let prefix = |p: &'static str| part(Path::new(p).components().next().unwrap(), None);
369 assert_eq!(
370 prefix(r"\\?\UNC\Server\Share\x"),
371 prefix(r"\\server\share\x")
372 );
373 assert_eq!(prefix(r"\\?\c:\x"), prefix(r"C:\x"));
374 }
375
376 #[test]
378 fn a_place_knows_its_directory() {
379 let case = NameCase::Sensitive;
380 let file = Place::of(Path::new("/p/src/a.c"), case);
381 let src = Place::of(Path::new("/p/src"), case);
382 assert!(file.parent().unwrap().same(&src));
383 assert!(!file.same(&src));
384 }
385
386 #[cfg(windows)]
392 #[test]
393 fn a_verbatim_path_is_written_plain() {
394 let plain_of = |p: &str| plain(Path::new(p)).map(|p| p.to_string_lossy().into_owned());
395 assert_eq!(plain_of(r"\\?\C:\a\out").as_deref(), Some(r"C:\a\out"));
396 assert_eq!(plain_of(r"\\?\d:\x").as_deref(), Some(r"D:\x"));
397 assert_eq!(
398 plain_of(r"\\?\UNC\srv\share\out").as_deref(),
399 Some(r"\\srv\share\out")
400 );
401 assert_eq!(plain_of(r"C:\a\..\b").as_deref(), Some(r"C:\a\..\b"));
402 assert_eq!(
403 plain_of(r"\\srv\share\x").as_deref(),
404 Some(r"\\srv\share\x")
405 );
406 assert_eq!(plain_of("out").as_deref(), Some("out"));
407 assert_eq!(plain_of(r"\\.\C:\x").as_deref(), Some(r"\\.\C:\x"));
409 }
410
411 #[cfg(windows)]
417 #[test]
418 fn a_verbatim_path_that_means_something_else_plain_has_no_plain_form() {
419 for path in [
420 r"\\?\C:\a\..\b",
421 r"\\?\C:\a\.\b",
422 r"\\?\C:\out.",
423 r"\\?\C:\out ",
424 r"\\?\C:\a/b\out",
425 r"\\?\C:\nul",
426 r"\\?\C:\Con.txt",
427 r"\\?\C:\lpt9 .log",
428 r"\\?\C:\COM1",
429 r"\\?\C:\com3",
430 r"\\?\C:\prn",
431 r"\\?\C:\Aux.c",
432 r"\\?\GLOBALROOT\Device\x",
433 r"\\?\C:",
437 r"\\?\C:out",
438 r"\\?\UNC\srv",
439 r"\\?\UNC\srv\",
440 r"\\?\UNC\",
441 ] {
442 assert_eq!(plain(Path::new(path)), None, "{path}");
443 }
444 for path in [
446 r"\\?\C:\console",
447 r"\\?\C:\com10",
448 r"\\?\C:\a.b\out",
449 r"\\?\C:\lpt0",
450 ] {
451 assert!(plain(Path::new(path)).is_some(), "{path}");
452 }
453 }
454}