Coverage for src/romfarmer/cas/tree.py: 76%
159 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""
2Tree Manifests for Content-Addressable Store.
4Extends the CAS to handle folder-based outputs (PS3 JB folders, daphne,
5scummvm, Xbox 360 GOD, Wii U NUS, PS Vita, OpenBOR).
7A TreeManifest is a JSON document listing every file in a folder output,
8each with its relative path, SHA-256 hash, size, and permissions. The
9manifest itself is content-addressed — its SHA-256 (the "tree hash")
10serves as the cache key.
12Architecture:
13 - Individual files are stored in the same CAS blob store as single files
14 - The manifest JSON is also stored as a CAS blob (.manifest extension)
15 - Restoring a tree = read manifest → hardlink each blob to its relative path
17This gives us full deduplication across folder outputs (shared DLLs, firmware
18files, etc.) while supporting atomic restore and garbage collection.
19"""
21import hashlib
22import json
23import logging
24import os
25import shutil
26from dataclasses import dataclass, field
27from pathlib import Path
29from .store import ContentStore
31logger = logging.getLogger(__name__)
34@dataclass
35class TreeEntry:
36 """A single file within a tree manifest."""
38 relative_path: str # e.g., "PS3_GAME/USRDIR/EBOOT.BIN"
39 sha256: str # SHA-256 of file contents
40 size: int # File size in bytes
41 executable: bool = False # Preserve +x permission
43 def to_dict(self) -> dict:
44 d = {
45 "path": self.relative_path,
46 "sha256": self.sha256,
47 "size": self.size,
48 }
49 if self.executable:
50 d["executable"] = True
51 return d
53 @classmethod
54 def from_dict(cls, d: dict) -> "TreeEntry":
55 return cls(
56 relative_path=d["path"],
57 sha256=d["sha256"],
58 size=d["size"],
59 executable=d.get("executable", False),
60 )
63@dataclass
64class TreeManifest:
65 """
66 Manifest describing all files in a folder-based output.
68 The tree_hash is computed from the sorted manifest content, making
69 it deterministic — identical folder contents always produce the
70 same tree hash regardless of creation order.
71 """
73 entries: list[TreeEntry] = field(default_factory=list)
74 tree_hash: str = "" # Computed after all entries are added
75 total_size: int = 0 # Sum of all entry sizes
76 total_files: int = 0 # Number of entries
78 # Optional metadata (not included in hash computation)
79 source_name: str = "" # e.g., "Borderlands 2 (USA)"
80 platform: str = "" # e.g., "ps3", "daphne", "scummvm"
81 format: str = "" # e.g., "ps3-jb", "daphne-folder"
82 tool: str = "" # e.g., "ps3dec+7z", "extract"
83 tool_version: str = ""
85 def compute_hash(self) -> str:
86 """Compute tree hash from sorted entry data.
88 The hash is deterministic: same files → same hash, regardless
89 of insertion order. Only file paths, hashes, and sizes are
90 included (not metadata like permissions).
91 """
92 # Sort by path for determinism
93 sorted_entries = sorted(self.entries, key=lambda e: e.relative_path)
95 # Build canonical representation
96 canonical = []
97 for entry in sorted_entries:
98 canonical.append(f"{entry.relative_path}\t{entry.sha256}\t{entry.size}")
100 content = "\n".join(canonical).encode("utf-8", "surrogateescape")
101 self.tree_hash = hashlib.sha256(content).hexdigest()
102 self.total_size = sum(e.size for e in self.entries)
103 self.total_files = len(self.entries)
104 return self.tree_hash
106 def to_json(self) -> str:
107 """Serialize manifest to JSON (for CAS storage)."""
108 data = {
109 "version": 1,
110 "tree_hash": self.tree_hash,
111 "total_size": self.total_size,
112 "total_files": self.total_files,
113 "metadata": {
114 "source_name": self.source_name,
115 "platform": self.platform,
116 "format": self.format,
117 "tool": self.tool,
118 "tool_version": self.tool_version,
119 },
120 "entries": [e.to_dict() for e in sorted(self.entries, key=lambda e: e.relative_path)],
121 }
122 return json.dumps(data, indent=2, ensure_ascii=True)
124 @classmethod
125 def from_json(cls, json_str: str) -> "TreeManifest":
126 """Deserialize manifest from JSON."""
127 data = json.loads(json_str)
129 if data.get("version", 1) != 1:
130 raise ValueError(f"Unsupported manifest version: {data['version']}")
132 metadata = data.get("metadata", {})
133 entries = [TreeEntry.from_dict(e) for e in data["entries"]]
135 manifest = cls(
136 entries=entries,
137 tree_hash=data["tree_hash"],
138 total_size=data["total_size"],
139 total_files=data["total_files"],
140 source_name=metadata.get("source_name", ""),
141 platform=metadata.get("platform", ""),
142 format=metadata.get("format", ""),
143 tool=metadata.get("tool", ""),
144 tool_version=metadata.get("tool_version", ""),
145 )
146 return manifest
148 def __repr__(self) -> str:
149 h = self.tree_hash[:12] if self.tree_hash else "uncomputed"
150 return f"<TreeManifest({h}..., {self.total_files} files, {self.total_size} bytes)>"
153class TreeStore:
154 """
155 Manages tree manifests on top of the ContentStore.
157 Provides store_tree() to ingest a folder, and restore_tree() to
158 recreate it. Individual files go into the regular CAS blob store;
159 the manifest JSON is stored as a .manifest blob.
160 """
162 MANIFEST_EXT = ".manifest"
164 def __init__(self, content_store: ContentStore):
165 self.store = content_store
167 def ingest(
168 self,
169 folder: Path,
170 *,
171 platform: str = "",
172 format: str = "",
173 source_name: str = "",
174 tool: str = "",
175 tool_version: str = "",
176 hardlink: bool = False,
177 ) -> TreeManifest:
178 """
179 Ingest a folder into the CAS, returning its tree manifest.
181 Every file in the folder is hashed and stored in the CAS.
182 A manifest JSON is created and also stored as a CAS blob.
184 Args:
185 folder: Root folder to ingest (e.g., "BLUS30455.ps3/")
186 platform: Platform identifier (e.g., "ps3")
187 format: Output format (e.g., "ps3-jb")
188 source_name: Human-readable source name
189 tool: Tool used for transformation
190 tool_version: Tool version string
191 hardlink: If True, use hardlinks instead of copies (zero-copy
192 on same filesystem). Source files become linked to
193 CAS blobs — same inode, no extra space.
195 Returns:
196 TreeManifest with computed tree_hash
197 """
198 folder = Path(folder)
199 if not folder.is_dir():
200 raise NotADirectoryError(f"Not a directory: {folder}")
202 manifest = TreeManifest(
203 source_name=source_name,
204 platform=platform,
205 format=format,
206 tool=tool,
207 tool_version=tool_version,
208 )
210 # Walk the folder and store each file
211 file_count = 0
212 for file_path in sorted(folder.rglob("*")):
213 if not file_path.is_file():
214 continue
216 # Compute relative path from folder root
217 # Handle surrogate escapes from non-UTF-8 filenames (common in
218 # PS3 game data) by encoding via filesystem codec then decoding
219 # with replacement so the path is safe for JSON/UTF-8.
220 rel_path = str(file_path.relative_to(folder))
221 try:
222 rel_path.encode("utf-8")
223 except UnicodeEncodeError:
224 # Convert surrogates to raw bytes, then back to safe UTF-8
225 raw = os.fsencode(rel_path)
226 rel_path = raw.decode("utf-8", "surrogateescape")
227 # Re-encode with backslashreplace for JSON-safe storage
228 rel_path = raw.decode("utf-8", "replace")
230 # Check if file is executable
231 is_exec = os.access(file_path, os.X_OK)
233 # Store in CAS (deduplicates automatically)
234 if hardlink:
235 file_hash, _blob_path = self.store.put_hardlink(file_path)
236 else:
237 file_hash, _blob_path = self.store.put(file_path)
239 entry = TreeEntry(
240 relative_path=rel_path,
241 sha256=file_hash,
242 size=file_path.stat().st_size,
243 executable=is_exec,
244 )
245 manifest.entries.append(entry)
246 file_count += 1
248 # Compute tree hash
249 manifest.compute_hash()
251 # Store the manifest itself as a CAS blob
252 self._store_manifest(manifest)
254 logger.info(
255 f"Ingested tree: {folder.name} → {manifest.tree_hash[:12]}... "
256 f"({file_count} files, {manifest.total_size / (1024**2):.1f} MB)"
257 )
259 return manifest
261 def restore(
262 self,
263 tree_hash: str,
264 target: Path,
265 *,
266 use_hardlinks: bool = True,
267 ) -> TreeManifest:
268 """
269 Restore a tree from the CAS to a target directory.
271 Reads the manifest, then hardlinks (or copies) each blob
272 to its relative path under target.
274 Args:
275 tree_hash: Tree manifest hash
276 target: Root directory to restore into
277 use_hardlinks: Use hardlinks (True) or copies (False)
279 Returns:
280 The TreeManifest that was restored
282 Raises:
283 FileNotFoundError: If manifest or any blob is missing
284 """
285 manifest = self.load_manifest(tree_hash)
286 target = Path(target)
288 restored = 0
289 for entry in manifest.entries:
290 dest = target / entry.relative_path
291 dest.parent.mkdir(parents=True, exist_ok=True)
293 blob = self.store.blob_path(entry.sha256, Path(entry.relative_path).suffix)
294 if not blob.exists():
295 # Try without extension (some files may have been stored differently)
296 blob = self.store.blob_path(entry.sha256, "")
297 if not blob.exists():
298 raise FileNotFoundError(
299 f"Blob missing for {entry.relative_path}: {entry.sha256[:12]}..."
300 )
302 if dest.exists():
303 dest.unlink()
305 if use_hardlinks:
306 try:
307 os.link(blob, dest)
308 except OSError:
309 shutil.copy2(blob, dest)
310 else:
311 shutil.copy2(blob, dest)
313 # Restore executable permission
314 if entry.executable:
315 dest.chmod(dest.stat().st_mode | 0o111)
317 restored += 1
319 logger.info(f"Restored tree: {tree_hash[:12]}... → {target} ({restored} files)")
321 return manifest
323 def exists(self, tree_hash: str) -> bool:
324 """Check if a tree manifest exists in the store."""
325 return self.store.exists(tree_hash, self.MANIFEST_EXT)
327 def load_manifest(self, tree_hash: str) -> TreeManifest:
328 """Load a tree manifest from the CAS.
330 Args:
331 tree_hash: SHA-256 of the manifest
333 Returns:
334 TreeManifest
336 Raises:
337 FileNotFoundError: If manifest doesn't exist
338 """
339 manifest_path = self.store.blob_path(tree_hash, self.MANIFEST_EXT)
340 if not manifest_path.exists():
341 raise FileNotFoundError(f"Tree manifest not found: {tree_hash[:12]}...")
343 json_str = manifest_path.read_text(encoding="utf-8")
344 manifest = TreeManifest.from_json(json_str)
346 # Verify tree hash matches
347 if manifest.tree_hash != tree_hash:
348 raise ValueError(
349 f"Manifest hash mismatch: expected {tree_hash[:12]}..., "
350 f"got {manifest.tree_hash[:12]}..."
351 )
353 return manifest
355 def verify(self, tree_hash: str) -> tuple[int, int, list[str]]:
356 """Verify all blobs for a tree exist and match.
358 Returns:
359 (valid_count, missing_count, missing_paths)
360 """
361 manifest = self.load_manifest(tree_hash)
363 valid = 0
364 missing = []
366 for entry in manifest.entries:
367 blob = self.store.blob_path(entry.sha256, Path(entry.relative_path).suffix)
368 if blob.exists():
369 valid += 1
370 else:
371 # Check without extension
372 blob_noext = self.store.blob_path(entry.sha256, "")
373 if blob_noext.exists():
374 valid += 1
375 else:
376 missing.append(entry.relative_path)
378 return valid, len(missing), missing
380 def referenced_hashes(self, tree_hash: str) -> set[str]:
381 """Get all blob hashes referenced by a tree manifest.
383 Useful for garbage collection — these hashes must be kept.
385 Args:
386 tree_hash: SHA-256 of the manifest
388 Returns:
389 Set of SHA-256 hashes (including the manifest hash itself)
390 """
391 manifest = self.load_manifest(tree_hash)
392 hashes = {entry.sha256 for entry in manifest.entries}
393 hashes.add(tree_hash) # The manifest blob itself
394 return hashes
396 def _store_manifest(self, manifest: TreeManifest) -> Path:
397 """Store a manifest JSON as a CAS blob.
399 The manifest is written to a temp file, then stored via
400 the normal CAS put() flow.
401 """
402 import tempfile
404 json_str = manifest.to_json()
406 # Write to temp file, then store via CAS
407 with tempfile.NamedTemporaryFile(
408 mode="w",
409 suffix=self.MANIFEST_EXT,
410 delete=False,
411 encoding="utf-8",
412 ) as tmp:
413 tmp.write(json_str)
414 tmp_path = Path(tmp.name)
416 try:
417 # Store manifest blob — use the tree_hash as the content hash
418 # (not the hash of the JSON text, since we want to look up by tree_hash)
419 blob_path = self.store.blob_path(manifest.tree_hash, self.MANIFEST_EXT)
420 blob_path.parent.mkdir(parents=True, exist_ok=True)
422 if not blob_path.exists():
423 shutil.copy2(tmp_path, blob_path)
425 return blob_path
426 finally:
427 tmp_path.unlink(missing_ok=True)
429 def __repr__(self) -> str:
430 return f"TreeStore({self.store!r})"