codetree 0.1.1

AI-native version control system for autonomous agents
Documentation
use crate::error::{Context, Result};

use crate::branch::{BranchInfo, BranchManager, BranchStatus};
use crate::vcs::VcsManager;

use super::load_config;

pub async fn compare_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 active_branches: Vec<_> = branch_manager.list_branches()
        .into_iter()
        .filter(|b| matches!(b.status, BranchStatus::Active) && !b.branchless)
        .collect();

    if active_branches.is_empty() {
        println!("No active branched operations to compare");
        return Ok(());
    }

    println!("=== Active Operations ===\n");
    for branch in &active_branches {
        println!("--- {} ---", branch.name);
        println!("  Description: {}", branch.change_group.description);
        println!("  Files: {}", branch.change_group.files.len());
        if let Some(template) = &branch.template {
            println!("  Template: {}", template);
        }

        match git_manager.get_branch_diff(&branch.name) {
            Ok(diff) => {
                if diff.is_empty() {
                    println!("  Diff: no changes");
                } else {
                    let files_changed = diff.lines().filter(|l: &&str| l.starts_with("diff --git")).count();
                    let insertions = diff.lines().filter(|l: &&str| l.starts_with('+')).count();
                    let deletions = diff.lines().filter(|l: &&str| l.starts_with('-')).count();
                    println!("  Diff: {} files changed, +{} -{}", files_changed, insertions, deletions);
                }
            }
            Err(e) => {
                println!("  Diff: error - {}", e);
            }
        }
        println!();
    }

    let branches_with_deps: Vec<_> = active_branches.iter()
        .filter(|b| !b.depends_on.is_empty())
        .collect();
    if !branches_with_deps.is_empty() {
        println!("=== Dependency Graph ===\n");
        for branch in &branches_with_deps {
            print!("{}\n  └── depends on:\n", branch.name);
            for dep in &branch.depends_on {
                let dep_status = branch_manager.get_branch(dep)
                    .map(|b| b.status.as_str().to_string())
                    .unwrap_or_else(|| "unknown".to_string());
                let symbol = if dep_status == "merged" { "✓" } else { "○" };
                println!("      {} {} ({})", symbol, dep, dep_status);
            }
            println!();
        }

        if let Some(cycle) = detect_cycle(&active_branches) {
            println!("Cycle detected: {}", cycle.join(" -> "));
        }
    }

    let mut file_to_branches: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
    for branch in &active_branches {
        for file in &branch.change_group.files {
            file_to_branches.entry(file.clone()).or_default().push(branch.name.clone());
        }
    }

    let conflicts: Vec<_> = file_to_branches.iter()
        .filter(|(_, branches)| branches.len() > 1)
        .collect();

    if !conflicts.is_empty() {
        println!("⚠️  File conflicts detected:");
        for (file, branches) in conflicts {
            println!("  {} — touched by: {}", file, branches.join(", "));
        }
    }

    Ok(())
}

fn detect_cycle(branches: &[&BranchInfo]) -> Option<Vec<String>> {
    use std::collections::HashSet;

    fn dfs(name: &str, branches: &[&BranchInfo], visited: &mut HashSet<String>, path: &mut Vec<String>) -> Option<Vec<String>> {
        if path.contains(&name.to_string()) {
            let cycle_start = path.iter().position(|n| n == name).unwrap();
            return Some(path[cycle_start..].to_vec());
        }
        if visited.contains(name) {
            return None;
        }
        visited.insert(name.to_string());
        path.push(name.to_string());

        if let Some(branch) = branches.iter().find(|b| b.name == name) {
            for dep in &branch.depends_on {
                if let Some(cycle) = dfs(dep, branches, visited, path) {
                    return Some(cycle);
                }
            }
        }
        path.pop();
        None
    }

    let mut visited = HashSet::new();
    for branch in branches {
        let mut path = Vec::new();
        if let Some(cycle) = dfs(&branch.name, branches, &mut visited, &mut path) {
            return Some(cycle);
        }
    }
    None
}

pub async fn publish_command(branch: Option<String>) -> Result<()> {
    let config = load_config(None).await?;
    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 target_branch = match branch {
        Some(b) => b,
        None => git_manager.get_current_branch().await?,
    };

    let branch_info = branch_manager.get_branch(&target_branch)
        .context(format!("Branch '{}' not tracked by codetree", target_branch))?;

    if !matches!(branch_info.status, BranchStatus::Active) {
        return Err(format!("Branch '{}' is not active", target_branch).into());
    }

    // Export CodeTree history to Git (initializes .git if needed).
    println!("Exporting CodeTree history to Git...");
    super::export_command().await?;

    let remote = &config.git.remote_name;

    // Push the branch to the remote via git CLI.
    println!("Pushing '{}' to remote '{}'...", target_branch, remote);
    let push_output = tokio::process::Command::new("git")
        .args(["push", "-u", remote, &target_branch])
        .current_dir(&current_dir)
        .output()
        .await;

    match push_output {
        Ok(output) if output.status.success() => {
            println!("Pushed successfully");
        }
        Ok(output) => {
            let stderr = String::from_utf8_lossy(&output.stderr);
            bail!("Failed to push to '{}': {}", remote, stderr.trim());
        }
        Err(_) => {
            bail!("'git' CLI not found. Install git to push.");
        }
    }

    let title = &branch_info.change_group.description;
    let commits = git_manager.get_commit_history(&target_branch, 20)
        .unwrap_or_default();

    let mut body = String::new();
    body.push_str("## Commits\n\n");
    for commit in &commits {
        let msg = commit.message.lines().next().unwrap_or("");
        body.push_str(&format!("- `{}` {}\n", &commit.hash[..7], msg));
    }

    body.push_str("\n## Files Changed\n\n");
    if let Ok(diff) = git_manager.get_branch_diff(&target_branch) {
        let files: Vec<_> = diff.lines()
            .filter(|l| l.starts_with("diff --git"))
            .map(|l| {
                l.split_whitespace().nth(2)
                    .unwrap_or("")
                    .strip_prefix("b/")
                    .unwrap_or("")
                    .to_string()
            })
            .collect();
        for file in &files {
            body.push_str(&format!("- `{}`\n", file));
        }
        body.push_str(&format!("\n## Diff Summary\n\n+{} insertions, -{} deletions\n",
            diff.lines().filter(|l| l.starts_with('+')).count(),
            diff.lines().filter(|l| l.starts_with('-')).count()));
    }

    println!("\n=== PR Content ===");
    println!("Title: {}", title);
    println!("\nBody:\n{}", body);
    println!("==================");

    let gh_output = tokio::process::Command::new("gh")
        .args(["pr", "create",
            "--title", title,
            "--body", &body,
            "--head", &target_branch,
            "--base", &config.git.base_branch])
        .current_dir(&current_dir)
        .output()
        .await;

    match gh_output {
        Ok(output) if output.status.success() => {
            let url = String::from_utf8_lossy(&output.stdout);
            println!("\nPR created: {}", url.trim());
        }
        Ok(output) => {
            let stderr = String::from_utf8_lossy(&output.stderr);
            println!("\ngh CLI failed (install gh and authenticate to auto-create PRs): {}", stderr.trim());
        }
        Err(_) => {
            println!("\ngh CLI not found. Install it to auto-create PRs: https://cli.github.com");
        }
    }

    Ok(())
}