use std::path::{Path, PathBuf};
pub fn expand_tilde(path: &str) -> PathBuf {
if let Some(rest) = path.strip_prefix("~/") {
if let Some(home) = dirs::home_dir() {
return home.join(rest);
}
} else if path == "~" {
if let Some(home) = dirs::home_dir() {
return home;
}
}
PathBuf::from(path)
}
pub fn resolve_to_cwd(path: &str, cwd: &Path) -> PathBuf {
let expanded = expand_tilde(path);
if expanded.is_absolute() {
expanded
} else {
cwd.join(expanded)
}
}
pub fn resolve_read_path(path: &str, cwd: &Path) -> PathBuf {
resolve_to_cwd(path, cwd)
}
pub fn shorten_path(path: &Path, cwd: &Path) -> String {
if let Ok(rel) = path.strip_prefix(cwd) {
let s = rel.to_string_lossy().to_string();
return if s.is_empty() { ".".to_string() } else { s };
}
if let Some(home) = dirs::home_dir() {
if let Ok(rel) = path.strip_prefix(&home) {
return format!("~/{}", rel.to_string_lossy());
}
}
path.to_string_lossy().to_string()
}
pub fn display_path(raw: &str, cwd: &Path) -> String {
shorten_path(&resolve_to_cwd(raw, cwd), cwd)
}