Skip to main content

kizz_store/
location.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! The location of the cache directory.
6//!
7//! The cache is `KIZZ_CACHE_DIR` when set, otherwise `$XDG_CACHE_HOME/kizz`,
8//! otherwise `~/.cache/kizz`. [`cache_dir`] computes it from the three values, so
9//! that callers and tests never need to change the process environment;
10//! [`cache_dir_from_env`] reads them from the environment of the process.
11//!
12//! The rules for unusual values:
13//!
14//! * An empty `KIZZ_CACHE_DIR` counts as unset, as an empty `XDG_CACHE_HOME` does.
15//! * A relative `KIZZ_CACHE_DIR` is an error: the cache serves every build on the machine
16//!   wherever it starts, and a relative path would name a different cache in every
17//!   directory.
18//! * An empty or relative `XDG_CACHE_HOME` is ignored, as the XDG Base Directory
19//!   Specification requires.
20//! * When `HOME` is needed and is unset, empty, or relative, there is no cache location,
21//!   and the error says which variables can provide one.
22
23use std::{
24    ffi::{OsStr, OsString},
25    path::{Path, PathBuf},
26};
27
28/// The variable that names the cache directory directly.
29pub const KIZZ_CACHE_DIR: &str = "KIZZ_CACHE_DIR";
30/// The XDG Base Directory variable for user cache files.
31pub const XDG_CACHE_HOME: &str = "XDG_CACHE_HOME";
32/// The variable that names the home directory of the user.
33pub const HOME: &str = "HOME";
34
35/// Why the cache directory cannot be located.
36#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
37pub enum LocationError {
38    /// `KIZZ_CACHE_DIR` is set to a relative path.
39    #[error(
40        "KIZZ_CACHE_DIR must be an absolute path, but it is `{}`",
41        .0.display()
42    )]
43    RelativeCacheDir(PathBuf),
44    /// Neither `KIZZ_CACHE_DIR` nor a usable `XDG_CACHE_HOME` is set, and `HOME` is
45    /// unset, empty, or relative.
46    #[error(
47        "cannot locate the kizz cache: set KIZZ_CACHE_DIR or XDG_CACHE_HOME to an \
48         absolute path, or set HOME to an absolute path"
49    )]
50    NoHome,
51}
52
53/// The cache directory from the values of `KIZZ_CACHE_DIR`, `XDG_CACHE_HOME`, and
54/// `HOME`, each `None` when the variable is unset.
55///
56/// # Errors
57///
58/// [`LocationError::RelativeCacheDir`] when `KIZZ_CACHE_DIR` is relative, and
59/// [`LocationError::NoHome`] when `HOME` is needed but unusable.
60pub fn cache_dir(
61    kizz_cache_dir: Option<&OsStr>,
62    xdg_cache_home: Option<&OsStr>,
63    home: Option<&OsStr>,
64) -> Result<PathBuf, LocationError> {
65    if let Some(value) = non_empty(kizz_cache_dir) {
66        let path = Path::new(value);
67        if path.is_absolute() {
68            return Ok(path.to_path_buf());
69        }
70        return Err(LocationError::RelativeCacheDir(path.to_path_buf()));
71    }
72    if let Some(value) = non_empty(xdg_cache_home) {
73        let path = Path::new(value);
74        if path.is_absolute() {
75            return Ok(path.join("kizz"));
76        }
77    }
78    if let Some(value) = non_empty(home) {
79        let path = Path::new(value);
80        if path.is_absolute() {
81            return Ok(path.join(".cache").join("kizz"));
82        }
83    }
84    Err(LocationError::NoHome)
85}
86
87/// The cache directory from the environment of this process.
88///
89/// # Errors
90///
91/// As for [`cache_dir`].
92pub fn cache_dir_from_env() -> Result<PathBuf, LocationError> {
93    let kizz_cache_dir: Option<OsString> = std::env::var_os(KIZZ_CACHE_DIR);
94    let xdg_cache_home: Option<OsString> = std::env::var_os(XDG_CACHE_HOME);
95    let home: Option<OsString> = std::env::var_os(HOME);
96    cache_dir(
97        kizz_cache_dir.as_deref(),
98        xdg_cache_home.as_deref(),
99        home.as_deref(),
100    )
101}
102
103/// `value` unless it is unset or empty.
104fn non_empty(value: Option<&OsStr>) -> Option<&OsStr> {
105    value.filter(|value| !value.is_empty())
106}
107
108/// Unit tests for the location rules.
109#[cfg(test)]
110#[allow(
111    clippy::disallowed_macros,
112    clippy::disallowed_methods,
113    reason = "test code: the tests assert and lock"
114)]
115mod tests {
116    use super::*;
117
118    /// Shorthand for the value of a variable that is set.
119    #[expect(
120        clippy::unnecessary_wraps,
121        reason = "the tests pass the result where `cache_dir` takes an optional value"
122    )]
123    fn var(value: &str) -> Option<&OsStr> {
124        Some(OsStr::new(value))
125    }
126
127    #[test]
128    fn kizz_cache_dir_wins_over_xdg_cache_home_and_home() {
129        assert_eq!(
130            cache_dir(var("/kizz"), var("/xdg"), var("/home/user")),
131            Ok(PathBuf::from("/kizz"))
132        );
133    }
134
135    #[test]
136    fn xdg_cache_home_wins_over_home() {
137        assert_eq!(
138            cache_dir(None, var("/xdg"), var("/home/user")),
139            Ok(PathBuf::from("/xdg/kizz"))
140        );
141    }
142
143    #[test]
144    fn home_is_the_last_resort() {
145        assert_eq!(
146            cache_dir(None, None, var("/home/user")),
147            Ok(PathBuf::from("/home/user/.cache/kizz"))
148        );
149    }
150
151    #[test]
152    fn empty_kizz_cache_dir_counts_as_unset() {
153        assert_eq!(
154            cache_dir(var(""), var("/xdg"), var("/home/user")),
155            Ok(PathBuf::from("/xdg/kizz"))
156        );
157        assert_eq!(
158            cache_dir(var(""), None, var("/home/user")),
159            Ok(PathBuf::from("/home/user/.cache/kizz"))
160        );
161    }
162
163    #[test]
164    fn relative_kizz_cache_dir_is_an_error() {
165        let error = cache_dir(var("cache"), var("/xdg"), var("/home/user")).unwrap_err();
166        assert_eq!(
167            error,
168            LocationError::RelativeCacheDir(PathBuf::from("cache"))
169        );
170        assert!(error.to_string().contains("KIZZ_CACHE_DIR"));
171        assert!(error.to_string().contains("`cache`"));
172    }
173
174    #[test]
175    fn empty_or_relative_xdg_cache_home_is_ignored() {
176        assert_eq!(
177            cache_dir(None, var(""), var("/home/user")),
178            Ok(PathBuf::from("/home/user/.cache/kizz"))
179        );
180        assert_eq!(
181            cache_dir(None, var("relative/cache"), var("/home/user")),
182            Ok(PathBuf::from("/home/user/.cache/kizz"))
183        );
184    }
185
186    #[test]
187    fn missing_empty_or_relative_home_is_an_error_when_needed() {
188        assert_eq!(cache_dir(None, None, None), Err(LocationError::NoHome));
189        assert_eq!(cache_dir(None, None, var("")), Err(LocationError::NoHome));
190        assert_eq!(
191            cache_dir(None, var("relative"), var("home")),
192            Err(LocationError::NoHome)
193        );
194        let message = LocationError::NoHome.to_string();
195        assert!(message.contains("KIZZ_CACHE_DIR"));
196        assert!(message.contains("XDG_CACHE_HOME"));
197        assert!(message.contains("HOME"));
198    }
199
200    #[test]
201    fn home_is_not_needed_when_another_variable_gives_the_location() {
202        assert_eq!(
203            cache_dir(var("/kizz"), None, None),
204            Ok(PathBuf::from("/kizz"))
205        );
206        assert_eq!(
207            cache_dir(None, var("/xdg"), None),
208            Ok(PathBuf::from("/xdg/kizz"))
209        );
210    }
211}