Skip to main content

libbrat_worktree/
manager.rs

1//! Worktree manager for polecat sessions.
2//!
3//! This module provides the main `WorktreeManager` struct for creating,
4//! tracking, and cleaning up git worktrees for polecat sessions.
5
6use std::collections::HashSet;
7use std::fs;
8use std::path::{Path, PathBuf};
9
10use crate::error::WorktreeError;
11use crate::git::{GitWorktree, WorktreeEntry};
12
13/// Information about a managed worktree.
14#[derive(Debug, Clone)]
15pub struct WorktreeInfo {
16    /// Absolute path to the worktree directory.
17    pub path: PathBuf,
18    /// HEAD commit hash.
19    pub head: String,
20    /// Whether this is the main worktree (not linked).
21    pub is_main: bool,
22    /// Whether the worktree is locked.
23    pub locked: bool,
24    /// Session ID if this worktree is managed by Brat.
25    pub session_id: Option<String>,
26}
27
28impl From<WorktreeEntry> for WorktreeInfo {
29    fn from(entry: WorktreeEntry) -> Self {
30        let session_id = extract_session_id_from_path(&entry.path);
31        Self {
32            path: entry.path,
33            head: entry.head,
34            is_main: entry.branch.is_some() && !entry.detached,
35            locked: entry.locked,
36            session_id,
37        }
38    }
39}
40
41/// Report from cleanup operation.
42#[derive(Debug, Default)]
43pub struct CleanupReport {
44    /// Session IDs that were cleaned up.
45    pub cleaned: Vec<String>,
46    /// Errors encountered during cleanup.
47    pub errors: Vec<(String, WorktreeError)>,
48}
49
50/// Manages git worktrees for polecat sessions.
51///
52/// Each polecat session runs in an isolated git worktree to enable
53/// parallel work without conflicts. The manager handles creation,
54/// tracking, and cleanup of these worktrees.
55pub struct WorktreeManager {
56    /// Path to the repository root.
57    #[allow(dead_code)]
58    repo_root: PathBuf,
59    /// Root directory for worktrees (e.g., `.grite/worktrees`).
60    worktree_root: PathBuf,
61    /// Maximum number of polecat worktrees allowed.
62    max_polecats: u32,
63    /// Git worktree command wrapper.
64    git: GitWorktree,
65}
66
67impl WorktreeManager {
68    /// Create a new WorktreeManager.
69    ///
70    /// # Arguments
71    ///
72    /// * `repo_root` - Path to the repository root.
73    /// * `worktree_root` - Relative path for worktrees (e.g., `.grite/worktrees`).
74    /// * `max_polecats` - Maximum number of concurrent polecat worktrees.
75    pub fn new(
76        repo_root: impl Into<PathBuf>,
77        worktree_root: impl AsRef<str>,
78        max_polecats: u32,
79    ) -> Self {
80        let repo_root = repo_root.into();
81        let worktree_root = repo_root.join(worktree_root.as_ref());
82        let git = GitWorktree::new(&repo_root);
83
84        Self {
85            repo_root,
86            worktree_root,
87            max_polecats,
88            git,
89        }
90    }
91
92    /// Get the worktree root path.
93    pub fn worktree_root(&self) -> &Path {
94        &self.worktree_root
95    }
96
97    /// Create a new worktree for a session.
98    ///
99    /// The worktree is named after the session ID and created with a
100    /// detached HEAD at the current commit.
101    ///
102    /// # Arguments
103    ///
104    /// * `session_id` - Session ID (e.g., `s-20250117-a2f9`).
105    ///
106    /// # Returns
107    ///
108    /// The absolute path to the created worktree.
109    pub fn create(&self, session_id: &str) -> Result<PathBuf, WorktreeError> {
110        // Validate session ID format
111        if !is_valid_session_id(session_id) {
112            return Err(WorktreeError::InvalidSessionId(session_id.to_string()));
113        }
114
115        // Build worktree path
116        let worktree_path = self.worktree_root.join(session_id);
117
118        // Check if already exists
119        if worktree_path.exists() {
120            return Err(WorktreeError::AlreadyExists(session_id.to_string()));
121        }
122
123        // Check max polecats limit
124        let current_count = self.count_managed_worktrees()?;
125        if current_count >= self.max_polecats {
126            return Err(WorktreeError::MaxReached {
127                current: current_count,
128                max: self.max_polecats,
129            });
130        }
131
132        // Ensure worktree root exists
133        fs::create_dir_all(&self.worktree_root)?;
134
135        // Create the worktree with detached HEAD
136        self.git.add(&worktree_path, "HEAD", true)?;
137
138        Ok(worktree_path)
139    }
140
141    /// List all managed worktrees.
142    ///
143    /// Returns worktrees in the worktree_root directory, excluding the main worktree.
144    pub fn list(&self) -> Result<Vec<WorktreeInfo>, WorktreeError> {
145        let entries = self.git.list()?;
146
147        Ok(entries
148            .into_iter()
149            .map(WorktreeInfo::from)
150            .filter(|w| !w.is_main && w.path.starts_with(&self.worktree_root))
151            .collect())
152    }
153
154    /// Get a worktree by session ID.
155    pub fn get(&self, session_id: &str) -> Result<WorktreeInfo, WorktreeError> {
156        let worktree_path = self.worktree_root.join(session_id);
157
158        for entry in self.git.list()? {
159            if entry.path == worktree_path {
160                return Ok(WorktreeInfo::from(entry));
161            }
162        }
163
164        Err(WorktreeError::NotFound(session_id.to_string()))
165    }
166
167    /// Remove a worktree by session ID.
168    ///
169    /// Uses `--force` to remove even if the worktree has uncommitted changes.
170    pub fn remove(&self, session_id: &str) -> Result<(), WorktreeError> {
171        let worktree_path = self.worktree_root.join(session_id);
172
173        if !worktree_path.exists() {
174            // Already removed, just prune git metadata
175            self.git.prune()?;
176            return Ok(());
177        }
178
179        self.git.remove(&worktree_path, true)?;
180        Ok(())
181    }
182
183    /// Prune stale worktree administrative files.
184    pub fn prune(&self) -> Result<(), WorktreeError> {
185        self.git.prune()?;
186        Ok(())
187    }
188
189    /// Clean up worktrees for sessions that are no longer active.
190    ///
191    /// # Arguments
192    ///
193    /// * `active_session_ids` - Set of session IDs that are still active.
194    ///
195    /// # Returns
196    ///
197    /// A report of cleaned up worktrees and any errors.
198    pub fn cleanup_stale(
199        &self,
200        active_session_ids: &HashSet<String>,
201    ) -> Result<CleanupReport, WorktreeError> {
202        let mut report = CleanupReport::default();
203
204        for worktree in self.list()? {
205            let Some(session_id) = worktree.session_id else {
206                continue; // Not a session worktree
207            };
208
209            // Skip if session is active
210            if active_session_ids.contains(&session_id) {
211                continue;
212            }
213
214            // Clean it up
215            match self.remove(&session_id) {
216                Ok(()) => report.cleaned.push(session_id),
217                Err(e) => report.errors.push((session_id, e)),
218            }
219        }
220
221        // Prune git metadata
222        self.prune()?;
223
224        Ok(report)
225    }
226
227    /// Count managed worktrees (excluding main).
228    fn count_managed_worktrees(&self) -> Result<u32, WorktreeError> {
229        Ok(self.list()?.len() as u32)
230    }
231}
232
233/// Check if a string is a valid session ID.
234///
235/// Session IDs have the format: `s-YYYYMMDD-XXXX` where XXXX is 4 hex characters.
236fn is_valid_session_id(s: &str) -> bool {
237    // Format: s-YYYYMMDD-XXXX (e.g., s-20250117-a2f9)
238    if s.len() != 15 {
239        return false;
240    }
241    if !s.starts_with("s-") {
242        return false;
243    }
244    let parts: Vec<&str> = s.split('-').collect();
245    if parts.len() != 3 {
246        return false;
247    }
248    // parts[0] = "s"
249    // parts[1] = YYYYMMDD (8 chars)
250    // parts[2] = XXXX (4 hex chars)
251    if parts[1].len() != 8 || !parts[1].chars().all(|c| c.is_ascii_digit()) {
252        return false;
253    }
254    if parts[2].len() != 4 || !parts[2].chars().all(|c| c.is_ascii_hexdigit()) {
255        return false;
256    }
257    true
258}
259
260/// Extract session ID from a worktree path.
261///
262/// Returns the session ID if the path's filename is a valid session ID.
263fn extract_session_id_from_path(path: &Path) -> Option<String> {
264    let name = path.file_name()?.to_str()?;
265    if is_valid_session_id(name) {
266        Some(name.to_string())
267    } else {
268        None
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn test_is_valid_session_id() {
278        assert!(is_valid_session_id("s-20250117-a2f9"));
279        assert!(is_valid_session_id("s-20240101-0000"));
280        assert!(is_valid_session_id("s-99991231-ffff"));
281
282        assert!(!is_valid_session_id(""));
283        assert!(!is_valid_session_id("s-2025011-a2f9")); // Date too short
284        assert!(!is_valid_session_id("s-20250117-a2f")); // Hex too short
285        assert!(!is_valid_session_id("t-20250117-a2f9")); // Wrong prefix
286        assert!(!is_valid_session_id("s-20250117-a2f9-extra")); // Too long
287        assert!(!is_valid_session_id("s-2025011a-a2f9")); // Non-digit in date
288        assert!(!is_valid_session_id("s-20250117-ghij")); // Non-hex in suffix
289    }
290
291    #[test]
292    fn test_extract_session_id_from_path() {
293        assert_eq!(
294            extract_session_id_from_path(Path::new("/repo/.grite/worktrees/s-20250117-a2f9")),
295            Some("s-20250117-a2f9".to_string())
296        );
297        assert_eq!(
298            extract_session_id_from_path(Path::new("s-20250117-a2f9")),
299            Some("s-20250117-a2f9".to_string())
300        );
301        assert_eq!(
302            extract_session_id_from_path(Path::new("/repo/.grite/worktrees/not-a-session")),
303            None
304        );
305        assert_eq!(extract_session_id_from_path(Path::new("/repo")), None);
306    }
307}