rosier 0.5.2

A fast picture and video viewer for large folders
//! The user's data and cache folders, as the XDG base directory spec names
//! them. The same lookup runs on every system; where neither variable is
//! set (usual on Windows), callers fall back to the temporary folder.

use std::ffi::OsString;
use std::path::PathBuf;

/// `$XDG_DATA_HOME`, or `~/.local/share` when it is unset or empty.
pub fn data_home() -> Option<PathBuf> {
    xdg(|k| std::env::var_os(k), "XDG_DATA_HOME", ".local/share")
}

/// `$XDG_CACHE_HOME`, or `~/.cache` when it is unset or empty.
pub fn cache_home() -> Option<PathBuf> {
    xdg(|k| std::env::var_os(k), "XDG_CACHE_HOME", ".cache")
}

/// The folder `key` names, or `under_home` inside HOME. The spec says an
/// empty value counts as unset.
fn xdg(var: impl Fn(&str) -> Option<OsString>, key: &str, under_home: &str) -> Option<PathBuf> {
    var(key)
        .filter(|v| !v.is_empty())
        .map(PathBuf::from)
        .or_else(|| var("HOME").filter(|h| !h.is_empty()).map(|h| PathBuf::from(h).join(under_home)))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<OsString> + 'a {
        move |k| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v))
    }

    #[test]
    fn the_variable_wins_then_home_then_nothing() {
        let both = [("XDG_DATA_HOME", "/data"), ("HOME", "/home/u")];
        assert_eq!(xdg(env(&both), "XDG_DATA_HOME", ".local/share"), Some(PathBuf::from("/data")));
        let home = [("HOME", "/home/u")];
        assert_eq!(xdg(env(&home), "XDG_CACHE_HOME", ".cache"), Some(PathBuf::from("/home/u/.cache")));
        let empty = [("XDG_DATA_HOME", ""), ("HOME", "/home/u")];
        assert_eq!(xdg(env(&empty), "XDG_DATA_HOME", ".local/share"), Some(PathBuf::from("/home/u/.local/share")));
        assert_eq!(xdg(env(&[("HOME", "")]), "XDG_DATA_HOME", ".local/share"), None);
        assert_eq!(xdg(env(&[]), "XDG_DATA_HOME", ".local/share"), None);
    }

    #[test]
    fn the_real_folders_are_read_from_this_process() {
        // Whatever this machine sets, a data folder is found from HOME.
        if std::env::var_os("HOME").is_some_and(|h| !h.is_empty()) {
            assert!(data_home().is_some());
            assert!(cache_home().is_some());
        }
    }
}