Optimize getting a relative path

pull/9932/head
mo8it 9 months ago committed by Blaž Hrastnik
parent 6ed93b6e49
commit e91ec8e880

@ -10,17 +10,21 @@ use crate::env::current_working_dir;
/// Replaces users home directory from `path` with tilde `~` if the directory /// Replaces users home directory from `path` with tilde `~` if the directory
/// is available, otherwise returns the path unchanged. /// is available, otherwise returns the path unchanged.
pub fn fold_home_dir(path: &Path) -> PathBuf { pub fn fold_home_dir<'a, P>(path: P) -> Cow<'a, Path>
where
P: Into<Cow<'a, Path>>,
{
let path = path.into();
if let Ok(home) = home_dir() { if let Ok(home) = home_dir() {
if let Ok(stripped) = path.strip_prefix(&home) { if let Ok(stripped) = path.strip_prefix(&home) {
let mut path = OsString::with_capacity(2 + stripped.as_os_str().len()); let mut path = OsString::with_capacity(2 + stripped.as_os_str().len());
path.push("~/"); path.push("~/");
path.push(stripped); path.push(stripped);
return PathBuf::from(path); return Cow::Owned(PathBuf::from(path));
} }
} }
path.to_path_buf() path
} }
/// Expands tilde `~` into users home directory if available, otherwise returns the path /// Expands tilde `~` into users home directory if available, otherwise returns the path
@ -129,18 +133,21 @@ pub fn canonicalize(path: impl AsRef<Path>) -> PathBuf {
normalize(path) normalize(path)
} }
pub fn get_relative_path(path: impl AsRef<Path>) -> PathBuf { pub fn get_relative_path<'a, P>(path: P) -> Cow<'a, Path>
let path = PathBuf::from(path.as_ref()); where
let path = if path.is_absolute() { P: Into<Cow<'a, Path>>,
{
let path = path.into();
if path.is_absolute() {
let cwdir = normalize(current_working_dir()); let cwdir = normalize(current_working_dir());
normalize(&path) if let Ok(stripped) = normalize(&path).strip_prefix(cwdir) {
.strip_prefix(cwdir) return Cow::Owned(PathBuf::from(stripped));
.map(PathBuf::from) }
.unwrap_or(path)
} else { return fold_home_dir(path);
path }
};
fold_home_dir(&path) path
} }
/// Returns a truncated filepath where the basepart of the path is reduced to the first /// Returns a truncated filepath where the basepart of the path is reduced to the first

@ -482,7 +482,7 @@ where
let rel_path = context.doc.relative_path(); let rel_path = context.doc.relative_path();
let path = rel_path let path = rel_path
.as_ref() .as_ref()
.and_then(|p| p.as_path().file_name().map(|s| s.to_string_lossy())) .and_then(|p| p.file_name().map(|s| s.to_string_lossy()))
.unwrap_or_else(|| SCRATCH_BUFFER_NAME.into()); .unwrap_or_else(|| SCRATCH_BUFFER_NAME.into());
format!(" {} ", path) format!(" {} ", path)
}; };

@ -1685,7 +1685,7 @@ impl Document {
&self.selections &self.selections
} }
pub fn relative_path(&self) -> Option<PathBuf> { pub fn relative_path(&self) -> Option<Cow<Path>> {
self.path self.path
.as_deref() .as_deref()
.map(helix_stdx::path::get_relative_path) .map(helix_stdx::path::get_relative_path)

Loading…
Cancel
Save