use crate::error::{Context, Result};
use crate::branch::{BranchManager, BranchStatus};
use crate::megamerge::{apply_hunks, diff_hunks, Hunk, MegamergeState};
use crate::provenance::ProvenanceLog;
use crate::vcs::VcsManager;
#[derive(Debug, Clone, serde::Serialize)]
pub struct RoutedChange {
pub operation: String,
pub file: String,
pub hunks: usize,
pub whole_file: bool,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct RouteReport {
pub routed: Vec<RoutedChange>,
pub unrouted: Vec<String>,
pub operations: Vec<String>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct MegamergeOutcome {
pub commit: Option<String>,
pub operations: Vec<String>,
pub conflicts: Vec<String>,
pub aborted: bool,
}
pub async fn megamerge_state(
git_manager: &VcsManager,
branch_manager: &mut BranchManager,
abort: bool,
) -> Result<MegamergeOutcome> {
let current_dir = git_manager.repo_path().to_path_buf();
let existing = MegamergeState::load(¤t_dir)?;
if abort {
let state = existing.ok_or("No megamerge in progress")?;
git_manager.checkout_branch(&state.base_branch).await
.context("Failed to restore the base branch")?;
MegamergeState::clear(¤t_dir)?;
return Ok(MegamergeOutcome {
commit: None,
operations: state.operations,
conflicts: vec![],
aborted: true,
});
}
if existing.is_some() {
return Err("A megamerge is already in progress. Finish it with `codetree absorb --route` or abort with `codetree megamerge --abort`.".into());
}
let base_branch = git_manager.get_current_branch().await?;
let base_commit = git_manager.get_head_hash()?;
let registered: Vec<crate::branch::BranchInfo> =
branch_manager.list_branches().into_iter().cloned().collect();
let mut op_tips: Vec<(String, String)> = Vec::new();
for info in ®istered {
if info.status != BranchStatus::Active || info.name == base_branch {
continue;
}
let tip = if info.branchless {
info.last_commit.clone()
} else {
git_manager.repo().refs().get_branch(&info.name)?
};
if let Some(tip) = tip.filter(|t| !t.is_empty()) {
op_tips.push((info.name.clone(), tip));
}
}
if op_tips.is_empty() {
return Err("No active operations to merge — start an operation first.".into());
}
let (commit, conflicts) = git_manager.create_megamerge(&base_commit, &op_tips)?;
git_manager.detach_head_at(&commit)?;
git_manager.restore_working_tree_pub(&commit)?;
git_manager.sync_index_to_commit(&commit)?;
let state = MegamergeState {
commit: commit.clone(),
operations: op_tips.iter().map(|(n, _)| n.clone()).collect(),
base_branch: base_branch.clone(),
timestamp: crate::branch::now_ts(),
};
state.save(¤t_dir)?;
Ok(MegamergeOutcome {
commit: Some(commit),
operations: state.operations,
conflicts: conflicts.iter().map(|c| c.path.clone()).collect(),
aborted: false,
})
}
pub async fn megamerge_command(abort: bool) -> Result<()> {
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 outcome = megamerge_state(&git_manager, &mut branch_manager, abort).await?;
if outcome.aborted {
println!("Megamerge aborted — back on '{}'", git_manager.get_current_branch().await?);
return Ok(());
}
let commit = outcome.commit.as_deref().unwrap_or("");
println!("Megamerge {}: {} operation(s) merged ({}), {} conflict(s)",
&commit[..7.min(commit.len())],
outcome.operations.len(),
outcome.operations.join(", "),
outcome.conflicts.len());
if !outcome.conflicts.is_empty() {
println!("Cross-operation conflicts: {}", outcome.conflicts.join(", "));
println!("Resolve them in the working tree, then run `codetree absorb --route` to send the work back.");
} else {
println!("Edit across operations, then run `codetree absorb --route` to send the work back.");
}
Ok(())
}
pub async fn route_changes(
git_manager: &VcsManager,
branch_manager: &mut BranchManager,
) -> Result<RouteReport> {
let current_dir = git_manager.repo_path().to_path_buf();
let state = MegamergeState::load(¤t_dir)?
.ok_or("No megamerge in progress — run `codetree megamerge` first")?;
let provenance = ProvenanceLog::load(¤t_dir)?;
let status = git_manager.get_status().await?;
let mut changed: Vec<String> = Vec::new();
changed.extend(status.modified.iter().cloned());
changed.extend(status.untracked.iter().cloned());
changed.extend(status.staged.iter().cloned());
changed.sort();
changed.dedup();
let mut routed: Vec<RoutedChange> = Vec::new();
let mut unrouted: Vec<String> = Vec::new();
let mut op_files: std::collections::HashMap<String, std::collections::HashMap<String, Vec<u8>>> =
std::collections::HashMap::new();
for path in &changed {
let mega_lines: Vec<String> = match git_manager.read_file_at(&state.commit, path)? {
Some(content) => String::from_utf8_lossy(&content)
.lines()
.map(|l| l.to_string())
.collect(),
None => Vec::new(),
};
let disk_content = std::fs::read(current_dir.join(path))?;
let new_lines: Vec<String> = String::from_utf8_lossy(&disk_content)
.lines()
.map(|l| l.to_string())
.collect();
let hunks = diff_hunks(&mega_lines, &new_lines);
if hunks.is_empty() {
continue;
}
let mut versions: Vec<(String, Vec<String>)> = Vec::new();
for op in &state.operations {
if let Some(version) = latest_version_for_op(git_manager, &provenance, op, path)? {
versions.push((op.clone(), version));
}
}
let mut file_hunks: Vec<(String, Hunk)> = Vec::new();
for hunk in &hunks {
let replaced: Vec<String> = mega_lines
.get(hunk.start.saturating_sub(1)..hunk.end.saturating_sub(1))
.map(|s| s.to_vec())
.unwrap_or_default();
let mut owner: Option<(String, usize)> = None;
for (op, version) in &versions {
if let Some(pos) = find_contiguous(version, &replaced) {
owner = Some((op.clone(), pos));
break;
}
}
match owner {
Some((op, pos)) => {
let mut rebased = hunk.clone();
rebased.start = pos + 1;
rebased.end = pos + replaced.len() + 1;
file_hunks.push((op.clone(), rebased));
}
None => {
let reason = if replaced.is_empty() {
"new file has no owning operation"
} else {
"no operation owns the edited lines"
};
unrouted.push(format!("{}: {}", path, reason));
}
}
}
let mut by_op: std::collections::HashMap<String, Vec<Hunk>> = std::collections::HashMap::new();
for (op, hunk) in file_hunks {
by_op.entry(op).or_default().push(hunk);
}
for (op, op_hunks) in by_op {
let tip = operation_tip(git_manager, branch_manager, &op)?;
let base_lines: Vec<String> = match git_manager.read_file_at(&tip, path)? {
Some(content) => String::from_utf8_lossy(&content)
.lines()
.map(|l| l.to_string())
.collect(),
None => Vec::new(),
};
let mut sorted = op_hunks.clone();
sorted.sort_by(|a, b| b.start.cmp(&a.start));
let mut content_lines = base_lines.clone();
for hunk in &sorted {
content_lines = apply_hunks(&content_lines, std::slice::from_ref(hunk));
}
let mut text = content_lines.join("\n");
if !text.is_empty() {
text.push('\n');
}
op_files
.entry(op.clone())
.or_default()
.insert(path.clone(), text.into_bytes());
routed.push(RoutedChange {
operation: op.clone(),
file: path.clone(),
hunks: op_hunks.len(),
whole_file: versions.len() > 1,
});
}
}
let mut touched_ops: Vec<String> = Vec::new();
for (op, files) in &op_files {
let tip = operation_tip(git_manager, branch_manager, op)?;
let file_list: Vec<(String, Vec<u8>)> = files
.iter()
.map(|(path, content)| (path.clone(), content.clone()))
.collect();
let message = format!("Route megamerge changes ({} file(s))", file_list.len());
let new_commit = git_manager.commit_files_on(&tip, &file_list, &message)?;
git_manager.set_branch_tip(op, &new_commit)?;
let mut provenance = ProvenanceLog::load(¤t_dir)?;
provenance.record(&new_commit, op, None, Some("routed from megamerge".to_string()));
provenance.save(¤t_dir)?;
touched_ops.push(op.clone());
}
git_manager.checkout_branch(&state.base_branch).await
.context("Failed to restore the base branch")?;
MegamergeState::clear(¤t_dir)?;
Ok(RouteReport {
routed,
unrouted,
operations: touched_ops,
})
}
fn latest_version_for_op(
git_manager: &VcsManager,
provenance: &ProvenanceLog,
operation: &str,
path: &str,
) -> Result<Option<Vec<String>>> {
let mut latest: Option<String> = None;
for entry in &provenance.entries {
if entry.operation != operation {
continue;
}
let changed = git_manager.files_changed_in_commit(&entry.commit)?;
if changed.iter().any(|f| f == path) {
latest = Some(entry.commit.clone());
}
}
let commit = match latest {
Some(c) => c,
None => return Ok(None),
};
Ok(match git_manager.read_file_at(&commit, path)? {
Some(content) => Some(
String::from_utf8_lossy(&content)
.lines()
.map(|l| l.to_string())
.collect(),
),
None => None,
})
}
fn find_contiguous(haystack: &[String], needle: &[String]) -> Option<usize> {
if needle.is_empty() {
return Some(0);
}
if needle.len() > haystack.len() {
return None;
}
(0..=haystack.len() - needle.len()).find(|&i| &haystack[i..i + needle.len()] == needle)
}
fn operation_tip(
git_manager: &VcsManager,
branch_manager: &BranchManager,
operation: &str,
) -> Result<String> {
if let Some(tip) = git_manager.repo().refs().get_branch(operation)? {
if !tip.is_empty() {
return Ok(tip);
}
}
let info = branch_manager
.get_branch(operation)
.ok_or_else(|| format!("Operation '{}' not found", operation))?;
info.last_commit
.clone()
.ok_or_else(|| format!("Operation '{}' has no commits yet", operation).into())
}