use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use crate::error::WorktreeError;
use crate::git::{GitWorktree, WorktreeEntry};
#[derive(Debug, Clone)]
pub struct WorktreeInfo {
pub path: PathBuf,
pub head: String,
pub is_main: bool,
pub locked: bool,
pub session_id: Option<String>,
}
impl From<WorktreeEntry> for WorktreeInfo {
fn from(entry: WorktreeEntry) -> Self {
let session_id = extract_session_id_from_path(&entry.path);
Self {
path: entry.path,
head: entry.head,
is_main: entry.branch.is_some() && !entry.detached,
locked: entry.locked,
session_id,
}
}
}
#[derive(Debug, Default)]
pub struct CleanupReport {
pub cleaned: Vec<String>,
pub errors: Vec<(String, WorktreeError)>,
}
pub struct WorktreeManager {
#[allow(dead_code)]
repo_root: PathBuf,
worktree_root: PathBuf,
max_polecats: u32,
git: GitWorktree,
}
impl WorktreeManager {
pub fn new(
repo_root: impl Into<PathBuf>,
worktree_root: impl AsRef<str>,
max_polecats: u32,
) -> Self {
let repo_root = repo_root.into();
let worktree_root = repo_root.join(worktree_root.as_ref());
let git = GitWorktree::new(&repo_root);
Self {
repo_root,
worktree_root,
max_polecats,
git,
}
}
pub fn worktree_root(&self) -> &Path {
&self.worktree_root
}
pub fn create(&self, session_id: &str) -> Result<PathBuf, WorktreeError> {
if !is_valid_session_id(session_id) {
return Err(WorktreeError::InvalidSessionId(session_id.to_string()));
}
let worktree_path = self.worktree_root.join(session_id);
if worktree_path.exists() {
return Err(WorktreeError::AlreadyExists(session_id.to_string()));
}
let current_count = self.count_managed_worktrees()?;
if current_count >= self.max_polecats {
return Err(WorktreeError::MaxReached {
current: current_count,
max: self.max_polecats,
});
}
fs::create_dir_all(&self.worktree_root)?;
self.git.add(&worktree_path, "HEAD", true)?;
Ok(worktree_path)
}
pub fn list(&self) -> Result<Vec<WorktreeInfo>, WorktreeError> {
let entries = self.git.list()?;
Ok(entries
.into_iter()
.map(WorktreeInfo::from)
.filter(|w| !w.is_main && w.path.starts_with(&self.worktree_root))
.collect())
}
pub fn get(&self, session_id: &str) -> Result<WorktreeInfo, WorktreeError> {
let worktree_path = self.worktree_root.join(session_id);
for entry in self.git.list()? {
if entry.path == worktree_path {
return Ok(WorktreeInfo::from(entry));
}
}
Err(WorktreeError::NotFound(session_id.to_string()))
}
pub fn remove(&self, session_id: &str) -> Result<(), WorktreeError> {
let worktree_path = self.worktree_root.join(session_id);
if !worktree_path.exists() {
self.git.prune()?;
return Ok(());
}
self.git.remove(&worktree_path, true)?;
Ok(())
}
pub fn prune(&self) -> Result<(), WorktreeError> {
self.git.prune()?;
Ok(())
}
pub fn cleanup_stale(
&self,
active_session_ids: &HashSet<String>,
) -> Result<CleanupReport, WorktreeError> {
let mut report = CleanupReport::default();
for worktree in self.list()? {
let Some(session_id) = worktree.session_id else {
continue; };
if active_session_ids.contains(&session_id) {
continue;
}
match self.remove(&session_id) {
Ok(()) => report.cleaned.push(session_id),
Err(e) => report.errors.push((session_id, e)),
}
}
self.prune()?;
Ok(report)
}
fn count_managed_worktrees(&self) -> Result<u32, WorktreeError> {
Ok(self.list()?.len() as u32)
}
}
fn is_valid_session_id(s: &str) -> bool {
if s.len() != 15 {
return false;
}
if !s.starts_with("s-") {
return false;
}
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 3 {
return false;
}
if parts[1].len() != 8 || !parts[1].chars().all(|c| c.is_ascii_digit()) {
return false;
}
if parts[2].len() != 4 || !parts[2].chars().all(|c| c.is_ascii_hexdigit()) {
return false;
}
true
}
fn extract_session_id_from_path(path: &Path) -> Option<String> {
let name = path.file_name()?.to_str()?;
if is_valid_session_id(name) {
Some(name.to_string())
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_valid_session_id() {
assert!(is_valid_session_id("s-20250117-a2f9"));
assert!(is_valid_session_id("s-20240101-0000"));
assert!(is_valid_session_id("s-99991231-ffff"));
assert!(!is_valid_session_id(""));
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")); }
#[test]
fn test_extract_session_id_from_path() {
assert_eq!(
extract_session_id_from_path(Path::new("/repo/.grite/worktrees/s-20250117-a2f9")),
Some("s-20250117-a2f9".to_string())
);
assert_eq!(
extract_session_id_from_path(Path::new("s-20250117-a2f9")),
Some("s-20250117-a2f9".to_string())
);
assert_eq!(
extract_session_id_from_path(Path::new("/repo/.grite/worktrees/not-a-session")),
None
);
assert_eq!(extract_session_id_from_path(Path::new("/repo")), None);
}
}