codetree 0.1.2

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

/// Create a bundle (tar archive) of the CodeTree repository state.
/// Includes: objects/, refs/, HEAD, branches.json, ops.json, config.toml,
/// resolutions.json, frozen.json, locks.json, candidates.json, snapshots.json.
/// Excludes: ops_backups/ (transient), pending_resolution.json (transient).
pub async fn bundle_command(output: Option<String>) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let codetree_dir = current_dir.join(".codetree");

    if !codetree_dir.exists() {
        bail!("No CodeTree repository found. Run 'codetree init' first.");
    }

    let output_path = match output {
        Some(p) => PathBuf::from(p),
        None => {
            let timestamp = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            current_dir.join(format!("codetree-bundle-{}.tar.gz", timestamp))
        }
    };

    // Build the tar archive using the tar crate (already a dependency via Cargo.toml? check).
    // We'll use std::process::Command to call tar CLI to avoid adding a dependency.
    let tar_check = std::process::Command::new("tar").arg("--version").output();
    if tar_check.is_err() {
        bail!("'tar' CLI not found. Install tar to create bundles.");
    }

    // Create the tar.gz archive of .codetree/, excluding transient files.
    let tar_output = std::process::Command::new("tar")
        .args([
            "-czf",
            output_path.to_str().unwrap_or("bundle.tar.gz"),
            "--exclude=.codetree/ops_backups",
            "--exclude=.codetree/pending_resolution.json",
            ".codetree",
        ])
        .current_dir(&current_dir)
        .output()
        .context("Failed to run tar")?;

    if !tar_output.status.success() {
        let stderr = String::from_utf8_lossy(&tar_output.stderr);
        bail!("Failed to create bundle: {}", stderr);
    }

    // Get file size.
    let size = std::fs::metadata(&output_path)
        .map(|m| m.len())
        .unwrap_or(0);

    println!("Bundle created: {}", output_path.display());
    println!("Size: {} bytes ({:.1} KB)", size, size as f64 / 1024.0);
    println!("\nRestore with: codetree unbundle {}", output_path.display());

    Ok(())
}

/// Restore a CodeTree repository from a bundle (tar archive).
/// Extracts the archive in the current directory, overwriting any existing
/// .codetree/ state.
pub async fn unbundle_command(bundle_path: String) -> Result<()> {
    let current_dir = std::env::current_dir()
        .context("Failed to get current directory")?;
    let bundle = PathBuf::from(&bundle_path);

    if !bundle.exists() {
        bail!("Bundle file not found: {}", bundle.display());
    }

    let tar_check = std::process::Command::new("tar").arg("--version").output();
    if tar_check.is_err() {
        bail!("'tar' CLI not found. Install tar to extract bundles.");
    }

    // If .codetree already exists, warn the user.
    let codetree_dir = current_dir.join(".codetree");
    if codetree_dir.exists() {
        // Back up the existing state.
        let backup_name = format!(".codetree.backup.{}", std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0));
        std::fs::rename(&codetree_dir, current_dir.join(&backup_name))?;
        println!("Existing .codetree/ backed up to {}", backup_name);
    }

    let tar_output = std::process::Command::new("tar")
        .args(["-xzf", bundle.to_str().unwrap_or("bundle.tar.gz")])
        .current_dir(&current_dir)
        .output()
        .context("Failed to run tar")?;

    if !tar_output.status.success() {
        let stderr = String::from_utf8_lossy(&tar_output.stderr);
        bail!("Failed to extract bundle: {}", stderr);
    }

    // Restore the working tree to match HEAD.
    let git_manager = crate::vcs::VcsManager::new(current_dir.clone())?;
    let head = git_manager.get_head_hash()?;
    git_manager.sync_index_to_commit(&head)?;
    git_manager.restore_working_tree_pub(&head)?;

    println!("Bundle restored from: {}", bundle.display());
    println!("CodeTree repository is ready in: {}", current_dir.display());

    Ok(())
}