diff --git a/src/indicators/pwd.rs b/src/indicators/pwd.rs index 4f0f320..b41a594 100644 --- a/src/indicators/pwd.rs +++ b/src/indicators/pwd.rs @@ -8,8 +8,19 @@ pub const PATH_COL: ansi_term::Colour = RGB(82, 82, 82); pub const REPO_COL: ansi_term::Colour = RGB(55, 120, 130); /// Find the current user's home directory. -fn home_dir() -> String { - std::env::var("HOME").map_or_else(|_| String::new(), |path| path.to_string()) +fn home_dir() -> Option { + // Try `passwd` file first + unsafe { + let pw = libc::getpwuid(libc::geteuid()); + if !pw.is_null() { + let dir = std::ffi::CStr::from_ptr((*pw).pw_dir); + if let Ok(s) = dir.to_str() { + return Some(s.to_owned()); + } + } + } + // Fallback: `$HOME` env var + std::env::var("HOME").ok() } /// Returns the full path of the current directory as a string. @@ -27,7 +38,12 @@ fn remove_repo(pwd_path: &str, repo_path: &str) -> String { /// Replace the 'home directory' part of the path with a the '~' symbol fn replace_home(path: &str) -> String { - path.replacen(&home_dir(), "~", 1) + if let Some(home) = home_dir() { + if path.starts_with(&home) { + return path.replacen(&home, "~", 1); + } + } + path.to_owned() } fn short(path: &str, slash_limit: u8) -> String {