1use std::path::{Path, PathBuf};
4
5pub trait PathExt {
6 fn replace<T: AsRef<str>>(&self, old: T, new: T) -> PathBuf;
7 fn contains<T: AsRef<str>>(&self, path: T) -> bool;
8}
9
10impl PathExt for Path {
11 fn replace<T: AsRef<str>>(&self, old: T, new: T) -> PathBuf {
12 let mut path = self.to_str().unwrap().to_string();
13
14 let new2 = new.as_ref().to_string().replace("\\", "/");
15 let old2 = old.as_ref().to_string().replace("\\", "/");
16
17 let new3 = new.as_ref().to_string().replace("/", "\\");
18 let old3 = old.as_ref().to_string().replace("/", "\\");
19
20 if path.contains(&old2) {
21 path = path.replace(&old2, &new2);
22 } else if path.contains(&old3) {
23 path = path.replace(&old3, &new3);
24 }
25
26 PathBuf::from(path)
27 }
28
29 fn contains<T: AsRef<str>>(&self, s: T) -> bool {
30 let path = self.to_str().unwrap().to_string();
31
32 let s2 = s.as_ref().to_string().replace("\\", "/");
33 let s3 = s.as_ref().to_string().replace("/", "\\");
34
35 path.contains(&s2) || path.contains(&s3) }
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42
43 #[test]
44 fn test_replace() {
45 let path = Path::new("C:\\Users\\user\\Desktop\\test.txt");
46 let path = path.replace("C:\\Users\\user\\Desktop", "C:\\Users\\user\\Documents");
47 assert_eq!(path, PathBuf::from("C:\\Users\\user\\Documents\\test.txt"));
48
49
50 let path = Path::new("/home/user/Desktop/test.txt");
52 let path = path.replace("/home/user/Desktop", "/home/user/Documents");
53 assert_eq!(path, PathBuf::from("/home/user/Documents/test.txt"));
54
55 let path = Path::new("C:\\Users\\user\\Desktop\\test.txt");
57 let path = path.replace("user/Desktop", "user/Documents");
58 assert_eq!(path, PathBuf::from("C:\\Users\\user\\Documents\\test.txt"));
59 }
60
61 #[test]
62 fn test_contains() {
63 let path = Path::new("C:\\Users\\user\\Desktop\\test.txt");
64 assert!(path.contains("Desktop"));
65 assert!(!path.contains("Documents"));
66
67 assert!(path.contains("user\\Desktop"));
69 assert!(!path.contains("user\\Documents"));
70
71 assert!(path.contains("user/Desktop"));
73 assert!(!path.contains("user/Documents"));
74
75 }
76
77}
78
79