hazine 0.2.8

Runs a DuckDB Quack server for DuckLake on localhost, reached through an SSH tunnel.
Documentation
//! Where commonmeta caches downloads, so an import finds what `commonmeta`
//! (or an earlier import) downloaded.

use std::path::{Path, PathBuf};

/// commonmeta's cache directories for `namespace` (e.g. `orcid`): that of
/// whoever runs hazine, and, under sudo, the invoking user's
/// (`~/.cache/commonmeta/<namespace>`).
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
}

/// `user`'s home directory in `/etc/passwd` content.
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);
    }
}