Improve Homedir detection
- Try passwd file - Handle cases of empty strings
This commit is contained in:
parent
6fe31a8e46
commit
905d3489f7
@ -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);
|
pub const REPO_COL: ansi_term::Colour = RGB(55, 120, 130);
|
||||||
|
|
||||||
/// Find the current user's home directory.
|
/// Find the current user's home directory.
|
||||||
fn home_dir() -> String {
|
fn home_dir() -> Option<String> {
|
||||||
std::env::var("HOME").map_or_else(|_| String::new(), |path| path.to_string())
|
// 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.
|
/// 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
|
/// Replace the 'home directory' part of the path with a the '~' symbol
|
||||||
fn replace_home(path: &str) -> String {
|
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 {
|
fn short(path: &str, slash_limit: u8) -> String {
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user