use crate::error::{Context, Result};
use crate::resolution::ConflictInfo;
use std::collections::HashSet;
use super::objects::{Commit, Tree};
use super::manager::VcsManager;
#[derive(Debug)]
pub struct ConvergeOutcome {
pub commit: Option<String>,
pub conflicts: Vec<ConflictInfo>,
}
impl VcsManager {
pub fn ancestor_set(&self, commit: &str) -> Result<HashSet<String>> {
let mut seen = HashSet::new();
let mut stack = vec![commit.to_string()];
while let Some(id) = stack.pop() {
if !seen.insert(id.clone()) {
continue;
}
if let Ok(c) = self.repo.read_commit(&id) {
for p in &c.parents {
stack.push(p.clone());
}
}
}
Ok(seen)
}
pub fn commit_heads(&self, commits: &[String]) -> Result<Vec<String>> {
let mut heads: Vec<String> = Vec::new();
for c in commits {
let covered_by_other = commits.iter().any(|other| {
other != c && self.ancestor_set(other).map(|a| a.contains(c)).unwrap_or(false)
});
if !covered_by_other {
heads.push(c.clone());
}
}
heads.sort();
heads.dedup();
Ok(heads)
}
pub fn dedupe_heads_by_tree(&self, heads: &[String]) -> Result<Vec<String>> {
let mut unique: Vec<(String, String, u64)> = Vec::new(); for h in heads {
let c = self.repo.read_commit(h)?;
match unique.iter_mut().find(|(_, tree, _)| *tree == c.tree) {
Some(existing) => {
if c.timestamp >= existing.2 {
existing.0 = h.clone();
existing.2 = c.timestamp;
}
}
None => unique.push((h.clone(), c.tree.clone(), c.timestamp)),
}
}
let mut out: Vec<String> = unique.into_iter().map(|(c, _, _)| c).collect();
out.sort();
Ok(out)
}
pub fn converge_heads(&self, heads: &[String]) -> Result<ConvergeOutcome> {
let heads = self.dedupe_heads_by_tree(heads)?;
if heads.len() < 2 {
return Ok(ConvergeOutcome { commit: None, conflicts: vec![] });
}
let mut current = heads[0].clone();
for next in &heads[1..] {
let base = self.find_merge_base(¤t, next)?;
let base_tree = self.commit_tree(&base)?;
let our_tree = self.commit_tree(¤t)?;
let their_tree = self.commit_tree(next)?;
let (merged_entries, conflicts) = self.merge_trees(&base_tree, &our_tree, &their_tree)?;
if !conflicts.is_empty() {
return Ok(ConvergeOutcome { commit: None, 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![current.clone(), next.clone()],
"CodeTree <agent@codetree>".to_string(),
format!("Converge divergent commits ({} and {})", ¤t[..7.min(current.len())], &next[..7.min(next.len())]),
timestamp,
);
current = self.repo.write_commit(&commit)?;
}
Ok(ConvergeOutcome { commit: Some(current), conflicts: vec![] })
}
pub fn set_branch_tip(&self, branch: &str, commit: &str) -> Result<()> {
self.repo.refs().set_branch(branch, commit)
}
pub fn commit_parents(&self, commit: &str) -> Result<Vec<String>> {
let c = self
.repo
.read_commit(&commit.to_string())
.with_context(|| format!("Commit '{}' not found", commit))?;
Ok(c.parents)
}
}