Skip to main content

kh_runtime/bottle/
registry.rs

1//! Single active bottle pointer.
2//!
3//! Exactly one bottle may be registered at a time. The bottle directory name is
4//! not fixed — only the absolute path stored in the registry matters. Override
5//! locations with `KAKEHASHI_CONFIG_DIR` / `KAKEHASHI_DATA_DIR` for tests.
6
7use std::env;
8use std::fs;
9use std::io;
10use std::path::{Path, PathBuf};
11
12/// File under the config directory that stores the absolute bottle path.
13pub(super) const ACTIVE_FILE: &str = "active_bottle";
14
15/// Default bottle directory name under the data directory (when path omitted).
16///
17/// Users may rename the directory after creation; the registry tracks the
18/// absolute path, not this name.
19const DEFAULT_BOTTLE_DIRNAME: &str = "bottle";
20
21/// Resolves the config directory (registry lives here).
22///
23/// Order: `KAKEHASHI_CONFIG_DIR` → `$XDG_CONFIG_HOME/kakehashi` →
24/// `$HOME/.config/kakehashi`.
25pub fn config_dir() -> io::Result<PathBuf> {
26    if let Some(p) = env::var_os("KAKEHASHI_CONFIG_DIR") {
27        return Ok(PathBuf::from(p));
28    }
29    if let Some(xdg) = env::var_os("XDG_CONFIG_HOME") {
30        return Ok(PathBuf::from(xdg).join("kakehashi"));
31    }
32    let home = env::var_os("HOME").ok_or_else(|| {
33        io::Error::new(
34            io::ErrorKind::NotFound,
35            "HOME is unset and KAKEHASHI_CONFIG_DIR is not set",
36        )
37    })?;
38    Ok(PathBuf::from(home).join(".config").join("kakehashi"))
39}
40
41/// Resolves the default data directory for a new bottle (parent of `bottle/`).
42///
43/// Order: `KAKEHASHI_DATA_DIR` → `$XDG_DATA_HOME/kakehashi` →
44/// `$HOME/.local/share/kakehashi`.
45pub fn data_dir() -> io::Result<PathBuf> {
46    if let Some(p) = env::var_os("KAKEHASHI_DATA_DIR") {
47        return Ok(PathBuf::from(p));
48    }
49    if let Some(xdg) = env::var_os("XDG_DATA_HOME") {
50        return Ok(PathBuf::from(xdg).join("kakehashi"));
51    }
52    let home = env::var_os("HOME").ok_or_else(|| {
53        io::Error::new(
54            io::ErrorKind::NotFound,
55            "HOME is unset and KAKEHASHI_DATA_DIR is not set",
56        )
57    })?;
58    Ok(PathBuf::from(home)
59        .join(".local")
60        .join("share")
61        .join("kakehashi"))
62}
63
64/// Default absolute path used when `kh bottle create` is given no path.
65pub fn default_bottle_path() -> io::Result<PathBuf> {
66    Ok(data_dir()?.join(DEFAULT_BOTTLE_DIRNAME))
67}
68
69/// Path of the registry file that points at the active bottle.
70pub fn active_file_path() -> io::Result<PathBuf> {
71    Ok(config_dir()?.join(ACTIVE_FILE))
72}
73
74/// Reads the registered active bottle path, if any.
75///
76/// Returns `Ok(None)` when no registry file exists. Does not verify the bottle
77/// still exists or still has a valid marker.
78pub fn read_active() -> io::Result<Option<PathBuf>> {
79    let file = active_file_path()?;
80    match fs::read_to_string(&file) {
81        Ok(s) => {
82            let trimmed = s.trim();
83            if trimmed.is_empty() {
84                Ok(None)
85            } else {
86                Ok(Some(PathBuf::from(trimmed)))
87            }
88        }
89        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
90        Err(e) => Err(e),
91    }
92}
93
94/// Writes `path` as the single active bottle (creates config dir as needed).
95///
96/// `path` is canonicalized when it exists so renames of parent dirs that keep
97/// the same resolved location stay stable; otherwise the absolute form is stored.
98pub fn write_active(path: &Path) -> io::Result<()> {
99    let cfg = config_dir()?;
100    fs::create_dir_all(&cfg)?;
101    let abs = absolute_path(path)?;
102    let file = cfg.join(ACTIVE_FILE);
103    // Atomic-ish replace: write temp then rename.
104    let tmp = cfg.join(format!(".{ACTIVE_FILE}.tmp"));
105    fs::write(&tmp, format!("{}\n", abs.display()))?;
106    fs::rename(&tmp, &file)?;
107    Ok(())
108}
109
110/// Clears the active bottle registry entry (no-op if already empty).
111pub fn clear_active() -> io::Result<()> {
112    let file = active_file_path()?;
113    match fs::remove_file(&file) {
114        Ok(()) => Ok(()),
115        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
116        Err(e) => Err(e),
117    }
118}
119
120/// Makes `path` absolute without requiring it to exist.
121fn absolute_path(path: &Path) -> io::Result<PathBuf> {
122    if path.is_absolute() {
123        return Ok(path.to_path_buf());
124    }
125    let cwd = env::current_dir()?;
126    Ok(cwd.join(path))
127}
128
129/// Serializes tests that mutate `KAKEHASHI_*` process environment variables.
130#[cfg(test)]
131pub(super) fn test_env_lock() -> std::sync::MutexGuard<'static, ()> {
132    use std::sync::{Mutex, OnceLock};
133    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
134    LOCK.get_or_init(|| Mutex::new(()))
135        .lock()
136        .unwrap_or_else(std::sync::PoisonError::into_inner)
137}
138
139#[cfg(test)]
140#[allow(clippy::expect_used, unsafe_code)]
141mod tests {
142    use super::*;
143    use std::sync::atomic::{AtomicU64, Ordering};
144
145    fn unique(prefix: &str) -> PathBuf {
146        static N: AtomicU64 = AtomicU64::new(0);
147        let n = N.fetch_add(1, Ordering::Relaxed);
148        std::env::temp_dir().join(format!("kh-reg-{}-{}-{n}", prefix, std::process::id()))
149    }
150
151    #[test]
152    fn write_read_clear_active() {
153        let _g = test_env_lock();
154        let cfg = unique("cfg");
155        let data = unique("data");
156        drop(fs::remove_dir_all(&cfg));
157        drop(fs::remove_dir_all(&data));
158        // SAFETY: serialized by env_lock; only these tests touch the vars.
159        unsafe {
160            env::set_var("KAKEHASHI_CONFIG_DIR", &cfg);
161            env::set_var("KAKEHASHI_DATA_DIR", &data);
162        }
163
164        assert!(read_active().expect("read empty").is_none());
165        let bottle = data.join("my-custom-name");
166        write_active(&bottle).expect("write");
167        let got = read_active().expect("read").expect("some");
168        assert_eq!(got, bottle);
169        clear_active().expect("clear");
170        assert!(read_active().expect("read after clear").is_none());
171
172        // SAFETY: paired with set_var above under the same lock.
173        unsafe {
174            env::remove_var("KAKEHASHI_CONFIG_DIR");
175            env::remove_var("KAKEHASHI_DATA_DIR");
176        }
177        drop(fs::remove_dir_all(&cfg));
178        drop(fs::remove_dir_all(&data));
179    }
180
181    #[test]
182    fn default_path_uses_data_dir() {
183        let _g = test_env_lock();
184        let data = unique("defdata");
185        // SAFETY: serialized by env_lock.
186        unsafe {
187            env::set_var("KAKEHASHI_DATA_DIR", &data);
188        }
189        let p = default_bottle_path().expect("default");
190        assert_eq!(p, data.join(DEFAULT_BOTTLE_DIRNAME));
191        // SAFETY: paired cleanup under env_lock.
192        unsafe {
193            env::remove_var("KAKEHASHI_DATA_DIR");
194        }
195    }
196}