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 /// Persistent record of prompts the user has dismissed (e.g.
151 /// onboarding hints, install offers). Content-agnostic: callers
152 /// pass opaque keys, the registry just tracks dismissed/active.
153 /// Lives under `data_dir` (not `cache_dir`) because losing it
154 /// would re-prompt the user — preference state, not cache.
155 fn prompts_path(&self) -> PathBuf {
156 self.data_dir().join("prompts.json")
157 }
158}
159
160/// XDG-compliant path resolver.
161///
162/// Reads standard environment variables (`HOME`, `XDG_DATA_HOME`, etc.)
163/// and the dodot-specific `DOTFILES_ROOT`. All paths can also be set
164/// explicitly via the builder for testing.
165#[derive(Debug, Clone)]
166pub struct XdgPather {
167 home: PathBuf,
168 dotfiles_root: PathBuf,
169 data_dir: PathBuf,
170 config_dir: PathBuf,
171 cache_dir: PathBuf,
172 xdg_config_home: PathBuf,
173 app_support_dir: PathBuf,
174 shell_dir: PathBuf,
175}
176
177/// Builder for [`XdgPather`].
178///
179/// All fields are optional. Unset fields are resolved from environment
180/// variables or XDG defaults.
181#[derive(Debug, Default)]
182pub struct XdgPatherBuilder {
183 home: Option<PathBuf>,
184 dotfiles_root: Option<PathBuf>,
185 data_dir: Option<PathBuf>,
186 config_dir: Option<PathBuf>,
187 cache_dir: Option<PathBuf>,
188 xdg_config_home: Option<PathBuf>,
189 app_support_dir: Option<PathBuf>,
190}
191
192impl XdgPatherBuilder {
193 pub fn home(mut self, path: impl Into<PathBuf>) -> Self {
194 self.home = Some(path.into());
195 self
196 }
197
198 pub fn dotfiles_root(mut self, path: impl Into<PathBuf>) -> Self {
199 self.dotfiles_root = Some(path.into());
200 self
201 }
202
203 pub fn data_dir(mut self, path: impl Into<PathBuf>) -> Self {
204 self.data_dir = Some(path.into());
205 self
206 }
207
208 pub fn config_dir(mut self, path: impl Into<PathBuf>) -> Self {
209 self.config_dir = Some(path.into());
210 self
211 }
212
213 pub fn cache_dir(mut self, path: impl Into<PathBuf>) -> Self {
214 self.cache_dir = Some(path.into());
215 self
216 }
217
218 pub fn xdg_config_home(mut self, path: impl Into<PathBuf>) -> Self {
219 self.xdg_config_home = Some(path.into());
220 self
221 }
222
223 /// Override the application-support root.
224 ///
225 /// Tests pin this to a non-default location so prefix matches are
226 /// deterministic across platforms. End users may also flip this
227 /// (typically via the `app_uses_library` config key, which is
228 /// ultimately what wires through here) to opt into Linux-style
229 /// `~/.config` placement on macOS.
230 pub fn app_support_dir(mut self, path: impl Into<PathBuf>) -> Self {
231 self.app_support_dir = Some(path.into());
232 self
233 }
234
235 pub fn build(self) -> Result<XdgPather> {
236 let home = self.home.unwrap_or_else(resolve_home);
237
238 let dotfiles_root = self
239 .dotfiles_root
240 .unwrap_or_else(|| resolve_dotfiles_root(&home));
241
242 let xdg_config_home = self.xdg_config_home.unwrap_or_else(|| {
243 std::env::var("XDG_CONFIG_HOME")
244 .map(PathBuf::from)
245 .unwrap_or_else(|_| home.join(".config"))
246 });
247
248 let data_dir = self.data_dir.unwrap_or_else(|| {
249 let xdg_data = std::env::var("XDG_DATA_HOME")
250 .map(PathBuf::from)
251 .unwrap_or_else(|_| home.join(".local").join("share"));
252 xdg_data.join("dodot")
253 });
254
255 let config_dir = self
256 .config_dir
257 .unwrap_or_else(|| xdg_config_home.join("dodot"));
258
259 let cache_dir = self.cache_dir.unwrap_or_else(|| {
260 let xdg_cache = std::env::var("XDG_CACHE_HOME")
261 .map(PathBuf::from)
262 .unwrap_or_else(|_| home.join(".cache"));
263 xdg_cache.join("dodot")
264 });
265
266 let shell_dir = data_dir.join("shell");
267
268 // Application-support root: macOS routes to `~/Library/Application Support`,
269 // every other platform falls through to `xdg_config_home`. The OS
270 // branch lives here exclusively; the resolver only sees a path.
271 let app_support_dir = self.app_support_dir.unwrap_or_else(|| {
272 if cfg!(target_os = "macos") {
273 home.join("Library").join("Application Support")
274 } else {
275 xdg_config_home.clone()
276 }
277 });
278
279 Ok(XdgPather {
280 home,
281 dotfiles_root,
282 data_dir,
283 config_dir,
284 cache_dir,
285 xdg_config_home,
286 app_support_dir,
287 shell_dir,
288 })
289 }
290}
291
292impl XdgPather {
293 /// Creates a builder for configuring an `XdgPather`.
294 pub fn builder() -> XdgPatherBuilder {
295 XdgPatherBuilder::default()
296 }
297
298 /// Creates an `XdgPather` using environment variables and XDG defaults.
299 pub fn from_env() -> Result<Self> {
300 Self::builder().build()
301 }
302}
303
304impl Pather for XdgPather {
305 fn home_dir(&self) -> &Path {
306 &self.home
307 }
308
309 fn dotfiles_root(&self) -> &Path {
310 &self.dotfiles_root
311 }
312
313 fn data_dir(&self) -> &Path {
314 &self.data_dir
315 }
316
317 fn config_dir(&self) -> &Path {
318 &self.config_dir
319 }
320
321 fn cache_dir(&self) -> &Path {
322 &self.cache_dir
323 }
324
325 fn xdg_config_home(&self) -> &Path {
326 &self.xdg_config_home
327 }
328
329 fn app_support_dir(&self) -> &Path {
330 &self.app_support_dir
331 }
332
333 fn shell_dir(&self) -> &Path {
334 &self.shell_dir
335 }
336}
337
338/// Resolve `HOME` from environment, falling back to the `dirs` approach.
339fn resolve_home() -> PathBuf {
340 std::env::var("HOME")
341 .map(PathBuf::from)
342 .unwrap_or_else(|_| {
343 // Last resort fallback
344 PathBuf::from("/tmp/dodot-unknown-home")
345 })
346}
347
348/// Resolve the dotfiles root directory.
349///
350/// Priority:
351/// 1. `DOTFILES_ROOT` environment variable
352/// 2. Git repository root (`git rev-parse --show-toplevel`)
353/// 3. `$HOME/dotfiles` fallback
354fn resolve_dotfiles_root(home: &Path) -> PathBuf {
355 // 1. Explicit env var
356 if let Ok(root) = std::env::var("DOTFILES_ROOT") {
357 return expand_tilde(&root, home);
358 }
359
360 // 2. Git toplevel
361 if let Ok(output) = std::process::Command::new("git")
362 .args(["rev-parse", "--show-toplevel"])
363 .output()
364 {
365 if output.status.success() {
366 let toplevel = String::from_utf8_lossy(&output.stdout).trim().to_string();
367 if !toplevel.is_empty() {
368 return PathBuf::from(toplevel);
369 }
370 }
371 }
372
373 // 3. Fallback
374 home.join("dotfiles")
375}
376
377/// Expand a leading `~` to the home directory.
378fn expand_tilde(path: &str, home: &Path) -> PathBuf {
379 if let Some(rest) = path.strip_prefix("~/") {
380 home.join(rest)
381 } else if path == "~" {
382 home.to_path_buf()
383 } else {
384 PathBuf::from(path)
385 }
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391
392 #[test]
393 fn builder_explicit_paths() {
394 let pather = XdgPather::builder()
395 .home("/test/home")
396 .dotfiles_root("/test/home/dotfiles")
397 .data_dir("/test/data/dodot")
398 .config_dir("/test/config/dodot")
399 .cache_dir("/test/cache/dodot")
400 .xdg_config_home("/test/home/.config")
401 .build()
402 .unwrap();
403
404 assert_eq!(pather.home_dir(), Path::new("/test/home"));
405 assert_eq!(pather.dotfiles_root(), Path::new("/test/home/dotfiles"));
406 assert_eq!(pather.data_dir(), Path::new("/test/data/dodot"));
407 assert_eq!(pather.config_dir(), Path::new("/test/config/dodot"));
408 assert_eq!(pather.cache_dir(), Path::new("/test/cache/dodot"));
409 assert_eq!(pather.xdg_config_home(), Path::new("/test/home/.config"));
410 }
411
412 #[test]
413 fn shell_dir_derived_from_data_dir() {
414 let pather = XdgPather::builder()
415 .home("/h")
416 .dotfiles_root("/h/dots")
417 .data_dir("/h/data/dodot")
418 .build()
419 .unwrap();
420
421 assert_eq!(pather.shell_dir(), Path::new("/h/data/dodot/shell"));
422 }
423
424 #[test]
425 fn pack_path_joins_dotfiles_root() {
426 let pather = XdgPather::builder()
427 .home("/h")
428 .dotfiles_root("/h/dotfiles")
429 .build()
430 .unwrap();
431
432 assert_eq!(pather.pack_path("vim"), PathBuf::from("/h/dotfiles/vim"));
433 }
434
435 #[test]
436 fn pack_data_dir_structure() {
437 let pather = XdgPather::builder()
438 .home("/h")
439 .data_dir("/h/data/dodot")
440 .build()
441 .unwrap();
442
443 assert_eq!(
444 pather.pack_data_dir("vim"),
445 PathBuf::from("/h/data/dodot/packs/vim")
446 );
447 }
448
449 #[test]
450 fn handler_data_dir_structure() {
451 let pather = XdgPather::builder()
452 .home("/h")
453 .data_dir("/h/data/dodot")
454 .build()
455 .unwrap();
456
457 assert_eq!(
458 pather.handler_data_dir("vim", "symlink"),
459 PathBuf::from("/h/data/dodot/packs/vim/symlink")
460 );
461 }
462
463 #[test]
464 fn init_script_path() {
465 let pather = XdgPather::builder()
466 .home("/h")
467 .data_dir("/h/data/dodot")
468 .build()
469 .unwrap();
470
471 assert_eq!(
472 pather.init_script_path(),
473 PathBuf::from("/h/data/dodot/shell/dodot-init.sh")
474 );
475 }
476
477 #[test]
478 fn expand_tilde_cases() {
479 let home = Path::new("/home/alice");
480 assert_eq!(
481 expand_tilde("~/dotfiles", home),
482 PathBuf::from("/home/alice/dotfiles")
483 );
484 assert_eq!(expand_tilde("~", home), PathBuf::from("/home/alice"));
485 assert_eq!(
486 expand_tilde("/absolute/path", home),
487 PathBuf::from("/absolute/path")
488 );
489 assert_eq!(expand_tilde("relative", home), PathBuf::from("relative"));
490 }
491
492 /// Default-XDG nesting: with no explicit `xdg_config_home`, the
493 /// builder defaults to `$HOME/.config`. Adopt's inference relies on
494 /// XDG being checked *before* HOME (longest-prefix wins) precisely
495 /// because of this nesting; pin the layout so a future change that
496 /// flips the default to `$HOME/Library/...` (macOS) or somewhere
497 /// outside HOME forces a deliberate update to the inference rules.
498 #[test]
499 fn default_xdg_config_home_is_nested_under_home() {
500 let pather = XdgPather::builder()
501 .home("/u")
502 .dotfiles_root("/u/dotfiles")
503 .data_dir("/u/.local/share/dodot")
504 .config_dir("/u/.config/dodot")
505 .cache_dir("/u/.cache/dodot")
506 // No xdg_config_home set; falls back to env or `$HOME/.config`.
507 .build()
508 .unwrap();
509 // The default fallback (no `XDG_CONFIG_HOME` env) is `$HOME/.config`.
510 // The assertion has to tolerate a user-set `XDG_CONFIG_HOME` since
511 // tests inherit the ambient env — `cargo test` from a developer
512 // shell with the env set would otherwise fail spuriously. The
513 // disjunct below means: either XDG nests under HOME (the default
514 // case the invariant talks about), OR the env override is set
515 // (the user opted out of the default; adopt's inference handles
516 // that case via root canonicalization, separate code path).
517 let xdg = pather.xdg_config_home();
518 let home = pather.home_dir();
519 assert!(
520 xdg.starts_with(home) || std::env::var("XDG_CONFIG_HOME").is_ok(),
521 "default xdg_config_home `{}` is not nested under home `{}` \
522 — adopt's inference assumes XDG ⊆ HOME on the default config; \
523 update both if this changes",
524 xdg.display(),
525 home.display()
526 );
527 }
528
529 /// Explicit `xdg_config_home(...)` takes precedence over env / defaults.
530 /// Critical for the test environment, where adopt-inference tests pin
531 /// XDG to a non-default location so prefix matches are unambiguous.
532 #[test]
533 fn explicit_xdg_config_home_overrides_default() {
534 let pather = XdgPather::builder()
535 .home("/u")
536 .dotfiles_root("/u/dotfiles")
537 .xdg_config_home("/somewhere/else/.config")
538 .build()
539 .unwrap();
540 assert_eq!(
541 pather.xdg_config_home(),
542 Path::new("/somewhere/else/.config")
543 );
544 }
545
546 /// Each accessor returns a stable, distinct subdir layout. Adopt's
547 /// auto-create path lands the new pack at `dotfiles_root/<pack>`,
548 /// and the data layer keeps state at `data_dir/packs/<pack>/...`;
549 /// these must not alias.
550 #[test]
551 fn dotfiles_root_and_data_dir_are_distinct_namespaces() {
552 let pather = XdgPather::builder()
553 .home("/u")
554 .dotfiles_root("/u/dotfiles")
555 .data_dir("/u/.local/share/dodot")
556 .build()
557 .unwrap();
558 let pack_dir = pather.pack_path("nvim");
559 let pack_data = pather.pack_data_dir("nvim");
560 assert!(
561 !pack_dir.starts_with(&pack_data) && !pack_data.starts_with(&pack_dir),
562 "pack_path `{}` and pack_data_dir `{}` overlap",
563 pack_dir.display(),
564 pack_data.display(),
565 );
566 }
567
568 /// Explicit `app_support_dir(...)` overrides the platform default.
569 /// Tests rely on this to pin the third coordinate at a known
570 /// non-XDG, non-HOME location so the resolver's `_app/` rule has
571 /// somewhere unambiguous to land.
572 #[test]
573 fn explicit_app_support_dir_overrides_default() {
574 let pather = XdgPather::builder()
575 .home("/u")
576 .dotfiles_root("/u/dotfiles")
577 .xdg_config_home("/u/.config")
578 .app_support_dir("/u/Library/Application Support")
579 .build()
580 .unwrap();
581 assert_eq!(
582 pather.app_support_dir(),
583 Path::new("/u/Library/Application Support")
584 );
585 }
586
587 /// Default app_support_dir on Linux/non-macOS collapses to xdg_config_home.
588 /// On macOS it points under `$HOME/Library/Application Support`.
589 /// We don't `cfg!` the assertion here because the explicit-builder
590 /// test above pins the override path; this test exercises the
591 /// implicit default and the platform branch together.
592 #[test]
593 fn default_app_support_dir_is_platform_aware() {
594 let pather = XdgPather::builder()
595 .home("/u")
596 .dotfiles_root("/u/dotfiles")
597 .xdg_config_home("/u/.config")
598 .build()
599 .unwrap();
600 if cfg!(target_os = "macos") {
601 assert_eq!(
602 pather.app_support_dir(),
603 Path::new("/u/Library/Application Support"),
604 "macOS default should route under $HOME/Library/Application Support"
605 );
606 } else {
607 assert_eq!(
608 pather.app_support_dir(),
609 pather.xdg_config_home(),
610 "non-macOS default should collapse to xdg_config_home"
611 );
612 }
613 }
614
615 // Compile-time check: Pather must be object-safe
616 #[allow(dead_code)]
617 fn assert_object_safe(_: &dyn Pather) {}
618}