1use regex::Regex;
2use std::env;
3use std::path::PathBuf;
4
5pub fn untildify(input_path: &str) -> String {
20 if input_path.is_empty() {
21 return String::from(input_path);
22 }
23 return match get_host_dir() {
24 Some(path) => {
25 let host_dir = path.to_str().unwrap();
26 let re = Regex::new(r"^~([/\w.]+)").unwrap();
27 match re.captures(input_path) {
28 Some(captures) => {
29 return format!("{}{}", host_dir, &captures[1]);
30 }
31 None => String::from(input_path),
32 }
33 }
34 None => String::from(input_path),
35 };
36}
37
38#[cfg(any(unix, target_os = "redox"))]
39fn get_host_dir() -> Option<PathBuf> {
40 #[allow(deprecated)]
41 env::home_dir()
42}
43
44#[cfg(test)]
45mod tests {
46 use crate::untildify;
47 use std::env;
48 use std::path::Path;
49
50 #[test]
51 fn test_returns_untildfyed_string() {
52 env::remove_var("HOME");
53
54 let home = Path::new("/User/Untildify");
55 env::set_var("HOME", home.as_os_str());
56
57 assert_eq!(untildify("~/Desktop"), "/User/Untildify/Desktop");
58 assert_eq!(untildify("~/a/b/c/d/e"), "/User/Untildify/a/b/c/d/e");
59 assert_eq!(untildify("~/"), "/User/Untildify/");
60 }
61
62 #[test]
63 fn test_returns_empty_string() {
64 env::remove_var("HOME");
65
66 let home = Path::new("/User/Untildify");
67 env::set_var("HOME", home.as_os_str());
68
69 assert_eq!(untildify("Desktop"), "Desktop");
70 assert_eq!(untildify(""), "");
71 assert_eq!(untildify("/"), "/");
72 assert_eq!(untildify("~/Desktop/~/Code"), "/User/Untildify/Desktop/");
73 }
74
75 #[test]
76 fn test_with_dot_folders() {
77 env::remove_var("HOME");
78
79 let home = Path::new("/User/Untildify");
80 env::set_var("HOME", home.as_os_str());
81
82 assert_eq!(untildify("~/.ssh/id_rsa"), "/User/Untildify/.ssh/id_rsa");
83 }
84}