rmv-core 1.0.0

Configuration, retries, stop resolution and connection status for the RMV API
Documentation
//! Where `rmv` keeps its configuration. On Linux and macOS it follows the
//! XDG base directories: `~/.config/rmv`, or below `$XDG_CONFIG_HOME`. On
//! Windows it is the usual one below `%APPDATA%`.
//!
//! `rmv` keeps nothing else: no cache and no state, so no answer of the API
//! is stored.

#[cfg(not(windows))]
use std::ffi::OsString;
#[cfg(not(windows))]
use std::path::Path;
use std::path::PathBuf;

const NAME: &str = "rmv";

/// The directory of the configuration. `None` if the home directory is
/// unknown.
#[cfg(not(windows))]
pub fn config() -> Option<PathBuf> {
    xdg(
        std::env::var_os("XDG_CONFIG_HOME"),
        home().as_deref(),
        ".config",
    )
}

/// The directory of the configuration. `None` if the home directory is
/// unknown.
#[cfg(windows)]
pub fn config() -> Option<PathBuf> {
    directories::ProjectDirs::from("", "", NAME).map(|dirs| dirs.config_dir().to_owned())
}

#[cfg(not(windows))]
fn home() -> Option<PathBuf> {
    directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_owned())
}

/// The directory of `rmv` below the XDG variable, or below its default in
/// the home directory. The specification ignores relative paths.
#[cfg(not(windows))]
fn xdg(variable: Option<OsString>, home: Option<&Path>, default: &str) -> Option<PathBuf> {
    let base = variable
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
        .or_else(|| home.map(|home| home.join(default)))?;
    Some(base.join(NAME))
}

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

    #[test]
    #[cfg(not(windows))]
    fn follows_the_variable() {
        assert_eq!(
            xdg(Some("/xdg".into()), Some(Path::new("/home/me")), ".config"),
            Some(PathBuf::from("/xdg/rmv"))
        );
    }

    #[test]
    #[cfg(not(windows))]
    fn falls_back_to_the_home_directory() {
        let home = Some(Path::new("/home/me"));
        let expected = Some(PathBuf::from("/home/me/.config/rmv"));
        assert_eq!(xdg(None, home, ".config"), expected);
        assert_eq!(xdg(Some("".into()), home, ".config"), expected);
        assert_eq!(xdg(Some("relative".into()), home, ".config"), expected);
    }

    #[test]
    #[cfg(not(windows))]
    fn needs_a_home_directory() {
        assert_eq!(xdg(None, None, ".config"), None);
    }

    #[test]
    fn lies_in_a_directory_of_rmv() {
        let dir = config().unwrap();
        assert!(
            dir.components().any(|part| part.as_os_str() == NAME),
            "{}",
            dir.display()
        );
    }
}