Skip to main content

tracevault_cli/
paths.rs

1/// Shared project-root resolution for the entire CLI.
2///
3/// This module provides a single [`resolve_project_root`] function that all CLI
4/// paths (stream, check, verify-start, context, …) use to locate the primary
5/// `.tracevault/` directory.  The resolution strategy is:
6///
7/// 1. **Git-aware (primary):** run `git rev-parse --git-common-dir` from
8///    `start`; the primary worktree root is `parent(canonicalized git-common-dir)`.
9///    This works correctly from a primary checkout, a nested worktree, AND a
10///    sibling linked worktree (where the primary `.tracevault/` is not an
11///    ancestor of the working directory).
12///
13/// 2. **Fallback (non-git):** ancestor-walk from `start` to the nearest
14///    `.tracevault/` directory (matching the existing `stream.rs` behaviour).
15///    Returns `start` itself if nothing is found.
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19// ---------------------------------------------------------------------------
20// Public types
21// ---------------------------------------------------------------------------
22
23/// The resolved project root and how it was found.
24#[derive(Debug, Clone, PartialEq)]
25pub struct ProjectRoot {
26    /// The directory that directly contains (or should contain) `.tracevault/`.
27    pub root: PathBuf,
28    /// How the root was discovered.
29    pub source: ProjectRootSource,
30}
31
32/// How [`ProjectRoot`] was determined.
33#[derive(Debug, Clone, PartialEq)]
34pub enum ProjectRootSource {
35    /// Resolved via `git rev-parse --git-common-dir` (works from any worktree).
36    Git,
37    /// Git is not available or `start` is not in a git repo; root was found by
38    /// walking ancestors for the nearest `.tracevault/` directory.
39    AncestorWalk,
40    /// Neither git nor an ancestor `.tracevault/` was found; `start` itself is
41    /// returned as the root (matching the existing `unwrap_or(start)` fallback).
42    Fallback,
43}
44
45// ---------------------------------------------------------------------------
46// Public API
47// ---------------------------------------------------------------------------
48
49/// Resolve the primary project root starting from `start`.
50///
51/// See module-level documentation for the resolution strategy.
52///
53/// # Panics
54/// Never panics.
55pub fn resolve_project_root(start: &Path) -> ProjectRoot {
56    // --- Strategy 1: git rev-parse --git-common-dir ---
57    if let Some(primary_root) = git_common_dir_root(start) {
58        return ProjectRoot {
59            root: primary_root,
60            source: ProjectRootSource::Git,
61        };
62    }
63
64    // --- Strategy 2: ancestor walk for .tracevault/ ---
65    for ancestor in start.ancestors() {
66        if ancestor.join(".tracevault").is_dir() {
67            return ProjectRoot {
68                root: ancestor.to_path_buf(),
69                source: ProjectRootSource::AncestorWalk,
70            };
71        }
72    }
73
74    // --- Strategy 3: last resort — return start itself ---
75    ProjectRoot {
76        root: start.to_path_buf(),
77        source: ProjectRootSource::Fallback,
78    }
79}
80
81/// Return the canonicalized git worktree toplevel for `from`.
82///
83/// Runs `git rev-parse --show-toplevel` in `from` and canonicalizes the result
84/// so the value is comparable across the write side (the `stream` hook's origin
85/// marker) and the read side (`verify-start` disambiguation) regardless of
86/// symlinked paths (e.g. `/tmp` → `/private/tmp`). Falls back to the
87/// canonicalized `from` when git is unavailable or `from` is not a repo.
88///
89/// # Panics
90/// Never panics.
91pub fn worktree_toplevel(from: &Path) -> String {
92    Command::new("git")
93        .args(["rev-parse", "--show-toplevel"])
94        .current_dir(from)
95        .output()
96        .ok()
97        .filter(|o| o.status.success())
98        .and_then(|o| String::from_utf8(o.stdout).ok())
99        .map(|s| {
100            let p = PathBuf::from(s.trim());
101            p.canonicalize().unwrap_or(p).to_string_lossy().into_owned()
102        })
103        .unwrap_or_else(|| {
104            from.canonicalize()
105                .unwrap_or_else(|_| from.to_path_buf())
106                .to_string_lossy()
107                .into_owned()
108        })
109}
110
111// ---------------------------------------------------------------------------
112// Internal helpers
113// ---------------------------------------------------------------------------
114
115/// Run `git rev-parse --git-common-dir` from `start_dir` and return
116/// `parent(canonicalized git-common-dir)`, i.e. the primary worktree root.
117///
118/// Returns `None` if git is not available, `start_dir` is not inside a git
119/// repo, or the git-common-dir has no parent (shouldn't happen in practice).
120fn git_common_dir_root(start_dir: &Path) -> Option<PathBuf> {
121    let output = Command::new("git")
122        .args([
123            "-C",
124            &start_dir.to_string_lossy(),
125            "rev-parse",
126            "--git-common-dir",
127        ])
128        .output()
129        .ok()?;
130
131    if !output.status.success() {
132        return None;
133    }
134
135    let stdout = std::str::from_utf8(&output.stdout).ok()?;
136    let raw = stdout.lines().next()?.trim();
137
138    // git may return a relative path; canonicalize against start_dir.
139    let p = PathBuf::from(raw);
140    let git_common_dir = if p.is_absolute() {
141        p.canonicalize().ok()?
142    } else {
143        start_dir.join(&p).canonicalize().ok()?
144    };
145
146    // primary_root = parent of git-common-dir (the dir containing `.git/`)
147    git_common_dir.parent().map(PathBuf::from)
148}
149
150// ---------------------------------------------------------------------------
151// Tests
152// ---------------------------------------------------------------------------
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157    use crate::test_helpers::{add_worktree, init_git_repo};
158
159    // -----------------------------------------------------------------------
160    // Git-aware resolution tests
161    // -----------------------------------------------------------------------
162
163    #[test]
164    fn primary_checkout_resolves_to_repo_root() {
165        let tmp = tempfile::tempdir().unwrap();
166        let repo = tmp.path().join("repo");
167        std::fs::create_dir_all(&repo).unwrap();
168        init_git_repo(&repo);
169
170        let result = resolve_project_root(&repo);
171
172        assert_eq!(result.source, ProjectRootSource::Git);
173        assert_eq!(
174            result.root.canonicalize().unwrap(),
175            repo.canonicalize().unwrap(),
176            "primary checkout must resolve to repo root"
177        );
178    }
179
180    #[test]
181    fn nested_worktree_resolves_to_primary_root() {
182        let tmp = tempfile::tempdir().unwrap();
183        let repo = tmp.path().join("repo");
184        // Nested worktree lives INSIDE the primary repo directory tree.
185        let wt = repo.join("nested-wt");
186
187        std::fs::create_dir_all(&repo).unwrap();
188        init_git_repo(&repo);
189        add_worktree(&repo, &wt);
190
191        let result = resolve_project_root(&wt);
192
193        assert_eq!(result.source, ProjectRootSource::Git);
194        assert_eq!(
195            result.root.canonicalize().unwrap(),
196            repo.canonicalize().unwrap(),
197            "nested worktree must resolve to primary repo root"
198        );
199    }
200
201    #[test]
202    fn sibling_worktree_resolves_to_primary_root() {
203        let tmp = tempfile::tempdir().unwrap();
204        let repo = tmp.path().join("repo");
205        // Sibling worktree is OUTSIDE the primary repo directory tree —
206        // the primary `.tracevault/` is NOT an ancestor.
207        let wt = tmp.path().join("sibling-wt");
208
209        std::fs::create_dir_all(&repo).unwrap();
210        init_git_repo(&repo);
211        add_worktree(&repo, &wt);
212
213        let result = resolve_project_root(&wt);
214
215        assert_eq!(result.source, ProjectRootSource::Git);
216        assert_eq!(
217            result.root.canonicalize().unwrap(),
218            repo.canonicalize().unwrap(),
219            "sibling worktree must resolve to primary repo root (not the worktree dir)"
220        );
221    }
222
223    // -----------------------------------------------------------------------
224    // Fallback: non-git directory with .tracevault/ ancestor
225    // -----------------------------------------------------------------------
226
227    #[test]
228    fn non_git_with_tracevault_ancestor_uses_ancestor_walk() {
229        let tmp = tempfile::tempdir().unwrap();
230        // Create .tracevault/ at the tmp root.
231        std::fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
232
233        // Start from a subdirectory.
234        let subdir = tmp.path().join("a").join("b").join("c");
235        std::fs::create_dir_all(&subdir).unwrap();
236
237        let result = resolve_project_root(&subdir);
238
239        assert_eq!(result.source, ProjectRootSource::AncestorWalk);
240        assert_eq!(
241            result.root.canonicalize().unwrap(),
242            tmp.path().canonicalize().unwrap(),
243            "ancestor walk must find the directory that contains .tracevault/"
244        );
245    }
246
247    #[test]
248    fn non_git_no_tracevault_falls_back_to_start() {
249        let tmp = tempfile::tempdir().unwrap();
250        // No git repo, no .tracevault/ anywhere under /tmp (usually).
251        let result = resolve_project_root(tmp.path());
252
253        assert_eq!(result.source, ProjectRootSource::Fallback);
254        assert_eq!(
255            result.root,
256            tmp.path(),
257            "with no git and no .tracevault/, root must be start itself"
258        );
259    }
260}