mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-26 19:38:52 -06:00
refactor: move dedup and integrity into collection
This commit is contained in:
1 parent
056e12a14c
commit
198515f1cb
14 files changed
+532
-486
No files matched your search
+2
-149
@@ -32,162 +32,15 @@ Usage:
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from collection.gitrestore import GitFailed
|
||||
from collection.integrity import check
|
||||
from core.cli import add_repo_inputs
|
||||
from core.hashing import file_digest, git_blob_sha
|
||||
from model.largefiles import load_registered_paths
|
||||
|
||||
MISREAD = "misread"
|
||||
RESTORED = "restored"
|
||||
FLAGGED = "flagged"
|
||||
SKIPPED = "skipped"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Finding:
|
||||
path: str
|
||||
verdict: str # misread, restored, flagged, skipped
|
||||
reason: str
|
||||
expected: str
|
||||
found: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class Report:
|
||||
checked: int = 0
|
||||
findings: list[Finding] = field(default_factory=list)
|
||||
|
||||
def counts(self) -> dict[str, int]:
|
||||
counts: dict[str, int] = {}
|
||||
for f in self.findings:
|
||||
counts[f.verdict] = counts.get(f.verdict, 0) + 1
|
||||
return counts
|
||||
|
||||
def as_dict(self) -> dict:
|
||||
return {
|
||||
"checked": self.checked,
|
||||
"counts": self.counts(),
|
||||
"findings": [f.__dict__ for f in self.findings],
|
||||
}
|
||||
|
||||
@property
|
||||
def clean(self) -> bool:
|
||||
return all(f.verdict in (MISREAD, RESTORED) for f in self.findings)
|
||||
|
||||
|
||||
class GitFailed(RuntimeError):
|
||||
"""A git command failed: its empty output says nothing about the file."""
|
||||
|
||||
|
||||
def git(root: Path, *args: str) -> subprocess.CompletedProcess:
|
||||
"""Run git in root. A failure raises: an unreadable index read as an empty
|
||||
status made a session's working change look unmodified, and --apply wrote
|
||||
HEAD's bytes over it."""
|
||||
done = subprocess.run(["git", "-C", str(root), *args], capture_output=True, check=False)
|
||||
if done.returncode:
|
||||
message = done.stderr.decode(errors="replace").strip()
|
||||
raise GitFailed(f"git {' '.join(args)} exited {done.returncode}: {message}")
|
||||
return done
|
||||
|
||||
|
||||
def head_blob(root: Path, path: str) -> str:
|
||||
"""The blob HEAD records for path, empty when HEAD has none."""
|
||||
out = git(root, "ls-tree", "HEAD", "--", path).stdout.decode()
|
||||
parts = out.split()
|
||||
return parts[2] if len(parts) >= 3 and parts[1] == "blob" else ""
|
||||
|
||||
|
||||
def modified_for_git(root: Path, path: str) -> bool:
|
||||
return bool(git(root, "status", "--porcelain", "--", path).stdout.strip())
|
||||
|
||||
|
||||
def restore_from_blob(root: Path, path: str, blob: str, expected: str) -> str:
|
||||
"""Write the blob's bytes over path, after checking them. Empty on success."""
|
||||
data = git(root, "cat-file", "blob", blob).stdout
|
||||
object_id = git_blob_sha(data)
|
||||
if object_id != blob:
|
||||
return f"blob read back as {object_id[:12]}, not {blob[:12]}"
|
||||
if hashlib.sha1(data).hexdigest() != expected:
|
||||
return "HEAD holds other bytes than database.json records"
|
||||
target = root / path
|
||||
handle, scratch = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.")
|
||||
try:
|
||||
with os.fdopen(handle, "wb") as out:
|
||||
out.write(data)
|
||||
os.chmod(scratch, target.stat().st_mode & 0o777)
|
||||
os.replace(scratch, target)
|
||||
except OSError:
|
||||
if os.path.exists(scratch):
|
||||
os.unlink(scratch)
|
||||
raise
|
||||
return ""
|
||||
|
||||
|
||||
def check(
|
||||
root: Path,
|
||||
db: dict,
|
||||
apply: bool,
|
||||
hasher: Callable[[Path], str] = file_digest,
|
||||
) -> Report:
|
||||
"""Hash every database path, confirm each mismatch, repair what may be."""
|
||||
ignored = set(load_registered_paths(root / ".gitignore"))
|
||||
report = Report()
|
||||
for key, entry in sorted(db.get("files", {}).items(), key=lambda kv: kv[1]["path"]):
|
||||
path = entry["path"]
|
||||
expected = str(entry.get("sha1") or key).lower()
|
||||
local = root / path
|
||||
if not local.is_file():
|
||||
continue # a release asset not fetched yet, verify reports it
|
||||
report.checked += 1
|
||||
first = hasher(local)
|
||||
if first == expected:
|
||||
continue
|
||||
second = hasher(local)
|
||||
if second != first:
|
||||
verdict = MISREAD if second == expected else FLAGGED
|
||||
report.findings.append(Finding(
|
||||
path, verdict, f"two reads disagree ({first[:12]}, {second[:12]})",
|
||||
expected, second))
|
||||
continue
|
||||
if path in ignored:
|
||||
report.findings.append(Finding(
|
||||
path, FLAGGED, "gitignored large file, never repaired here", expected, first))
|
||||
continue
|
||||
blob = head_blob(root, path)
|
||||
if not blob:
|
||||
report.findings.append(Finding(path, FLAGGED, "not in HEAD", expected, first))
|
||||
continue
|
||||
if modified_for_git(root, path):
|
||||
report.findings.append(Finding(
|
||||
path, SKIPPED, "modified for git: a working change, left alone",
|
||||
expected, first))
|
||||
continue
|
||||
if not apply:
|
||||
report.findings.append(Finding(
|
||||
path, FLAGGED, "bit flip, restorable from HEAD with --apply", expected, first))
|
||||
continue
|
||||
problem = restore_from_blob(root, path, blob, expected)
|
||||
if problem:
|
||||
report.findings.append(Finding(path, FLAGGED, problem, expected, first))
|
||||
continue
|
||||
after = hasher(local)
|
||||
if after == expected:
|
||||
report.findings.append(Finding(
|
||||
path, RESTORED, f"restored from blob {blob[:12]}", expected, first))
|
||||
else:
|
||||
report.findings.append(Finding(
|
||||
path, FLAGGED, f"restored but reads {after[:12]}", expected, after))
|
||||
return report
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
Reference in new issue
Block a user