codetree 0.1.1

AI-native version control system for autonomous agents
Documentation
use sha1::{Sha1, Digest};
use std::path::{Path, PathBuf};

/// A 40-character hex SHA-1 hash identifying an object.
pub type ObjectId = String;

/// Object types in the content-addressable store.
#[derive(Debug, Clone, PartialEq)]
pub enum ObjectType {
    Blob,
    Tree,
    Commit,
}

impl ObjectType {
    fn as_str(&self) -> &'static str {
        match self {
            ObjectType::Blob => "blob",
            ObjectType::Tree => "tree",
            ObjectType::Commit => "commit",
        }
    }
}

/// A blob stores file content.
#[derive(Debug, Clone)]
pub struct Blob {
    pub content: Vec<u8>,
}

impl Blob {
    pub fn new(content: Vec<u8>) -> Self {
        Self { content }
    }

    /// Compute the object ID for this blob.
    /// Format: "blob \<len\>\0\<content\>" hashed with SHA-1.
    pub fn id(&self) -> ObjectId {
        hash_object(ObjectType::Blob, &self.content)
    }

    /// Serialize to bytes for storage.
    pub fn serialize(&self) -> Vec<u8> {
        self.content.clone()
    }

    /// Deserialize from stored bytes.
    pub fn deserialize(data: &[u8]) -> Self {
        Self {
            content: data.to_vec(),
        }
    }
}

/// A tree entry maps a name to a blob or subtree.
#[derive(Debug, Clone)]
pub struct TreeEntry {
    pub mode: u32,
    pub name: String,
    pub id: ObjectId,
}

/// A tree stores a directory listing (list of entries).
#[derive(Debug, Clone)]
pub struct Tree {
    pub entries: Vec<TreeEntry>,
}

impl Tree {
    pub fn new(entries: Vec<TreeEntry>) -> Self {
        Self { entries }
    }

    pub fn id(&self) -> ObjectId {
        let data = self.serialize();
        hash_object(ObjectType::Tree, &data)
    }

    /// Serialize: "\<mode\> \<name\>\0\<20-byte-hash\>" repeated for each entry.
    pub fn serialize(&self) -> Vec<u8> {
        let mut out = Vec::new();
        for entry in &self.entries {
            out.extend_from_slice(format!("{} {}\0", entry.mode, entry.name).as_bytes());
            let bytes = hex_decode(&entry.id);
            out.extend_from_slice(&bytes);
        }
        out
    }

    pub fn deserialize(data: &[u8]) -> Self {
        let mut entries = Vec::new();
        let mut pos = 0;
        while pos < data.len() {
            // Read "<mode> <name>\0"
            let null_pos = match data[pos..].iter().position(|&b| b == 0) {
                Some(p) => pos + p,
                None => break,
            };
            let header = String::from_utf8_lossy(&data[pos..null_pos]);
            let mut parts = header.splitn(2, ' ');
            let mode: u32 = parts.next().unwrap_or("0").parse().unwrap_or(0);
            let name = parts.next().unwrap_or("").to_string();
            pos = null_pos + 1;
            // Read 20-byte hash
            if pos + 20 > data.len() {
                break;
            }
            let hash_bytes = &data[pos..pos + 20];
            let id = hex_encode(hash_bytes);
            pos += 20;
            entries.push(TreeEntry { mode, name, id });
        }
        Self { entries }
    }
}

/// A commit stores a tree hash, parent commit hashes, and metadata.
#[derive(Debug, Clone)]
pub struct Commit {
    pub tree: ObjectId,
    pub parents: Vec<ObjectId>,
    pub author: String,
    pub message: String,
    pub timestamp: u64,
}

impl Commit {
    pub fn new(tree: ObjectId, parents: Vec<ObjectId>, author: String, message: String, timestamp: u64) -> Self {
        Self { tree, parents, author, message, timestamp }
    }

    pub fn id(&self) -> ObjectId {
        let data = self.serialize();
        hash_object(ObjectType::Commit, &data)
    }

    /// Serialize: text format similar to Git commits.
    pub fn serialize(&self) -> Vec<u8> {
        let mut out = String::new();
        out.push_str(&format!("tree {}\n", self.tree));
        for p in &self.parents {
            out.push_str(&format!("parent {}\n", p));
        }
        out.push_str(&format!("author {} {}\n", self.author, self.timestamp));
        out.push_str(&format!("committer {} {}\n", self.author, self.timestamp));
        out.push('\n');
        out.push_str(&self.message);
        out.into_bytes()
    }

    pub fn deserialize(data: &[u8]) -> Self {
        let text = String::from_utf8_lossy(data);
        let mut tree = String::new();
        let mut parents = Vec::new();
        let mut author = String::new();
        let mut timestamp = 0u64;
        let mut message = String::new();
        let mut in_header = true;

        for line in text.lines() {
            if in_header {
                if line.is_empty() {
                    in_header = false;
                    continue;
                }
                if let Some(rest) = line.strip_prefix("tree ") {
                    tree = rest.to_string();
                } else if let Some(rest) = line.strip_prefix("parent ") {
                    parents.push(rest.to_string());
                } else if let Some(rest) = line.strip_prefix("author ") {
                    let mut parts = rest.rsplitn(2, ' ');
                    if let Some(ts) = parts.next() {
                        timestamp = ts.parse().unwrap_or(0);
                    }
                    if let Some(name) = parts.next() {
                        author = name.to_string();
                    }
                }
            } else {
                if !message.is_empty() {
                    message.push('\n');
                }
                message.push_str(line);
            }
        }

        Self { tree, parents, author, message, timestamp }
    }
}

/// Compute SHA-1 hash of an object with its header.
/// Format: "\<type\> \<len\>\0\<content\>"
pub fn hash_object(obj_type: ObjectType, content: &[u8]) -> ObjectId {
    let header = format!("{} {}\0", obj_type.as_str(), content.len());
    let mut hasher = Sha1::new();
    hasher.update(header.as_bytes());
    hasher.update(content);
    let result = hasher.finalize();
    hex_encode(&result)
}

/// Convert bytes to hex string.
pub fn hex_encode(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{:02x}", b)).collect()
}

/// Convert hex string to bytes.
pub fn hex_decode(hex: &str) -> Vec<u8> {
    (0..hex.len())
        .step_by(2)
        .filter_map(|i| u8::from_str_radix(&hex[i..i + 2], 16).ok())
        .collect()
}

/// Compute the object path in the store: objects/<first 2>/<remaining 38>
pub fn object_path(store_root: &Path, id: &str) -> PathBuf {
    let (dir, file) = id.split_at(2);
    store_root.join("objects").join(dir).join(file)
}

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

    #[test]
    fn test_blob_hash_deterministic() {
        let blob1 = Blob::new(b"hello world".to_vec());
        let blob2 = Blob::new(b"hello world".to_vec());
        assert_eq!(blob1.id(), blob2.id());
    }

    #[test]
    fn test_blob_hash_differs_for_different_content() {
        let blob1 = Blob::new(b"hello".to_vec());
        let blob2 = Blob::new(b"world".to_vec());
        assert_ne!(blob1.id(), blob2.id());
    }

    #[test]
    fn test_blob_roundtrip() {
        let blob = Blob::new(b"test content".to_vec());
        let serialized = blob.serialize();
        let deserialized = Blob::deserialize(&serialized);
        assert_eq!(blob.content, deserialized.content);
        assert_eq!(blob.id(), deserialized.id());
    }

    #[test]
    fn test_tree_roundtrip() {
        let tree = Tree::new(vec![
            TreeEntry { mode: 0o100644, name: "file.txt".to_string(), id: "abcdef1234567890abcdef1234567890abcdef12".to_string() },
            TreeEntry { mode: 0o100644, name: "src/main.rs".to_string(), id: "1234567890abcdef1234567890abcdef12345678".to_string() },
        ]);
        let serialized = tree.serialize();
        let deserialized = Tree::deserialize(&serialized);
        assert_eq!(tree.entries.len(), deserialized.entries.len());
        for (a, b) in tree.entries.iter().zip(deserialized.entries.iter()) {
            assert_eq!(a.mode, b.mode);
            assert_eq!(a.name, b.name);
            assert_eq!(a.id, b.id);
        }
    }

    #[test]
    fn test_commit_roundtrip() {
        let commit = Commit::new(
            "abc123".to_string(),
            vec!["parent1".to_string()],
            "agent".to_string(),
            "Fix bug".to_string(),
            1700000000,
        );
        let serialized = commit.serialize();
        let deserialized = Commit::deserialize(&serialized);
        assert_eq!(commit.tree, deserialized.tree);
        assert_eq!(commit.parents, deserialized.parents);
        assert_eq!(commit.author, deserialized.author);
        assert_eq!(commit.message, deserialized.message);
        assert_eq!(commit.timestamp, deserialized.timestamp);
    }

    #[test]
    fn test_commit_hash_deterministic() {
        let c1 = Commit::new("tree1".to_string(), vec![], "agent".to_string(), "msg".to_string(), 100);
        let c2 = Commit::new("tree1".to_string(), vec![], "agent".to_string(), "msg".to_string(), 100);
        assert_eq!(c1.id(), c2.id());
    }

    #[test]
    fn test_hex_encode_decode() {
        let bytes = [0xab, 0xcd, 0xef];
        let hex = hex_encode(&bytes);
        assert_eq!(hex, "abcdef");
        let decoded = hex_decode(&hex);
        assert_eq!(decoded, bytes.to_vec());
    }

    #[test]
    fn test_object_path() {
        let root = PathBuf::from("/repo/.codetree");
        let path = object_path(&root, "abcdef1234567890abcdef1234567890abcdef12");
        assert_eq!(path, PathBuf::from("/repo/.codetree/objects/ab/cdef1234567890abcdef1234567890abcdef12"));
    }
}