summaryrefslogtreecommitdiff
path: root/timelord/core/compare.py
blob: b545766034f65bd91a9a4f0982f63e0fd47d32e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
"""
Timeline Comparator: Inspects differences between Prime and Parallel Universes.
Computes file modifications, additions, deletions, and line-level changes.
"""

import difflib
from pathlib import Path
from typing import Any, Dict, List, Optional, Set

from timelord.core.engine import ChronoEngine
from timelord.core.multiverse import MultiverseManager
from timelord.core.snapshot import hash_file


class TimelineComparator:
    def __init__(self, engine: ChronoEngine):
        self.engine = engine
        self.multiverse = MultiverseManager(engine)

    def _collect_files(self, root: Path, excludes: Set[str]) -> Dict[str, Path]:
        files = {}
        for p in root.rglob("*"):
            if not p.is_file():
                continue
            rel = p.relative_to(root)
            # Skip any relative path containing an excluded segment
            if any(part in excludes for part in rel.parts):
                continue
            files[str(rel)] = p
        return files

    def compare_universe_with_prime(self, universe_name: str) -> Dict[str, Any]:
        """Compares Prime Timeline (Earth-616) with the specified parallel universe."""
        universe = self.multiverse.get_universe(universe_name)
        if not universe:
            raise ValueError(f"Universe '{universe_name}' not found.")

        universe_dir = Path(universe["path"])
        prime_dir = self.engine.project_root

        config = self.engine.get_config()
        excludes = set(config.get("exclude_patterns", [".timelord", ".git"]))
        excludes.add("timelord_universe.json")

        prime_files = self._collect_files(prime_dir, excludes)
        universe_files = self._collect_files(universe_dir, excludes)

        prime_keys = set(prime_files.keys())
        universe_keys = set(universe_files.keys())

        added = sorted(list(universe_keys - prime_keys))
        deleted = sorted(list(prime_keys - universe_keys))
        common = sorted(list(prime_keys & universe_keys))

        modified = []
        remapped_ports = universe.get("remapped_ports", {})
        for rel in common:
            pf = prime_files[rel]
            uf = universe_files[rel]

            # Fast size check before hash
            if pf.stat().st_size != uf.stat().st_size or hash_file(pf) != hash_file(uf):
                # Ignore if the only change is the auto-injected port offset
                if self._is_only_port_remapped(pf, uf, remapped_ports):
                    continue

                # Count added and deleted lines
                additions, deletions = self._count_line_diffs(pf, uf)
                modified.append({
                    "path": rel,
                    "prime_path": str(pf),
                    "universe_path": str(uf),
                    "additions": additions,
                    "deletions": deletions,
                })

        return {
            "universe_name": universe_name,
            "prime_path": str(prime_dir),
            "universe_path": str(universe_dir),
            "added": added,
            "deleted": deleted,
            "modified": modified,
            "is_identical": not (added or deleted or modified),
        }

    def _count_line_diffs(self, file_a: Path, file_b: Path) -> tuple[int, int]:
        try:
            lines_a = file_a.read_text(encoding="utf-8", errors="ignore").splitlines()
            lines_b = file_b.read_text(encoding="utf-8", errors="ignore").splitlines()
            matcher = difflib.SequenceMatcher(None, lines_a, lines_b)
            additions = 0
            deletions = 0
            for tag, i1, i2, j1, j2 in matcher.get_opcodes():
                if tag in ("replace", "delete"):
                    deletions += (i2 - i1)
                if tag in ("replace", "insert"):
                    additions += (j2 - j1)
            return additions, deletions
        except Exception:
            return 0, 0

    def _is_only_port_remapped(self, pf: Path, uf: Path, remapped_ports: Dict[str, int]) -> bool:
        if not remapped_ports:
            return False
        try:
            lines_p = pf.read_text(encoding="utf-8", errors="ignore").splitlines()
            lines_u = uf.read_text(encoding="utf-8", errors="ignore").splitlines()
            if len(lines_p) != len(lines_u):
                return False
            import re
            for lp, lu in zip(lines_p, lines_u):
                if lp == lu:
                    continue
                mp = re.match(r"^(\s*PORT\s*=\s*)(\d+)(.*)$", lp, re.IGNORECASE)
                mu = re.match(r"^(\s*PORT\s*=\s*)(\d+)(.*)$", lu, re.IGNORECASE)
                if mp and mu and mp.group(1) == mu.group(1) and mp.group(3) == mu.group(3):
                    continue
                return False
            return True
        except Exception:
            return False

    def get_file_contents(
        self,
        universe_name: str,
        rel_path: str,
    ) -> tuple[str, str]:
        """Returns (prime_content, universe_content) for a specific relative file path."""
        universe = self.multiverse.get_universe(universe_name)
        if not universe:
            raise ValueError(f"Universe '{universe_name}' not found.")

        prime_file = self.engine.project_root / rel_path
        universe_file = Path(universe["path"]) / rel_path

        prime_txt = (
            prime_file.read_text(encoding="utf-8", errors="ignore")
            if prime_file.is_file()
            else ""
        )
        universe_txt = (
            universe_file.read_text(encoding="utf-8", errors="ignore")
            if universe_file.is_file()
            else ""
        )

        return prime_txt, universe_txt