codetree 0.1.2

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

use crate::vcs::VcsManager;
use crate::branch::BranchManager;

/// Import commits from a Git repository into CodeTree.
/// Uses `git` CLI as a subprocess (not a library dependency).
/// One-way bridge: reads Git history and recreates it in CodeTree's object store.
pub async fn import_command(force: bool) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;

    // Check for .git directory.
    if !current_dir.join(".git").exists() {
        bail!("No Git repository found (.git directory missing). Run in a Git repo to import.");
    }

    // Check if CodeTree is already initialized.
    let codetree_dir = current_dir.join(".codetree");
    if codetree_dir.exists() && !force {
        bail!("CodeTree already initialized. Use --force to reimport.");
    }

    // Verify git is available.
    let git_check = Command::new("git").arg("--version").output();
    if git_check.is_err() {
        bail!("'git' CLI not found. Install git to use the import feature.");
    }

    // Get the current branch name from Git.
    let git_branch = String::from_utf8(
        Command::new("git")
            .args(["rev-parse", "--abbrev-ref", "HEAD"])
            .current_dir(&current_dir)
            .output()
            .context("Failed to get Git branch")?
            .stdout
    ).unwrap_or_default().trim().to_string();

    println!("Importing from Git branch: {}", git_branch);

    // Get commit list (oldest first).
    let log_output = Command::new("git")
        .args(["log", "--reverse", "--format=%H|%an <%ae>|%at|%s"])
        .current_dir(&current_dir)
        .output()
        .context("Failed to get Git log")?;

    if !log_output.status.success() {
        bail!("Failed to read Git log: {}", String::from_utf8_lossy(&log_output.stderr));
    }

    let log = String::from_utf8_lossy(&log_output.stdout);
    let commits: Vec<&str> = log.lines().filter(|l| !l.is_empty()).collect();

    if commits.is_empty() {
        bail!("No commits found in Git repository");
    }

    println!("Found {} commits to import", commits.len());

    // Initialize CodeTree (remove existing if --force).
    if codetree_dir.exists() {
        std::fs::remove_dir_all(&codetree_dir)
            .context("Failed to remove existing .codetree directory")?;
    }

    let git_manager = VcsManager::init_at(&current_dir)?;
    let branch_manager = BranchManager::new(
        current_dir.join(".codetree").join("branches.json")
    ).await?;

    let mut imported = 0;
    let mut first_commit: Option<String> = None;

    for line in &commits {
        let parts: Vec<&str> = line.splitn(4, '|').collect();
        if parts.len() < 4 {
            continue;
        }
        let git_hash = parts[0];
        let author = parts[1];
        let timestamp: u64 = parts[2].parse().unwrap_or(0);
        let message = parts[3];

        // Extract the commit's tree using git archive.
        // Write files to the working directory, then stage + commit.
        // First, clean the working directory of tracked files.
        // Use git checkout to restore the tree.
        let checkout = Command::new("git")
            .args(["checkout", git_hash, "--", "."])
            .current_dir(&current_dir)
            .output();

        if checkout.is_err() || !checkout.as_ref().map(|o| o.status.success()).unwrap_or(false) {
            // Fallback: use git archive to extract.
            let archive_result = Command::new("git")
                .args(["archive", git_hash])
                .current_dir(&current_dir)
                .output();

            if let Ok(archive) = archive_result
                && archive.status.success() && !archive.stdout.is_empty()
            {
                // Extract tar to working directory.
                let _ = Command::new("tar")
                    .args(["-xf", "-"])
                    .current_dir(&current_dir)
                    .stdin(std::process::Stdio::piped())
                    .stdout(std::process::Stdio::null())
                    .stderr(std::process::Stdio::null())
                    .spawn()
                    .and_then(|mut child| {
                        use std::io::Write;
                        if let Some(stdin) = child.stdin.as_mut() {
                            let _ = stdin.write_all(&archive.stdout);
                        }
                        child.wait()
                    });
            }
        }

        // Remove .git from working tree (we don't want it in CodeTree).
        // The walk_working_tree already skips .git, so this is fine.

        // Stage all files and commit with original metadata.
        git_manager.add_all().await?;
        let commit_id = git_manager.commit_with_meta(message, author, timestamp).await?;

        if first_commit.is_none() {
            first_commit = Some(commit_id.clone());
        }

        imported += 1;
        if imported % 10 == 0 || imported == commits.len() {
            println!("  Imported {}/{} commits", imported, commits.len());
        }
    }

    // Register the base branch in branch manager.
    if let Some(first) = first_commit {
        let _ = branch_manager;
        println!("Base branch 'main' starts at commit {}", &first[..7.min(first.len())]);
    }

    // Restore working tree to the latest commit (HEAD).
    let head = git_manager.get_head_hash()?;
    git_manager.sync_index_to_commit(&head)?;
    git_manager.restore_working_tree_pub(&head)?;

    println!("\nImport complete: {} commits imported from Git to CodeTree", imported);
    println!("Branch: main (imported from Git '{}')", git_branch);
    println!("Note: Git history (.git) is preserved. Remove it with 'rm -rf .git' if desired.");

    Ok(())
}

/// Export commits from CodeTree to a Git repository.
/// Uses `git` CLI as a subprocess. One-way bridge: reads CodeTree history
/// and recreates it in a Git repo for PR creation and collaboration.
pub async fn export_command() -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;

    // Check for CodeTree repo.
    if !current_dir.join(".codetree").exists() {
        bail!("No CodeTree repository found. Run in a CodeTree repo to export.");
    }

    let git_manager = VcsManager::new(current_dir.clone())?;

    // Verify git is available.
    let git_check = Command::new("git").arg("--version").output();
    if git_check.is_err() {
        bail!("'git' CLI not found. Install git to use the export feature.");
    }

    // Initialize Git repo if needed.
    if !current_dir.join(".git").exists() {
        let init = Command::new("git")
            .args(["init"])
            .current_dir(&current_dir)
            .output()
            .context("Failed to init Git repo")?;
        if !init.status.success() {
            bail!("Failed to initialize Git repo: {}", String::from_utf8_lossy(&init.stderr));
        }
        println!("Initialized Git repository");
    }

    // Disable hooks for the export.
    let _ = Command::new("git")
        .args(["config", "core.hooksPath", "/dev/null"])
        .current_dir(&current_dir)
        .output();

    // Walk CodeTree commits from HEAD back to the root (oldest first).
    let head = git_manager.get_head_hash()?;
    let mut commits: Vec<(String, String, String, u64)> = Vec::new(); // (hash, author, message, timestamp)
    let mut current = head.clone();
    loop {
        let commit = git_manager.repo().read_commit(&current)?;
        commits.push((
            current.clone(),
            commit.author.clone(),
            commit.message.clone(),
            commit.timestamp,
        ));
        if commit.parents.is_empty() {
            break;
        }
        current = commit.parents[0].clone();
    }
    commits.reverse(); // oldest first

    println!("Exporting {} commits from CodeTree to Git", commits.len());

    let mut exported = 0;
    for (hash, author, message, timestamp) in &commits {
        // Restore the working tree to this commit.
        git_manager.restore_working_tree_pub(hash)?;
        git_manager.sync_index_to_commit(hash)?;

        // Stage all files in Git.
        let add = Command::new("git")
            .args(["add", "."])
            .current_dir(&current_dir)
            .output()
            .context("git add failed")?;
        if !add.status.success() {
            eprintln!("Warning: git add failed at commit {}", &hash[..7.min(hash.len())]);
        }

        // Create a Git commit with the original metadata.
        // Use GIT_AUTHOR_DATE and GIT_COMMITTER_DATE for timestamp fidelity.
        let date_str = format!("{}", timestamp);
        let commit_result = Command::new("git")
            .args(["commit", "-m", message])
            .env("GIT_AUTHOR_NAME", author.split('<').next().unwrap_or("CodeTree").trim())
            .env("GIT_AUTHOR_EMAIL", author.split('<').nth(1).and_then(|s| s.strip_suffix('>').map(|s| s.trim())).unwrap_or("agent@codetree"))
            .env("GIT_AUTHOR_DATE", &date_str)
            .env("GIT_COMMITTER_DATE", &date_str)
            .current_dir(&current_dir)
            .output()
            .context("git commit failed")?;

        if !commit_result.status.success() {
            let stderr = String::from_utf8_lossy(&commit_result.stderr);
            if stderr.contains("nothing to commit") {
                // Empty tree — create an empty commit.
                let _ = Command::new("git")
                    .args(["commit", "--allow-empty", "-m", message])
                    .env("GIT_AUTHOR_NAME", author.split('<').next().unwrap_or("CodeTree").trim())
                    .env("GIT_AUTHOR_EMAIL", author.split('<').nth(1).and_then(|s| s.strip_suffix('>').map(|s| s.trim())).unwrap_or("agent@codetree"))
                    .env("GIT_AUTHOR_DATE", &date_str)
                    .env("GIT_COMMITTER_DATE", &date_str)
                    .current_dir(&current_dir)
                    .output();
            } else {
                eprintln!("Warning: git commit failed at commit {}: {}", &hash[..7.min(hash.len())], stderr);
            }
        }

        exported += 1;
        if exported % 10 == 0 || exported == commits.len() {
            println!("  Exported {}/{} commits", exported, commits.len());
        }
    }

    // Restore working tree to HEAD.
    git_manager.restore_working_tree_pub(&head)?;
    git_manager.sync_index_to_commit(&head)?;

    println!("\nExport complete: {} commits exported from CodeTree to Git", exported);
    println!("You can now use 'git push' and 'gh pr create' for collaboration.");

    Ok(())
}