codetree 0.1.1

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

/// Manages frozen paths — files/directories that cannot be modified by any operation.
/// Stored in `.codetree/frozen.json` as a list of path strings.
pub struct FrozenPaths {
    path: PathBuf,
    frozen: HashSet<String>,
}

impl FrozenPaths {
    pub fn new(path: PathBuf) -> Self {
        Self {
            path,
            frozen: HashSet::new(),
        }
    }

    /// Load frozen paths from disk. If no file exists, starts empty.
    pub fn load(path: PathBuf) -> Result<Self> {
        let frozen = if path.exists() {
            let data = std::fs::read_to_string(&path)?;
            let list: Vec<String> = serde_json::from_str(&data).unwrap_or_default();
            list.into_iter().collect()
        } else {
            HashSet::new()
        };
        Ok(Self { path, frozen })
    }

    /// Save frozen paths to disk.
    pub fn save(&self) -> Result<()> {
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut list: Vec<_> = self.frozen.iter().collect();
        list.sort();
        let data = serde_json::to_string_pretty(&list)?;
        crate::atomic::write_atomic(&self.path, data.as_bytes())?;
        Ok(())
    }

    /// Freeze a path. Returns true if newly frozen, false if already frozen.
    pub fn freeze(&mut self, path: &str) -> bool {
        self.frozen.insert(path.to_string())
    }

    /// Unfreeze a path. Returns true if it was frozen, false if not.
    pub fn unfreeze(&mut self, path: &str) -> bool {
        self.frozen.remove(path)
    }

    /// Check if a path is frozen.
    pub fn is_frozen(&self, path: &str) -> bool {
        // Check exact match
        if self.frozen.contains(path) {
            return true;
        }
        // Check if any frozen directory is a parent of this path
        for frozen in &self.frozen {
            if frozen.ends_with('/') {
                if path.starts_with(frozen.as_str()) {
                    return true;
                }
            } else {
                // Frozen path without trailing slash — check if it's a parent directory
                let prefix = format!("{}/", frozen);
                if path.starts_with(&prefix) {
                    return true;
                }
            }
        }
        false
    }

    /// Check if any of the given paths are frozen. Returns the first frozen path found.
    pub fn check_paths<'a>(&self, paths: &'a [String]) -> Option<&'a str> {
        for path in paths {
            if self.is_frozen(path) {
                return Some(path.as_str());
            }
        }
        None
    }

    /// List all frozen paths, sorted.
    pub fn list(&self) -> Vec<String> {
        let mut list: Vec<_> = self.frozen.iter().cloned().collect();
        list.sort();
        list
    }

    /// Number of frozen paths.
    pub fn len(&self) -> usize {
        self.frozen.len()
    }

    /// Whether any paths are frozen.
    pub fn is_empty(&self) -> bool {
        self.frozen.is_empty()
    }
}

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

    fn setup() -> (TempDir, FrozenPaths) {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frozen.json");
        let fp = FrozenPaths::new(path);
        (tmp, fp)
    }

    #[test]
    fn test_freeze_and_check() {
        let (_tmp, mut fp) = setup();
        fp.freeze("src/core.rs");
        assert!(fp.is_frozen("src/core.rs"));
        assert!(!fp.is_frozen("src/other.rs"));
    }

    #[test]
    fn test_freeze_directory() {
        let (_tmp, mut fp) = setup();
        fp.freeze("src/core/");
        assert!(fp.is_frozen("src/core/mod.rs"));
        assert!(fp.is_frozen("src/core/types.rs"));
        assert!(!fp.is_frozen("src/other.rs"));
    }

    #[test]
    fn test_freeze_directory_without_slash() {
        let (_tmp, mut fp) = setup();
        fp.freeze("src/core");
        assert!(fp.is_frozen("src/core/mod.rs"));
        assert!(fp.is_frozen("src/core/"));
        assert!(!fp.is_frozen("src/other.rs"));
    }

    #[test]
    fn test_unfreeze() {
        let (_tmp, mut fp) = setup();
        fp.freeze("a.rs");
        assert!(fp.unfreeze("a.rs"));
        assert!(!fp.is_frozen("a.rs"));
        assert!(!fp.unfreeze("nonexistent.rs"));
    }

    #[test]
    fn test_freeze_already_frozen() {
        let (_tmp, mut fp) = setup();
        assert!(fp.freeze("a.rs"));
        assert!(!fp.freeze("a.rs")); // Second time returns false
    }

    #[test]
    fn test_check_paths() {
        let (_tmp, mut fp) = setup();
        fp.freeze("b.rs");
        let paths = ["a.rs".to_string(), "b.rs".to_string(), "c.rs".to_string()];
        let result = fp.check_paths(&paths);
        assert_eq!(result, Some("b.rs"));
    }

    #[test]
    fn test_check_paths_none_frozen() {
        let (_tmp, fp) = setup();
        let paths = ["a.rs".to_string(), "b.rs".to_string()];
        let result = fp.check_paths(&paths);
        assert_eq!(result, None);
    }

    #[test]
    fn test_save_and_load() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frozen.json");

        let mut fp = FrozenPaths::new(path.clone());
        fp.freeze("a.rs");
        fp.freeze("src/core/");
        fp.save().unwrap();

        let loaded = FrozenPaths::load(path).unwrap();
        assert!(loaded.is_frozen("a.rs"));
        assert!(loaded.is_frozen("src/core/mod.rs"));
        assert_eq!(loaded.len(), 2);
    }

    #[test]
    fn test_load_empty() {
        let tmp = TempDir::new().unwrap();
        let fp = FrozenPaths::load(tmp.path().join("frozen.json")).unwrap();
        assert!(fp.is_empty());
    }

    #[test]
    fn test_list_sorted() {
        let (_tmp, mut fp) = setup();
        fp.freeze("c.rs");
        fp.freeze("a.rs");
        fp.freeze("b.rs");
        let list = fp.list();
        assert_eq!(list, vec!["a.rs", "b.rs", "c.rs"]);
    }
}