vite_rust/utils/
resolve_path.rs1use std::env::current_dir;
2use std::path::{Component, Path, PathBuf};
3
4pub fn resolve_path(file: &str, path: &str) -> String {
42 let path: &Path = std::path::Path::new(path);
43 let mut this_file_directory = Path::new(file)
44 .parent()
45 .expect("Could not get current file's directory.")
46 .to_path_buf();
47
48 #[allow(unused_mut)]
49 let mut fp_fs: String; match this_file_directory.components().next() {
51 Some(Component::Normal(segment)) => fp_fs = segment.to_string_lossy().to_string(),
52 Some(Component::RootDir) => {
53 let component = this_file_directory.components().next().unwrap_or_else(|| {
54 panic!(
55 "Failed to find first directory segment from path {}.",
56 this_file_directory.to_string_lossy()
57 )
58 });
59
60 match component {
61 Component::Normal(segment) => fp_fs = segment.to_string_lossy().to_string(),
62 _ => {
63 panic!(
64 "Failed to find first directory normal segment from path {}.",
65 this_file_directory.to_string_lossy()
66 )
67 }
68 }
69 }
70 _ => panic!("Unexpected kind of directory."),
71 }
72
73 let curr_dir = current_dir().unwrap();
74
75 let paths_are_redundant = curr_dir.ends_with(&fp_fs) && this_file_directory.starts_with(&fp_fs);
76
77 if paths_are_redundant {
80 let mut new_path = PathBuf::new();
81 let mut components = this_file_directory.components();
82
83 if components.next().is_some() {
84 components.for_each(|component| new_path.push(component));
85 }
86
87 this_file_directory = new_path;
88 }
89
90 let joined_path = this_file_directory.join(path);
91 let canonicalized = joined_path.canonicalize();
92 match canonicalized {
93 Err(err) => panic!("{}\n{}\n", err, joined_path.to_string_lossy()),
94 Ok(path) => path.to_string_lossy().to_string(),
95 }
96}
97
98#[cfg(test)]
99mod test {
100 use std::io::Read;
101
102 #[test]
103 fn test_resolve_path() {
104 let abs_path = "tests/dummy.txt";
105 let rel_path = "../../tests/dummy.txt";
106 let resolved_rel_path = super::resolve_path(file!(), rel_path);
107
108 let mut abs_file_contents = String::new();
109 let mut rel_file_contents = String::new();
110
111 let _ = std::fs::File::open(abs_path)
112 .unwrap()
113 .read_to_string(&mut abs_file_contents);
114 let _ = std::fs::File::open(resolved_rel_path)
115 .unwrap()
116 .read_to_string(&mut rel_file_contents);
117
118 assert_eq!(abs_file_contents, rel_file_contents);
119 }
120}