use crate::error::{Context, Result};
use crate::branch::{BranchManager, BranchStatus};
use crate::vcs::VcsManager;
pub async fn worktree_add_command(branch_name: String) -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let mut branch_manager = BranchManager::new(
current_dir.join(".codetree").join("branches.json")
).await?;
if let Some(branch) = branch_manager.get_branch(&branch_name) {
if !matches!(branch.status, BranchStatus::Active) {
return Err(format!("Branch '{}' is not active", branch_name).into());
}
if let Some(wt_path) = &branch.worktree {
return Err(format!("Branch '{}' already has a worktree at {:?}", branch_name, wt_path).into());
}
} else {
return Err(format!("Branch '{}' is not tracked by codetree", branch_name).into());
}
let worktree_path = current_dir.join(".codetree").join("worktrees").join(&branch_name);
tokio::fs::create_dir_all(&worktree_path).await
.context("Failed to create worktree directory")?;
git_manager.add_worktree(&branch_name, &worktree_path).await
.context("Failed to add worktree")?;
branch_manager.set_branch_worktree(&branch_name, worktree_path.clone()).await?;
println!("Added worktree for '{}' at {:?}", branch_name, worktree_path);
Ok(())
}
pub async fn worktree_remove_command(branch_name: String) -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let mut branch_manager = BranchManager::new(
current_dir.join(".codetree").join("branches.json")
).await?;
let worktree_path = if let Some(branch) = branch_manager.get_branch(&branch_name) {
if let Some(path) = &branch.worktree {
path.clone()
} else {
return Err(format!("Branch '{}' has no worktree", branch_name).into());
}
} else {
return Err(format!("Branch '{}' is not tracked by codetree", branch_name).into());
};
git_manager.remove_worktree(&worktree_path).await
.context("Failed to remove worktree")?;
branch_manager.clear_branch_worktree(&branch_name).await?;
println!("Removed worktree for '{}'", branch_name);
Ok(())
}
pub async fn worktree_list_command() -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let branch_manager = BranchManager::new(
current_dir.join(".codetree").join("branches.json")
).await?;
let worktrees = git_manager.list_worktrees().await
.context("Failed to list worktrees")?;
if worktrees.is_empty() {
println!("No worktrees found");
return Ok(());
}
println!("Worktrees:");
for (path, branch) in worktrees {
let tracked = branch_manager.get_branch(&branch);
let status = tracked.map(|b| b.status.as_str()).unwrap_or("untracked");
println!(" {} -> {} ({})", branch, path, status);
}
Ok(())
}