Skip to main content

openlogi_core/
paths.rs

1//! Per-OS application directories, following the XDG Base Directory spec on
2//! **every** platform — including macOS, so configuration lives at the
3//! familiar `~/.config/openlogi/` rather than macOS's
4//! `~/Library/Application Support/`.
5//!
6//! | kind   | env override        | default                       |
7//! |--------|---------------------|-------------------------------|
8//! | config | `$XDG_CONFIG_HOME`  | `~/.config/openlogi`          |
9//! | data   | `$XDG_DATA_HOME`    | `~/.local/share/openlogi`     |
10//! | state  | `$XDG_STATE_HOME`   | `~/.local/state/openlogi`     |
11//!
12//! On Windows `$HOME` falls back to `%USERPROFILE%`, so paths resolve to
13//! `%USERPROFILE%\.config\openlogi` etc.
14//!
15//! **Decision (#347):** the Windows location is final, not best-effort.
16//! XDG-on-every-platform is this module's deliberate design — macOS also
17//! skips its native `~/Library/Application Support` — and Windows follows
18//! the same rule rather than `%APPDATA%`. Recorded before the agent first
19//! shipped in Windows artifacts, because moving it afterwards would strand
20//! every existing user's `config.toml` and the agent's first-run state.
21
22//! Local packaged macOS builds stamped with dev-channel identifiers use the
23//! same layout under an `openlogi-dev` app directory.
24
25use std::path::PathBuf;
26use std::sync::OnceLock;
27
28use etcetera::{BaseStrategy, base_strategy::Xdg};
29use thiserror::Error;
30
31/// Production subdirectory created under each XDG base directory.
32///
33/// Public because the dev tooling has to name the same directories from
34/// outside a running app — `xtask macos dev-bundle` remembers the developer's
35/// codesigning certificate under [`DEV_APP_DIR`], where `cargo clean` cannot
36/// reach it.
37pub const APP_DIR: &str = "openlogi";
38/// Local macOS dev builds use a separate profile so development agents
39/// cannot take over the installed app's socket, lock, config, or asset cache.
40pub const DEV_APP_DIR: &str = "openlogi-dev";
41
42/// Failure resolving the per-user base directories.
43#[derive(Debug, Error)]
44pub enum PathsError {
45    /// No home directory could be determined for the current user, so none
46    /// of the XDG bases resolve.
47    #[error("could not resolve a home directory for the current user")]
48    HomeNotFound,
49}
50
51fn xdg() -> Result<Xdg, PathsError> {
52    Xdg::new().map_err(|_| PathsError::HomeNotFound)
53}
54
55fn app_dir() -> &'static str {
56    if is_dev_profile() {
57        DEV_APP_DIR
58    } else {
59        APP_DIR
60    }
61}
62
63/// Whether this process runs under the dev profile: forced by
64/// `OPENLOGI_PROFILE=dev`/`prod`, or (macOS) detected from the bundle the
65/// executable lives in carrying a dev identifier. Decides the
66/// [`APP_DIR`]/[`DEV_APP_DIR`] split for every directory below, and which
67/// launchd service label the GUI manages. Memoized — the answer cannot change
68/// within a process lifetime.
69#[must_use]
70pub fn is_dev_profile() -> bool {
71    static IS_DEV_PROFILE: OnceLock<bool> = OnceLock::new();
72    *IS_DEV_PROFILE.get_or_init(detect_dev_profile)
73}
74
75fn detect_dev_profile() -> bool {
76    match std::env::var("OPENLOGI_PROFILE") {
77        Ok(value) if value == "dev" => return true,
78        Ok(value) if matches!(value.as_str(), "prod" | "production") => return false,
79        _ => {}
80    }
81
82    #[cfg(target_os = "macos")]
83    {
84        if let Some(identifier) = current_bundle_identifier() {
85            return crate::brand::is_dev_id(&identifier);
86        }
87    }
88
89    false
90}
91
92#[cfg(target_os = "macos")]
93fn current_bundle_identifier() -> Option<String> {
94    let exe = std::env::current_exe().ok()?;
95    for ancestor in exe.ancestors() {
96        if !ancestor
97            .extension()
98            .is_some_and(|ext| ext.eq_ignore_ascii_case("app"))
99        {
100            continue;
101        }
102
103        let info = ancestor.join("Contents/Info.plist");
104        let Ok(plist) = plist::Value::from_file(info) else {
105            continue;
106        };
107        let Some(identifier) = plist
108            .as_dictionary()
109            .and_then(|dictionary| dictionary.get("CFBundleIdentifier"))
110            .and_then(plist::Value::as_string)
111        else {
112            continue;
113        };
114        return Some(identifier.to_owned());
115    }
116
117    None
118}
119
120/// The current user's home directory.
121///
122/// The plain home, not an XDG base — for callers placing files under
123/// OS-native locations (e.g. macOS `~/Library/LaunchAgents`).
124pub fn home_dir() -> Result<PathBuf, PathsError> {
125    Ok(xdg()?.home_dir().to_path_buf())
126}
127
128/// The raw XDG config home directory (without the `openlogi` subdirectory).
129///
130/// Honours an absolute `$XDG_CONFIG_HOME`; falls back to `~/.config`.
131/// Useful when placing files that belong to other apps under the same base
132/// (e.g. systemd user units at `$XDG_CONFIG_HOME/systemd/user/`).
133pub fn xdg_config_home() -> Result<PathBuf, PathsError> {
134    Ok(xdg()?.config_dir())
135}
136
137/// Directory holding the user's `config.toml`.
138///
139/// `$XDG_CONFIG_HOME/openlogi`, default `~/.config/openlogi`.
140/// Local macOS dev builds use `openlogi-dev` instead.
141pub fn config_dir() -> Result<PathBuf, PathsError> {
142    Ok(xdg_config_home()?.join(app_dir()))
143}
144
145/// Full path to the user config file.
146pub fn config_path() -> Result<PathBuf, PathsError> {
147    Ok(config_dir()?.join("config.toml"))
148}
149
150/// Directory for downloaded application data; the device-render asset cache
151/// lives under `data_dir()/assets`.
152///
153/// `$XDG_DATA_HOME/openlogi`, default `~/.local/share/openlogi`.
154/// Local macOS dev builds use `openlogi-dev` instead.
155pub fn data_dir() -> Result<PathBuf, PathsError> {
156    Ok(xdg()?.data_dir().join(app_dir()))
157}
158
159/// Directory for logs and other rebuildable process state — the agent's
160/// rotated log files live here.
161///
162/// `$XDG_STATE_HOME/openlogi`, default `~/.local/state/openlogi`.
163/// Local macOS dev builds use `openlogi-dev` instead.
164pub fn state_dir() -> Result<PathBuf, PathsError> {
165    let xdg = xdg()?;
166    Ok(xdg
167        .state_dir()
168        .map_or_else(|| xdg.data_dir().join(app_dir()), |dir| dir.join(app_dir())))
169}
170
171/// Directory for runtime sockets — the background agent's IPC endpoint.
172pub fn runtime_dir() -> Result<PathBuf, PathsError> {
173    let xdg = xdg()?;
174    Ok(xdg.runtime_dir().map_or_else(
175        || xdg.config_dir().join(app_dir()),
176        |dir| dir.join(app_dir()),
177    ))
178}
179
180/// Path to the background agent's Unix-domain IPC socket: the GUI connects here
181/// to reach the agent that owns device I/O.
182pub fn agent_socket_path() -> Result<PathBuf, PathsError> {
183    Ok(runtime_dir()?.join("agent.sock"))
184}
185
186#[cfg(test)]
187#[cfg(unix)]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn config_dir_keeps_openlogi_under_xdg_config_home() {
193        assert!(config_dir().expect("config dir").ends_with("openlogi"));
194    }
195
196    #[test]
197    fn data_dir_keeps_openlogi_under_xdg_data_home() {
198        assert!(data_dir().expect("data dir").ends_with("openlogi"));
199    }
200
201    #[test]
202    fn runtime_dir_keeps_openlogi_suffix() {
203        assert!(runtime_dir().expect("runtime dir").ends_with("openlogi"));
204    }
205}