use crate::error::{Context, Result};
use crate::branch::{BranchManager, BranchStatus};
use crate::vcs::VcsManager;
use super::{load_config, auto_snapshot};
pub async fn sync_command() -> Result<()> {
let config = load_config(None).await?;
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_check = std::process::Command::new("git").arg("--version").output();
if git_check.is_err() {
bail!("'git' CLI not found. sync requires git for remote operations.");
}
if !current_dir.join(".git").exists() {
bail!("No Git repository found. Run 'codetree export' first to create one, then 'codetree sync'.");
}
let remote = &config.git.remote_name;
let base_branch = &config.git.base_branch;
println!("Pulling from {}/{}...", remote, base_branch);
let pull_output = tokio::process::Command::new("git")
.args(["pull", remote, base_branch])
.current_dir(¤t_dir)
.output()
.await
.context("Failed to run git pull")?;
if !pull_output.status.success() {
let stderr = String::from_utf8_lossy(&pull_output.stderr);
bail!("git pull failed: {}", stderr.trim());
}
let stdout = String::from_utf8_lossy(&pull_output.stdout);
if !stdout.trim().is_empty() {
println!("{}", stdout.trim());
}
println!("\nRebasing active branches onto {}...", base_branch);
rebase_command(false).await?;
Ok(())
}
pub async fn rebase_command(dry_run: bool) -> Result<()> {
if !dry_run {
auto_snapshot().await;
}
let config = load_config(None).await?;
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let branch_manager = BranchManager::new(
current_dir.join(".codetree").join("branches.json")
).await?;
let active_branches: Vec<_> = branch_manager.list_branches()
.into_iter()
.filter(|b| matches!(b.status, BranchStatus::Active) && !b.branchless)
.collect();
if active_branches.is_empty() {
println!("No active branched operations to rebase");
return Ok(());
}
let base_branch = &config.git.base_branch;
let branch_names: Vec<String> = active_branches.iter()
.filter(|b| b.name != *base_branch)
.map(|b| b.name.clone())
.collect();
let mut parent_map: std::collections::HashMap<String, String> = std::collections::HashMap::new();
for name in &branch_names {
let parent = branch_manager.get_parent_branch(name)
.map(|p| p.to_string())
.unwrap_or_else(|| {
git_manager.get_branch_parent(name, base_branch, &branch_names)
.unwrap_or_else(|_| base_branch.clone())
});
parent_map.insert(name.clone(), parent);
}
let mut order: Vec<String> = Vec::new();
let mut processed: std::collections::HashSet<String> = std::collections::HashSet::new();
processed.insert(base_branch.clone());
while order.len() < branch_names.len() {
let mut progressed = false;
for name in &branch_names {
if processed.contains(name) {
continue;
}
let parent = parent_map.get(name).unwrap();
if processed.contains(parent) {
order.push(name.clone());
processed.insert(name.clone());
progressed = true;
}
}
if !progressed {
for name in &branch_names {
if !processed.contains(name) {
order.push(name.clone());
processed.insert(name.clone());
}
}
}
}
let mut rebased = 0;
let mut skipped = 0;
let mut failed = Vec::new();
for branch_name in &order {
let parent = parent_map.get(branch_name).unwrap();
match git_manager.is_branch_behind(branch_name, parent) {
Ok(true) => {
if dry_run {
rebased += 1;
if parent == base_branch {
println!("[dry-run] Would rebase '{}' onto '{}'", branch_name, parent);
} else {
println!("[dry-run] Would rebase '{}' onto parent '{}'", branch_name, parent);
}
} else {
match git_manager.rebase_branch(branch_name, parent).await {
Ok(()) => {
rebased += 1;
if parent == base_branch {
println!("Rebased '{}' onto '{}'", branch_name, parent);
} else {
println!("Rebased '{}' onto parent '{}'", branch_name, parent);
}
}
Err(e) => {
failed.push((branch_name.clone(), e.to_string()));
println!("Failed to rebase '{}': {}", branch_name, e);
}
}
}
}
Ok(false) => {
skipped += 1;
println!("Skipped '{}': already up to date with '{}'", branch_name, parent);
}
Err(e) => {
failed.push((branch_name.clone(), e.to_string()));
println!("Failed to check '{}' status: {}", branch_name, e);
}
}
}
println!("\nRebase summary: {} rebased, {} up-to-date, {} failed",
rebased, skipped, failed.len()
);
if !failed.is_empty() {
return Err(format!("Failed to rebase {} branch(es): {}",
failed.len(),
failed.iter().map(|(name, err)| format!("{} ({})", name, err)).collect::<Vec<_>>().join(", ")
).into());
}
Ok(())
}
pub async fn restack_command() -> Result<()> {
let config = load_config(None).await?;
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let branch_manager = BranchManager::new(
current_dir.join(".codetree").join("branches.json")
).await?;
let active_branches: Vec<_> = branch_manager.list_branches()
.into_iter()
.filter(|b| matches!(b.status, BranchStatus::Active) && !b.branchless)
.collect();
if active_branches.is_empty() {
println!("No active branched operations to restack");
return Ok(());
}
let base_branch = &config.git.base_branch;
let branch_names: Vec<String> = active_branches.iter()
.filter(|b| b.name != *base_branch)
.map(|b| b.name.clone())
.collect();
let mut parent_map: std::collections::HashMap<String, String> = std::collections::HashMap::new();
for name in &branch_names {
let parent = branch_manager.get_parent_branch(name)
.map(|p| p.to_string())
.unwrap_or_else(|| {
git_manager.get_branch_parent(name, base_branch, &branch_names)
.unwrap_or_else(|_| base_branch.clone())
});
parent_map.insert(name.clone(), parent);
}
let mut broken: Vec<(String, String)> = Vec::new();
for name in &branch_names {
let parent = parent_map.get(name).unwrap();
if parent == base_branch {
continue;
}
if let Ok(true) = git_manager.is_branch_behind(name, parent) {
broken.push((name.clone(), parent.clone()));
}
}
if broken.is_empty() {
println!("All stacked branches are up-to-date with their parents");
return Ok(());
}
println!("Found {} broken stacking relationship(s):", broken.len());
for (name, parent) in &broken {
println!(" {} needs restack onto {}", name, parent);
}
println!();
let mut order: Vec<String> = Vec::new();
let mut processed: std::collections::HashSet<String> = std::collections::HashSet::new();
processed.insert(base_branch.clone());
for name in &branch_names {
if !broken.iter().any(|(b, _)| b == name) {
processed.insert(name.clone());
}
}
while order.len() < broken.len() {
let mut progressed = false;
for (name, _) in &broken {
if processed.contains(name) {
continue;
}
let parent = parent_map.get(name).unwrap();
if processed.contains(parent) {
order.push(name.clone());
processed.insert(name.clone());
progressed = true;
}
}
if !progressed {
for (name, _) in &broken {
if !processed.contains(name) {
order.push(name.clone());
processed.insert(name.clone());
}
}
}
}
let mut rebased = 0;
let mut failed = Vec::new();
for branch_name in &order {
let parent = parent_map.get(branch_name).unwrap();
match git_manager.rebase_branch(branch_name, parent).await {
Ok(()) => {
rebased += 1;
println!("Restacked '{}' onto '{}'", branch_name, parent);
}
Err(e) => {
failed.push((branch_name.clone(), e.to_string()));
println!("Failed to restack '{}': {}", branch_name, e);
}
}
}
println!("\nRestack summary: {} rebased, {} failed", rebased, failed.len());
if !failed.is_empty() {
return Err(format!("Failed to restack {} branch(es): {}",
failed.len(),
failed.iter().map(|(name, err)| format!("{} ({})", name, err)).collect::<Vec<_>>().join(", ")
).into());
}
Ok(())
}