use crate::error::{Context, Result};
use std::path::PathBuf;
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))
}
};
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.");
}
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(¤t_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);
}
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(())
}
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.");
}
let codetree_dir = current_dir.join(".codetree");
if codetree_dir.exists() {
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(¤t_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);
}
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(())
}