Skip to main content

cortexkit_paths/
dirs.rs

1//! Absolute user directories shared by CortexKit tools.
2//!
3//! Unix (including macOS) uses the XDG layout, not `~/Library`: absolute,
4//! non-empty XDG values win, then the user's home directory supplies the default.
5//! Windows also honors XDG overrides, but otherwise uses roaming `APPDATA` for
6//! config and local `LOCALAPPDATA` for data, state, and cache. Large databases
7//! should not roam with a domain profile.
8//!
9//! # Existing Windows installations
10//!
11//! [`cortexkit_data_dir`] preserves an existing `APPDATA/cortexkit` directory
12//! when the local `cortexkit` directory does not exist. An XDG data override
13//! disables this legacy lookup. No files are moved, merged, or created. The run
14//! directory follows the selected data directory. Without a legacy installation,
15//! Windows uses local data, unlike older daemons that always used roaming data.
16//!
17//! # Joining paths
18//!
19//! Paths are assembled with [`Path::join`] or [`PathBuf::push`], never by adding
20//! slash-delimited strings. Hard-coded `/` produces mixed separators on Windows.
21//! A path below a regular file fails with "not a directory" on Unix but can fail
22//! with "not found" on Windows; treating `NotFound` as "absent" can therefore
23//! silently skip that path. Resolution does not assert that a directory exists
24//! or is writable; callers must still handle filesystem errors when opening it.
25
26use std::{
27    env,
28    error::Error,
29    ffi::OsString,
30    fmt, io,
31    path::{Path, PathBuf},
32};
33
34/// Environment and filesystem inputs used by a directory resolver.
35///
36/// Override the filesystem methods as well as `var_os` for fully isolated tests.
37/// No resolver mutates the process environment.
38pub trait EnvSource {
39    /// Read a variable without losing non-Unicode path characters.
40    fn var_os(&self, key: &str) -> Option<OsString>;
41
42    /// Whether `path` exists. The resolver uses it to tell an existing
43    /// installation's data directory from one that has never been created.
44    fn path_exists(&self, path: &Path) -> bool {
45        path.exists()
46    }
47
48    /// The system temporary directory. It holds the last fallback location of
49    /// the daemon's connection file (see [`Dirs::connection_file_candidates`]).
50    fn temp_dir(&self) -> PathBuf {
51        env::temp_dir()
52    }
53
54    /// The process's current directory, which a relative path given explicitly
55    /// by the user (for example a `--subc ./conn.json` argument) is joined to.
56    fn current_dir(&self) -> io::Result<PathBuf> {
57        env::current_dir()
58    }
59}
60
61/// Inputs from the current process and filesystem.
62#[derive(Clone, Copy, Debug, Default)]
63pub struct SystemEnv;
64
65impl EnvSource for SystemEnv {
66    fn var_os(&self, key: &str) -> Option<OsString> {
67        env::var_os(key)
68    }
69}
70
71/// A path could not be resolved without an unsafe relative fallback.
72#[derive(Debug)]
73#[non_exhaustive]
74pub enum PathsError {
75    /// None of the listed variables supplied a usable absolute directory.
76    Unresolved {
77        /// The directory being resolved.
78        directory: &'static str,
79        /// Variables considered, in priority order.
80        variables: &'static [&'static str],
81    },
82    /// An exclusive connection-file override or base directory was relative.
83    RelativePath {
84        /// The input that supplied the path.
85        source: String,
86        /// The rejected path.
87        path: PathBuf,
88    },
89    /// The current directory could not be read for an explicit relative path.
90    CurrentDir(io::Error),
91    /// A per-user token was empty or contained a path separator.
92    InvalidUserToken,
93}
94
95impl fmt::Display for PathsError {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        match self {
98            Self::Unresolved {
99                directory,
100                variables,
101            } => write!(
102                f,
103                "could not resolve an absolute {directory}; tried {}",
104                variables.join(", ")
105            ),
106            Self::RelativePath { source, path } => {
107                write!(f, "{source} must be absolute, got {}", path.display())
108            }
109            Self::CurrentDir(error) => write!(f, "could not resolve current directory: {error}"),
110            Self::InvalidUserToken => f.write_str(
111                "connection-file user token must be non-empty and contain no path separators",
112            ),
113        }
114    }
115}
116
117impl Error for PathsError {
118    fn source(&self) -> Option<&(dyn Error + 'static)> {
119        match self {
120            Self::CurrentDir(error) => Some(error),
121            _ => None,
122        }
123    }
124}
125
126#[derive(Clone, Copy)]
127enum Platform {
128    Unix,
129    Windows,
130}
131
132/// A resolver borrowing injectable inputs. Construct it with [`with_env`].
133pub struct Dirs<'a, E: EnvSource + ?Sized> {
134    env: &'a E,
135    platform: Platform,
136}
137
138/// Resolve directories using the supplied inputs on the current platform.
139pub fn with_env<E: EnvSource + ?Sized>(env: &E) -> Dirs<'_, E> {
140    Dirs {
141        env,
142        platform: if cfg!(windows) {
143            Platform::Windows
144        } else {
145            Platform::Unix
146        },
147    }
148}
149
150impl<E: EnvSource + ?Sized> Dirs<'_, E> {
151    fn non_empty(&self, key: &str) -> Option<OsString> {
152        self.env.var_os(key).filter(|value| !value.is_empty())
153    }
154
155    fn absolute_var(&self, key: &str) -> Option<PathBuf> {
156        self.non_empty(key)
157            .map(PathBuf::from)
158            .filter(|path| path.is_absolute())
159    }
160
161    /// Unix `HOME`, or Windows `USERPROFILE`, then `HOMEDRIVE` + `HOMEPATH`,
162    /// then `HOME`. `USERPROFILE` wins over Git Bash's `HOME` when both are set.
163    /// Empty and relative values cannot supply a home directory.
164    pub fn home(&self) -> Result<PathBuf, PathsError> {
165        match self.platform {
166            Platform::Unix => self.absolute_var("HOME").ok_or(PathsError::Unresolved {
167                directory: "home directory",
168                variables: &["HOME"],
169            }),
170            Platform::Windows => {
171                if let Some(path) = self.absolute_var("USERPROFILE") {
172                    return Ok(path);
173                }
174                if let (Some(drive), Some(path)) =
175                    (self.non_empty("HOMEDRIVE"), self.non_empty("HOMEPATH"))
176                {
177                    let mut home = PathBuf::from(drive);
178                    home.push(path);
179                    if home.is_absolute() {
180                        return Ok(home);
181                    }
182                }
183                self.absolute_var("HOME").ok_or(PathsError::Unresolved {
184                    directory: "home directory",
185                    variables: &["USERPROFILE", "HOMEDRIVE", "HOMEPATH", "HOME"],
186                })
187            }
188        }
189    }
190
191    fn base(
192        &self,
193        xdg: &'static str,
194        windows: &'static str,
195        unix_tail: &[&str],
196        windows_tail: &str,
197    ) -> Result<PathBuf, PathsError> {
198        if let Some(path) = self.absolute_var(xdg) {
199            return Ok(path);
200        }
201        match self.platform {
202            Platform::Unix => {
203                let mut path = self.home().map_err(|_| PathsError::Unresolved {
204                    directory: xdg,
205                    variables: match xdg {
206                        "XDG_DATA_HOME" => &["XDG_DATA_HOME", "HOME"],
207                        "XDG_CONFIG_HOME" => &["XDG_CONFIG_HOME", "HOME"],
208                        "XDG_STATE_HOME" => &["XDG_STATE_HOME", "HOME"],
209                        _ => &["XDG_CACHE_HOME", "HOME"],
210                    },
211                })?;
212                for component in unix_tail {
213                    path.push(component);
214                }
215                Ok(path)
216            }
217            Platform::Windows => {
218                self.windows_base(windows, windows_tail)
219                    .ok_or(PathsError::Unresolved {
220                        directory: xdg,
221                        variables: match xdg {
222                            "XDG_DATA_HOME" => &["XDG_DATA_HOME", "LOCALAPPDATA", "USERPROFILE"],
223                            "XDG_CONFIG_HOME" => &["XDG_CONFIG_HOME", "APPDATA", "USERPROFILE"],
224                            "XDG_STATE_HOME" => &["XDG_STATE_HOME", "LOCALAPPDATA", "USERPROFILE"],
225                            _ => &["XDG_CACHE_HOME", "LOCALAPPDATA", "USERPROFILE"],
226                        },
227                    })
228            }
229        }
230    }
231
232    fn windows_base(&self, variable: &str, tail: &str) -> Option<PathBuf> {
233        self.absolute_var(variable).or_else(|| {
234            self.absolute_var("USERPROFILE")
235                .map(|path| path.join("AppData").join(tail))
236        })
237    }
238
239    /// XDG data home, Unix `HOME/.local/share`, or Windows local application data.
240    /// Unlike [`Self::xdg_data_home`], this uses `LOCALAPPDATA` on Windows when
241    /// there is no absolute XDG override.
242    pub fn data_home(&self) -> Result<PathBuf, PathsError> {
243        self.base(
244            "XDG_DATA_HOME",
245            "LOCALAPPDATA",
246            &[".local", "share"],
247            "Local",
248        )
249    }
250
251    /// XDG data layout on every OS: an absolute `XDG_DATA_HOME` override, then
252    /// [`Self::home`] plus `.local/share`. Empty or relative overrides are ignored.
253    /// Unlike [`Self::data_home`], this never consults `APPDATA` or `LOCALAPPDATA`;
254    /// use it for applications that follow XDG layout even on Windows.
255    pub fn xdg_data_home(&self) -> Result<PathBuf, PathsError> {
256        if let Some(path) = self.absolute_var("XDG_DATA_HOME") {
257            return Ok(path);
258        }
259        let home = self.home().map_err(|_| PathsError::Unresolved {
260            directory: "XDG data home",
261            variables: match self.platform {
262                Platform::Unix => &["XDG_DATA_HOME", "HOME"],
263                Platform::Windows => &[
264                    "XDG_DATA_HOME",
265                    "USERPROFILE",
266                    "HOMEDRIVE",
267                    "HOMEPATH",
268                    "HOME",
269                ],
270            },
271        })?;
272        Ok(home.join(".local").join("share"))
273    }
274
275    /// XDG config home, Unix `HOME/.config`, or Windows roaming application data.
276    pub fn config_home(&self) -> Result<PathBuf, PathsError> {
277        self.base("XDG_CONFIG_HOME", "APPDATA", &[".config"], "Roaming")
278    }
279
280    /// XDG state home, Unix `HOME/.local/state`, or Windows local application data.
281    pub fn state_home(&self) -> Result<PathBuf, PathsError> {
282        self.base(
283            "XDG_STATE_HOME",
284            "LOCALAPPDATA",
285            &[".local", "state"],
286            "Local",
287        )
288    }
289
290    /// XDG cache home, Unix `HOME/.cache`, or Windows local application data.
291    pub fn cache_home(&self) -> Result<PathBuf, PathsError> {
292        self.base("XDG_CACHE_HOME", "LOCALAPPDATA", &[".cache"], "Local")
293    }
294
295    /// Data home plus `cortexkit`, preserving an existing roaming Windows install
296    /// only when no local install exists and no absolute XDG override is set.
297    pub fn cortexkit_data_dir(&self) -> Result<PathBuf, PathsError> {
298        let local = self.data_home().map(|home| home.join("cortexkit"));
299        if matches!(self.platform, Platform::Windows)
300            && self.absolute_var("XDG_DATA_HOME").is_none()
301        {
302            if let Some(roaming) = self.windows_base("APPDATA", "Roaming") {
303                let legacy = roaming.join("cortexkit");
304                if self.env.path_exists(&legacy)
305                    && !local.as_ref().is_ok_and(|path| self.env.path_exists(path))
306                {
307                    return Ok(legacy);
308                }
309            }
310        }
311        local
312    }
313
314    /// Config home plus `cortexkit`.
315    pub fn cortexkit_config_dir(&self) -> Result<PathBuf, PathsError> {
316        Ok(self.config_home()?.join("cortexkit"))
317    }
318
319    /// Selected data directory plus `run`. On Windows this follows the existing
320    /// roaming installation when no local installation exists; see
321    /// [`Self::cortexkit_data_dir`].
322    pub fn cortexkit_run_dir(&self) -> Result<PathBuf, PathsError> {
323        Ok(self.cortexkit_data_dir()?.join("run"))
324    }
325
326    /// State home plus `cortexkit`.
327    pub fn cortexkit_state_dir(&self) -> Result<PathBuf, PathsError> {
328        Ok(self.state_home()?.join("cortexkit"))
329    }
330
331    /// Cache home plus `cortexkit`.
332    pub fn cortexkit_cache_dir(&self) -> Result<PathBuf, PathsError> {
333        Ok(self.cache_home()?.join("cortexkit"))
334    }
335
336    /// Ordered transport discovery candidates, without creating or reading files.
337    ///
338    /// An explicit path is exclusive. A relative explicit path (such as a user's
339    /// `--subc ./conn.json`) is joined to the current directory, without requiring
340    /// the file to exist. Otherwise a non-empty `SUBC_CONNECTION_FILE` is exclusive
341    /// and must be absolute: a relative environment override is an error, not a
342    /// reason to silently try another daemon.
343    ///
344    /// With no override, candidates are `XDG_RUNTIME_DIR/subc-connection.json`,
345    /// `HOME/.local/share/cortexkit/run/subc-connection.json`, then the temporary
346    /// directory's `subc-{per_user_token}.connection.json`. Empty or relative
347    /// runtime and home values are skipped. The temporary directory must be
348    /// absolute. The caller supplies the transport's per-user token, which must
349    /// be non-empty and contain neither `/` nor `\`.
350    ///
351    /// This deliberately retains the transport's HOME-based discovery order even
352    /// on Windows; it does not substitute the new local data directory.
353    pub fn connection_file_candidates(
354        &self,
355        explicit: Option<&Path>,
356        per_user_token: &str,
357    ) -> Result<Vec<PathBuf>, PathsError> {
358        if let Some(path) = explicit {
359            if path.is_absolute() {
360                return Ok(vec![path.to_path_buf()]);
361            }
362            let cwd = self.env.current_dir().map_err(PathsError::CurrentDir)?;
363            return Ok(vec![require_absolute(
364                require_absolute(cwd, "current directory")?.join(path),
365                "explicit connection file",
366            )?]);
367        }
368        if let Some(path) = self.non_empty("SUBC_CONNECTION_FILE") {
369            return Ok(vec![require_absolute(
370                PathBuf::from(path),
371                "SUBC_CONNECTION_FILE",
372            )?]);
373        }
374        if per_user_token.is_empty() || per_user_token.contains(['/', '\\']) {
375            return Err(PathsError::InvalidUserToken);
376        }
377        let mut candidates = Vec::new();
378        if let Some(path) = self.absolute_var("XDG_RUNTIME_DIR") {
379            candidates.push(path.join("subc-connection.json"));
380        }
381        if let Some(path) = self.absolute_var("HOME") {
382            candidates.push(
383                path.join(".local")
384                    .join("share")
385                    .join("cortexkit")
386                    .join("run")
387                    .join("subc-connection.json"),
388            );
389        }
390        candidates.push(
391            require_absolute(self.env.temp_dir(), "temporary directory")?
392                .join(format!("subc-{per_user_token}.connection.json")),
393        );
394        Ok(candidates)
395    }
396}
397
398fn require_absolute(path: PathBuf, source: &str) -> Result<PathBuf, PathsError> {
399    if path.is_absolute() {
400        Ok(path)
401    } else {
402        Err(PathsError::RelativePath {
403            source: source.to_owned(),
404            path,
405        })
406    }
407}
408
409/// Read a path-valued variable, such as an application's own home override, from
410/// `env` (pass [`SystemEnv`] for the process environment, or a test double).
411/// Unset or empty values return `None`; absolute values are preserved verbatim.
412/// A relative value is an error naming `variable`, unlike XDG directory resolution,
413/// which ignores relative overrides and tries the home-directory fallback.
414pub fn env_absolute_path<E: EnvSource + ?Sized>(
415    env: &E,
416    variable: &str,
417) -> Result<Option<PathBuf>, PathsError> {
418    env.var_os(variable)
419        .filter(|value| !value.is_empty())
420        .map(|value| require_absolute(PathBuf::from(value), variable))
421        .transpose()
422}
423
424macro_rules! process_dirs {
425    ($($name:ident),+ $(,)?) => {$(
426        #[doc = concat!("Resolve using the process environment; see [`Dirs::", stringify!($name), "`].")]
427        pub fn $name() -> Result<PathBuf, PathsError> { with_env(&SystemEnv).$name() }
428    )+};
429}
430
431process_dirs!(
432    home,
433    data_home,
434    xdg_data_home,
435    config_home,
436    state_home,
437    cache_home,
438    cortexkit_data_dir,
439    cortexkit_config_dir,
440    cortexkit_run_dir,
441    cortexkit_state_dir,
442    cortexkit_cache_dir
443);
444
445/// Discover connection files using process inputs; see [`Dirs::connection_file_candidates`].
446pub fn connection_file_candidates(
447    explicit: Option<&Path>,
448    per_user_token: &str,
449) -> Result<Vec<PathBuf>, PathsError> {
450    with_env(&SystemEnv).connection_file_candidates(explicit, per_user_token)
451}
452
453#[cfg(test)]
454mod tests;