//! Where libbui keeps its files. //! //! Terminal users expect the XDG layout, so every unix (macOS included) uses //! `~/.config/libbui`, `~/.local/share/libbui`, `~/.cache/libbui` and //! `~/.local/state/libbui`, honouring `XDG_*_HOME`. Windows uses its native //! known folders (via `directories`). `LIBBUI_CONFIG_DIR`, `LIBBUI_DATA_DIR`, //! `LIBBUI_CACHE_DIR` and `LIBBUI_STATE_DIR` override each root. //! //! Environment access goes through an injected lookup function so tests //! never read or mutate the process environment. use std::path::{Path, PathBuf}; /// Application name used for every directory. const APP: &str = "libbui"; /// The folder the Windows layout nests the app under. #[cfg(any(windows, test))] const ORG: &str = "vinnymac"; /// The directories libbui reads and writes. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Paths { /// `config.toml` and `identity.json`. pub config_dir: PathBuf, /// Durable data: the library index and ebook authorization. pub data_dir: PathBuf, /// Disposable data: cover cache and download staging. pub cache_dir: PathBuf, /// Runtime state that should survive restarts: the download queue. pub state_dir: PathBuf, /// Daily-rotated log files. pub log_dir: PathBuf, /// Where books go when the config does not name a download directory. /// /// `~/Documents/Libby`: a durable, user-visible place rather than /// `~/Downloads`, which many people (and macOS storage tooling) treat as /// scratch space to be emptied. pub default_download_dir: PathBuf, /// The user's home directory, used to expand `~/` in configured paths. /// `None` only for [`Paths::rooted_at`]. pub home_dir: Option, } /// Why the directories could not be determined. #[derive(Debug, thiserror::Error)] pub enum PathsError { /// No home directory could be found (unix: `HOME` unset or empty). #[error( "cannot determine the home directory; set {}", if cfg!(windows) { "USERPROFILE" } else { "HOME" } )] NoHome, /// An override variable holds a relative path, which would silently /// depend on the working directory. #[error("{var} must be an absolute path, got {value:?}")] RelativeOverride { /// The variable name. var: &'static str, /// What it was set to. value: PathBuf, }, } impl Paths { /// Resolves the directories from the real process environment. /// /// # Errors /// See [`Paths::from_env`]. pub fn discover() -> Result { Self::from_env(|key| std::env::var_os(key).map(PathBuf::from)) } /// Resolves the directories using `lookup` for every environment /// variable. Empty values count as unset. /// /// # Errors /// [`PathsError::NoHome`] when no home directory is available and /// [`PathsError::RelativeOverride`] for a relative `LIBBUI_*_DIR`. pub fn from_env(lookup: impl Fn(&str) -> Option) -> Result { let get = |key: &str| lookup(key).filter(|v| !v.as_os_str().is_empty()); let platform = Platform::detect(&get)?; let over = |var: &'static str| -> Result, PathsError> { match get(var) { Some(v) if v.is_absolute() => Ok(Some(v)), Some(v) => Err(PathsError::RelativeOverride { var, value: v }), None => Ok(None), } }; let config_dir = over("LIBBUI_CONFIG_DIR")?.unwrap_or(platform.config); let data_dir = over("LIBBUI_DATA_DIR")?.unwrap_or(platform.data); let cache_dir = over("LIBBUI_CACHE_DIR")?.unwrap_or(platform.cache); let state_dir = over("LIBBUI_STATE_DIR")?.unwrap_or(platform.state); let log_dir = state_dir.join("logs"); Ok(Self { config_dir, data_dir, cache_dir, state_dir, log_dir, default_download_dir: platform.documents.join("Libby"), home_dir: Some(platform.home), }) } /// Puts every directory under `root`. For tests and portable installs. pub fn rooted_at(root: impl AsRef) -> Self { let root = root.as_ref(); let state_dir = root.join("state"); Self { config_dir: root.join("config"), data_dir: root.join("data"), cache_dir: root.join("cache"), log_dir: state_dir.join("logs"), state_dir, default_download_dir: root.join("library"), home_dir: None, } } /// `config.toml`. pub fn config_file(&self) -> PathBuf { self.config_dir.join("config.toml") } /// `identity.json`, the stored Libby credential. pub fn identity_file(&self) -> PathBuf { self.config_dir.join("identity.json") } /// Durable ebook authorization, kept separately from Libby pairing. pub fn ebook_authorization_dir(&self) -> PathBuf { self.data_dir.join("ebook-authorization") } /// The persisted download queue. pub fn queue_file(&self) -> PathBuf { self.state_dir.join("downloads.json") } /// The index of finished downloads. pub fn library_index_file(&self) -> PathBuf { self.data_dir.join("library.json") } /// Local collections, reading observations, follows and annotations. pub fn personal_library_file(&self) -> PathBuf { self.data_dir.join("personal-library.json") } /// Partial downloads live here until verified. pub fn staging_dir(&self) -> PathBuf { self.cache_dir.join("staging") } /// Cached cover images. pub fn covers_dir(&self) -> PathBuf { self.cache_dir.join("covers") } /// Expands a leading `~/` (or a bare `~`) against the home directory. /// Other paths are returned unchanged. pub fn expand_tilde(&self, path: &Path) -> PathBuf { let Some(home) = &self.home_dir else { return path.to_path_buf(); }; match path.strip_prefix("~") { Ok(rest) => home.join(rest), Err(_) => path.to_path_buf(), } } } /// Platform defaults before overrides. struct Platform { home: PathBuf, config: PathBuf, data: PathBuf, cache: PathBuf, state: PathBuf, documents: PathBuf, } impl Platform { #[cfg(unix)] fn detect(get: &impl Fn(&str) -> Option) -> Result { let home = get("HOME").ok_or(PathsError::NoHome)?; // The XDG spec says relative values must be ignored. let xdg = |var: &str, default: &str| { get(var) .filter(|p| p.is_absolute()) .unwrap_or_else(|| home.join(default)) .join(APP) }; Ok(Self { config: xdg("XDG_CONFIG_HOME", ".config"), data: xdg("XDG_DATA_HOME", ".local/share"), cache: xdg("XDG_CACHE_HOME", ".cache"), state: xdg("XDG_STATE_HOME", ".local/state"), documents: home.join("Documents"), home, }) } #[cfg(windows)] fn detect(get: &impl Fn(&str) -> Option) -> Result { // Known folders come from the shell API, which follows a redirected // Documents folder. A stripped-down session (a service, a sandbox) // may have no shell profile; the environment still names the folders. let (Some(base), Some(project)) = ( directories::BaseDirs::new(), directories::ProjectDirs::from("dev", ORG, APP), ) else { return Self::windows_from_env(get); }; let documents = directories::UserDirs::new() .and_then(|u| u.document_dir().map(Path::to_path_buf)) .unwrap_or_else(|| base.home_dir().join("Documents")); Ok(Self { home: base.home_dir().to_path_buf(), config: project.config_dir().to_path_buf(), data: project.data_dir().to_path_buf(), cache: project.cache_dir().to_path_buf(), state: project.data_local_dir().join("state"), documents, }) } /// The Windows layout from `USERPROFILE`, `APPDATA` and `LOCALAPPDATA`, /// matching what the shell API gives on a default profile. #[cfg(any(windows, test))] fn windows_from_env(get: &impl Fn(&str) -> Option) -> Result { let home = get("USERPROFILE") .filter(|p| p.is_absolute()) .ok_or(PathsError::NoHome)?; let folder = |var: &str, default: &[&str]| { get(var) .filter(|p| p.is_absolute()) .unwrap_or_else(|| { default .iter() .fold(home.clone(), |dir, part| dir.join(part)) }) .join(ORG) .join(APP) }; let roaming = folder("APPDATA", &["AppData", "Roaming"]); let local = folder("LOCALAPPDATA", &["AppData", "Local"]); Ok(Self { config: roaming.join("config"), data: roaming.join("data"), cache: local.join("cache"), state: local.join("data").join("state"), documents: home.join("Documents"), home, }) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; use std::collections::HashMap; fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { let map: HashMap = pairs .iter() .map(|(k, v)| ((*k).to_owned(), PathBuf::from(v))) .collect(); move |k| map.get(k).cloned() } /// Runs on every platform: on Windows the defaults come from the shell, /// but the overrides still come from the environment. #[test] fn overrides_replace_the_platform_folders_everywhere() { let root = if cfg!(windows) { r"C:\libbui" } else { "/libbui" }; let at = |leaf: &str| Path::new(root).join(leaf); let dirs = ["config", "data", "cache", "state"].map(at); let texts = dirs .each_ref() .map(|dir| dir.to_string_lossy().into_owned()); let p = Paths::from_env(env(&[ ("HOME", root), ("LIBBUI_CONFIG_DIR", &texts[0]), ("LIBBUI_DATA_DIR", &texts[1]), ("LIBBUI_CACHE_DIR", &texts[2]), ("LIBBUI_STATE_DIR", &texts[3]), ])) .unwrap(); assert_eq!(p.config_dir, dirs[0]); assert_eq!(p.data_dir, dirs[1]); assert_eq!(p.cache_dir, dirs[2]); assert_eq!(p.state_dir, dirs[3]); assert_eq!(p.log_dir, dirs[3].join("logs")); let relative = Paths::from_env(env(&[("HOME", root), ("LIBBUI_DATA_DIR", "books")])); assert!(matches!( relative, Err(PathsError::RelativeOverride { var: "LIBBUI_DATA_DIR", .. }) )); } #[test] fn windows_folders_come_from_the_environment_when_the_shell_has_none() { let home = if cfg!(windows) { r"C:\Users\u" } else { "/Users/u" }; let home_dir = PathBuf::from(home); let pairs = [("USERPROFILE", home)]; let p = Platform::windows_from_env(&env(&pairs)).unwrap(); let roaming = home_dir.join("AppData").join("Roaming").join("vinnymac"); let local = home_dir.join("AppData").join("Local").join("vinnymac"); assert_eq!(p.config, roaming.join("libbui").join("config")); assert_eq!(p.data, roaming.join("libbui").join("data")); assert_eq!(p.cache, local.join("libbui").join("cache")); assert_eq!(p.state, local.join("libbui").join("data").join("state")); assert_eq!(p.documents, home_dir.join("Documents")); assert_eq!(p.home, home_dir); let nothing: [(&str, &str); 0] = []; assert!(matches!( Platform::windows_from_env(&env(¬hing)), Err(PathsError::NoHome) )); } #[cfg(unix)] #[test] fn xdg_defaults_from_home() { let p = Paths::from_env(env(&[("HOME", "/home/u")])).unwrap(); assert_eq!(p.config_dir, PathBuf::from("/home/u/.config/libbui")); assert_eq!(p.data_dir, PathBuf::from("/home/u/.local/share/libbui")); assert_eq!(p.cache_dir, PathBuf::from("/home/u/.cache/libbui")); assert_eq!(p.state_dir, PathBuf::from("/home/u/.local/state/libbui")); assert_eq!(p.log_dir, PathBuf::from("/home/u/.local/state/libbui/logs")); assert_eq!( p.default_download_dir, PathBuf::from("/home/u/Documents/Libby") ); } #[cfg(unix)] #[test] fn xdg_vars_are_honoured_and_relative_ones_ignored() { let p = Paths::from_env(env(&[ ("HOME", "/home/u"), ("XDG_CONFIG_HOME", "/cfg"), ("XDG_CACHE_HOME", "relative/cache"), ("XDG_DATA_HOME", ""), ])) .unwrap(); assert_eq!(p.config_dir, PathBuf::from("/cfg/libbui")); assert_eq!(p.cache_dir, PathBuf::from("/home/u/.cache/libbui")); assert_eq!(p.data_dir, PathBuf::from("/home/u/.local/share/libbui")); } #[cfg(unix)] #[test] fn libbui_overrides_win() { let p = Paths::from_env(env(&[ ("HOME", "/home/u"), ("XDG_CONFIG_HOME", "/cfg"), ("LIBBUI_CONFIG_DIR", "/o/config"), ("LIBBUI_DATA_DIR", "/o/data"), ("LIBBUI_CACHE_DIR", "/o/cache"), ("LIBBUI_STATE_DIR", "/o/state"), ])) .unwrap(); assert_eq!(p.config_dir, PathBuf::from("/o/config")); assert_eq!(p.data_dir, PathBuf::from("/o/data")); assert_eq!(p.cache_dir, PathBuf::from("/o/cache")); assert_eq!(p.state_dir, PathBuf::from("/o/state")); assert_eq!(p.log_dir, PathBuf::from("/o/state/logs")); } #[cfg(unix)] #[test] fn relative_override_is_an_error() { let err = Paths::from_env(env(&[("HOME", "/h"), ("LIBBUI_DATA_DIR", "data")])).unwrap_err(); assert!(matches!( err, PathsError::RelativeOverride { var: "LIBBUI_DATA_DIR", .. } )); } #[cfg(unix)] #[test] fn missing_home_is_an_error() { assert!(matches!( Paths::from_env(env(&[])).unwrap_err(), PathsError::NoHome )); } #[test] fn rooted_at_keeps_everything_inside() { let p = Paths::rooted_at("/t"); for dir in [ &p.config_dir, &p.data_dir, &p.cache_dir, &p.state_dir, &p.log_dir, &p.default_download_dir, ] { assert!(dir.starts_with("/t"), "{dir:?}"); } } #[cfg(unix)] #[test] fn tilde_expansion() { let p = Paths::from_env(env(&[("HOME", "/home/u")])).unwrap(); assert_eq!( p.expand_tilde(Path::new("~/Books")), PathBuf::from("/home/u/Books") ); assert_eq!(p.expand_tilde(Path::new("~")), PathBuf::from("/home/u")); assert_eq!(p.expand_tilde(Path::new("/abs")), PathBuf::from("/abs")); assert_eq!( p.expand_tilde(Path::new("~other/x")), PathBuf::from("~other/x") ); } }