Newer
Older
cortex-hub / poc-grpc-agent / shared_core / ignore.py
import os
import fnmatch

class CortexIgnore:
    """Handles .cortexignore (and .gitignore) pattern matching."""
    def __init__(self, root_path):
        self.root_path = root_path
        self.patterns = self._load_patterns()

    def _load_patterns(self):
        patterns = [".git", "node_modules", ".cortex_sync", "__pycache__", "*.pyc"] # Default ignores
        ignore_file = os.path.join(self.root_path, ".cortexignore")
        if not os.path.exists(ignore_file):
            ignore_file = os.path.join(self.root_path, ".gitignore")
            
        if os.path.exists(ignore_file):
            with open(ignore_file, "r") as f:
                for line in f:
                    line = line.strip()
                    if line and not line.startswith("#"):
                        patterns.append(line)
        return patterns

    def is_ignored(self, rel_path):
        """Returns True if the path matches any ignore pattern."""
        for pattern in self.patterns:
            # Handle directory patterns
            if pattern.endswith("/"):
                if rel_path.startswith(pattern) or f"/{pattern}" in f"/{rel_path}":
                    return True
            # Standard glob matching
            if fnmatch.fnmatch(rel_path, pattern) or fnmatch.fnmatch(os.path.basename(rel_path), pattern):
                return True
            # Handle nested matches
            for part in rel_path.split(os.sep):
                if fnmatch.fnmatch(part, pattern):
                    return True
        return False