Skip to main content

dodot_lib/paths/
mod.rs

1//! Path resolution for dodot.
2//!
3//! `Pather` is dodot's single source of truth for *every* filesystem
4//! coordinate the rest of the codebase touches: `$HOME`, the dotfiles
5//! repo root, the XDG data/config/cache directories, and per-pack and
6//! per-handler subdirectories. Two reasons it's a trait, not free
7//! functions:
8//!
9//! 1. **Testability.** Constructing a `Pather` whose roots all live
10//!    under a `tempfile::TempDir` lets every command run end-to-end
11//!    against a real filesystem without ever touching the user's
12//!    actual `$HOME`. The `testing::TempEnvironment` builder does
13//!    exactly this.
14//!
15//! 2. **Centralisation of OS-shaped policy.** The XDG fallback chain,
16//!    the `DOTFILES_ROOT` env-var lookup, and (planned, per
17//!    `docs/proposals/macos-paths.lex`) the macOS `app_support_dir`
18//!    selection all live in one place. The resolver, the symlink
19//!    handler, and `adopt`'s source-path inference all consult the
20//!    same accessors — drift between them is impossible by construction.
21//!
22//! ## Adopt source-root invariants
23//!
24//! The inference function in `commands::adopt::infer` needs *stable
25//! root strings* it can prefix-match against canonicalised source
26//! paths. The accessors exposed here meet two requirements that make
27//! that work safely:
28//!
29//! - `home_dir()` and `xdg_config_home()` return paths that
30//!   `std::fs::canonicalize` resolves to themselves on a real
31//!   filesystem (they're real directories, not synthetic constants).
32//!   This is what makes the `/var` ↔ `/private/var` macOS equivalence
33//!   collapse cleanly when both a source and a root are canonicalised
34//!   before comparison.
35//!
36//! - On the default config (no `XDG_CONFIG_HOME` set), `xdg_config_home()`
37//!   is `home_dir().join(".config")` — i.e. *nested under* `$HOME`.
38//!   Inference must check the more-specific (XDG) root before HOME so
39//!   `~/.config/nvim/init.lua` matches XDG, not "nested under HOME".
40//!   That's enforced by the inference function, not by `Pather`, but
41//!   the nesting shape originates here.
42
43use std::path::{Path, PathBuf};
44
45use crate::Result;
46
47/// Provides all path calculations for dodot.
48///
49/// Every path that dodot uses — XDG directories, pack locations,
50/// handler data directories — is computed through this trait. This
51/// keeps path logic centralised and makes testing straightforward:
52/// construct a `Pather` whose directories all live under a temp dir.
53///
54/// Use `&dyn Pather` (trait objects) throughout the codebase.
55pub trait Pather: Send + Sync {
56    /// The user's home directory (e.g. `/home/alice`).
57    fn home_dir(&self) -> &Path;
58
59    /// Root of the dotfiles repository.
60    fn dotfiles_root(&self) -> &Path;
61
62    /// XDG data directory for dodot (e.g. `~/.local/share/dodot`).
63    fn data_dir(&self) -> &Path;
64
65    /// XDG config directory for dodot (e.g. `~/.config/dodot`).
66    fn config_dir(&self) -> &Path;
67
68    /// XDG cache directory for dodot (e.g. `~/.cache/dodot`).
69    fn cache_dir(&self) -> &Path;
70
71    /// XDG config home (e.g. `~/.config`). Used by symlink handler
72    /// for subdirectory target mapping.
73    fn xdg_config_home(&self) -> &Path;
74
75    /// Application-support root, the third filesystem coordinate the
76    /// symlink resolver understands.
77    ///
78    /// On macOS this resolves to `$HOME/Library/Application Support` by
79    /// default, the canonical home for GUI app config. On Linux and
80    /// other platforms it resolves to `xdg_config_home()` so the `_app/`
81    /// prefix and `app_aliases` route through `~/.config` —
82    /// indistinguishable from `_xdg/` on those platforms but the
83    /// mechanism stays platform-agnostic.
84    ///
85    /// The OS check lives only in [`XdgPatherBuilder::build`]; the
86    /// resolver operates on textual prefixes alone. See
87    /// `docs/proposals/macos-paths.lex` §2.1.
88    fn app_support_dir(&self) -> &Path;
89
90    /// Shell scripts directory (e.g. `~/.local/share/dodot/shell`).
91    fn shell_dir(&self) -> &Path;
92
93    /// Absolute path to a pack's source directory.
94    fn pack_path(&self, pack: &str) -> PathBuf {
95        self.dotfiles_root().join(pack)
96    }
97
98    /// Data directory for a specific pack (e.g. `.../data/packs/{pack}`).
99    fn pack_data_dir(&self, pack: &str) -> PathBuf {
100        self.data_dir().join("packs").join(pack)
101    }
102
103    /// Data directory for a specific handler within a pack
104    /// (e.g. `.../data/packs/{pack}/{handler}`).
105    fn handler_data_dir(&self, pack: &str, handler: &str) -> PathBuf {
106        self.pack_data_dir(pack).join(handler)
107    }
108
109    /// Log directory for dodot (e.g. `~/.cache/dodot/logs`).
110    fn log_dir(&self) -> PathBuf {
111        self.cache_dir().join("logs")
112    }
113
114    /// Path to the generated shell init script.
115    fn init_script_path(&self) -> PathBuf {
116        self.shell_dir().join("dodot-init.sh")
117    }
118
119    /// Path to the deployment map TSV, overwritten on every `up` / `down`.
120    /// See `docs/proposals/profiling.lex` §3.2.
121    fn deployment_map_path(&self) -> PathBuf {
122        self.data_dir().join("deployment-map.tsv")
123    }
124
125    /// Path to a single-line file recording the unix timestamp of the
126    /// most recent successful `dodot up`. Used by `dodot probe
127    /// shell-init` to flag profiles captured before that `up` as stale.
128    /// Absent until the first `up` runs.
129    fn last_up_path(&self) -> PathBuf {
130        self.data_dir().join("last-up-at")
131    }
132
133    /// Directory where shell-init profile reports are written, one TSV
134    /// per shell start. See `docs/proposals/profiling.lex` §3.1.
135    fn probes_shell_init_dir(&self) -> PathBuf {
136        self.data_dir().join("probes").join("shell-init")
137    }
138
139    /// On-disk cache for homebrew-cask probe data. One JSON file per
140    /// cask token; TTL-based invalidation. See
141    /// `docs/proposals/macos-paths.lex` §8.2.
142    ///
143    /// Lives under `cache_dir` (not `data_dir`) because the contents are
144    /// rederivable — losing them is fine, the next probe re-runs `brew
145    /// info`. Co-located with future probe caches under `probes/`.
146    fn probes_brew_cache_dir(&self) -> PathBuf {
147        self.cache_dir().join("probes").join("brew")
148    }
149}
150
151/// XDG-compliant path resolver.
152///
153/// Reads standard environment variables (`HOME`, `XDG_DATA_HOME`, etc.)
154/// and the dodot-specific `DOTFILES_ROOT`. All paths can also be set
155/// explicitly via the builder for testing.
156#[derive(Debug, Clone)]
157pub struct XdgPather {
158    home: PathBuf,
159    dotfiles_root: PathBuf,
160    data_dir: PathBuf,
161    config_dir: PathBuf,
162    cache_dir: PathBuf,
163    xdg_config_home: PathBuf,
164    app_support_dir: PathBuf,
165    shell_dir: PathBuf,
166}
167
168/// Builder for [`XdgPather`].
169///
170/// All fields are optional. Unset fields are resolved from environment
171/// variables or XDG defaults.
172#[derive(Debug, Default)]
173pub struct XdgPatherBuilder {
174    home: Option<PathBuf>,
175    dotfiles_root: Option<PathBuf>,
176    data_dir: Option<PathBuf>,
177    config_dir: Option<PathBuf>,
178    cache_dir: Option<PathBuf>,
179    xdg_config_home: Option<PathBuf>,
180    app_support_dir: Option<PathBuf>,
181}
182
183impl XdgPatherBuilder {
184    pub fn home(mut self, path: impl Into<PathBuf>) -> Self {
185        self.home = Some(path.into());
186        self
187    }
188
189    pub fn dotfiles_root(mut self, path: impl Into<PathBuf>) -> Self {
190        self.dotfiles_root = Some(path.into());
191        self
192    }
193
194    pub fn data_dir(mut self, path: impl Into<PathBuf>) -> Self {
195        self.data_dir = Some(path.into());
196        self
197    }
198
199    pub fn config_dir(mut self, path: impl Into<PathBuf>) -> Self {
200        self.config_dir = Some(path.into());
201        self
202    }
203
204    pub fn cache_dir(mut self, path: impl Into<PathBuf>) -> Self {
205        self.cache_dir = Some(path.into());
206        self
207    }
208
209    pub fn xdg_config_home(mut self, path: impl Into<PathBuf>) -> Self {
210        self.xdg_config_home = Some(path.into());
211        self
212    }
213
214    /// Override the application-support root.
215    ///
216    /// Tests pin this to a non-default location so prefix matches are
217    /// deterministic across platforms. End users may also flip this
218    /// (typically via the `app_uses_library` config key, which is
219    /// ultimately what wires through here) to opt into Linux-style
220    /// `~/.config` placement on macOS.
221    pub fn app_support_dir(mut self, path: impl Into<PathBuf>) -> Self {
222        self.app_support_dir = Some(path.into());
223        self
224    }
225
226    pub fn build(self) -> Result<XdgPather> {
227        let home = self.home.unwrap_or_else(resolve_home);
228
229        let dotfiles_root = self
230            .dotfiles_root
231            .unwrap_or_else(|| resolve_dotfiles_root(&home));
232
233        let xdg_config_home = self.xdg_config_home.unwrap_or_else(|| {
234            std::env::var("XDG_CONFIG_HOME")
235                .map(PathBuf::from)
236                .unwrap_or_else(|_| home.join(".config"))
237        });
238
239        let data_dir = self.data_dir.unwrap_or_else(|| {
240            let xdg_data = std::env::var("XDG_DATA_HOME")
241                .map(PathBuf::from)
242                .unwrap_or_else(|_| home.join(".local").join("share"));
243            xdg_data.join("dodot")
244        });
245
246        let config_dir = self
247            .config_dir
248            .unwrap_or_else(|| xdg_config_home.join("dodot"));
249
250        let cache_dir = self.cache_dir.unwrap_or_else(|| {
251            let xdg_cache = std::env::var("XDG_CACHE_HOME")
252                .map(PathBuf::from)
253                .unwrap_or_else(|_| home.join(".cache"));
254            xdg_cache.join("dodot")
255        });
256
257        let shell_dir = data_dir.join("shell");
258
259        // Application-support root: macOS routes to `~/Library/Application Support`,
260        // every other platform falls through to `xdg_config_home`. The OS
261        // branch lives here exclusively; the resolver only sees a path.
262        let app_support_dir = self.app_support_dir.unwrap_or_else(|| {
263            if cfg!(target_os = "macos") {
264                home.join("Library").join("Application Support")
265            } else {
266                xdg_config_home.clone()
267            }
268        });
269
270        Ok(XdgPather {
271            home,
272            dotfiles_root,
273            data_dir,
274            config_dir,
275            cache_dir,
276            xdg_config_home,
277            app_support_dir,
278            shell_dir,
279        })
280    }
281}
282
283impl XdgPather {
284    /// Creates a builder for configuring an `XdgPather`.
285    pub fn builder() -> XdgPatherBuilder {
286        XdgPatherBuilder::default()
287    }
288
289    /// Creates an `XdgPather` using environment variables and XDG defaults.
290    pub fn from_env() -> Result<Self> {
291        Self::builder().build()
292    }
293}
294
295impl Pather for XdgPather {
296    fn home_dir(&self) -> &Path {
297        &self.home
298    }
299
300    fn dotfiles_root(&self) -> &Path {
301        &self.dotfiles_root
302    }
303
304    fn data_dir(&self) -> &Path {
305        &self.data_dir
306    }
307
308    fn config_dir(&self) -> &Path {
309        &self.config_dir
310    }
311
312    fn cache_dir(&self) -> &Path {
313        &self.cache_dir
314    }
315
316    fn xdg_config_home(&self) -> &Path {
317        &self.xdg_config_home
318    }
319
320    fn app_support_dir(&self) -> &Path {
321        &self.app_support_dir
322    }
323
324    fn shell_dir(&self) -> &Path {
325        &self.shell_dir
326    }
327}
328
329/// Resolve `HOME` from environment, falling back to the `dirs` approach.
330fn resolve_home() -> PathBuf {
331    std::env::var("HOME")
332        .map(PathBuf::from)
333        .unwrap_or_else(|_| {
334            // Last resort fallback
335            PathBuf::from("/tmp/dodot-unknown-home")
336        })
337}
338
339/// Resolve the dotfiles root directory.
340///
341/// Priority:
342/// 1. `DOTFILES_ROOT` environment variable
343/// 2. Git repository root (`git rev-parse --show-toplevel`)
344/// 3. `$HOME/dotfiles` fallback
345fn resolve_dotfiles_root(home: &Path) -> PathBuf {
346    // 1. Explicit env var
347    if let Ok(root) = std::env::var("DOTFILES_ROOT") {
348        return expand_tilde(&root, home);
349    }
350
351    // 2. Git toplevel
352    if let Ok(output) = std::process::Command::new("git")
353        .args(["rev-parse", "--show-toplevel"])
354        .output()
355    {
356        if output.status.success() {
357            let toplevel = String::from_utf8_lossy(&output.stdout).trim().to_string();
358            if !toplevel.is_empty() {
359                return PathBuf::from(toplevel);
360            }
361        }
362    }
363
364    // 3. Fallback
365    home.join("dotfiles")
366}
367
368/// Expand a leading `~` to the home directory.
369fn expand_tilde(path: &str, home: &Path) -> PathBuf {
370    if let Some(rest) = path.strip_prefix("~/") {
371        home.join(rest)
372    } else if path == "~" {
373        home.to_path_buf()
374    } else {
375        PathBuf::from(path)
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    #[test]
384    fn builder_explicit_paths() {
385        let pather = XdgPather::builder()
386            .home("/test/home")
387            .dotfiles_root("/test/home/dotfiles")
388            .data_dir("/test/data/dodot")
389            .config_dir("/test/config/dodot")
390            .cache_dir("/test/cache/dodot")
391            .xdg_config_home("/test/home/.config")
392            .build()
393            .unwrap();
394
395        assert_eq!(pather.home_dir(), Path::new("/test/home"));
396        assert_eq!(pather.dotfiles_root(), Path::new("/test/home/dotfiles"));
397        assert_eq!(pather.data_dir(), Path::new("/test/data/dodot"));
398        assert_eq!(pather.config_dir(), Path::new("/test/config/dodot"));
399        assert_eq!(pather.cache_dir(), Path::new("/test/cache/dodot"));
400        assert_eq!(pather.xdg_config_home(), Path::new("/test/home/.config"));
401    }
402
403    #[test]
404    fn shell_dir_derived_from_data_dir() {
405        let pather = XdgPather::builder()
406            .home("/h")
407            .dotfiles_root("/h/dots")
408            .data_dir("/h/data/dodot")
409            .build()
410            .unwrap();
411
412        assert_eq!(pather.shell_dir(), Path::new("/h/data/dodot/shell"));
413    }
414
415    #[test]
416    fn pack_path_joins_dotfiles_root() {
417        let pather = XdgPather::builder()
418            .home("/h")
419            .dotfiles_root("/h/dotfiles")
420            .build()
421            .unwrap();
422
423        assert_eq!(pather.pack_path("vim"), PathBuf::from("/h/dotfiles/vim"));
424    }
425
426    #[test]
427    fn pack_data_dir_structure() {
428        let pather = XdgPather::builder()
429            .home("/h")
430            .data_dir("/h/data/dodot")
431            .build()
432            .unwrap();
433
434        assert_eq!(
435            pather.pack_data_dir("vim"),
436            PathBuf::from("/h/data/dodot/packs/vim")
437        );
438    }
439
440    #[test]
441    fn handler_data_dir_structure() {
442        let pather = XdgPather::builder()
443            .home("/h")
444            .data_dir("/h/data/dodot")
445            .build()
446            .unwrap();
447
448        assert_eq!(
449            pather.handler_data_dir("vim", "symlink"),
450            PathBuf::from("/h/data/dodot/packs/vim/symlink")
451        );
452    }
453
454    #[test]
455    fn init_script_path() {
456        let pather = XdgPather::builder()
457            .home("/h")
458            .data_dir("/h/data/dodot")
459            .build()
460            .unwrap();
461
462        assert_eq!(
463            pather.init_script_path(),
464            PathBuf::from("/h/data/dodot/shell/dodot-init.sh")
465        );
466    }
467
468    #[test]
469    fn expand_tilde_cases() {
470        let home = Path::new("/home/alice");
471        assert_eq!(
472            expand_tilde("~/dotfiles", home),
473            PathBuf::from("/home/alice/dotfiles")
474        );
475        assert_eq!(expand_tilde("~", home), PathBuf::from("/home/alice"));
476        assert_eq!(
477            expand_tilde("/absolute/path", home),
478            PathBuf::from("/absolute/path")
479        );
480        assert_eq!(expand_tilde("relative", home), PathBuf::from("relative"));
481    }
482
483    /// Default-XDG nesting: with no explicit `xdg_config_home`, the
484    /// builder defaults to `$HOME/.config`. Adopt's inference relies on
485    /// XDG being checked *before* HOME (longest-prefix wins) precisely
486    /// because of this nesting; pin the layout so a future change that
487    /// flips the default to `$HOME/Library/...` (macOS) or somewhere
488    /// outside HOME forces a deliberate update to the inference rules.
489    #[test]
490    fn default_xdg_config_home_is_nested_under_home() {
491        let pather = XdgPather::builder()
492            .home("/u")
493            .dotfiles_root("/u/dotfiles")
494            .data_dir("/u/.local/share/dodot")
495            .config_dir("/u/.config/dodot")
496            .cache_dir("/u/.cache/dodot")
497            // No xdg_config_home set; falls back to env or `$HOME/.config`.
498            .build()
499            .unwrap();
500        // The default fallback (no `XDG_CONFIG_HOME` env) is `$HOME/.config`.
501        // The assertion has to tolerate a user-set `XDG_CONFIG_HOME` since
502        // tests inherit the ambient env — `cargo test` from a developer
503        // shell with the env set would otherwise fail spuriously. The
504        // disjunct below means: either XDG nests under HOME (the default
505        // case the invariant talks about), OR the env override is set
506        // (the user opted out of the default; adopt's inference handles
507        // that case via root canonicalization, separate code path).
508        let xdg = pather.xdg_config_home();
509        let home = pather.home_dir();
510        assert!(
511            xdg.starts_with(home) || std::env::var("XDG_CONFIG_HOME").is_ok(),
512            "default xdg_config_home `{}` is not nested under home `{}` \
513             — adopt's inference assumes XDG ⊆ HOME on the default config; \
514             update both if this changes",
515            xdg.display(),
516            home.display()
517        );
518    }
519
520    /// Explicit `xdg_config_home(...)` takes precedence over env / defaults.
521    /// Critical for the test environment, where adopt-inference tests pin
522    /// XDG to a non-default location so prefix matches are unambiguous.
523    #[test]
524    fn explicit_xdg_config_home_overrides_default() {
525        let pather = XdgPather::builder()
526            .home("/u")
527            .dotfiles_root("/u/dotfiles")
528            .xdg_config_home("/somewhere/else/.config")
529            .build()
530            .unwrap();
531        assert_eq!(
532            pather.xdg_config_home(),
533            Path::new("/somewhere/else/.config")
534        );
535    }
536
537    /// Each accessor returns a stable, distinct subdir layout. Adopt's
538    /// auto-create path lands the new pack at `dotfiles_root/<pack>`,
539    /// and the data layer keeps state at `data_dir/packs/<pack>/...`;
540    /// these must not alias.
541    #[test]
542    fn dotfiles_root_and_data_dir_are_distinct_namespaces() {
543        let pather = XdgPather::builder()
544            .home("/u")
545            .dotfiles_root("/u/dotfiles")
546            .data_dir("/u/.local/share/dodot")
547            .build()
548            .unwrap();
549        let pack_dir = pather.pack_path("nvim");
550        let pack_data = pather.pack_data_dir("nvim");
551        assert!(
552            !pack_dir.starts_with(&pack_data) && !pack_data.starts_with(&pack_dir),
553            "pack_path `{}` and pack_data_dir `{}` overlap",
554            pack_dir.display(),
555            pack_data.display(),
556        );
557    }
558
559    /// Explicit `app_support_dir(...)` overrides the platform default.
560    /// Tests rely on this to pin the third coordinate at a known
561    /// non-XDG, non-HOME location so the resolver's `_app/` rule has
562    /// somewhere unambiguous to land.
563    #[test]
564    fn explicit_app_support_dir_overrides_default() {
565        let pather = XdgPather::builder()
566            .home("/u")
567            .dotfiles_root("/u/dotfiles")
568            .xdg_config_home("/u/.config")
569            .app_support_dir("/u/Library/Application Support")
570            .build()
571            .unwrap();
572        assert_eq!(
573            pather.app_support_dir(),
574            Path::new("/u/Library/Application Support")
575        );
576    }
577
578    /// Default app_support_dir on Linux/non-macOS collapses to xdg_config_home.
579    /// On macOS it points under `$HOME/Library/Application Support`.
580    /// We don't `cfg!` the assertion here because the explicit-builder
581    /// test above pins the override path; this test exercises the
582    /// implicit default and the platform branch together.
583    #[test]
584    fn default_app_support_dir_is_platform_aware() {
585        let pather = XdgPather::builder()
586            .home("/u")
587            .dotfiles_root("/u/dotfiles")
588            .xdg_config_home("/u/.config")
589            .build()
590            .unwrap();
591        if cfg!(target_os = "macos") {
592            assert_eq!(
593                pather.app_support_dir(),
594                Path::new("/u/Library/Application Support"),
595                "macOS default should route under $HOME/Library/Application Support"
596            );
597        } else {
598            assert_eq!(
599                pather.app_support_dir(),
600                pather.xdg_config_home(),
601                "non-macOS default should collapse to xdg_config_home"
602            );
603        }
604    }
605
606    // Compile-time check: Pather must be object-safe
607    #[allow(dead_code)]
608    fn assert_object_safe(_: &dyn Pather) {}
609}