codetree 0.1.2

AI-native version control system for autonomous agents
Documentation
use std::path::PathBuf;
use std::collections::HashMap;
use crate::error::Result;

/// A staged entry: blob ID plus the stat fingerprint of the working-tree file
/// it was staged from. The stat fingerprint is a git-style cache — if a file's
/// mtime/size/inode are unchanged since staging, its content is unchanged and
/// re-hashing can be skipped.
#[derive(Debug, Clone, PartialEq)]
pub struct IndexEntry {
    pub blob_id: String,
    pub mtime_secs: u64,
    pub mtime_nanos: u32,
    pub size: u64,
    pub inode: u64,
}

impl IndexEntry {
    /// A fingerprint of all zeros means "no stat info" (legacy entry or added
    /// without stat) — it never matches, forcing a re-hash.
    pub fn matches_stat(&self, mtime_secs: u64, mtime_nanos: u32, size: u64, inode: u64) -> bool {
        self.mtime_secs != 0
            && self.mtime_secs == mtime_secs
            && self.mtime_nanos == mtime_nanos
            && self.size == size
            && self.inode == inode
    }
}

/// The index (staging area) maps file paths to blob object IDs.
pub struct Index {
    root: PathBuf,
    entries: HashMap<String, IndexEntry>,
}

impl Index {
    pub fn new(root: PathBuf) -> Self {
        Self {
            root,
            entries: HashMap::new(),
        }
    }

    fn index_path(&self) -> PathBuf {
        self.root.join("index")
    }

    /// Load the index from disk. If no index file exists, starts empty.
    /// Accepts both the current format
    /// (`path\0blob\0mtime_secs\0mtime_nanos\0size\0inode`) and the legacy
    /// format (`path\0blob`) — legacy entries carry no stat info.
    pub fn load(root: PathBuf) -> Result<Self> {
        let path = root.join("index");
        let entries = if path.exists() {
            let data = std::fs::read_to_string(&path)?;
            let mut map = HashMap::new();
            for line in data.lines() {
                let parts: Vec<&str> = line.split('\0').collect();
                match parts.as_slice() {
                    [path, blob, secs, nanos, size, ino] => {
                        map.insert(
                            path.to_string(),
                            IndexEntry {
                                blob_id: blob.to_string(),
                                mtime_secs: secs.parse().unwrap_or(0),
                                mtime_nanos: nanos.parse().unwrap_or(0),
                                size: size.parse().unwrap_or(0),
                                inode: ino.parse().unwrap_or(0),
                            },
                        );
                    }
                    [path, blob] => {
                        map.insert(
                            path.to_string(),
                            IndexEntry {
                                blob_id: blob.to_string(),
                                mtime_secs: 0,
                                mtime_nanos: 0,
                                size: 0,
                                inode: 0,
                            },
                        );
                    }
                    _ => {}
                }
            }
            map
        } else {
            HashMap::new()
        };
        Ok(Self { root, entries })
    }

    /// Save the index to disk (atomic: temp file + rename, writer-serialized).
    pub fn save(&self) -> Result<()> {
        let path = self.index_path();
        let mut data = String::new();
        let mut paths: Vec<_> = self.entries.keys().collect();
        paths.sort();
        for p in paths {
            if let Some(e) = self.entries.get(p) {
                data.push_str(&format!(
                    "{}\0{}\0{}\0{}\0{}\0{}\n",
                    p, e.blob_id, e.mtime_secs, e.mtime_nanos, e.size, e.inode
                ));
            }
        }
        crate::atomic::write_atomic(&path, data.as_bytes())?;
        Ok(())
    }

    /// Add or update a file entry in the index without stat info.
    /// The next staging pass will re-hash the file.
    pub fn add(&mut self, path: &str, blob_id: &str) {
        self.entries.insert(
            path.to_string(),
            IndexEntry {
                blob_id: blob_id.to_string(),
                mtime_secs: 0,
                mtime_nanos: 0,
                size: 0,
                inode: 0,
            },
        );
    }

    /// Add or update an entry with the stat fingerprint of the staged file.
    pub fn add_staged(
        &mut self,
        path: &str,
        blob_id: &str,
        mtime_secs: u64,
        mtime_nanos: u32,
        size: u64,
        inode: u64,
    ) {
        self.entries.insert(
            path.to_string(),
            IndexEntry {
                blob_id: blob_id.to_string(),
                mtime_secs,
                mtime_nanos,
                size,
                inode,
            },
        );
    }

    /// Remove a file entry from the index.
    pub fn remove(&mut self, path: &str) {
        self.entries.remove(path);
    }

    /// Get the blob ID for a path, if it exists in the index.
    pub fn get(&self, path: &str) -> Option<&str> {
        self.entries.get(path).map(|e| e.blob_id.as_str())
    }

    /// Get the full entry (blob ID + stat fingerprint) for a path.
    pub fn entry(&self, path: &str) -> Option<&IndexEntry> {
        self.entries.get(path)
    }

    /// Get all entries as a sorted list of (path, blob_id) pairs.
    pub fn entries_sorted(&self) -> Vec<(String, String)> {
        let mut entries: Vec<_> = self
            .entries
            .iter()
            .map(|(k, v)| (k.clone(), v.blob_id.clone()))
            .collect();
        entries.sort_by(|a, b| a.0.cmp(&b.0));
        entries
    }

    /// Check if the index is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Get the number of entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Clear all entries.
    pub fn clear(&mut self) {
        self.entries.clear();
    }
}

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

    #[test]
    fn test_index_add_and_get() {
        let tmp = TempDir::new().unwrap();
        let mut idx = Index::new(tmp.path().to_path_buf());
        idx.add("src/main.rs", "abc123");
        assert_eq!(idx.get("src/main.rs"), Some("abc123"));
        assert_eq!(idx.get("src/other.rs"), None);
    }

    #[test]
    fn test_index_remove() {
        let tmp = TempDir::new().unwrap();
        let mut idx = Index::new(tmp.path().to_path_buf());
        idx.add("file.txt", "hash1");
        idx.remove("file.txt");
        assert_eq!(idx.get("file.txt"), None);
    }

    #[test]
    fn test_index_save_and_load() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();

        let mut idx = Index::new(root.clone());
        idx.add("a.rs", "hash_a");
        idx.add_staged("b.rs", "hash_b", 1700000000, 123, 456, 789);
        idx.save().unwrap();

        let loaded = Index::load(root).unwrap();
        assert_eq!(loaded.get("a.rs"), Some("hash_a"));
        assert_eq!(loaded.get("b.rs"), Some("hash_b"));
        assert_eq!(loaded.len(), 2);

        let b = loaded.entry("b.rs").unwrap();
        assert_eq!(b.mtime_secs, 1700000000);
        assert_eq!(b.mtime_nanos, 123);
        assert_eq!(b.size, 456);
        assert_eq!(b.inode, 789);
        assert!(b.matches_stat(1700000000, 123, 456, 789));
        assert!(!b.matches_stat(1700000000, 123, 457, 789));

        // Entries added without stat never match (forces re-hash).
        let a = loaded.entry("a.rs").unwrap();
        assert!(!a.matches_stat(0, 0, 0, 0));
    }

    #[test]
    fn test_index_load_legacy_format() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().to_path_buf();
        std::fs::write(root.join("index"), "a.rs\0hash_a\nb.rs\0hash_b\n").unwrap();

        let loaded = Index::load(root).unwrap();
        assert_eq!(loaded.get("a.rs"), Some("hash_a"));
        assert_eq!(loaded.get("b.rs"), Some("hash_b"));
        assert!(loaded.entry("a.rs").unwrap().mtime_secs == 0);
    }

    #[test]
    fn test_index_load_empty() {
        let tmp = TempDir::new().unwrap();
        let idx = Index::load(tmp.path().to_path_buf()).unwrap();
        assert!(idx.is_empty());
    }

    #[test]
    fn test_index_entries_sorted() {
        let tmp = TempDir::new().unwrap();
        let mut idx = Index::new(tmp.path().to_path_buf());
        idx.add("c.rs", "3");
        idx.add("a.rs", "1");
        idx.add("b.rs", "2");
        let entries = idx.entries_sorted();
        assert_eq!(entries[0].0, "a.rs");
        assert_eq!(entries[1].0, "b.rs");
        assert_eq!(entries[2].0, "c.rs");
    }
}