|
| 1 | +import json |
| 2 | +import sys |
| 3 | +from datetime import datetime |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +from pacta.cli._io import ensure_repo_root |
| 7 | +from pacta.cli.exitcodes import EXIT_OK |
| 8 | +from pacta.snapshot.store import FsSnapshotStore |
| 9 | + |
| 10 | + |
| 11 | +def show( |
| 12 | + *, |
| 13 | + path: str, |
| 14 | + last: int | None = None, |
| 15 | + since: str | None = None, |
| 16 | + branch: str | None = None, |
| 17 | + format: str = "text", |
| 18 | +) -> int: |
| 19 | + """ |
| 20 | + Show architecture history (list of snapshots). |
| 21 | +
|
| 22 | + Args: |
| 23 | + path: Repository root path |
| 24 | + last: Show only last N entries |
| 25 | + since: Show entries since date (ISO-8601) |
| 26 | + branch: Filter by branch name |
| 27 | + format: Output format (text or json) |
| 28 | + """ |
| 29 | + repo_root = Path(ensure_repo_root(path)) |
| 30 | + store = FsSnapshotStore(repo_root=str(repo_root)) |
| 31 | + |
| 32 | + # Get all objects sorted by timestamp |
| 33 | + objects = store.list_objects() |
| 34 | + |
| 35 | + if not objects: |
| 36 | + if format == "json": |
| 37 | + print(json.dumps({"entries": [], "count": 0})) |
| 38 | + else: |
| 39 | + print("No history entries found.") |
| 40 | + print("Run 'pacta scan' to create snapshots.") |
| 41 | + return EXIT_OK |
| 42 | + |
| 43 | + # Apply filters |
| 44 | + entries = [] |
| 45 | + for short_hash, snapshot in objects: |
| 46 | + meta = snapshot.meta |
| 47 | + |
| 48 | + # Filter by branch if specified |
| 49 | + if branch and meta.branch != branch: |
| 50 | + continue |
| 51 | + |
| 52 | + # Filter by since date if specified |
| 53 | + if since and meta.created_at: |
| 54 | + try: |
| 55 | + since_dt = datetime.fromisoformat(since.replace("Z", "+00:00")) |
| 56 | + created_dt = datetime.fromisoformat(meta.created_at.replace("Z", "+00:00")) |
| 57 | + # Normalize to compare: strip timezone info for comparison |
| 58 | + since_naive = since_dt.replace(tzinfo=None) if since_dt.tzinfo else since_dt |
| 59 | + created_naive = created_dt.replace(tzinfo=None) if created_dt.tzinfo else created_dt |
| 60 | + if created_naive < since_naive: |
| 61 | + continue |
| 62 | + except ValueError: |
| 63 | + pass # Invalid date format, skip filter |
| 64 | + |
| 65 | + entries.append((short_hash, snapshot)) |
| 66 | + |
| 67 | + # Apply limit |
| 68 | + if last and last > 0: |
| 69 | + entries = entries[:last] |
| 70 | + |
| 71 | + # Get refs for display |
| 72 | + refs = store.list_refs() |
| 73 | + hash_to_refs: dict[str, list[str]] = {} |
| 74 | + for ref_name, ref_hash in refs.items(): |
| 75 | + if ref_hash not in hash_to_refs: |
| 76 | + hash_to_refs[ref_hash] = [] |
| 77 | + hash_to_refs[ref_hash].append(ref_name) |
| 78 | + |
| 79 | + if format == "json": |
| 80 | + _output_json(entries, hash_to_refs) |
| 81 | + else: |
| 82 | + _output_text(entries, hash_to_refs) |
| 83 | + |
| 84 | + return EXIT_OK |
| 85 | + |
| 86 | + |
| 87 | +def _output_text( |
| 88 | + entries: list[tuple[str, "Snapshot"]], # noqa: F821 |
| 89 | + hash_to_refs: dict[str, list[str]], |
| 90 | +) -> None: |
| 91 | + """Output history in text format.""" |
| 92 | + print(f"Architecture Timeline ({len(entries)} entries)") |
| 93 | + print("=" * 60) |
| 94 | + print() |
| 95 | + |
| 96 | + for short_hash, snapshot in entries: |
| 97 | + meta = snapshot.meta |
| 98 | + refs_list = hash_to_refs.get(short_hash, []) |
| 99 | + |
| 100 | + # Format timestamp |
| 101 | + timestamp = meta.created_at or "unknown" |
| 102 | + if "T" in timestamp: |
| 103 | + timestamp = timestamp.split("T")[0] # Just date |
| 104 | + |
| 105 | + # Format commit (short) |
| 106 | + commit = (meta.commit or "-------")[:7] |
| 107 | + |
| 108 | + # Format branch |
| 109 | + branch = meta.branch or "?" |
| 110 | + |
| 111 | + # Counts |
| 112 | + node_count = len(snapshot.nodes) |
| 113 | + edge_count = len(snapshot.edges) |
| 114 | + violation_count = len(snapshot.violations) |
| 115 | + |
| 116 | + # Refs |
| 117 | + refs_str = f" ({', '.join(refs_list)})" if refs_list else "" |
| 118 | + |
| 119 | + # Output line |
| 120 | + print(f"{short_hash} {timestamp} {commit} {branch:<12} " |
| 121 | + f"{node_count:>3} nodes {edge_count:>3} edges " |
| 122 | + f"{violation_count:>2} violations{refs_str}") |
| 123 | + |
| 124 | + print() |
| 125 | + |
| 126 | + |
| 127 | +def _output_json( |
| 128 | + entries: list[tuple[str, "Snapshot"]], # noqa: F821 |
| 129 | + hash_to_refs: dict[str, list[str]], |
| 130 | +) -> None: |
| 131 | + """Output history in JSON format.""" |
| 132 | + result = { |
| 133 | + "entries": [], |
| 134 | + "count": len(entries), |
| 135 | + } |
| 136 | + |
| 137 | + for short_hash, snapshot in entries: |
| 138 | + meta = snapshot.meta |
| 139 | + refs_list = hash_to_refs.get(short_hash, []) |
| 140 | + |
| 141 | + # Count violations by severity |
| 142 | + violations_by_severity: dict[str, int] = {} |
| 143 | + for v in snapshot.violations: |
| 144 | + if hasattr(v, "rule") and hasattr(v.rule, "severity"): |
| 145 | + sev = str(v.rule.severity.value) if hasattr(v.rule.severity, "value") else str(v.rule.severity) |
| 146 | + elif isinstance(v, dict) and "rule" in v and "severity" in v["rule"]: |
| 147 | + sev = v["rule"]["severity"] |
| 148 | + else: |
| 149 | + sev = "unknown" |
| 150 | + violations_by_severity[sev] = violations_by_severity.get(sev, 0) + 1 |
| 151 | + |
| 152 | + entry = { |
| 153 | + "hash": short_hash, |
| 154 | + "timestamp": meta.created_at, |
| 155 | + "commit": meta.commit, |
| 156 | + "branch": meta.branch, |
| 157 | + "refs": refs_list, |
| 158 | + "node_count": len(snapshot.nodes), |
| 159 | + "edge_count": len(snapshot.edges), |
| 160 | + "violation_count": len(snapshot.violations), |
| 161 | + "violations_by_severity": violations_by_severity, |
| 162 | + } |
| 163 | + result["entries"].append(entry) |
| 164 | + |
| 165 | + print(json.dumps(result, indent=2, default=str)) |
| 166 | + |
| 167 | + |
| 168 | +def export( |
| 169 | + *, |
| 170 | + path: str, |
| 171 | + format: str = "json", |
| 172 | + output: str | None = None, |
| 173 | +) -> int: |
| 174 | + """ |
| 175 | + Export full history data for external processing. |
| 176 | +
|
| 177 | + Args: |
| 178 | + path: Repository root path |
| 179 | + format: Export format (json or jsonl) |
| 180 | + output: Output file path (default: stdout) |
| 181 | + """ |
| 182 | + repo_root = Path(ensure_repo_root(path)) |
| 183 | + store = FsSnapshotStore(repo_root=str(repo_root)) |
| 184 | + |
| 185 | + objects = store.list_objects() |
| 186 | + refs = store.list_refs() |
| 187 | + |
| 188 | + # Build hash to refs mapping |
| 189 | + hash_to_refs: dict[str, list[str]] = {} |
| 190 | + for ref_name, ref_hash in refs.items(): |
| 191 | + if ref_hash not in hash_to_refs: |
| 192 | + hash_to_refs[ref_hash] = [] |
| 193 | + hash_to_refs[ref_hash].append(ref_name) |
| 194 | + |
| 195 | + # Build export data |
| 196 | + entries = [] |
| 197 | + for short_hash, snapshot in objects: |
| 198 | + meta = snapshot.meta |
| 199 | + |
| 200 | + entry = { |
| 201 | + "hash": short_hash, |
| 202 | + "timestamp": meta.created_at, |
| 203 | + "commit": meta.commit, |
| 204 | + "branch": meta.branch, |
| 205 | + "refs": hash_to_refs.get(short_hash, []), |
| 206 | + "repo_root": meta.repo_root, |
| 207 | + "tool_version": meta.tool_version, |
| 208 | + "node_count": len(snapshot.nodes), |
| 209 | + "edge_count": len(snapshot.edges), |
| 210 | + "violations": [ |
| 211 | + v.to_dict() if hasattr(v, "to_dict") else v |
| 212 | + for v in snapshot.violations |
| 213 | + ], |
| 214 | + } |
| 215 | + entries.append(entry) |
| 216 | + |
| 217 | + # Output |
| 218 | + out_stream = open(output, "w") if output else sys.stdout |
| 219 | + |
| 220 | + try: |
| 221 | + if format == "jsonl": |
| 222 | + for entry in entries: |
| 223 | + out_stream.write(json.dumps(entry, default=str) + "\n") |
| 224 | + else: |
| 225 | + result = { |
| 226 | + "version": 1, |
| 227 | + "exported_at": datetime.now().isoformat(), |
| 228 | + "repo_root": str(repo_root), |
| 229 | + "refs": refs, |
| 230 | + "entries": entries, |
| 231 | + } |
| 232 | + out_stream.write(json.dumps(result, indent=2, default=str) + "\n") |
| 233 | + finally: |
| 234 | + if output: |
| 235 | + out_stream.close() |
| 236 | + |
| 237 | + if output: |
| 238 | + print(f"Exported {len(entries)} entries to {output}", file=sys.stderr) |
| 239 | + |
| 240 | + return EXIT_OK |
0 commit comments