mimir_node_map/
source_file.rs1use std::path::{Component, Path, PathBuf};
4
5pub fn clean_source_path(path: &Path) -> PathBuf {
7 let mut out = PathBuf::new();
8 for c in path.components() {
9 match c {
10 Component::CurDir => {}
11 Component::ParentDir
12 if matches!(out.components().next_back(), Some(Component::Normal(_))) =>
13 {
14 out.pop();
15 }
16 Component::ParentDir
17 if matches!(out.components().next_back(), Some(Component::RootDir)) => {}
18 other => out.push(other),
19 }
20 }
21 out
22}
23
24pub fn same_source_file(a: &str, b: &str) -> bool {
27 if a.is_empty() || b.is_empty() {
28 return false;
29 }
30 let a = clean_source_path(Path::new(a));
31 let b = clean_source_path(Path::new(b));
32 let a = a.to_string_lossy();
33 let b = b.to_string_lossy();
34 let tail = |long: &str, short: &str| {
35 !short.is_empty()
36 && long.len() > short.len()
37 && long.ends_with(short)
38 && long.as_bytes()[long.len() - short.len() - 1] == b'/'
39 };
40 !a.is_empty() && !b.is_empty() && (a == b || tail(&a, &b) || tail(&b, &a))
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46 #[test]
47 fn cleaning_matches_the_driver_without_resolving_files() {
48 for (from, to) in [
49 ("src/storage/../lib.rs", "src/lib.rs"),
50 ("../../src/./lib.rs", "../../src/lib.rs"),
51 ("/../../src/../lib.rs", "/lib.rs"),
52 (
53 "/w/library/std/src/../../backtrace/src/print.rs",
54 "/w/library/backtrace/src/print.rs",
55 ),
56 ] {
57 assert_eq!(clean_source_path(Path::new(from)), Path::new(to));
58 }
59 assert!(same_source_file("/w/src/storage/../lib.rs", "src/lib.rs"));
60 assert!(!same_source_file("/w/src/first.rs", "src/second.rs"));
61 assert!(!same_source_file("", ""));
62 }
63}