use std::path::{Path, PathBuf};
pub(crate) fn dirs(namespace: &str) -> Vec<PathBuf> {
let mut dirs = vec![commonmeta::io_utils::cache_dir(namespace)];
if let Ok(user) = std::env::var("SUDO_USER")
&& let Ok(passwd) = std::fs::read_to_string("/etc/passwd")
&& let Some(home) = home_of(&passwd, &user)
{
let dir = Path::new(&home).join(".cache/commonmeta").join(namespace);
if !dirs.contains(&dir) {
dirs.push(dir);
}
}
dirs
}
fn home_of(passwd: &str, user: &str) -> Option<String> {
passwd.lines().find_map(|line| {
let fields: Vec<&str> = line.split(':').collect();
(fields.len() >= 7 && fields[0] == user).then(|| fields[5].to_string())
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sudo_users_have_homes() {
let passwd =
"root:x:0:0:root:/root:/bin/bash\nmartin:x:1000:1000::/home/martin:/bin/bash\n";
assert_eq!(home_of(passwd, "martin").as_deref(), Some("/home/martin"));
assert_eq!(home_of(passwd, "nobody"), None);
}
}