codetree 0.2.0

AI-native version control system for autonomous agents
Documentation
use std::path::PathBuf;
use crate::atomic::{write_atomic, with_file_lock, write_locked};
use crate::error::Result;

/// Bound on how long ref/tag/HEAD writers wait for a contended ref lockfile.
const REF_LOCK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// Manages branch refs and HEAD symbolic ref.
#[derive(Clone)]
pub struct RefManager {
    root: PathBuf,
}

impl RefManager {
    pub fn new(root: PathBuf) -> Self {
        Self { root }
    }

    /// Get the refs/heads directory.
    fn heads_dir(&self) -> PathBuf {
        self.root.join("refs").join("heads")
    }

    /// Get the refs/tags directory.
    fn tags_dir(&self) -> PathBuf {
        self.root.join("refs").join("tags")
    }

    /// Get the path for a branch ref.
    fn ref_path(&self, name: &str) -> PathBuf {
        self.heads_dir().join(name)
    }

    /// Get the path for a tag ref.
    pub fn tag_path(&self, name: &str) -> PathBuf {
        self.tags_dir().join(name)
    }

    /// Get the HEAD file path.
    fn head_path(&self) -> PathBuf {
        self.root.join("HEAD")
    }

    /// Write a branch ref to point at a commit hash.
    /// The write is atomic (temp file + rename) and serialized against other
    /// writers, so a crash can never leave a truncated ref.
    pub fn set_branch(&self, name: &str, commit_id: &str) -> Result<()> {
        write_atomic(&self.ref_path(name), format!("{}\n", commit_id).as_bytes())
    }

    /// Compare-and-swap a branch ref: only applies `new_id` if the ref
    /// currently points at `expected`.
    ///
    /// - `expected = Some(id)` → apply only if the ref reads `id` (update-in-place).
    /// - `expected = None` → apply only if the ref does not exist (create-only).
    ///
    /// Returns `true` if applied, `false` if the ref moved underneath us.
    /// The check and the write happen under one exclusive lockfile, so the
    /// cycle is atomic even with concurrent writers.
    pub fn set_branch_if_current(
        &self,
        name: &str,
        new_id: &str,
        expected: Option<&str>,
    ) -> Result<bool> {
        let path = self.ref_path(name);
        let payload = format!("{}\n", new_id);
        with_file_lock(&path, REF_LOCK_TIMEOUT, || {
            let current = self.get_branch(name)?;
            let matches = match expected {
                Some(exp) => current.as_deref() == Some(exp.trim()),
                None => current.is_none(),
            };
            if !matches {
                return Ok(false);
            }
            write_locked(&path, payload.as_bytes())?;
            Ok(true)
        })
    }

    /// Read the commit hash a branch ref points to.
    pub fn get_branch(&self, name: &str) -> Result<Option<String>> {
        let path = self.ref_path(name);
        if !path.exists() {
            return Ok(None);
        }
        let content = std::fs::read_to_string(&path)?;
        Ok(Some(content.trim().to_string()))
    }

    /// Delete a branch ref.
    pub fn delete_branch(&self, name: &str) -> Result<()> {
        let path = self.ref_path(name);
        if path.exists() {
            std::fs::remove_file(&path)?;
        }
        Ok(())
    }

    /// Rename a branch ref.
    pub fn rename_branch(&self, old_name: &str, new_name: &str) -> Result<()> {
        let old_path = self.ref_path(old_name);
        if !old_path.exists() {
            bail!("Branch '{}' not found", old_name);
        }
        let new_path = self.ref_path(new_name);
        if new_path.exists() {
            bail!("Branch '{}' already exists", new_name);
        }
        std::fs::rename(&old_path, &new_path)?;
        Ok(())
    }

    /// List all branch names. Ignores atomic-write staging/lock litter
    /// (`.name.tmp.<pid>` and `name.lock`).
    pub fn list_branches(&self) -> Result<Vec<String>> {
        let dir = self.heads_dir();
        if !dir.exists() {
            return Ok(Vec::new());
        }
        let mut branches = Vec::new();
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            if entry.file_type()?.is_file()
                && let Some(name) = entry.file_name().to_str()
                && is_ref_name(name)
            {
                branches.push(name.to_string());
            }
        }
        branches.sort();
        Ok(branches)
    }

    /// Write a tag ref to point at a commit hash (atomic, see `set_branch`).
    pub fn set_tag(&self, name: &str, commit_id: &str) -> Result<()> {
        write_atomic(&self.tag_path(name), format!("{}\n", commit_id).as_bytes())
    }

    /// Read the commit hash a tag ref points to.
    pub fn get_tag(&self, name: &str) -> Result<Option<String>> {
        let path = self.tag_path(name);
        if !path.exists() {
            return Ok(None);
        }
        let content = std::fs::read_to_string(&path)?;
        Ok(Some(content.trim().to_string()))
    }

    /// Delete a tag ref.
    pub fn delete_tag(&self, name: &str) -> Result<()> {
        let path = self.tag_path(name);
        if path.exists() {
            std::fs::remove_file(&path)?;
        }
        Ok(())
    }

    /// List all tag names. Ignores atomic-write staging/lock litter.
    pub fn list_tags(&self) -> Result<Vec<String>> {
        let dir = self.tags_dir();
        if !dir.exists() {
            return Ok(Vec::new());
        }
        let mut tags = Vec::new();
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            if entry.file_type()?.is_file()
                && let Some(name) = entry.file_name().to_str()
                && is_ref_name(name)
            {
                tags.push(name.to_string());
            }
        }
        tags.sort();
        Ok(tags)
    }

    /// Set HEAD to point at a branch (symbolic ref). Atomic.
    pub fn set_head(&self, branch: &str) -> Result<()> {
        write_atomic(
            &self.head_path(),
            format!("ref: refs/heads/{}\n", branch).as_bytes(),
        )
    }

    /// Set HEAD to point directly at a commit (detached HEAD). Atomic.
    pub fn set_detached_head(&self, commit_id: &str) -> Result<()> {
        write_atomic(&self.head_path(), format!("{}\n", commit_id).as_bytes())
    }

    /// Read HEAD. Returns either a branch name (symbolic ref) or a commit hash (detached).
    pub fn get_head(&self) -> Result<HeadRef> {
        let content = std::fs::read_to_string(self.head_path())?;
        let content = content.trim();
        if let Some(branch) = content.strip_prefix("ref: refs/heads/") {
            Ok(HeadRef::Branch(branch.to_string()))
        } else {
            Ok(HeadRef::Detached(content.to_string()))
        }
    }

    /// Resolve HEAD to a commit hash.
    pub fn resolve_head(&self) -> Result<Option<String>> {
        match self.get_head()? {
            HeadRef::Branch(name) => self.get_branch(&name),
            HeadRef::Detached(id) => Ok(Some(id)),
        }
    }

    /// Get the current branch name (if HEAD is a symbolic ref).
    pub fn current_branch(&self) -> Result<Option<String>> {
        match self.get_head()? {
            HeadRef::Branch(name) => Ok(Some(name)),
            HeadRef::Detached(_) => Ok(None),
        }
    }
}

/// HEAD can be either a symbolic ref to a branch or a detached commit hash.
#[derive(Debug, Clone, PartialEq)]
pub enum HeadRef {
    Branch(String),
    Detached(String),
}

/// A real ref file name: not a hidden staging file (`.x.tmp.<pid>`) and not a
/// lockfile (`x.lock`) produced by `crate::atomic`.
fn is_ref_name(name: &str) -> bool {
    !name.starts_with('.') && !name.ends_with(".lock")
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use tempfile::TempDir;

    fn setup() -> (TempDir, RefManager) {
        let tmp = TempDir::new().unwrap();
        let mgr = RefManager::new(tmp.path().to_path_buf());
        std::fs::create_dir_all(mgr.heads_dir()).unwrap();
        (tmp, mgr)
    }

    #[test]
    fn test_set_and_get_branch() {
        let (_tmp, mgr) = setup();
        mgr.set_branch("main", "abc123").unwrap();
        assert_eq!(mgr.get_branch("main").unwrap(), Some("abc123".to_string()));
    }

    #[test]
    fn test_get_nonexistent_branch() {
        let (_tmp, mgr) = setup();
        assert_eq!(mgr.get_branch("nope").unwrap(), None);
    }

    #[test]
    fn test_delete_branch() {
        let (_tmp, mgr) = setup();
        mgr.set_branch("feature", "def456").unwrap();
        mgr.delete_branch("feature").unwrap();
        assert_eq!(mgr.get_branch("feature").unwrap(), None);
    }

    #[test]
    fn test_list_branches() {
        let (_tmp, mgr) = setup();
        mgr.set_branch("main", "a").unwrap();
        mgr.set_branch("feature", "b").unwrap();
        mgr.set_branch("hotfix", "c").unwrap();
        let branches = mgr.list_branches().unwrap();
        assert_eq!(branches, vec!["feature", "hotfix", "main"]);
    }

    #[test]
    fn test_head_symbolic_ref() {
        let (_tmp, mgr) = setup();
        mgr.set_branch("main", "abc123").unwrap();
        mgr.set_head("main").unwrap();
        assert_eq!(mgr.get_head().unwrap(), HeadRef::Branch("main".to_string()));
        assert_eq!(mgr.current_branch().unwrap(), Some("main".to_string()));
        assert_eq!(mgr.resolve_head().unwrap(), Some("abc123".to_string()));
    }

    #[test]
    fn test_head_detached() {
        let (_tmp, mgr) = setup();
        std::fs::write(mgr.head_path(), "deadbeef\n").unwrap();
        assert_eq!(mgr.get_head().unwrap(), HeadRef::Detached("deadbeef".to_string()));
        assert_eq!(mgr.current_branch().unwrap(), None);
        assert_eq!(mgr.resolve_head().unwrap(), Some("deadbeef".to_string()));
    }

    #[test]
    fn test_cas_branch_update_applies_on_match() {
        let (_tmp, mgr) = setup();
        mgr.set_branch("main", "aaa").unwrap();
        assert!(mgr.set_branch_if_current("main", "bbb", Some("aaa")).unwrap());
        assert_eq!(mgr.get_branch("main").unwrap(), Some("bbb".to_string()));
    }

    #[test]
    fn test_cas_branch_rejects_on_mismatch() {
        let (_tmp, mgr) = setup();
        mgr.set_branch("main", "moved").unwrap();
        assert!(!mgr.set_branch_if_current("main", "bbb", Some("old")).unwrap());
        assert_eq!(mgr.get_branch("main").unwrap(), Some("moved".to_string()));
    }

    #[test]
    fn test_cas_branch_create_only() {
        let (_tmp, mgr) = setup();
        // None expected: create-only, applies on missing ref.
        assert!(mgr.set_branch_if_current("feat", "v1", None).unwrap());
        assert_eq!(mgr.get_branch("feat").unwrap(), Some("v1".to_string()));
        // Second create-only attempt must be rejected.
        assert!(!mgr.set_branch_if_current("feat", "v2", None).unwrap());
        assert_eq!(mgr.get_branch("feat").unwrap(), Some("v1".to_string()));
    }

    #[test]
    fn test_cas_branch_concurrent_writers_one_wins() {
        let tmp = TempDir::new().unwrap();
        let mgr = RefManager::new(tmp.path().to_path_buf());
        std::fs::create_dir_all(mgr.heads_dir()).unwrap();
        mgr.set_branch("main", "base").unwrap();

        // Two threads CAS from the same base value; the ref must end at
        // exactly one of them, and exactly one CAS must report success.
        let successes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let mut handles = Vec::new();
        for i in 0..2u32 {
            let m = mgr.clone();
            let s = Arc::clone(&successes);
            handles.push(std::thread::spawn(move || {
                let new_val = format!("winner-{}", i);
                if m.set_branch_if_current("main", &new_val, Some("base")).unwrap() {
                    s.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    return new_val;
                }
                "loser".to_string()
            }));
        }
        let outcomes: Vec<String> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        assert_eq!(successes.load(std::sync::atomic::Ordering::SeqCst), 1);
        let final_val = mgr.get_branch("main").unwrap().unwrap();
        assert!(final_val == "winner-0" || final_val == "winner-1");
        assert!(outcomes.contains(&final_val));
    }

    #[test]
    fn test_listing_ignores_atomic_litter() {
        let (_tmp, mgr) = setup();
        mgr.set_branch("main", "abc").unwrap();
        // Simulate staging + lockfile leftovers from a crashed writer.
        std::fs::write(mgr.heads_dir().join(".main.tmp.4242"), "garbage").unwrap();
        std::fs::write(mgr.heads_dir().join("main.lock"), "").unwrap();
        let branches = mgr.list_branches().unwrap();
        assert_eq!(branches, vec!["main"]);
    }
}