libbrat_worktree/
manager.rs1use std::collections::HashSet;
7use std::fs;
8use std::path::{Path, PathBuf};
9
10use crate::error::WorktreeError;
11use crate::git::{GitWorktree, WorktreeEntry};
12
13#[derive(Debug, Clone)]
15pub struct WorktreeInfo {
16 pub path: PathBuf,
18 pub head: String,
20 pub is_main: bool,
22 pub locked: bool,
24 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#[derive(Debug, Default)]
43pub struct CleanupReport {
44 pub cleaned: Vec<String>,
46 pub errors: Vec<(String, WorktreeError)>,
48}
49
50pub struct WorktreeManager {
56 #[allow(dead_code)]
58 repo_root: PathBuf,
59 worktree_root: PathBuf,
61 max_polecats: u32,
63 git: GitWorktree,
65}
66
67impl WorktreeManager {
68 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 pub fn worktree_root(&self) -> &Path {
94 &self.worktree_root
95 }
96
97 pub fn create(&self, session_id: &str) -> Result<PathBuf, WorktreeError> {
110 if !is_valid_session_id(session_id) {
112 return Err(WorktreeError::InvalidSessionId(session_id.to_string()));
113 }
114
115 let worktree_path = self.worktree_root.join(session_id);
117
118 if worktree_path.exists() {
120 return Err(WorktreeError::AlreadyExists(session_id.to_string()));
121 }
122
123 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 fs::create_dir_all(&self.worktree_root)?;
134
135 self.git.add(&worktree_path, "HEAD", true)?;
137
138 Ok(worktree_path)
139 }
140
141 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 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 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 self.git.prune()?;
176 return Ok(());
177 }
178
179 self.git.remove(&worktree_path, true)?;
180 Ok(())
181 }
182
183 pub fn prune(&self) -> Result<(), WorktreeError> {
185 self.git.prune()?;
186 Ok(())
187 }
188
189 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; };
208
209 if active_session_ids.contains(&session_id) {
211 continue;
212 }
213
214 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 self.prune()?;
223
224 Ok(report)
225 }
226
227 fn count_managed_worktrees(&self) -> Result<u32, WorktreeError> {
229 Ok(self.list()?.len() as u32)
230 }
231}
232
233fn is_valid_session_id(s: &str) -> bool {
237 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 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
260fn 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")); assert!(!is_valid_session_id("s-20250117-a2f")); assert!(!is_valid_session_id("t-20250117-a2f9")); assert!(!is_valid_session_id("s-20250117-a2f9-extra")); assert!(!is_valid_session_id("s-2025011a-a2f9")); assert!(!is_valid_session_id("s-20250117-ghij")); }
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}