use crate::error::{Context, Result};
use crate::resolution::ConflictInfo;
use super::objects::{hash_object, Blob, ObjectType, Tree, TreeEntry, Commit};
use super::repo::Repository;
use std::path::{Path, PathBuf};
pub(super) fn commit_tree_entries(repo: &Repository, commit_id: &str) -> Result<Vec<TreeEntry>> {
let commit = repo.read_commit(&commit_id.to_string())?;
let tree = repo.read_tree(&commit.tree)?;
Ok(tree.entries)
}
fn walk_object_hashes(objects_dir: &Path) -> Result<Vec<String>> {
let mut hashes = Vec::new();
if !objects_dir.exists() {
return Ok(hashes);
}
for entry in std::fs::read_dir(objects_dir)? {
let entry = entry?;
if !entry.file_type()?.is_dir() {
continue;
}
let dir_name = entry.file_name().to_string_lossy().to_string();
if dir_name.len() != 2 {
continue;
}
for file_entry in std::fs::read_dir(entry.path())? {
let file_entry = file_entry?;
let file_name = file_entry.file_name().to_string_lossy().to_string();
let hash = format!("{}{}", dir_name, file_name);
if hash.len() == 40 {
hashes.push(hash);
}
}
}
Ok(hashes)
}
fn stat_fingerprint(meta: &std::fs::Metadata) -> (u64, u32, u64, u64) {
let (secs, nanos) = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| (d.as_secs(), d.subsec_nanos()))
.unwrap_or((0, 0));
#[cfg(unix)]
let ino = std::os::unix::fs::MetadataExt::ino(meta);
#[cfg(not(unix))]
let ino = 0u64;
(secs, nanos, meta.len(), ino)
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct VcsStatus {
pub modified: Vec<String>,
pub untracked: Vec<String>,
pub staged: Vec<String>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct BranchInfo {
pub name: String,
pub is_current: bool,
pub commit_hash: String,
pub commit_message: String,
pub author: String,
pub timestamp: i64,
}
#[derive(Debug, Clone)]
pub struct CommitInfo {
pub hash: String,
pub message: String,
pub author: String,
pub timestamp: i64,
pub files_changed: Vec<String>,
}
#[derive(Debug)]
pub struct MergeResult {
pub resolved_from_cache: bool,
pub conflicts: Vec<ConflictInfo>,
}
#[derive(Debug)]
pub struct SnapshotResult {
pub commit_hash: String,
pub file_count: usize,
pub branch: String,
pub timestamp: u64,
}
#[derive(Debug)]
pub struct AbsorbResult {
pub new_head: String,
pub target_commit: String,
pub absorbed_files: Vec<String>,
pub was_head: bool,
}
#[derive(Debug, serde::Serialize)]
pub struct ReadyCheck {
pub ahead: usize,
pub behind: usize,
pub up_to_date: bool,
pub conflict_count: usize,
pub auto_resolvable: bool,
pub conflict_files: Vec<String>,
}
#[derive(Clone)]
pub struct VcsManager {
pub(super) repo_path: PathBuf,
pub(super) repo: Repository,
pub(super) max_file_size: u64,
}
impl VcsManager {
pub fn new(repo_path: PathBuf) -> Result<Self> {
let codetree_dir = repo_path.join(".codetree");
if !codetree_dir.exists() {
bail!("No CodeTree repository found at {}. Run `codetree init` first.", repo_path.display());
}
let repo = Repository::open(&repo_path)?;
Ok(Self { repo_path, repo, max_file_size: 0 })
}
pub fn init_at(path: &Path) -> Result<Self> {
let repo = Repository::init(path)?;
Ok(Self {
repo_path: path.to_path_buf(),
repo,
max_file_size: 0,
})
}
pub fn repo_path(&self) -> &Path {
&self.repo_path
}
pub fn repo(&self) -> &Repository {
&self.repo
}
pub async fn get_current_branch(&self) -> Result<String> {
self.repo
.refs()
.current_branch()?
.context("HEAD is detached (no current branch)")
}
pub async fn create_branch(&self, branch_name: &str, base_branch: Option<&str>) -> Result<()> {
let commit_id = if let Some(base) = base_branch {
self.repo
.refs()
.get_branch(base)?
.with_context(|| format!("Base branch '{}' not found", base))?
} else {
self.repo
.refs()
.resolve_head()?
.context("HEAD does not point to a commit")?
};
self.repo.refs().set_branch(branch_name, &commit_id)?;
Ok(())
}
pub async fn checkout_branch(&self, branch_name: &str) -> Result<()> {
let commit_id = self
.repo
.refs()
.get_branch(branch_name)?
.with_context(|| format!("Branch '{}' not found", branch_name))?;
self.restore_working_tree(&commit_id)?;
self.repo.refs().set_head(branch_name)?;
let tree = self.commit_tree(&commit_id)?;
let mut index = self.repo.load_index()?;
index.clear();
for entry in &tree.entries {
index.add(&entry.name, &entry.id);
}
index.save()?;
Ok(())
}
pub async fn delete_branch(&self, branch_name: &str, _force: bool) -> Result<()> {
if let Ok(Some(current)) = self.repo.refs().current_branch()
&& current == branch_name
{
bail!("Cannot delete current branch '{}'", branch_name);
}
self.repo.refs().delete_branch(branch_name)?;
Ok(())
}
pub fn branch_exists(&self, branch_name: &str) -> bool {
self.repo
.refs()
.get_branch(branch_name)
.map(|o| o.is_some())
.unwrap_or(false)
}
pub fn list_branches(&self) -> Result<Vec<BranchInfo>> {
let names = self.repo.refs().list_branches()?;
let current = self
.repo
.refs()
.current_branch()
.unwrap_or(None)
.unwrap_or_default();
let mut branches = Vec::new();
for name in names {
let commit_hash = self
.repo
.refs()
.get_branch(&name)?
.unwrap_or_default();
let (message, author, timestamp) = self
.read_commit_meta(&commit_hash)
.unwrap_or(("".to_string(), "".to_string(), 0));
branches.push(BranchInfo {
name: name.clone(),
is_current: name == current,
commit_hash,
commit_message: message,
author,
timestamp: timestamp as i64,
});
}
Ok(branches)
}
pub fn set_max_file_size(&mut self, size: u64) {
self.max_file_size = size;
}
pub async fn add_all(&self) -> Result<()> {
let repo_path = self.repo_path.clone();
let repo = self.repo.clone();
let max_size = self.max_file_size;
tokio::task::spawn_blocking(move || -> Result<()> {
let files = {
let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0 };
mgr.walk_working_tree(&repo_path)?
};
let mut index = repo.load_index()?;
for file in &files {
let relative = file.strip_prefix(&repo_path).unwrap_or(file);
let relative_str = relative.to_string_lossy().to_string();
let meta = std::fs::metadata(file)?;
let (secs, nanos, size, ino) = stat_fingerprint(&meta);
if max_size > 0 && size > max_size {
eprintln!("[warn] Skipping large file: {} ({} bytes, limit: {})", relative_str, size, max_size);
continue;
}
if let Some(entry) = index.entry(&relative_str)
&& entry.matches_stat(secs, nanos, size, ino)
&& repo.has_object(&entry.blob_id)
{
continue;
}
let content = std::fs::read(file)?;
let blob_id = repo.write_blob(&content)?;
index.add_staged(&relative_str, &blob_id, secs, nanos, size, ino);
}
index.save()?;
Ok(())
}).await?
}
pub async fn add_files(&self, files: &[String]) -> Result<()> {
if files.is_empty() {
return self.add_all().await;
}
let repo_path = self.repo_path.clone();
let repo = self.repo.clone();
let files = files.to_vec();
tokio::task::spawn_blocking(move || -> Result<()> {
let mut index = repo.load_index()?;
for file in &files {
let full_path = repo_path.join(file);
if !full_path.exists() {
index.remove(file);
continue;
}
let meta = std::fs::metadata(&full_path)?;
let (secs, nanos, size, ino) = stat_fingerprint(&meta);
if let Some(entry) = index.entry(file)
&& entry.matches_stat(secs, nanos, size, ino)
&& repo.has_object(&entry.blob_id)
{
continue;
}
let content = std::fs::read(&full_path)?;
let blob_id = repo.write_blob(&content)?;
index.add_staged(file, &blob_id, secs, nanos, size, ino);
}
index.save()?;
Ok(())
}).await?
}
pub async fn commit(&self, message: &str) -> Result<String> {
let author = "CodeTree <agent@codetree>";
let commit_id = self.repo.commit(message, author)?;
Ok(commit_id)
}
pub async fn commit_with_meta(&self, message: &str, author: &str, timestamp: u64) -> Result<String> {
let commit_id = self.repo.commit_with_meta(message, author, timestamp)?;
Ok(commit_id)
}
pub async fn commit_empty(&self, message: &str) -> Result<String> {
let repo = self.repo.clone();
let message = message.to_string();
tokio::task::spawn_blocking(move || -> Result<String> {
let head_id = repo
.refs()
.resolve_head()?
.context("HEAD does not point to a commit")?;
let head_commit = repo.read_commit(&head_id)?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let commit = Commit::new(
head_commit.tree,
vec![head_id],
"CodeTree <agent@codetree>".to_string(),
message,
timestamp,
);
let commit_id = repo.write_commit(&commit)?;
if let Some(branch) = repo.refs().current_branch()? {
repo.refs().set_branch(&branch, &commit_id)?;
}
Ok(commit_id)
})
.await?
}
pub fn resolve_commit_pub(&self, spec: &str, head_id: &str) -> Result<String> {
self.resolve_commit(spec, head_id)
}
pub async fn goto_commit(&self, commit_spec: &str) -> Result<()> {
let repo = self.repo.clone();
let repo_path = self.repo_path.clone();
let commit_spec = commit_spec.to_string();
tokio::task::spawn_blocking(move || -> Result<()> {
let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0 };
let head_id = repo.refs().resolve_head()?
.context("HEAD does not point to a commit")?;
let target_id = mgr.resolve_commit(&commit_spec, &head_id)?;
mgr.restore_working_tree(&target_id)?;
repo.refs().set_detached_head(&target_id)?;
let tree = mgr.commit_tree(&target_id)?;
let mut index = repo.load_index()?;
index.clear();
for entry in &tree.entries {
index.add(&entry.name, &entry.id);
}
index.save()?;
Ok(())
})
.await?
}
pub(super) fn resolve_commit(&self, spec: &str, head_id: &str) -> Result<String> {
if spec == "HEAD" {
return Ok(head_id.to_string());
}
if let Some(rest) = spec.strip_prefix("HEAD~") {
let n: usize = rest.parse().unwrap_or(0);
let mut current = head_id.to_string();
for _ in 0..n {
let commit = self.repo.read_commit(¤t)?;
if commit.parents.is_empty() {
bail!("HEAD~{} goes beyond the root commit", n);
}
current = commit.parents[0].clone();
}
return Ok(current);
}
let objects_dir = self.repo.root().join("objects");
for entry in walk_object_hashes(&objects_dir)? {
if entry.starts_with(spec) {
return Ok(entry);
}
}
bail!("Commit '{}' not found", spec)
}
pub async fn snapshot_working_tree(&self) -> Result<Option<SnapshotResult>> {
let repo_path = self.repo_path.clone();
let repo = self.repo.clone();
tokio::task::spawn_blocking(move || -> Result<Option<SnapshotResult>> {
let head_tree = {
let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0 };
mgr.head_tree()?
};
let head_map: std::collections::HashMap<String, String> = head_tree
.entries
.iter()
.map(|e| (e.name.clone(), e.id.clone()))
.collect();
let files = {
let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0 };
mgr.walk_working_tree(&repo_path)?
};
let mut entries = Vec::with_capacity(files.len());
let mut dirty = false;
for file in &files {
let relative = file.strip_prefix(&repo_path).unwrap_or(file);
let relative_str = relative.to_string_lossy().to_string();
let content = std::fs::read(file)?;
let blob_id = repo.write_blob(&content)?;
match head_map.get(&relative_str) {
Some(h) if *h == blob_id => {}
_ => dirty = true,
}
entries.push(TreeEntry {
mode: 0o100644,
name: relative_str,
id: blob_id,
});
}
let wt_set: std::collections::HashSet<&str> =
entries.iter().map(|e| e.name.as_str()).collect();
for name in head_map.keys() {
if !wt_set.contains(name.as_str()) {
dirty = true;
break;
}
}
if !dirty {
return Ok(None);
}
let tree = Tree::new(entries);
let tree_id = repo.write_tree(&tree)?;
let parents = repo
.refs()
.resolve_head()?
.map(|h| vec![h])
.unwrap_or_default();
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,
parents,
"CodeTree <agent@codetree>".to_string(),
"Working copy snapshot".to_string(),
timestamp,
);
let commit_id = repo.write_commit(&commit)?;
let branch = repo
.refs()
.current_branch()?
.unwrap_or_default();
Ok(Some(SnapshotResult {
commit_hash: commit_id,
file_count: tree.entries.len(),
branch,
timestamp,
}))
})
.await?
}
pub async fn get_status(&self) -> Result<VcsStatus> {
let head_tree = self.head_tree()?;
let index = self.repo.load_index()?;
let wt_files = self.walk_working_tree(&self.repo_path)?;
let wt_set: std::collections::HashMap<String, PathBuf> = wt_files
.iter()
.map(|p| {
let rel = p.strip_prefix(&self.repo_path).unwrap_or(p);
(rel.to_string_lossy().to_string(), p.clone())
})
.collect();
let head_set: std::collections::HashMap<&String, &String> = head_tree
.entries
.iter()
.map(|e| (&e.name, &e.id))
.collect();
let index_entries = index.entries_sorted();
let index_set: std::collections::HashMap<&String, &String> = index_entries
.iter()
.map(|(p, h)| (p, h))
.collect();
let mut modified = Vec::new();
let mut untracked = Vec::new();
let mut staged = Vec::new();
for (rel, full) in &wt_set {
if let Some(head_blob) = head_set.get(rel) {
let mut is_modified = true;
if let Some(entry) = index.entry(rel)
&& entry.blob_id == **head_blob
{
let meta = std::fs::metadata(full)?;
let (secs, nanos, size, ino) = stat_fingerprint(&meta);
if entry.matches_stat(secs, nanos, size, ino) {
is_modified = false;
}
}
if is_modified {
let content = std::fs::read(full)?;
let blob = Blob::new(content);
if &blob.id() != *head_blob {
modified.push(rel.clone());
}
}
} else if index_set.contains_key(rel) {
} else {
untracked.push(rel.clone());
}
}
for name in head_set.keys() {
if !wt_set.contains_key(*name) {
modified.push(name.to_string());
}
}
for (path, blob_id) in &index_set {
match head_set.get(path) {
Some(head_blob) if *head_blob != *blob_id => staged.push(path.to_string()),
None => staged.push(path.to_string()),
_ => {}
}
}
modified.sort();
untracked.sort();
staged.sort();
Ok(VcsStatus {
modified,
untracked,
staged,
})
}
pub fn pending_resolution_path(&self) -> PathBuf {
self.repo_path.join(".codetree").join("pending_resolution.json")
}
pub fn snapshots_path(&self) -> PathBuf {
self.repo_path.join(".codetree").join("snapshots.json")
}
pub fn get_head_hash(&self) -> Result<String> {
self.repo
.refs()
.resolve_head()?
.context("HEAD does not point to a commit")
}
fn read_commit_meta(&self, commit_id: &str) -> Result<(String, String, u64)> {
let commit = self.repo.read_commit(&commit_id.to_string())?;
Ok((commit.message, commit.author, commit.timestamp))
}
pub(super) fn commit_tree(&self, commit_id: &str) -> Result<Tree> {
let commit = self.repo.read_commit(&commit_id.to_string())?;
self.repo.read_tree(&commit.tree)
}
pub(super) fn head_tree(&self) -> Result<Tree> {
let head_id = self
.repo
.refs()
.resolve_head()?
.unwrap_or_default();
if head_id.is_empty() {
return Ok(Tree::new(vec![]));
}
self.commit_tree(&head_id)
}
pub(super) fn commit_files(&self, commit_id: &str) -> Result<Vec<String>> {
let commit = self.repo.read_commit(&commit_id.to_string())?;
let tree = self.repo.read_tree(&commit.tree)?;
let parent_tree = if !commit.parents.is_empty() {
let parent = self.repo.read_commit(&commit.parents[0])?;
self.repo.read_tree(&parent.tree)?
} else {
Tree::new(vec![])
};
let parent_set: std::collections::HashMap<&String, &String> = parent_tree
.entries
.iter()
.map(|e| (&e.name, &e.id))
.collect();
let mut files = Vec::new();
for entry in &tree.entries {
match parent_set.get(&entry.name) {
Some(parent_blob) if **parent_blob != entry.id => files.push(entry.name.clone()),
None => files.push(entry.name.clone()),
_ => {}
}
}
for name in parent_tree.entries.iter().map(|e| &e.name) {
if !tree.entries.iter().any(|e| &e.name == name) {
files.push(name.clone());
}
}
Ok(files)
}
pub(super) fn walk_working_tree(&self, dir: &Path) -> Result<Vec<PathBuf>> {
let mut files = Vec::new();
self.walk_dir_recursive(dir, &mut files)?;
Ok(files)
}
fn walk_dir_recursive(&self, dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str == ".codetree" || name_str == ".git" || name_str == "target" || name_str == "node_modules" {
continue;
}
let file_type = entry.file_type()?;
if file_type.is_dir() {
self.walk_dir_recursive(&path, files)?;
} else if file_type.is_file() {
files.push(path);
}
}
Ok(())
}
pub fn restore_working_tree_pub(&self, commit_id: &str) -> Result<()> {
self.restore_working_tree(commit_id)
}
pub(super) fn restore_working_tree(&self, commit_id: &str) -> Result<()> {
let tree = self.commit_tree(commit_id)?;
let existing = self.walk_working_tree(&self.repo_path)?;
let existing_set: std::collections::HashSet<String> = existing
.iter()
.map(|p| {
p.strip_prefix(&self.repo_path)
.unwrap_or(p)
.to_string_lossy()
.to_string()
})
.collect();
let tree_set: std::collections::HashSet<String> = tree
.entries
.iter()
.map(|e| e.name.clone())
.collect();
let index = self.repo.load_index()?;
for entry in &tree.entries {
let file_path = self.repo_path.join(&entry.name);
let mut matches = false;
if let Some(ie) = index.entry(&entry.name)
&& ie.blob_id == entry.id
&& let Ok(meta) = std::fs::metadata(&file_path)
{
let (secs, nanos, size, ino) = stat_fingerprint(&meta);
matches = ie.matches_stat(secs, nanos, size, ino);
}
if !matches
&& let Ok(content) = std::fs::read(&file_path)
{
let id = hash_object(ObjectType::Blob, &content);
matches = id == entry.id;
}
if matches {
continue;
}
let blob = self.repo.read_blob(&entry.id)?;
if let Some(parent) = file_path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&file_path, &blob.content)?;
}
for file in &existing_set {
if !tree_set.contains(file) {
let path = self.repo_path.join(file);
let _ = std::fs::remove_file(&path);
}
}
Ok(())
}
pub(super) fn sync_index_to_head(&self) -> Result<()> {
let tree = self.head_tree()?;
let mut index = self.repo.load_index()?;
index.clear();
for entry in &tree.entries {
index.add(&entry.name, &entry.id);
}
index.save()?;
Ok(())
}
pub fn sync_index_to_commit(&self, commit_id: &str) -> Result<()> {
let tree = self.commit_tree(commit_id)?;
let mut index = self.repo.load_index()?;
index.clear();
for entry in &tree.entries {
index.add(&entry.name, &entry.id);
}
index.save()?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::resolution::{PendingResolution, ResolutionCache};
use tempfile::TempDir;
fn setup_repo() -> (TempDir, VcsManager) {
let tmp = TempDir::new().unwrap();
let mgr = VcsManager::init_at(tmp.path()).unwrap();
(tmp, mgr)
}
#[tokio::test]
async fn test_create_and_checkout_branch() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("file.txt"), "hello").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Add file.txt").await.unwrap();
mgr.create_branch("feature", Some("main")).await.unwrap();
assert!(mgr.branch_exists("feature"));
mgr.checkout_branch("feature").await.unwrap();
let current = mgr.get_current_branch().await.unwrap();
assert_eq!(current, "feature");
}
#[tokio::test]
async fn test_status() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("file.txt"), "hello").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Add file.txt").await.unwrap();
std::fs::write(tmp.path().join("file.txt"), "hello world").unwrap();
std::fs::write(tmp.path().join("new.txt"), "new").unwrap();
let status = mgr.get_status().await.unwrap();
assert!(status.modified.contains(&"file.txt".to_string()));
assert!(status.untracked.contains(&"new.txt".to_string()));
}
#[tokio::test]
async fn test_commit_history() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("a.txt"), "a").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("First").await.unwrap();
std::fs::write(tmp.path().join("b.txt"), "b").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Second").await.unwrap();
let history = mgr.get_commit_history("main", 10).unwrap();
assert_eq!(history.len(), 3); assert_eq!(history[0].message, "Second");
assert_eq!(history[1].message, "First");
}
#[tokio::test]
async fn test_merge_no_conflicts() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("base.txt"), "base").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Base commit").await.unwrap();
mgr.create_branch("feature", Some("main")).await.unwrap();
mgr.checkout_branch("feature").await.unwrap();
std::fs::write(tmp.path().join("feature.txt"), "feature").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Feature commit").await.unwrap();
mgr.checkout_branch("main").await.unwrap();
std::fs::write(tmp.path().join("main.txt"), "main").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Main commit").await.unwrap();
let cache = ResolutionCache::default();
let result = mgr.merge_branch_with_cache("feature", &cache).await.unwrap();
assert!(!result.resolved_from_cache);
assert!(result.conflicts.is_empty());
assert!(tmp.path().join("feature.txt").exists());
assert!(tmp.path().join("main.txt").exists());
}
#[tokio::test]
async fn test_merge_with_conflict() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("file.txt"), "base").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Base commit").await.unwrap();
mgr.create_branch("feature", Some("main")).await.unwrap();
mgr.checkout_branch("feature").await.unwrap();
std::fs::write(tmp.path().join("file.txt"), "feature version").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Feature change").await.unwrap();
mgr.checkout_branch("main").await.unwrap();
std::fs::write(tmp.path().join("file.txt"), "main version").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Main change").await.unwrap();
let cache = ResolutionCache::default();
let result = mgr.merge_branch_with_cache("feature", &cache).await.unwrap();
assert!(!result.resolved_from_cache);
assert_eq!(result.conflicts.len(), 1);
assert_eq!(result.conflicts[0].path, "file.txt");
let pending = PendingResolution::load(&mgr.pending_resolution_path())
.await
.unwrap()
.expect("pending resolution should be written");
assert_eq!(pending.branch, "feature");
assert_eq!(pending.conflicts.len(), 1);
let head = mgr.repo.refs().resolve_head().unwrap().unwrap();
let head_commit = mgr.repo.read_commit(&head).unwrap();
assert_eq!(head_commit.parents.len(), 2);
let content = std::fs::read_to_string(tmp.path().join("file.txt")).unwrap();
assert_eq!(content, "main version");
}
#[tokio::test]
async fn test_amend_commit() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("a.txt"), "a").unwrap();
mgr.add_all().await.unwrap();
let first_hash = mgr.commit("First").await.unwrap();
std::fs::write(tmp.path().join("b.txt"), "b").unwrap();
mgr.add_all().await.unwrap();
let amended_hash = mgr.amend_commit().await.unwrap();
assert_ne!(first_hash, amended_hash);
let history = mgr.get_commit_history("main", 10).unwrap();
assert_eq!(history.len(), 2);
assert_eq!(history[0].message, "First");
}
#[tokio::test]
async fn test_reset_soft_parent() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("a.txt"), "a").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("First").await.unwrap();
std::fs::write(tmp.path().join("b.txt"), "b").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Second").await.unwrap();
mgr.reset_soft_parent().await.unwrap();
let history = mgr.get_commit_history("main", 10).unwrap();
assert_eq!(history.len(), 2);
assert_eq!(history[0].message, "First");
}
#[tokio::test]
async fn test_divergence() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("base.txt"), "base").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Base").await.unwrap();
mgr.create_branch("feature", Some("main")).await.unwrap();
mgr.checkout_branch("feature").await.unwrap();
std::fs::write(tmp.path().join("feat.txt"), "feat").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Feature").await.unwrap();
mgr.checkout_branch("main").await.unwrap();
std::fs::write(tmp.path().join("main.txt"), "main").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Main update").await.unwrap();
let (ahead, behind) = mgr.get_branch_divergence("feature", "main").unwrap();
assert_eq!(ahead, 1); assert_eq!(behind, 1); }
#[tokio::test]
async fn test_delete_branch() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("file.txt"), "content").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Initial").await.unwrap();
mgr.create_branch("feature", Some("main")).await.unwrap();
assert!(mgr.branch_exists("feature"));
mgr.delete_branch("feature", false).await.unwrap();
assert!(!mgr.branch_exists("feature"));
}
#[tokio::test]
async fn test_rebase() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("base.txt"), "base").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Base").await.unwrap();
mgr.create_branch("feature", Some("main")).await.unwrap();
mgr.checkout_branch("feature").await.unwrap();
std::fs::write(tmp.path().join("feat.txt"), "feat").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Feature").await.unwrap();
mgr.checkout_branch("main").await.unwrap();
std::fs::write(tmp.path().join("main.txt"), "main").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Main update").await.unwrap();
mgr.rebase_branch("feature", "main").await.unwrap();
let (ahead, behind) = mgr.get_branch_divergence("feature", "main").unwrap();
assert_eq!(ahead, 1);
assert_eq!(behind, 0);
}
#[tokio::test]
async fn test_get_diff() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("file.txt"), "line1\n").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Add file").await.unwrap();
std::fs::write(tmp.path().join("file.txt"), "line1\nline2\n").unwrap();
let diff = mgr.get_diff().unwrap();
assert!(diff.contains("diff --git"));
assert!(diff.contains("+line2"));
}
#[tokio::test]
async fn test_worktree() {
let (tmp, mgr) = setup_repo();
std::fs::write(tmp.path().join("file.txt"), "content").unwrap();
mgr.add_all().await.unwrap();
mgr.commit("Initial").await.unwrap();
let wt_path = tmp.path().join(".codetree").join("worktrees").join("feature");
mgr.add_worktree_new_branch("feature", &wt_path, "main").await.unwrap();
assert!(wt_path.exists());
assert!(wt_path.join("file.txt").exists());
let worktrees = mgr.list_worktrees().await.unwrap();
assert!(!worktrees.is_empty());
mgr.remove_worktree(&wt_path).await.unwrap();
assert!(!wt_path.exists());
}
}