Skip to main content

defect_cli/
paths.rs

1//! Path resolution helpers — session storage root, etc.
2
3use std::path::{Path, PathBuf};
4
5use directories::ProjectDirs;
6
7/// Default session persistence root directory, resolved via the platform's standard
8/// per-app state/data location (the `directories` crate):
9/// - Linux: `$XDG_STATE_HOME/defect/sessions` (or `~/.local/state/defect/sessions`)
10/// - macOS: `~/Library/Application Support/defect/sessions`
11/// - Windows: `%LOCALAPPDATA%\defect\sessions`
12///
13/// On Linux `state_dir()` follows XDG; on macOS/Windows there is no separate state
14/// directory, so we fall back to the per-app data directory.
15///
16/// # Errors
17///
18/// Returns an error when no home directory can be determined at all (e.g. a stripped
19/// environment with no `HOME` on Unix or no profile dir on Windows) — in that case the
20/// OS itself cannot tell us where per-user data belongs.
21pub fn default_sessions_root() -> anyhow::Result<PathBuf> {
22    let dirs = ProjectDirs::from("", "", "defect").ok_or_else(|| {
23        anyhow::anyhow!(
24            "cannot resolve session storage root: no home directory found for the current user"
25        )
26    })?;
27    // state_dir() is Some only on Linux (XDG_STATE_HOME); elsewhere use data_dir().
28    let base = dirs.state_dir().unwrap_or_else(|| dirs.data_dir());
29    Ok(base.join("sessions"))
30}
31
32/// Session persistence root directory for `--local` sandbox mode:
33/// `<repo-root>/.defect/sessions`.
34///
35/// The project root is detected via `.git` (same source as the project layer in the
36/// config system); if no `.git` is found, falls back to `cwd/.defect/sessions` so that
37/// sandbox directories without a repository can still be used.
38#[must_use]
39pub fn local_sessions_root(cwd: &Path) -> PathBuf {
40    let root = defect_config::find_repo_root(cwd).unwrap_or_else(|| cwd.to_path_buf());
41    root.join(".defect/sessions")
42}