refactor: move the truth diff into exporter

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 14:59:03 +01:00
1 parent 75a69a4a42
commit 2428d92e6a
6 files changed
+209 -180

No files matched your search

+13 -176
View File
@@ -10,7 +10,6 @@ Usage:
from __future__ import annotations
from core.paths import TRUTH_DIR
import argparse
import json
import os
@@ -18,170 +17,14 @@ import sys
sys.path.insert(0, os.path.dirname(__file__))
from core.cli import add_repo_inputs
from core.paths import TRUTH_DIR
from exporter.diffreport import format_markdown, format_terminal
from exporter.truthdiff import NoDiffInput, platform_diff
from model.cliargs import platform_arg, selected_platforms
from model.platforms import load_platform_config, native_layer
from model.safeparse import require_yaml, yaml_load
from model.targets import truth_target_dir
from resolve.truth import diff_platform_truth
yaml = require_yaml()
def _load_truth(truth_dir: str, platform: str) -> dict | None:
path = os.path.join(truth_dir, f"{platform}.yml")
if not os.path.exists(path):
return None
with open(path, encoding="utf-8") as f:
return yaml_load(f) or {}
def _where(entry: dict) -> str:
"""Where a diffed entry sits: one name can be declared at several paths."""
return entry.get("destination") or entry["name"]
_TOTAL_LABELS = (
("total_missing", "missing"),
("total_extra_phantom", "unpaired"),
("total_extra_unprofiled", "unprofiled"),
("total_hash_mismatch", "hash"),
("total_required_mismatch", "required"),
)
_DIVERGENCE_LABELS = (
("missing", "MISSING"),
("extra_phantom", "UNPAIRED"),
("extra_unprofiled", "UNPROF"),
("hash_mismatch", "HASH"),
("required_mismatch", "REQ"),
)
def _terminal_divergence(sys_id: str, div: dict) -> list[str]:
labels = [f"{label}:{len(div[key])}" for key, label in _DIVERGENCE_LABELS if div.get(key)]
lines = [f" {sys_id}: {' '.join(labels)}"]
lines.extend(
f" + {_where(m)} [{', '.join(m.get('cores', []))}]"
for m in div.get("missing", [])
)
lines.extend(
f" ~ {_where(h)} {h['hash_type']}: "
f"{h['truth_' + h['hash_type']]} != {h['scraped_' + h['hash_type']]}"
for h in div.get("hash_mismatch", [])
)
lines.extend(
f" - {_where(p)} (no profile entry of this system matches it)"
for p in div.get("extra_phantom", [])
)
lines.extend(
f" ? {_where(u)} (unprofiled cores)"
for u in div.get("extra_unprofiled", [])
)
lines.extend(
f" ! {_where(r)} required: {r['truth_required']} != {r['scraped_required']}"
for r in div.get("required_mismatch", [])
)
return lines
def _format_terminal(report: dict) -> str:
lines: list[str] = []
platform = report.get("platform", "unknown")
s = report["summary"]
lines.append(f"=== {platform} ===")
lines.append(
f" {s['systems_compared']} systems compared: "
f"{s['systems_fully_covered']} full, "
f"{s['systems_partially_covered']} partial, "
f"{s['systems_uncovered']} uncovered"
)
totals = [f"{s[key]} {label}" for key, label in _TOTAL_LABELS if s[key]]
if totals:
lines.append(f" divergences: {', '.join(totals)}")
else:
lines.append(" no divergences")
for sys_id, div in sorted(report.get("divergences", {}).items()):
lines.extend(_terminal_divergence(sys_id, div))
uncovered = report.get("uncovered_systems", [])
if uncovered:
lines.append(f" uncovered ({len(uncovered)}): {', '.join(uncovered)}")
return "\n".join(lines)
def _markdown_divergence(sys_id: str, div: dict) -> list[str]:
lines = [f"## {sys_id}", ""]
for m in div.get("missing", []):
refs = ""
if m.get("source_refs"):
refs = " " + " ".join(f"`{r}`" for r in m["source_refs"])
lines.append(f"- **Add** `{_where(m)}`{refs}")
lines.extend(
f"- **Fix hash** `{_where(h)}` {h['hash_type']}: "
f"`{h['truth_' + h['hash_type']]}` != `{h['scraped_' + h['hash_type']]}`"
for h in div.get("hash_mismatch", [])
)
# Evidence, not a request: an entry leaves a platform's file only on
# proof (export_native's removal_candidates). A core can read a
# file its profile does not pair with this declaration.
lines.extend(
f"- **Unpaired** `{_where(p)}`: no profile entry of this system matches it "
"by path, name or hash"
for p in div.get("extra_phantom", [])
)
lines.extend(
f"- **Unpaired** `{_where(u)}`: some cores of this platform "
"have no profile yet"
for u in div.get("extra_unprofiled", [])
)
lines.extend(
f"- **Fix required** `{_where(r)}`: truth={r['truth_required']}, scraped={r['scraped_required']}"
for r in div.get("required_mismatch", [])
)
lines.append("")
return lines
def _format_markdown(report: dict) -> str:
lines: list[str] = []
platform = report.get("platform", "unknown")
s = report["summary"]
lines.append(f"# {platform}")
lines.append("")
lines.append(
f"**{s['systems_compared']}** systems compared | "
f"**{s['systems_fully_covered']}** full | "
f"**{s['systems_partially_covered']}** partial | "
f"**{s['systems_uncovered']}** uncovered"
)
lines.append(
f"**{s['total_missing']}** missing | "
f"**{s['total_extra_phantom']}** unpaired | "
f"**{s['total_extra_unprofiled']}** unprofiled | "
f"**{s['total_hash_mismatch']}** hash | "
f"**{s['total_required_mismatch']}** required"
)
lines.append("")
for sys_id, div in sorted(report.get("divergences", {}).items()):
lines.extend(_markdown_divergence(sys_id, div))
uncovered = report.get("uncovered_systems", [])
if uncovered:
lines.append("## Uncovered systems")
lines.append("")
lines.extend(f"- {u}" for u in uncovered)
lines.append("")
return "\n".join(lines)
def main() -> None:
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(allow_abbrev=False, description="Compare scraped vs truth YAMLs")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
@@ -213,12 +56,16 @@ def main() -> None:
help="read the models generate_truth --target wrote, each under the "
"target as its platform files it",
)
args = parser.parse_args()
return parser
def main() -> None:
args = build_parser().parse_args()
platforms = selected_platforms(args)
reports: list[dict] = []
formatter = _format_markdown if args.format == "markdown" else _format_terminal
formatter = format_markdown if args.format == "markdown" else format_terminal
compared = 0
for platform in platforms:
@@ -226,21 +73,11 @@ def main() -> None:
truth_target_dir(args.truth_dir, [platform], args.target, args.platforms_dir)
if args.target else args.truth_dir
)
truth = _load_truth(truth_dir, platform)
if truth is None:
print(f"skip {platform}: no truth YAML in {truth_dir}/", file=sys.stderr)
continue
try:
# What the platform's own file declares: our shared groups,
# mirrors and curated additions are not theirs to be credited.
scraped = native_layer(load_platform_config(platform, args.platforms_dir))
except FileNotFoundError:
print(f"skip {platform}: no scraped config", file=sys.stderr)
report = platform_diff(platform, truth_dir, args.platforms_dir)
except NoDiffInput as exc:
print(f"skip {platform}: {exc}", file=sys.stderr)
continue
report = diff_platform_truth(truth, scraped)
report["platform"] = platform
compared += 1
if args.json_output:
+151
View File
@@ -0,0 +1,151 @@
"""The truth diff of one platform rendered for a terminal or as markdown."""
from __future__ import annotations
def _where(entry: dict) -> str:
"""Where a diffed entry sits: one name can be declared at several paths."""
return entry.get("destination") or entry["name"]
_TOTAL_LABELS = (
("total_missing", "missing"),
("total_extra_phantom", "unpaired"),
("total_extra_unprofiled", "unprofiled"),
("total_hash_mismatch", "hash"),
("total_required_mismatch", "required"),
)
_DIVERGENCE_LABELS = (
("missing", "MISSING"),
("extra_phantom", "UNPAIRED"),
("extra_unprofiled", "UNPROF"),
("hash_mismatch", "HASH"),
("required_mismatch", "REQ"),
)
def _terminal_divergence(sys_id: str, div: dict) -> list[str]:
labels = [f"{label}:{len(div[key])}" for key, label in _DIVERGENCE_LABELS if div.get(key)]
lines = [f" {sys_id}: {' '.join(labels)}"]
lines.extend(
f" + {_where(m)} [{', '.join(m.get('cores', []))}]"
for m in div.get("missing", [])
)
lines.extend(
f" ~ {_where(h)} {h['hash_type']}: "
f"{h['truth_' + h['hash_type']]} != {h['scraped_' + h['hash_type']]}"
for h in div.get("hash_mismatch", [])
)
lines.extend(
f" - {_where(p)} (no profile entry of this system matches it)"
for p in div.get("extra_phantom", [])
)
lines.extend(
f" ? {_where(u)} (unprofiled cores)"
for u in div.get("extra_unprofiled", [])
)
lines.extend(
f" ! {_where(r)} required: {r['truth_required']} != {r['scraped_required']}"
for r in div.get("required_mismatch", [])
)
return lines
def format_terminal(report: dict) -> str:
"""The report as terminal lines: totals, then each divergent system."""
lines: list[str] = []
platform = report.get("platform", "unknown")
s = report["summary"]
lines.append(f"=== {platform} ===")
lines.append(
f" {s['systems_compared']} systems compared: "
f"{s['systems_fully_covered']} full, "
f"{s['systems_partially_covered']} partial, "
f"{s['systems_uncovered']} uncovered"
)
totals = [f"{s[key]} {label}" for key, label in _TOTAL_LABELS if s[key]]
if totals:
lines.append(f" divergences: {', '.join(totals)}")
else:
lines.append(" no divergences")
for sys_id, div in sorted(report.get("divergences", {}).items()):
lines.extend(_terminal_divergence(sys_id, div))
uncovered = report.get("uncovered_systems", [])
if uncovered:
lines.append(f" uncovered ({len(uncovered)}): {', '.join(uncovered)}")
return "\n".join(lines)
def _markdown_divergence(sys_id: str, div: dict) -> list[str]:
lines = [f"## {sys_id}", ""]
for m in div.get("missing", []):
refs = ""
if m.get("source_refs"):
refs = " " + " ".join(f"`{r}`" for r in m["source_refs"])
lines.append(f"- **Add** `{_where(m)}`{refs}")
lines.extend(
f"- **Fix hash** `{_where(h)}` {h['hash_type']}: "
f"`{h['truth_' + h['hash_type']]}` != `{h['scraped_' + h['hash_type']]}`"
for h in div.get("hash_mismatch", [])
)
# Evidence, not a request: an entry leaves a platform's file only on
# proof (export_native's removal_candidates). A core can read a
# file its profile does not pair with this declaration.
lines.extend(
f"- **Unpaired** `{_where(p)}`: no profile entry of this system matches it "
"by path, name or hash"
for p in div.get("extra_phantom", [])
)
lines.extend(
f"- **Unpaired** `{_where(u)}`: some cores of this platform "
"have no profile yet"
for u in div.get("extra_unprofiled", [])
)
lines.extend(
f"- **Fix required** `{_where(r)}`: truth={r['truth_required']}, scraped={r['scraped_required']}"
for r in div.get("required_mismatch", [])
)
lines.append("")
return lines
def format_markdown(report: dict) -> str:
"""The report as a markdown page, one section per divergent system."""
lines: list[str] = []
platform = report.get("platform", "unknown")
s = report["summary"]
lines.append(f"# {platform}")
lines.append("")
lines.append(
f"**{s['systems_compared']}** systems compared | "
f"**{s['systems_fully_covered']}** full | "
f"**{s['systems_partially_covered']}** partial | "
f"**{s['systems_uncovered']}** uncovered"
)
lines.append(
f"**{s['total_missing']}** missing | "
f"**{s['total_extra_phantom']}** unpaired | "
f"**{s['total_extra_unprofiled']}** unprofiled | "
f"**{s['total_hash_mismatch']}** hash | "
f"**{s['total_required_mismatch']}** required"
)
lines.append("")
for sys_id, div in sorted(report.get("divergences", {}).items()):
lines.extend(_markdown_divergence(sys_id, div))
uncovered = report.get("uncovered_systems", [])
if uncovered:
lines.append("## Uncovered systems")
lines.append("")
lines.extend(f"- {u}" for u in uncovered)
lines.append("")
return "\n".join(lines)
+40
View File
@@ -0,0 +1,40 @@
"""One platform's truth model read beside its own scraped file and diffed."""
from __future__ import annotations
import os
from model.platforms import load_platform_config, native_layer
from model.safeparse import require_yaml, yaml_load
from resolve.truth import diff_platform_truth
require_yaml()
class NoDiffInput(LookupError):
"""One side of the diff is absent: the message says which."""
def load_truth(truth_dir: str, platform: str) -> dict | None:
"""The truth model generate_truth wrote for a platform, None when absent."""
path = os.path.join(truth_dir, f"{platform}.yml")
if not os.path.exists(path):
return None
with open(path, encoding="utf-8") as f:
return yaml_load(f) or {}
def platform_diff(platform: str, truth_dir: str, platforms_dir: str) -> dict:
"""The diff report of one platform, raising NoDiffInput when a side is absent."""
truth = load_truth(truth_dir, platform)
if truth is None:
raise NoDiffInput(f"no truth YAML in {truth_dir}/")
try:
# What the platform's own file declares: our shared groups,
# mirrors and curated additions are not theirs to be credited.
scraped = native_layer(load_platform_config(platform, platforms_dir))
except FileNotFoundError as exc:
raise NoDiffInput("no scraped config") from exc
report = diff_platform_truth(truth, scraped)
report["platform"] = platform
return report
+1
View File
@@ -126,6 +126,7 @@ COMMANDS = {
"sitegen/demovariants.py", "sitegen/democard.py", "sitegen/demosession.py",
"sitegen/demorecord.py",
),
"diff_truth.py": ("exporter/truthdiff.py", "exporter/diffreport.py"),
"romset_recipes.py": (
"romrecipes/romsets.py", "romrecipes/pool.py", "romrecipes/pins.py", "romrecipes/identify.py",
"romrecipes/ledger.py", "romrecipes/members.py", "romrecipes/capture.py", "romrecipes/build.py",
+3 -3
View File
@@ -20,7 +20,7 @@ from core.github import github_token, _gh_cli_token
from model.profiles import select_emulator_profiles, ProfileSelectionError
from model.registry import list_registered_platforms
from model.targets import load_target_config, build_target_cores_cache
import diff_truth
from exporter import diffreport
import pipeline
from orchestrate import guards, labels, prepare, runner
from resolve import truth
@@ -507,8 +507,8 @@ class TheTruthDiffShowsWhereAndAsksNothing(unittest.TestCase):
def test_neither_format_asks_for_a_removal(self):
report = self._report()
for text in (diff_truth._format_markdown(report),
diff_truth._format_terminal(report)):
for text in (diffreport.format_markdown(report),
diffreport.format_terminal(report)):
self.assertNotIn("Remove", text)
self.assertNotIn("phantom", text.lower())
self.assertIn("fbneo/hiscore.dat", text)
+1 -1
View File
@@ -47,7 +47,7 @@ scripts/ all tooling (Python and pyyaml, jsonschema for schema c
games/ the games-on-card rules and the index the installer reads for them
scraper/ upstream scrapers (libretro, batocera, recalbox...)
scraper/targets/ hardware target scrapers (one *_targets_scraper.py per platform)
exporter/ native format exporters (batocera, recalbox, emudeck...)
exporter/ native format exporters (batocera, recalbox, emudeck...), the truth diff
sitegen/ the site and README generators: pages, navigation, data files
probes/ real-condition runs: the campaign, the pack and region probes
release/ the release record, its notes, the checks of its assets and the pack downloader