codetree 0.2.0

AI-native version control system for autonomous agents
Documentation
//! Worktree management and the remote-push stub on VcsManager.

use crate::error::{Context, Result};
use super::manager::VcsManager;
use std::path::Path;

impl VcsManager {
    /// Push branch to remote. Not yet implemented for native VCS.
    pub async fn push_branch(&self, _branch_name: &str, _remote_name: &str) -> Result<()> {
        bail!("Remote push not yet implemented for native VCS. Use `git push` manually if needed.");
    }

    // ── Worktrees (simplified — directory with checked-out branch) ─

    /// Add a worktree for an existing branch.
    pub async fn add_worktree(&self, branch_name: &str, path: &Path) -> Result<()> {
        std::fs::create_dir_all(path)?;
        let commit_id = self
            .repo
            .refs()
            .get_branch(branch_name)?
            .with_context(|| format!("Branch '{}' not found", branch_name))?;

        // Write all files from the branch's tree to the worktree path
        let tree = self.commit_tree(&commit_id)?;
        for entry in &tree.entries {
            let blob = self.repo.read_blob(&entry.id)?;
            let file_path = path.join(&entry.name);
            if let Some(parent) = file_path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&file_path, &blob.content)?;
        }
        Ok(())
    }

    /// Add a worktree creating a new branch from a base.
    pub async fn add_worktree_new_branch(
        &self,
        branch_name: &str,
        path: &Path,
        base_branch: &str,
    ) -> Result<()> {
        // Create the branch first
        self.create_branch(branch_name, Some(base_branch)).await?;
        // Then add worktree
        self.add_worktree(branch_name, path).await
    }

    /// Remove a worktree.
    pub async fn remove_worktree(&self, path: &Path) -> Result<()> {
        if path.exists() {
            std::fs::remove_dir_all(path)?;
        }
        Ok(())
    }

    /// List worktrees. Returns (path, branch_name) pairs.
    pub async fn list_worktrees(&self) -> Result<Vec<(String, String)>> {
        let worktree_root = self.repo_path.join(".codetree").join("worktrees");
        let mut worktrees = Vec::new();
        if !worktree_root.exists() {
            return Ok(worktrees);
        }
        for entry in std::fs::read_dir(&worktree_root)? {
            let entry = entry?;
            if entry.file_type()?.is_dir()
                && let Some(name) = entry.file_name().to_str()
            {
                worktrees.push((entry.path().to_string_lossy().to_string(), name.to_string()));
            }
        }
        Ok(worktrees)
    }

    // ── HEAD helpers ───────────────────────────────────────────────

}