codetree 0.1.1

AI-native version control system for autonomous agents
Documentation
use std::path::{Path, PathBuf};
use crate::error::{Result, Context};
use super::objects::{Blob, Tree, TreeEntry, Commit, ObjectId, object_path, hash_object, ObjectType};
use super::refs::RefManager;
use super::index::Index;

/// A CodeTree repository. Owns the `.codetree/` directory structure.
#[derive(Clone)]
pub struct Repository {
    root: PathBuf,
    refs: RefManager,
}

impl Repository {
    /// Initialize a new repository at the given path.
    /// Creates `.codetree/` with objects/, refs/heads/, HEAD, and an empty index.
    pub fn init(path: &Path) -> Result<Self> {
        let codetree_dir = path.join(".codetree");
        if codetree_dir.exists() {
            bail!("Repository already exists at {}", codetree_dir.display());
        }

        std::fs::create_dir_all(codetree_dir.join("objects"))?;
        std::fs::create_dir_all(codetree_dir.join("refs").join("heads"))?;

        let repo = Self {
            root: codetree_dir.clone(),
            refs: RefManager::new(codetree_dir.clone()),
        };

        // Create initial commit on main with an empty tree
        let empty_tree = Tree::new(vec![]);
        repo.write_object(ObjectType::Tree, &empty_tree.serialize())?;
        let tree_id = empty_tree.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(
            tree_id,
            vec![],
            "CodeTree <init@codetree>".to_string(),
            "Initial commit".to_string(),
            timestamp,
        );
        repo.write_object(ObjectType::Commit, &commit.serialize())?;
        let commit_id = commit.id();

        repo.refs.set_branch("main", &commit_id)?;
        repo.refs.set_head("main")?;

        // Create empty index
        Index::new(codetree_dir.clone()).save()?;

        Ok(repo)
    }

    /// Open an existing repository at the given path.
    pub fn open(path: &Path) -> Result<Self> {
        let codetree_dir = path.join(".codetree");
        if !codetree_dir.exists() {
            bail!("No CodeTree repository found at {}", path.display());
        }
        Ok(Self {
            root: codetree_dir.clone(),
            refs: RefManager::new(codetree_dir),
        })
    }

    /// Get the root `.codetree/` path.
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Get a reference to the ref manager.
    pub fn refs(&self) -> &RefManager {
        &self.refs
    }

    /// Write an object to the store. Content-addressed and immutable, so the
    /// write uses temp-file + rename (no lockfile): concurrent writers of the
    /// same object produce identical bytes, and rename is atomic — readers can
    /// never observe a torn object at its final path.
    pub fn write_object(&self, obj_type: ObjectType, data: &[u8]) -> Result<ObjectId> {
        let id = hash_object(obj_type.clone(), data);
        let path = object_path(&self.root, &id);
        if !path.exists() {
            let tmp = crate::atomic::temp_sibling(&path);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            std::fs::write(&tmp, data)?;
            std::fs::rename(&tmp, &path)?;
        }
        Ok(id)
    }

    /// Read an object from the store by ID.
    pub fn read_object(&self, id: &ObjectId) -> Result<Vec<u8>> {
        let path = object_path(&self.root, id);
        std::fs::read(&path).context("Object not found")
    }

    /// Check if an object exists in the store.
    pub fn has_object(&self, id: &str) -> bool {
        object_path(&self.root, id).exists()
    }

    /// Write a blob to the store and return its ID.
    /// Blob serialization is the raw content, so no intermediate copy is made.
    pub fn write_blob(&self, content: &[u8]) -> Result<ObjectId> {
        self.write_object(ObjectType::Blob, content)
    }

    /// Read a blob from the store.
    pub fn read_blob(&self, id: &ObjectId) -> Result<Blob> {
        let data = self.read_object(id)?;
        Ok(Blob::deserialize(&data))
    }

    /// Write a tree to the store and return its ID.
    pub fn write_tree(&self, tree: &Tree) -> Result<ObjectId> {
        self.write_object(ObjectType::Tree, &tree.serialize())
    }

    /// Read a tree from the store.
    pub fn read_tree(&self, id: &ObjectId) -> Result<Tree> {
        let data = self.read_object(id)?;
        Ok(Tree::deserialize(&data))
    }

    /// Write a commit to the store and return its ID.
    pub fn write_commit(&self, commit: &Commit) -> Result<ObjectId> {
        self.write_object(ObjectType::Commit, &commit.serialize())
    }

    /// Read a commit from the store.
    pub fn read_commit(&self, id: &ObjectId) -> Result<Commit> {
        let data = self.read_object(id)?;
        Ok(Commit::deserialize(&data))
    }

    /// Load the index.
    pub fn load_index(&self) -> Result<Index> {
        Index::load(self.root.clone())
    }

    /// Create a commit from the current index, updating the current branch ref.
    pub fn commit(&self, message: &str, author: &str) -> Result<ObjectId> {
        let index = self.load_index()?;

        // Build tree from index
        let entries: Vec<TreeEntry> = index.entries_sorted().into_iter().map(|(path, blob_id)| {
            TreeEntry { mode: 0o100644, name: path, id: blob_id }
        }).collect();
        let tree = Tree::new(entries);
        let tree_id = self.write_tree(&tree)?;

        // Get parent commit (current HEAD)
        let parent = self.refs.resolve_head()?;
        let parents = parent.into_iter().collect();

        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, author.to_string(), message.to_string(), timestamp);
        let commit_id = self.write_commit(&commit)?;

        // Update current branch ref
        if let Some(branch) = self.refs.current_branch()? {
            self.refs.set_branch(&branch, &commit_id)?;
        }

        Ok(commit_id)
    }

    /// Create a commit from the current index with custom author and timestamp.
    pub fn commit_with_meta(&self, message: &str, author: &str, timestamp: u64) -> Result<ObjectId> {
        let index = self.load_index()?;
        let entries: Vec<TreeEntry> = index.entries_sorted().into_iter().map(|(path, blob_id)| {
            TreeEntry { mode: 0o100644, name: path, id: blob_id }
        }).collect();
        let tree = Tree::new(entries);
        let tree_id = self.write_tree(&tree)?;
        let parent = self.refs.resolve_head()?;
        let parents = parent.into_iter().collect();
        let commit = Commit::new(tree_id, parents, author.to_string(), message.to_string(), timestamp);
        let commit_id = self.write_commit(&commit)?;
        if let Some(branch) = self.refs.current_branch()? {
            self.refs.set_branch(&branch, &commit_id)?;
        }
        Ok(commit_id)
    }

    /// Create a new branch pointing at the current HEAD commit.
    pub fn create_branch(&self, name: &str) -> Result<()> {
        let head = self.refs.resolve_head()?
            .context("HEAD does not point to a commit")?;
        self.refs.set_branch(name, &head)?;
        Ok(())
    }

    /// Checkout a branch: update HEAD and restore working tree.
    /// (Working tree restoration will be implemented in Phase 2.)
    pub fn checkout(&self, branch: &str) -> Result<()> {
        let commit_id = self.refs.get_branch(branch)?
            .context(format!("Branch '{}' not found", branch))?;
        self.refs.set_head(branch)?;
        // Phase 2: restore working tree from commit_id's tree
        let _ = commit_id;
        Ok(())
    }
}

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

    fn init_repo() -> (TempDir, Repository) {
        let tmp = TempDir::new().unwrap();
        let repo = Repository::init(tmp.path()).unwrap();
        (tmp, repo)
    }

    #[test]
    fn test_init_creates_structure() {
        let (tmp, repo) = init_repo();
        assert!(tmp.path().join(".codetree").exists());
        assert!(tmp.path().join(".codetree/objects").exists());
        assert!(tmp.path().join(".codetree/refs/heads").exists());
        assert!(tmp.path().join(".codetree/HEAD").exists());
        assert!(tmp.path().join(".codetree/index").exists());

        // main branch should exist
        let branches = repo.refs().list_branches().unwrap();
        assert!(branches.contains(&"main".to_string()));

        // HEAD should point to main
        assert_eq!(repo.refs().current_branch().unwrap(), Some("main".to_string()));
    }

    #[test]
    fn test_init_fails_if_already_exists() {
        let tmp = TempDir::new().unwrap();
        Repository::init(tmp.path()).unwrap();
        let result = Repository::init(tmp.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_open_existing_repo() {
        let tmp = TempDir::new().unwrap();
        Repository::init(tmp.path()).unwrap();
        let repo = Repository::open(tmp.path()).unwrap();
        assert_eq!(repo.refs().current_branch().unwrap(), Some("main".to_string()));
    }

    #[test]
    fn test_open_fails_if_no_repo() {
        let tmp = TempDir::new().unwrap();
        let result = Repository::open(tmp.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_write_and_read_blob() {
        let (_tmp, repo) = init_repo();
        let id = repo.write_blob(b"hello world").unwrap();
        let blob = repo.read_blob(&id).unwrap();
        assert_eq!(blob.content, b"hello world");
    }

    #[test]
    fn test_write_and_read_tree() {
        let (_tmp, repo) = init_repo();
        let blob_id = repo.write_blob(b"content").unwrap();
        let tree = Tree::new(vec![
            TreeEntry { mode: 0o100644, name: "file.txt".to_string(), id: blob_id.clone() },
        ]);
        let tree_id = repo.write_tree(&tree).unwrap();
        let read_tree = repo.read_tree(&tree_id).unwrap();
        assert_eq!(read_tree.entries.len(), 1);
        assert_eq!(read_tree.entries[0].name, "file.txt");
        assert_eq!(read_tree.entries[0].id, blob_id);
    }

    #[test]
    fn test_write_and_read_commit() {
        let (_tmp, repo) = init_repo();
        let tree = Tree::new(vec![]);
        let tree_id = repo.write_tree(&tree).unwrap();
        let commit = Commit::new(
            tree_id,
            vec![],
            "test".to_string(),
            "test commit".to_string(),
            12345,
        );
        let commit_id = repo.write_commit(&commit).unwrap();
        let read_commit = repo.read_commit(&commit_id).unwrap();
        assert_eq!(read_commit.message, "test commit");
        assert_eq!(read_commit.author, "test");
    }

    #[test]
    fn test_has_object() {
        let (_tmp, repo) = init_repo();
        let id = repo.write_blob(b"data").unwrap();
        assert!(repo.has_object(&id));
        assert!(!repo.has_object("0000000000000000000000000000000000000000"));
    }

    #[test]
    fn test_create_branch() {
        let (_tmp, repo) = init_repo();
        repo.create_branch("feature").unwrap();
        let branches = repo.refs().list_branches().unwrap();
        assert!(branches.contains(&"feature".to_string()));
        // feature should point at same commit as main
        let main_commit = repo.refs().get_branch("main").unwrap().unwrap();
        let feature_commit = repo.refs().get_branch("feature").unwrap().unwrap();
        assert_eq!(main_commit, feature_commit);
    }

    #[test]
    fn test_commit_updates_branch_ref() {
        let (_tmp, repo) = init_repo();

        // Stage a file
        let mut index = repo.load_index().unwrap();
        let blob_id = repo.write_blob(b"hello").unwrap();
        index.add("hello.txt", &blob_id);
        index.save().unwrap();

        // Commit
        let commit_id = repo.commit("Add hello.txt", "agent").unwrap();

        // main should now point to the new commit
        let main_commit = repo.refs().get_branch("main").unwrap().unwrap();
        assert_eq!(main_commit, commit_id);

        // The commit should have the initial commit as parent
        let commit = repo.read_commit(&commit_id).unwrap();
        assert_eq!(commit.parents.len(), 1);
    }

    #[test]
    fn test_checkout() {
        let (_tmp, repo) = init_repo();
        repo.create_branch("feature").unwrap();
        repo.checkout("feature").unwrap();
        assert_eq!(repo.refs().current_branch().unwrap(), Some("feature".to_string()));
    }
}