use crate::error::{Context, Result};
use std::process::Command;
use crate::vcs::VcsManager;
use crate::branch::BranchManager;
pub async fn import_command(force: bool) -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
if !current_dir.join(".git").exists() {
bail!("No Git repository found (.git directory missing). Run in a Git repo to import.");
}
let codetree_dir = current_dir.join(".codetree");
if codetree_dir.exists() && !force {
bail!("CodeTree already initialized. Use --force to reimport.");
}
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.");
}
let git_branch = String::from_utf8(
Command::new("git")
.args(["rev-parse", "--abbrev-ref", "HEAD"])
.current_dir(¤t_dir)
.output()
.context("Failed to get Git branch")?
.stdout
).unwrap_or_default().trim().to_string();
println!("Importing from Git branch: {}", git_branch);
let log_output = Command::new("git")
.args(["log", "--reverse", "--format=%H|%an <%ae>|%at|%s"])
.current_dir(¤t_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());
if codetree_dir.exists() {
std::fs::remove_dir_all(&codetree_dir)
.context("Failed to remove existing .codetree directory")?;
}
let git_manager = VcsManager::init_at(¤t_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];
let checkout = Command::new("git")
.args(["checkout", git_hash, "--", "."])
.current_dir(¤t_dir)
.output();
if checkout.is_err() || !checkout.as_ref().map(|o| o.status.success()).unwrap_or(false) {
let archive_result = Command::new("git")
.args(["archive", git_hash])
.current_dir(¤t_dir)
.output();
if let Ok(archive) = archive_result
&& archive.status.success() && !archive.stdout.is_empty()
{
let _ = Command::new("tar")
.args(["-xf", "-"])
.current_dir(¤t_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()
});
}
}
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());
}
}
if let Some(first) = first_commit {
let _ = branch_manager;
println!("Base branch 'main' starts at commit {}", &first[..7.min(first.len())]);
}
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(())
}
pub async fn export_command() -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
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())?;
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.");
}
if !current_dir.join(".git").exists() {
let init = Command::new("git")
.args(["init"])
.current_dir(¤t_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");
}
let _ = Command::new("git")
.args(["config", "core.hooksPath", "/dev/null"])
.current_dir(¤t_dir)
.output();
let head = git_manager.get_head_hash()?;
let mut commits: Vec<(String, String, String, u64)> = Vec::new(); let mut current = head.clone();
loop {
let commit = git_manager.repo().read_commit(¤t)?;
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();
println!("Exporting {} commits from CodeTree to Git", commits.len());
let mut exported = 0;
for (hash, author, message, timestamp) in &commits {
git_manager.restore_working_tree_pub(hash)?;
git_manager.sync_index_to_commit(hash)?;
let add = Command::new("git")
.args(["add", "."])
.current_dir(¤t_dir)
.output()
.context("git add failed")?;
if !add.status.success() {
eprintln!("Warning: git add failed at commit {}", &hash[..7.min(hash.len())]);
}
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(¤t_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") {
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(¤t_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());
}
}
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(())
}