codetree 0.1.2

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

/// Bisect subcommands.
pub enum BisectAction {
    /// Start a bisect session. The current HEAD is marked as bad.
    Start,
    /// Mark the current (or specified) commit as good.
    Good(Option<String>),
    /// Mark the current (or specified) commit as bad.
    Bad(Option<String>),
    /// Show the current bisect state.
    Log,
    /// End the bisect session and restore the original HEAD.
    Reset,
}

/// Handle `codetree bisect <subcommand>`.
pub async fn bisect_command(action: BisectAction) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let git_manager = VcsManager::new(current_dir.clone())?;
    let repo = git_manager.repo();

    match action {
        BisectAction::Start => {
            let head_id = repo.refs().resolve_head()?
                .context("HEAD does not point to a commit")?;
            let original_branch = repo.refs().current_branch()?;

            let mut state = BisectState::load(&current_dir)?;
            if state.is_active() {
                bail!("Bisect already in progress. Use `codetree bisect reset` first.");
            }

            state.bad = Some(head_id.clone());
            state.original_head = Some(head_id.clone());
            state.original_branch = original_branch;
            state.save(&current_dir)?;

            println!("Bisect started. HEAD '{}' marked as bad.", &head_id[..7.min(head_id.len())]);
            println!("Mark a known-good ancestor with: codetree bisect good <commit>");
        }
        BisectAction::Good(commit) => {
            let mut state = BisectState::load(&current_dir)?;
            if !state.is_active() {
                bail!("No bisect in progress. Use `codetree bisect start` first.");
            }

            let good_id = if let Some(spec) = commit {
                let head_id = repo.refs().resolve_head()?
                    .context("HEAD does not point to a commit")?;
                git_manager.resolve_commit_pub(&spec, &head_id)?
            } else {
                repo.refs().resolve_head()?
                    .context("HEAD does not point to a commit")?
            };

            if !state.good.contains(&good_id) {
                state.good.push(good_id.clone());
            }
            state.save(&current_dir)?;

            let short = &good_id[..7.min(good_id.len())];
            println!("Marked '{}' as good.", short);

            // Find the next commit to test.
            if let Some(mid) = state.midpoint(repo)? {
                state.current = Some(mid.clone());
                state.save(&current_dir)?;
                git_manager.goto_commit(&mid).await?;
                let short_mid = &mid[..7.min(mid.len())];
                println!("Testing '{}' ({} commits remaining)", short_mid, remaining_count(repo, &state)?);
            } else {
                // The bad commit is the first bad commit.
                if let Some(bad) = &state.bad {
                    let short = &bad[..7.min(bad.len())];
                    println!("\nBisect complete! First bad commit: {}", short);
                    let commit = repo.read_commit(bad)?;
                    println!("    {}", commit.message.lines().next().unwrap_or(""));
                    println!("\nUse `codetree bisect reset` to return to the original HEAD.");
                }
            }
        }
        BisectAction::Bad(commit) => {
            let mut state = BisectState::load(&current_dir)?;
            if !state.is_active() {
                bail!("No bisect in progress. Use `codetree bisect start` first.");
            }

            let bad_id = if let Some(spec) = commit {
                let head_id = repo.refs().resolve_head()?
                    .context("HEAD does not point to a commit")?;
                git_manager.resolve_commit_pub(&spec, &head_id)?
            } else {
                repo.refs().resolve_head()?
                    .context("HEAD does not point to a commit")?
            };

            state.bad = Some(bad_id.clone());
            state.save(&current_dir)?;

            let short = &bad_id[..7.min(bad_id.len())];
            println!("Marked '{}' as bad.", short);

            // Find the next commit to test.
            if let Some(mid) = state.midpoint(repo)? {
                state.current = Some(mid.clone());
                state.save(&current_dir)?;
                git_manager.goto_commit(&mid).await?;
                let short_mid = &mid[..7.min(mid.len())];
                println!("Testing '{}' ({} commits remaining)", short_mid, remaining_count(repo, &state)?);
            } else {
                if let Some(bad) = &state.bad {
                    let short = &bad[..7.min(bad.len())];
                    println!("\nBisect complete! First bad commit: {}", short);
                    let commit = repo.read_commit(bad)?;
                    println!("    {}", commit.message.lines().next().unwrap_or(""));
                    println!("\nUse `codetree bisect reset` to return to the original HEAD.");
                }
            }
        }
        BisectAction::Log => {
            let state = BisectState::load(&current_dir)?;
            if !state.is_active() {
                println!("No bisect in progress.");
                return Ok(());
            }
            println!("Bisect state:");
            if let Some(bad) = &state.bad {
                println!("  bad:     {}", &bad[..7.min(bad.len())]);
            }
            for g in &state.good {
                println!("  good:    {}", &g[..7.min(g.len())]);
            }
            if let Some(cur) = &state.current {
                println!("  current: {}", &cur[..7.min(cur.len())]);
            }
        }
        BisectAction::Reset => {
            let state = BisectState::load(&current_dir)?;
            if let Some(branch) = &state.original_branch {
                git_manager.checkout_branch(branch).await?;
                println!("Restored branch '{}'.", branch);
            } else if let Some(head) = &state.original_head {
                git_manager.goto_commit(head).await?;
                println!("Restored HEAD '{}'.", &head[..7.min(head.len())]);
            }
            BisectState::clear(&current_dir)?;
            println!("Bisect session ended.");
        }
    }

    Ok(())
}

/// Count how many commits remain between the bad commit and the nearest
/// good ancestor (exclusive on both ends).
fn remaining_count(repo: &crate::vcs::Repository, state: &BisectState) -> Result<usize> {
    let Some(bad) = &state.bad else {
        return Ok(0);
    };
    let mut count: usize = 0;
    let mut current = bad.clone();
    loop {
        if state.good.contains(&current) {
            break;
        }
        count += 1;
        let commit = repo.read_commit(&current)?;
        if commit.parents.is_empty() {
            break;
        }
        current = commit.parents[0].clone();
    }
    Ok(count.saturating_sub(1usize))
}