use crate::error::{Context, Result};
use crate::branch::BranchManager;
use crate::config::Config;
use crate::vcs::VcsManager;
pub async fn init_command(force: bool) -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
info!("Initializing codetree in: {}", current_dir.display());
let config_path = current_dir.join(".codetree").join("config.toml");
if config_path.exists() && !force {
return Err("CodeTree already initialized. Use --force to reinitialize.".into());
}
let _vcs_manager = if current_dir.join(".codetree").exists() {
VcsManager::new(current_dir.clone())?
} else {
info!("Initializing native VCS repository...");
VcsManager::init_at(¤t_dir)?
};
let codetree_dir = current_dir.join(".codetree");
tokio::fs::create_dir_all(&codetree_dir).await
.context("Failed to create .codetree directory")?;
let config = Config::default();
config.save(&config_path).await
.context("Failed to save configuration")?;
let branch_manager = BranchManager::new(codetree_dir.join("branches.json")).await?;
branch_manager.save().await
.context("Failed to initialize branches database")?;
let gitignore_path = current_dir.join(".gitignore");
let gitignore_content = if gitignore_path.exists() {
tokio::fs::read_to_string(&gitignore_path).await
.context("Failed to read .gitignore")?
} else {
String::new()
};
if !gitignore_content.contains(".codetree") {
let updated_content = if gitignore_content.is_empty() {
".codetree/\n".to_string()
} else {
format!("{}\n.codetree/\n", gitignore_content.trim_end())
};
tokio::fs::write(&gitignore_path, updated_content).await
.context("Failed to update .gitignore")?;
info!("Added .codetree/ to .gitignore");
}
println!("CodeTree initialized");
println!("Config: {}", config_path.display());
Ok(())
}