use crate::error::{Context, Result};
use crate::resolution::{ConflictInfo, PendingResolution, ResolutionCache};
use super::objects::{Tree, TreeEntry, Commit};
use super::manager::{MergeResult, ReadyCheck, VcsManager};
impl VcsManager {
pub fn get_branch_divergence(&self, branch_name: &str, base_branch: &str) -> Result<(usize, usize)> {
let branch_id = self
.repo
.refs()
.get_branch(branch_name)?
.unwrap_or_default();
let base_id = self
.repo
.refs()
.get_branch(base_branch)?
.unwrap_or_default();
if branch_id.is_empty() || base_id.is_empty() {
return Ok((0, 0));
}
let merge_base = self.find_merge_base(&branch_id, &base_id)?;
let ahead = self.count_commits_to(&branch_id, &merge_base)?;
let behind = self.count_commits_to(&base_id, &merge_base)?;
Ok((ahead, behind))
}
pub fn is_branch_behind(&self, branch_name: &str, base_branch: &str) -> Result<bool> {
let (_, behind) = self.get_branch_divergence(branch_name, base_branch)?;
Ok(behind > 0)
}
pub fn get_branch_parent(
&self,
branch_name: &str,
base_branch: &str,
candidate_parents: &[String],
) -> Result<String> {
let branch_id = self
.repo
.refs()
.get_branch(branch_name)?
.with_context(|| format!("Branch '{}' not found", branch_name))?;
for parent_name in candidate_parents {
if parent_name == branch_name || parent_name == base_branch {
continue;
}
if let Ok(Some(parent_id)) = self.repo.refs().get_branch(parent_name)
&& let Ok(mb) = self.find_merge_base(&branch_id, &parent_id)
&& mb == parent_id
{
return Ok(parent_name.clone());
}
}
Ok(base_branch.to_string())
}
pub async fn check_ready(&self, branch_name: &str, base_branch: &str) -> Result<ReadyCheck> {
let branch_id = self
.repo
.refs()
.get_branch(branch_name)?
.with_context(|| format!("Branch '{}' not found", branch_name))?;
let base_id = self
.repo
.refs()
.get_branch(base_branch)?
.with_context(|| format!("Base branch '{}' not found", base_branch))?;
let (ahead, behind) = self.get_branch_divergence(branch_name, base_branch)?;
let merge_base = self.find_merge_base(&base_id, &branch_id)?;
let base_tree = self.commit_tree(&merge_base)?;
let our_tree = self.commit_tree(&base_id)?;
let their_tree = self.commit_tree(&branch_id)?;
let (_, conflicts) = self.merge_trees(&base_tree, &our_tree, &their_tree)?;
let cache = ResolutionCache::load(
&self.repo_path.join(".codetree").join("resolutions.json"),
).await?;
let mut auto_resolvable = true;
for conflict in &conflicts {
if cache.get(&conflict.path, &conflict.our_blob, &conflict.their_blob).is_none() {
auto_resolvable = false;
break;
}
}
Ok(ReadyCheck {
ahead,
behind,
up_to_date: behind == 0,
conflict_count: conflicts.len(),
auto_resolvable: conflicts.is_empty() || auto_resolvable,
conflict_files: conflicts.iter().map(|c| c.path.clone()).collect(),
})
}
pub async fn merge_branch_with_cache(
&self,
branch_name: &str,
cache: &ResolutionCache,
) -> Result<MergeResult> {
let branch_id = self
.repo
.refs()
.get_branch(branch_name)?
.with_context(|| format!("Branch '{}' not found", branch_name))?;
let head_id = self
.repo
.refs()
.resolve_head()?
.context("HEAD does not point to a commit")?;
let merge_base = self.find_merge_base(&head_id, &branch_id)?;
let base_tree = self.commit_tree(&merge_base)?;
let our_tree = self.commit_tree(&head_id)?;
let their_tree = self.commit_tree(&branch_id)?;
let (merged_entries, conflicts) = self.merge_trees(&base_tree, &our_tree, &their_tree)?;
if !conflicts.is_empty() {
let mut resolved = true;
let mut final_entries = merged_entries.clone();
for conflict in &conflicts {
if let Some(resolved_blob) = cache.get(&conflict.path, &conflict.our_blob, &conflict.their_blob) {
final_entries.retain(|e: &TreeEntry| e.name != conflict.path);
final_entries.push(TreeEntry {
mode: 0o100644,
name: conflict.path.clone(),
id: resolved_blob.to_string(),
});
} else {
resolved = false;
break;
}
}
if resolved {
let tree = Tree::new(final_entries);
let tree_id = self.repo.write_tree(&tree)?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let commit = Commit::new(
tree_id,
vec![head_id.clone(), branch_id.clone()],
"CodeTree <agent@codetree>".to_string(),
format!("Merge branch '{}' (conflicts auto-resolved)", branch_name),
timestamp,
);
let commit_id = self.repo.write_commit(&commit)?;
if let Some(branch) = self.repo.refs().current_branch()? {
self.repo.refs().set_branch(&branch, &commit_id)?;
}
self.restore_working_tree(&commit_id)?;
self.sync_index_to_head()?;
return Ok(MergeResult {
resolved_from_cache: true,
conflicts,
});
}
let tree = Tree::new(merged_entries);
let tree_id = self.repo.write_tree(&tree)?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let commit = Commit::new(
tree_id,
vec![head_id.clone(), branch_id.clone()],
"CodeTree <agent@codetree>".to_string(),
format!("Merge branch '{}' ({} conflict(s) pending resolution)", branch_name, conflicts.len()),
timestamp,
);
let commit_id = self.repo.write_commit(&commit)?;
if let Some(branch) = self.repo.refs().current_branch()? {
self.repo.refs().set_branch(&branch, &commit_id)?;
}
self.restore_working_tree(&commit_id)?;
self.sync_index_to_head()?;
let pending = PendingResolution {
branch: branch_name.to_string(),
base_branch: head_id,
conflicts: conflicts.clone(),
};
pending.save(&self.pending_resolution_path()).await?;
return Ok(MergeResult {
resolved_from_cache: false,
conflicts,
});
}
let tree = Tree::new(merged_entries);
let tree_id = self.repo.write_tree(&tree)?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let commit = Commit::new(
tree_id,
vec![head_id.clone(), branch_id.clone()],
"CodeTree <agent@codetree>".to_string(),
format!("Merge branch '{}'", branch_name),
timestamp,
);
let commit_id = self.repo.write_commit(&commit)?;
if let Some(branch) = self.repo.refs().current_branch()? {
self.repo.refs().set_branch(&branch, &commit_id)?;
}
self.restore_working_tree(&commit_id)?;
self.sync_index_to_head()?;
Ok(MergeResult {
resolved_from_cache: false,
conflicts: vec![],
})
}
pub async fn squash_merge_branch_with_cache(
&self,
branch_name: &str,
cache: &ResolutionCache,
) -> Result<MergeResult> {
let branch_id = self
.repo
.refs()
.get_branch(branch_name)?
.with_context(|| format!("Branch '{}' not found", branch_name))?;
let head_id = self
.repo
.refs()
.resolve_head()?
.context("HEAD does not point to a commit")?;
let merge_base = self.find_merge_base(&head_id, &branch_id)?;
let base_tree = self.commit_tree(&merge_base)?;
let our_tree = self.commit_tree(&head_id)?;
let their_tree = self.commit_tree(&branch_id)?;
let (merged_entries, conflicts) = self.merge_trees(&base_tree, &our_tree, &their_tree)?;
if !conflicts.is_empty() {
let mut resolved = true;
let mut final_entries = merged_entries.clone();
for conflict in &conflicts {
if let Some(resolved_blob) = cache.get(&conflict.path, &conflict.our_blob, &conflict.their_blob) {
final_entries.retain(|e: &TreeEntry| e.name != conflict.path);
final_entries.push(TreeEntry {
mode: 0o100644,
name: conflict.path.clone(),
id: resolved_blob.to_string(),
});
} else {
resolved = false;
break;
}
}
if resolved {
let tree = Tree::new(final_entries);
let tree_id = self.repo.write_tree(&tree)?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let commit = Commit::new(
tree_id,
vec![head_id.clone()],
"CodeTree <agent@codetree>".to_string(),
format!("Squashed merge of branch '{}' (conflicts auto-resolved)", branch_name),
timestamp,
);
let commit_id = self.repo.write_commit(&commit)?;
if let Some(branch) = self.repo.refs().current_branch()? {
self.repo.refs().set_branch(&branch, &commit_id)?;
}
self.restore_working_tree(&commit_id)?;
self.sync_index_to_head()?;
return Ok(MergeResult {
resolved_from_cache: true,
conflicts,
});
}
let tree = Tree::new(merged_entries);
let tree_id = self.repo.write_tree(&tree)?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let commit = Commit::new(
tree_id,
vec![head_id.clone()],
"CodeTree <agent@codetree>".to_string(),
format!("Squashed merge of branch '{}' ({} conflict(s) pending resolution)", branch_name, conflicts.len()),
timestamp,
);
let commit_id = self.repo.write_commit(&commit)?;
if let Some(branch) = self.repo.refs().current_branch()? {
self.repo.refs().set_branch(&branch, &commit_id)?;
}
self.restore_working_tree(&commit_id)?;
self.sync_index_to_head()?;
let pending = PendingResolution {
branch: branch_name.to_string(),
base_branch: head_id,
conflicts: conflicts.clone(),
};
pending.save(&self.pending_resolution_path()).await?;
return Ok(MergeResult {
resolved_from_cache: false,
conflicts,
});
}
let tree = Tree::new(merged_entries);
let tree_id = self.repo.write_tree(&tree)?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let commit = Commit::new(
tree_id,
vec![head_id.clone()],
"CodeTree <agent@codetree>".to_string(),
format!("Squashed merge of branch '{}'", branch_name),
timestamp,
);
let commit_id = self.repo.write_commit(&commit)?;
if let Some(branch) = self.repo.refs().current_branch()? {
self.repo.refs().set_branch(&branch, &commit_id)?;
}
self.restore_working_tree(&commit_id)?;
self.sync_index_to_head()?;
Ok(MergeResult {
resolved_from_cache: false,
conflicts: vec![],
})
}
pub async fn merge_branch(&self, branch_name: &str) -> Result<()> {
let cache = ResolutionCache::default();
let result = self.merge_branch_with_cache(branch_name, &cache).await?;
if result.resolved_from_cache {
}
Ok(())
}
pub async fn squash_merge_branch(&self, branch_name: &str) -> Result<()> {
let cache = ResolutionCache::default();
let _ = self.squash_merge_branch_with_cache(branch_name, &cache).await?;
Ok(())
}
pub fn is_in_merge_state(&self) -> bool {
self.pending_resolution_path().exists()
}
pub fn get_staged_blob_hash(&self, file_path: &str) -> Result<String> {
let index = self.repo.load_index()?;
index
.get(file_path)
.map(|s| s.to_string())
.with_context(|| format!("File '{}' not found in index", file_path))
}
pub async fn rebase_branch(&self, branch_name: &str, base_branch: &str) -> Result<()> {
let branch_id = self
.repo
.refs()
.get_branch(branch_name)?
.with_context(|| format!("Branch '{}' not found", branch_name))?;
let base_id = self
.repo
.refs()
.get_branch(base_branch)?
.with_context(|| format!("Base branch '{}' not found", base_branch))?;
let merge_base = self.find_merge_base(&branch_id, &base_id)?;
let mut commits_to_replay = Vec::new();
let mut current = branch_id.clone();
while current != merge_base {
let commit = self.repo.read_commit(¤t)?;
let parents = commit.parents.clone();
commits_to_replay.push(commit);
if parents.is_empty() {
break;
}
current = parents[0].clone();
}
commits_to_replay.reverse();
let mut new_parent = base_id.clone();
for old_commit in commits_to_replay {
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let new_commit = Commit::new(
old_commit.tree.clone(),
vec![new_parent.clone()],
old_commit.author.clone(),
old_commit.message.clone(),
timestamp,
);
let new_id = self.repo.write_commit(&new_commit)?;
new_parent = new_id;
}
self.repo.refs().set_branch(branch_name, &new_parent)?;
Ok(())
}
pub(super) fn find_merge_base(&self, a: &str, b: &str) -> Result<String> {
let mut ancestors_a = std::collections::HashSet::new();
let mut stack = vec![a.to_string()];
while let Some(id) = stack.pop() {
if ancestors_a.contains(&id) {
continue;
}
ancestors_a.insert(id.clone());
if let Ok(commit) = self.repo.read_commit(&id) {
for p in &commit.parents {
stack.push(p.clone());
}
}
}
let mut queue = vec![b.to_string()];
let mut visited = std::collections::HashSet::new();
while let Some(id) = queue.pop() {
if visited.contains(&id) {
continue;
}
visited.insert(id.clone());
if ancestors_a.contains(&id) {
return Ok(id);
}
if let Ok(commit) = self.repo.read_commit(&id) {
for p in &commit.parents {
queue.push(p.clone());
}
}
}
Ok(String::new())
}
fn count_commits_to(&self, start: &str, ancestor: &str) -> Result<usize> {
if start == ancestor {
return Ok(0);
}
let mut count = 0;
let mut current = start.to_string();
loop {
if current == ancestor || current.is_empty() {
break;
}
let commit = self.repo.read_commit(¤t)?;
count += 1;
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
Ok(count)
}
pub(super) fn merge_trees(
&self,
base: &Tree,
ours: &Tree,
theirs: &Tree,
) -> Result<(Vec<TreeEntry>, Vec<ConflictInfo>)> {
let base_map: std::collections::HashMap<&String, &String> = base
.entries
.iter()
.map(|e| (&e.name, &e.id))
.collect();
let our_map: std::collections::HashMap<&String, &String> = ours
.entries
.iter()
.map(|e| (&e.name, &e.id))
.collect();
let their_map: std::collections::HashMap<&String, &String> = theirs
.entries
.iter()
.map(|e| (&e.name, &e.id))
.collect();
let all_names: std::collections::BTreeSet<String> = base
.entries
.iter()
.chain(ours.entries.iter())
.chain(theirs.entries.iter())
.map(|e| e.name.clone())
.collect();
let mut merged = Vec::new();
let mut conflicts = Vec::new();
for name in &all_names {
let base_blob = base_map.get(name);
let our_blob = our_map.get(name);
let their_blob = their_map.get(name);
match (base_blob, our_blob, their_blob) {
(_b, o, t) if o == t => {
if let Some(blob) = o {
merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: blob.to_string() });
}
}
(Some(b), Some(o), Some(t)) if b == t && o != b => {
merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: o.to_string() });
}
(Some(b), Some(o), Some(t)) if b == o && t != b => {
merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: t.to_string() });
}
(None, Some(o), None) => {
merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: o.to_string() });
}
(None, None, Some(t)) => {
merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: t.to_string() });
}
(None, Some(o), Some(t)) if o == t => {
merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: o.to_string() });
}
(Some(b), Some(o), None) if b == o => { }
(Some(b), None, Some(t)) if b == t => { }
(Some(_), None, None) => { }
_ => {
conflicts.push(ConflictInfo {
path: name.clone(),
our_blob: our_blob.map(|s| s.to_string()).unwrap_or_default(),
their_blob: their_blob.map(|s| s.to_string()).unwrap_or_default(),
});
if let Some(o) = our_blob {
merged.push(TreeEntry { mode: 0o100644, name: name.clone(), id: o.to_string() });
}
}
}
}
Ok((merged, conflicts))
}
pub fn speculative_merge(&self, branch_name: &str) -> Result<Vec<String>> {
let branch_tip = self.repo.refs().get_branch(branch_name)?
.context(format!("Branch '{}' not found", branch_name))?;
let head_id = self.repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let merge_base = self.merge_point(&head_id, &branch_tip)?
.context("No common ancestor found")?;
let base_tree = {
let base_commit = self.repo.read_commit(&merge_base)?;
self.repo.read_tree(&base_commit.tree)?
};
let our_tree = {
let our_commit = self.repo.read_commit(&head_id)?;
self.repo.read_tree(&our_commit.tree)?
};
let their_tree = {
let their_commit = self.repo.read_commit(&branch_tip)?;
self.repo.read_tree(&their_commit.tree)?
};
let conflicts = self.find_merge_conflicts(&base_tree, &our_tree, &their_tree);
Ok(conflicts)
}
fn find_merge_conflicts(&self, base: &Tree, ours: &Tree, theirs: &Tree) -> Vec<String> {
let base_map: std::collections::HashMap<&String, &String> = base.entries.iter()
.map(|e| (&e.name, &e.id)).collect();
let our_map: std::collections::HashMap<&String, &String> = ours.entries.iter()
.map(|e| (&e.name, &e.id)).collect();
let their_map: std::collections::HashMap<&String, &String> = theirs.entries.iter()
.map(|e| (&e.name, &e.id)).collect();
let all_files: std::collections::HashSet<&String> = base.entries.iter()
.map(|e| &e.name)
.chain(ours.entries.iter().map(|e| &e.name))
.chain(theirs.entries.iter().map(|e| &e.name))
.collect();
let mut conflicts = Vec::new();
for file in all_files {
let base_id = base_map.get(file);
let our_id = our_map.get(file);
let their_id = their_map.get(file);
if our_id != their_id && our_id != base_id && their_id != base_id {
conflicts.push(file.to_string());
}
}
conflicts.sort();
conflicts
}
}