use crate::error::{Context, Result};
use crate::branch::{BranchManager, BranchStatus};
use crate::vcs::VcsManager;
use crate::lock::LockManager;
use crate::ops::{Operation, OperationLog};
use super::load_config;
use super::get_active_op_branches_sorted;
use super::auto_snapshot;
use super::save_command;
#[allow(clippy::too_many_arguments)]
pub async fn start_command(description: String, parallel: bool, worktree: bool, branchless: bool, files: Option<Vec<String>>, depends_on: Option<Vec<String>>, template: Option<String>, tags: Option<Vec<String>>, agent_id: Option<String>, wait: bool) -> Result<()> {
if !parallel && !worktree {
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 mut branch_manager = BranchManager::new(
current_dir.join(".codetree").join("branches.json")
).await?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs();
let slug = crate::utils::slugify(&description);
let branch_prefix = if let Some(template_name) = &template {
if let Some(tmpl) = config.get_template(template_name) {
tmpl.branch_prefix.as_deref().unwrap_or(&config.git.branch_prefix)
} else {
return Err(format!("Unknown template: '{}'", template_name).into());
}
} else {
&config.git.branch_prefix
};
let branch_name = format!("{}_{}_{}", branch_prefix, timestamp, slug);
let current_branch = git_manager.get_current_branch().await?;
let base_branch = if let Some(branch) = branch_manager.get_branch(¤t_branch) {
if matches!(branch.status, BranchStatus::Active) {
if parallel || worktree {
info!("Creating parallel operation '{}' on branch '{}'", description, branch_name);
} else {
info!("Stacking operation '{}' on branch '{}'", description, branch_name);
}
current_branch.clone()
} else {
config.git.base_branch.clone()
}
} else {
config.git.base_branch.clone()
};
let file_list = files.unwrap_or_default();
let deps = depends_on.unwrap_or_default();
let tag_list = tags.unwrap_or_default();
if branchless {
branch_manager.register_branch_full_no_save(&branch_name, file_list.clone(), description, deps.clone(), template.clone(), tag_list.clone(), agent_id.clone()).await
.context("Failed to register branch")?;
if let Some(branch) = branch_manager.branches.get_mut(&branch_name) {
branch.branchless = true;
}
branch_manager.save().await?;
println!("Created branchless bookmark: {} (on {})", branch_name, current_branch);
} else if worktree {
let worktree_path = current_dir.join(".codetree").join("worktrees").join(&branch_name);
tokio::fs::create_dir_all(&worktree_path).await
.context("Failed to create worktree directory")?;
git_manager.add_worktree_new_branch(&branch_name, &worktree_path, &base_branch).await
.context("Failed to add worktree")?;
branch_manager.register_branch_full_no_save(&branch_name, file_list.clone(), description, deps.clone(), template.clone(), tag_list.clone(), agent_id.clone()).await
.context("Failed to register branch")?;
branch_manager.set_branch_worktree_no_save(&branch_name, worktree_path.clone()).await?;
branch_manager.save().await?;
println!("Created operation in worktree: {} at {:?}", branch_name, worktree_path);
} else {
git_manager.create_branch(&branch_name, Some(&base_branch)).await
.context("Failed to create branch")?;
if parallel {
branch_manager.register_branch_full_no_save(&branch_name, file_list.clone(), description, deps.clone(), template.clone(), tag_list.clone(), agent_id.clone()).await
.context("Failed to register branch")?;
branch_manager.save().await?;
println!("Created parallel operation on branch: {} (stay on {})", branch_name, current_branch);
} else {
git_manager.checkout_branch(&branch_name).await
.context("Failed to checkout branch")?;
branch_manager.register_branch_full_no_save(&branch_name, file_list.clone(), description, deps.clone(), template.clone(), tag_list.clone(), agent_id.clone()).await
.context("Failed to register branch")?;
if base_branch != config.git.base_branch {
branch_manager.set_parent_branch_no_save(&branch_name, &base_branch).await?;
}
branch_manager.save().await?;
}
}
if !file_list.is_empty() {
let locks_path = current_dir.join(".codetree").join("locks.json");
if wait {
let max_attempts = 150;
for attempt in 0..max_attempts {
let conflicts = LockManager::load(locks_path.clone())?
.conflicts(&file_list, &branch_name);
if conflicts.is_empty() {
break;
}
if attempt == 0 {
info!("Waiting for file locks: {}", conflicts.iter()
.map(|(f, h)| format!("{} (held by {})", f, h))
.collect::<Vec<_>>().join(", "));
}
if attempt == max_attempts - 1 {
bail!("Timed out waiting for file locks after 5 minutes: {}",
conflicts.iter().map(|(f, h)| format!("{} (held by {})", f, h))
.collect::<Vec<_>>().join(", "));
}
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}
}
LockManager::update_atomically(locks_path.clone(), |m| {
m.acquire(&file_list, &branch_name)
})?;
info!("Acquired {} file lock(s) for operation '{}'", file_list.len(), branch_name);
}
let ops_path = current_dir.join(".codetree").join("ops.json");
let mut op_log = OperationLog::new(&ops_path).await?;
op_log.push(Operation::Start {
branch: branch_name.clone(),
timestamp: crate::branch::now_ts(),
agent_id: agent_id.clone(),
});
op_log.save(&ops_path).await?;
Ok(())
}
pub async fn goto_command(commit: String) -> Result<()> {
auto_snapshot().await;
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
git_manager.goto_commit(&commit).await?;
let short = &commit[..7.min(commit.len())];
println!("Checked out commit {} (detached HEAD)", short);
println!("Use 'codetree switch <branch>' to return to a branch");
Ok(())
}
pub async fn next_commit_command() -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let repo = git_manager.repo();
let head_id = repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let branches = repo.refs().list_branches()?;
for branch in &branches {
if let Some(branch_tip) = repo.refs().get_branch(branch)? {
let mut current = branch_tip.clone();
let mut found_child = None;
loop {
let commit = repo.read_commit(¤t)?;
if !commit.parents.is_empty() && commit.parents[0] == head_id {
found_child = Some(current.clone());
break;
}
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
if let Some(child) = found_child {
git_manager.goto_commit(&child).await?;
let short = &child[..7.min(child.len())];
println!("Moved to next commit: {}", short);
return Ok(());
}
}
}
bail!("No next commit found (HEAD has no children on any branch)");
}
pub async fn prev_commit_command() -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let repo = git_manager.repo();
let head_id = repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let commit = repo.read_commit(&head_id)?;
if commit.parents.is_empty() {
bail!("No previous commit (HEAD is the root commit)");
}
let parent = &commit.parents[0];
git_manager.goto_commit(parent).await?;
let short = &parent[..7.min(parent.len())];
println!("Moved to previous commit: {}", short);
Ok(())
}
pub async fn restack_graph_command() -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let repo = git_manager.repo();
let branches = repo.refs().list_branches()?;
let mut repaired = 0;
for branch in &branches {
if let Some(tip) = repo.refs().get_branch(branch)? {
let mut current = tip.clone();
loop {
let commit = match repo.read_commit(¤t) {
Ok(c) => c,
Err(_) => {
repaired += 1;
break;
}
};
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
}
}
if repaired == 0 {
println!("No restack needed — commit graph is consistent.");
} else {
println!("Restacked {} broken commit(s).", repaired);
}
Ok(())
}
pub async fn branch_rename_command(old_name: String, new_name: String) -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
git_manager.repo().refs().rename_branch(&old_name, &new_name)?;
println!("Renamed branch '{}' to '{}'", old_name, new_name);
Ok(())
}
pub async fn branch_advance_command(name: String, commit: Option<String>) -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let repo = git_manager.repo();
let head_id = repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let target_id = if let Some(spec) = commit {
git_manager.resolve_commit_pub(&spec, &head_id)?
} else {
head_id
};
if repo.refs().get_branch(&name)?.is_none() {
bail!("Branch '{}' not found", name);
}
repo.refs().set_branch(&name, &target_id)?;
let short = &target_id[..7.min(target_id.len())];
println!("Advanced branch '{}' to {}", name, short);
Ok(())
}
pub async fn switch_command(branch_name: String) -> Result<()> {
let config = load_config(None).await?;
if config.auto.save_on_switch {
let git_manager = VcsManager::new(std::env::current_dir()
.context("Failed to get current directory")?)?;
let status = git_manager.get_status().await?;
if !status.modified.is_empty() || !status.untracked.is_empty() {
save_command(vec![], false, false, None).await?;
}
} else {
auto_snapshot().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?;
if branch_name == "-" {
let last_path = current_dir.join(".codetree").join("last_branch");
let last_branch = std::fs::read_to_string(&last_path)
.context("No previous branch to switch to. Use 'codetree switch <branch>' first.")?;
let last_branch = last_branch.trim().to_string();
if last_branch.is_empty() {
bail!("No previous branch recorded");
}
let current = git_manager.get_current_branch().await?;
if current == last_branch {
println!("Already on branch: {}", last_branch);
return Ok(());
}
crate::atomic::write_atomic(&last_path, current.as_bytes())?;
git_manager.checkout_branch(&last_branch).await
.context("Failed to checkout branch")?;
println!("Switched to branch: {}", last_branch);
return Ok(());
}
if let Some(branch) = branch_manager.get_branch(&branch_name) {
if !matches!(branch.status, BranchStatus::Active) {
return Err(format!("Branch '{}' is not active (status: {})", branch_name, branch.status.as_str()).into());
}
} else {
return Err(format!("Branch '{}' is not tracked by codetree", branch_name).into());
}
let current = git_manager.get_current_branch().await?;
if current == branch_name {
println!("Already on branch: {}", branch_name);
return Ok(());
}
let status = git_manager.get_status().await?;
let dirty = !status.modified.is_empty() || !status.untracked.is_empty() || !status.staged.is_empty();
if dirty {
warn!("Switching from '{}' with uncommitted changes; they will be left in working tree", current);
}
let last_path = current_dir.join(".codetree").join("last_branch");
crate::atomic::write_atomic(&last_path, current.as_bytes())?;
git_manager.checkout_branch(&branch_name).await
.context("Failed to checkout branch")?;
println!("Switched to branch: {}", branch_name);
Ok(())
}
pub async fn next_command() -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let current = git_manager.get_current_branch().await?;
let branches = get_active_op_branches_sorted(¤t_dir).await?;
if branches.is_empty() {
return Err("No active operations to switch to".into());
}
let target = if let Some(pos) = branches.iter().position(|b| b == ¤t) {
branches[(pos + 1) % branches.len()].clone()
} else {
branches[0].clone()
};
if target == current {
println!("Already on the last operation; wrapping to first: {}", target);
}
switch_command(target.clone()).await?;
println!("Next operation: {}", target);
Ok(())
}
pub async fn prev_command() -> Result<()> {
let current_dir = std::env::current_dir()
.context("Failed to get current directory")?;
let git_manager = VcsManager::new(current_dir.clone())?;
let current = git_manager.get_current_branch().await?;
let branches = get_active_op_branches_sorted(¤t_dir).await?;
if branches.is_empty() {
return Err("No active operations to switch to".into());
}
let target = if let Some(pos) = branches.iter().position(|b| b == ¤t) {
if pos == 0 {
branches[branches.len() - 1].clone()
} else {
branches[pos - 1].clone()
}
} else {
branches[branches.len() - 1].clone()
};
if target == current {
println!("Already on the first operation; wrapping to last: {}", target);
}
switch_command(target.clone()).await?;
println!("Previous operation: {}", target);
Ok(())
}