on aef00a3 help sign in
143 lines 4.9 kB history raw
1use etcetera::home_dir;
2use std::path::{Component, Path, PathBuf};
4/// Replaces users home directory from `path` with tilde `~` if the directory
5/// is available, otherwise returns the path unchanged.
6pub fn fold_home_dir(path: &Path) -> PathBuf {
7 if let Ok(home) = home_dir() {
8 if let Ok(stripped) = path.strip_prefix(&home) {
9 return PathBuf::from("~").join(stripped);
10 }
11 }
13 path.to_path_buf()
16/// Expands tilde `~` into users home directory if available, otherwise returns the path
17/// unchanged. The tilde will only be expanded when present as the first component of the path
18/// and only slash follows it.
19pub fn expand_tilde(path: &Path) -> PathBuf {
20 let mut components = path.components().peekable();
21 if let Some(Component::Normal(c)) = components.peek() {
22 if c == &"~" {
23 if let Ok(home) = home_dir() {
24 // it's ok to unwrap, the path starts with `~`
25 return home.join(path.strip_prefix("~").unwrap());
26 }
27 }
28 }
30 path.to_path_buf()
33/// Normalize a path, removing things like `.` and `..`.
34///
35/// CAUTION: This does not resolve symlinks (unlike
36/// [`std::fs::canonicalize`]). This may cause incorrect or surprising
37/// behavior at times. This should be used carefully. Unfortunately,
38/// [`std::fs::canonicalize`] can be hard to use correctly, since it can often
39/// fail, or on Windows returns annoying device paths. This is a problem Cargo
40/// needs to improve on.
41/// Copied from cargo: <https://github.com/rust-lang/cargo/blob/070e459c2d8b79c5b2ac5218064e7603329c92ae/crates/cargo-util/src/paths.rs#L81>
42pub fn get_normalized_path(path: &Path) -> PathBuf {
43 let mut components = path.components().peekable();
44 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
45 components.next();
46 PathBuf::from(c.as_os_str())
47 } else {
48 PathBuf::new()
49 };
51 for component in components {
52 match component {
53 Component::Prefix(..) => unreachable!(),
54 Component::RootDir => {
55 ret.push(component.as_os_str());
56 }
57 Component::CurDir => {}
58 Component::ParentDir => {
59 ret.pop();
60 }
61 Component::Normal(c) => {
62 ret.push(c);
63 }
64 }
65 }
66 ret
69/// Returns the canonical, absolute form of a path with all intermediate components normalized.
70///
71/// This function is used instead of `std::fs::canonicalize` because we don't want to verify
72/// here if the path exists, just normalize it's components.
73pub fn get_canonicalized_path(path: &Path) -> std::io::Result<PathBuf> {
74 let path = expand_tilde(path);
75 let path = if path.is_relative() {
76 std::env::current_dir().map(|current_dir| current_dir.join(path))?
77 } else {
78 path
79 };
81 Ok(get_normalized_path(path.as_path()))
84pub fn get_relative_path(path: &Path) -> PathBuf {
85 let path = if path.is_absolute() {
86 let cwdir = std::env::current_dir().expect("couldn't determine current directory");
87 path.strip_prefix(cwdir).unwrap_or(path)
88 } else {
89 path
90 };
91 fold_home_dir(path)
94/// Returns a truncated filepath where the basepart of the path is reduced to the first
95/// char of the folder and the whole filename appended.
96///
97/// Also strip the current working directory from the beginning of the path.
98/// Note that this function does not check if the truncated path is unambiguous.
99///
100/// ```
101/// use helix_core::path::get_truncated_path;
102/// use std::path::Path;
103///
104/// assert_eq!(
105/// get_truncated_path("/home/cnorris/documents/jokes.txt").as_path(),
106/// Path::new("/h/c/d/jokes.txt")
107/// );
108/// assert_eq!(
109/// get_truncated_path("jokes.txt").as_path(),
110/// Path::new("jokes.txt")
111/// );
112/// assert_eq!(
113/// get_truncated_path("/jokes.txt").as_path(),
114/// Path::new("/jokes.txt")
115/// );
116/// assert_eq!(
117/// get_truncated_path("/h/c/d/jokes.txt").as_path(),
118/// Path::new("/h/c/d/jokes.txt")
119/// );
120/// assert_eq!(get_truncated_path("").as_path(), Path::new(""));
121/// ```
122///
123pub fn get_truncated_path<P: AsRef<Path>>(path: P) -> PathBuf {
124 let cwd = std::env::current_dir().unwrap_or_default();
125 let path = path
126 .as_ref()
127 .strip_prefix(cwd)
128 .unwrap_or_else(|_| path.as_ref());
129 let file = path.file_name().unwrap_or_default();
130 let base = path.parent().unwrap_or_else(|| Path::new(""));
131 let mut ret = PathBuf::new();
132 for d in base {
133 ret.push(
134 d.to_string_lossy()
135 .chars()
136 .next()
137 .unwrap_or_default()
138 .to_string(),
139 );
140 }
141 ret.push(file);
142 ret