refactor: move the export library into exporter

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 13:38:44 +01:00
1 parent 8738179f42
commit a5834a4b8a
14 files changed
+1059 -1024

No files matched your search

+21 -12
View File
@@ -49,7 +49,16 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import export_native
from exporter.native import StaleTruth, export_platform, load_inputs
from exporter.originals import (
DEFAULT_CACHE,
SOURCES_INDEX,
SourcesIndexUnreadable,
load_sources,
source_key,
source_revision,
wanted_sources,
)
import pin_installer
import refresh_data_dirs
from core import upstream
@@ -427,7 +436,7 @@ def native_cache_state(
path = root / relative
if not path.is_file():
return f"{relative} not cached"
known = recorded.get(export_native.source_key(path, index))
known = recorded.get(source_key(path, index))
if known is None:
return f"{relative} cached from an unrecorded URL"
if known != url:
@@ -468,7 +477,7 @@ def published_export_state(
scratch_root.mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(dir=scratch_root) as scratch:
with contextlib.redirect_stdout(io.StringIO()):
ok, messages = export_native.export_platform(
ok, messages = export_platform(
platform, exporter_class, truth_dir, Path(scratch),
str(platforms_dir), cache_dir, False,
)
@@ -521,10 +530,10 @@ def check_native(
published: Path = Path("exports"),
) -> list[Finding]:
exporters = discover_exporters()
index = cache_dir / export_native.SOURCES_INDEX
index = cache_dir / SOURCES_INDEX
try:
recorded = export_native.load_sources(cache_dir)
except export_native.SourcesIndexUnreadable as exc:
recorded = load_sources(cache_dir)
except SourcesIndexUnreadable as exc:
return [Finding("native", index.name, ERROR, detail=str(exc))]
findings: list[Finding] = []
for name in list_registered_platforms(str(platforms_dir)):
@@ -533,12 +542,12 @@ def check_native(
continue
with _without_model_notes():
try:
truth, scraped = export_native.load_inputs(name, truth_dir, str(platforms_dir))
except export_native.StaleTruth as exc:
truth, scraped = load_inputs(name, truth_dir, str(platforms_dir))
except StaleTruth as exc:
findings.append(Finding("native", name, STALE, detail=str(exc)))
continue
systems, _ = build_native_model(truth or {}, scraped)
wanted = export_native.wanted_sources(exporter_class(), systems, scraped)
wanted = wanted_sources(exporter_class(), systems, scraped)
reason = native_cache_state(
wanted, cache_dir / name, recorded, index, _transcribed_at(platforms_dir, name)
)
@@ -778,7 +787,7 @@ def platform_revision(setup: str, doc: dict, platforms_dir: Path) -> str:
repo = upstream.parse_repo(str(_os_source(doc).get("repo") or ""))
if repo is None or f"/{repo.slug.lower()}/" not in source.lower() + "/":
return ""
return export_native.source_revision(source)
return source_revision(source)
def romfolder_pin_drift(setup: str, doc: dict, platforms_dir: Path) -> str | None:
@@ -1578,7 +1587,7 @@ def pin_build_revision(reference: dict, platforms_dir: Path) -> str:
source = str((yaml_load(fh) or {}).get("source") or "")
if f"/{repo.slug.lower()}/" not in source.lower() + "/":
return ""
return export_native.source_revision(source)
return source_revision(source)
def check_pin_builds(
@@ -1850,7 +1859,7 @@ def main() -> int:
help="download cache directory (default: %(default)s)",
)
parser.add_argument(
"--native-cache-dir", default=export_native.DEFAULT_CACHE,
"--native-cache-dir", default=DEFAULT_CACHE,
help="where the platforms' own files are cached (default: %(default)s)",
)
parser.add_argument(
+2 -931
View File
@@ -16,945 +16,16 @@ Usage:
from __future__ import annotations
import argparse
import contextlib
import functools
import http.client
import re
import json
import sys
import tarfile
import urllib.request
import zipfile
import zlib
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from core.artifacts import file_lock, write_bytes_atomic, write_if_changed, write_text_atomic
import yaml
from core.cli import InputMissing
from core.ziptools import build_zip_contents_index
from model.cliargs import platform_arg, require_platform
from model.registry import list_registered_platforms, load_data_dir_registry, load_platform_registry
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config, native_layer
from model.safeparse import yaml_load
from exporter import discover_exporters
from exporter.base_exporter import BaseExporter
from resolve.reconcile import (
HASH_FIELDS,
NativeFile,
Report,
_hash_values,
_single_size,
build_native_model,
)
from resolve.categories import removal_candidates
from exporter.doubled import doubled_destinations
from resolve.truth import generate_platform_truth
DEFAULT_CACHE = ".cache/upstream-native"
# The database generate_truth reads by default.
TRUTH_DB = "database.json"
SOURCES_INDEX = ".sources.json"
_USER_AGENT = "retrobios-exporter/1.0"
_MAX_BYTES = 64 * 1024 * 1024
class SourcesIndexUnreadable(InputMissing):
"""The cache's URL index exists and does not read as JSON."""
def _load_sources(index: Path | None) -> dict[str, str]:
"""The URL each cached file was fetched from.
An absent index records nothing. An index that does not read raises:
read as empty it let every cached original pass for current, and the
next download rewrote it with that one entry.
"""
if index is None or not index.is_file():
return {}
try:
return json.loads(index.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise SourcesIndexUnreadable(
f"{index} does not read ({exc}): remove it, then"
" python scripts/export_native.py --all --refresh-cache"
" downloads every original again and records its URL"
) from exc
def source_key(destination: Path, index: Path | None) -> str:
"""How the index names a cached file: its path below the cache root.
A key that repeated the cache directory as it was typed changed with the
working directory, and a file recorded from one place looked unrecorded
from another.
"""
if index is not None:
try:
return destination.resolve().relative_to(index.parent.resolve()).as_posix()
except ValueError:
pass
return str(destination)
def load_sources(upstream_dir: Path) -> dict[str, str]:
"""Cached file -> URL it was fetched from, for a whole cache directory."""
return _load_sources(upstream_dir / SOURCES_INDEX)
class OriginalUnreadable(ValueError):
"""A platform's file that is not what its format says it is."""
def _read_archive(unpack: Callable[[bytes], dict[str, str]], payload: bytes) -> dict[str, str]:
"""Unpack an original, naming the remedy when its bytes are not one."""
try:
return unpack(payload)
except (zipfile.BadZipFile, tarfile.TarError, EOFError, zlib.error, KeyError) as exc:
raise OriginalUnreadable(
f"archive unreadable ({exc}): --refresh-cache downloads it again"
) from exc
def _read_text(payload: bytes) -> str:
"""A text original, refused when it cannot be the platform's file.
An empty body or an HTML error page served with 200 parsed as a file
with no entries, and four exporters rebuilt the platform's file from our
data alone and said OK: libretro's quoted names and Recalbox's comments
were gone.
"""
text = payload.decode("utf-8", errors="replace")
head = text.lstrip()[:64].lower()
if not head:
raise OriginalUnreadable("empty file: --refresh-cache downloads it again")
if head.startswith(("<!doctype html", "<html")):
raise OriginalUnreadable(
"an HTML page, not the platform's file: --refresh-cache downloads it again"
)
return text
def fetch(
url: str,
destination: Path,
index: Path | None = None,
refresh: bool = False,
check: Callable[[bytes], object] | None = None,
) -> bytes:
"""Download an original once, then read it from the cache.
The cache path carries the file's own name and nothing of the revision it
came from, so a file fetched under one pin was served under every later
one and pinned_base() stopped having any effect after the first run. The
URL that produced each cached file is recorded beside the cache, and a
different URL refetches. A cache written before this index existed keeps
being served: nothing recorded means nothing contradicted.
A branch URL names no revision, so the same URL serves new bytes after
the platform moves. refresh downloads again whatever the cache holds:
it is what a rescrape calls, so the original and its transcription
describe the same moment.
"""
key = source_key(destination, index)
def locked() -> contextlib.AbstractContextManager[object]:
# The bytes and the URL that names them change together: written
# under two locks, two runs wanting two URLs for one path could leave
# one's bytes beside the other's index entry, and the wrong revision
# was then served as current.
if index is None:
return contextlib.nullcontext()
index.parent.mkdir(parents=True, exist_ok=True)
return file_lock(index.with_name(f".{index.name}.lock"))
with locked():
if (
not refresh
and destination.exists()
and _load_sources(index).get(key, url) == url
):
return destination.read_bytes()
request = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
with urllib.request.urlopen(request, timeout=60) as response:
payload = response.read(_MAX_BYTES + 1)
if len(payload) > _MAX_BYTES:
raise OriginalUnreadable(f"{url}: response larger than {_MAX_BYTES} bytes")
# An error page served with 200 replaced a good archive and was then
# served on every run: what does not read is never cached.
if check is not None:
check(payload)
destination.parent.mkdir(parents=True, exist_ok=True)
with locked():
write_bytes_atomic(str(destination), payload)
if index is not None:
# Platforms refresh in parallel: the index is read again under
# the lock, or the last writer erased what the others recorded.
recorded = _load_sources(index)
recorded[key] = url
write_text_atomic(
str(index), json.dumps(recorded, indent=2, sort_keys=True) + "\n"
)
return payload
def _remove_stale(platform_dir: Path, produced: set[str]) -> None:
"""Remove what an earlier run wrote and this one does not.
RetroPie writes one scriptmodule per package it corrects and RetroDECK one
manifest per component: a package corrected by an older truth kept its
file beside a report saying it was no longer touched, and the directory
contradicted the run.
"""
if not platform_dir.is_dir():
return
for path in sorted(platform_dir.rglob("*"), reverse=True):
relative = path.relative_to(platform_dir).as_posix()
if path.is_file() and relative not in produced:
path.unlink()
elif path.is_dir() and not any(path.iterdir()):
path.rmdir()
def pinned_base(wanted: dict[str, str], scraped: dict | None) -> str:
"""The revision our transcription came from, when the YAML records it.
A scraper pins a stable tag (batocera-43.1, BizHawk 2.11.1) and writes
that URL into the platform YAML. Patching the branch tip instead would
correct a file our data never described.
"""
source = _raw_url(str((scraped or {}).get("source", "")))
tree = _GITHUB_TREE.match(source)
if tree:
# RetroDECK reads one manifest per component: the YAML records the
# tree at the commit read, and every file is taken at that commit.
return "https://raw.githubusercontent.com/{}/{}/{}/".format(*tree.groups())
for relative in wanted:
if source.endswith("/" + relative):
return source[: -len(relative)]
return ""
_GITHUB_TREE = re.compile(r"^https://github\.com/([^/]+)/([^/]+)/tree/([0-9a-f]{40})/?$")
def _raw_url(url: str) -> str:
"""A GitHub blob page names a revision but serves HTML, raw serves bytes."""
marker = "/blob/"
if url.startswith("https://github.com/") and marker in url:
owner_repo, _, path = url[len("https://github.com/") :].partition(marker)
return f"https://raw.githubusercontent.com/{owner_repo}/{path}"
return url
def wanted_sources(
exporter: BaseExporter, systems: dict, scraped: dict | None = None
) -> dict[str, str]:
"""Cache-relative name -> URL of every file the exporter patches."""
wanted = dict(exporter.native_sources())
components = getattr(exporter, "components", None)
component_url = getattr(exporter, "component_url", None)
if callable(components) and callable(component_url):
for component in components(systems):
wanted[f"{component}/component_manifest.json"] = component_url(
component
)
base = pinned_base(wanted, scraped)
if base:
wanted = {
relative: _at_revision(wanted[relative], base) or base + relative
for relative in wanted
}
source = str((scraped or {}).get("source", ""))
return {
relative: _tarball_at(url, source) or url for relative, url in wanted.items()
}
_REVISION = (
re.compile(r"^https://raw\.githubusercontent\.com/[^/]+/[^/]+/([^/]+)/"),
re.compile(r"^https://github\.com/[^/]+/[^/]+/(?:tree|blob)/([^/]+)"),
re.compile(r"^https://gitlab\.com/.+?/-/(?:raw|archive)/([^/]+)/"),
re.compile(r"^https://codeload\.github\.com/[^/]+/[^/]+/tar\.gz/([^/]+)$"),
)
def source_revision(source: str) -> str:
"""The revision a platform YAML's source: URL names, '' when none."""
for pattern in _REVISION:
match = pattern.match(source)
if match:
return match.group(1)
return ""
def unpinned(wanted: dict[str, str], scraped: dict | None) -> list[str]:
"""Every file the export would read off the revision the YAML records.
pinned_base() returned '' when the source named no revision or no
longer ended in the file, and the exporter's own branch URL was then
patched without a word: a file our transcription never described.
"""
source = str((scraped or {}).get("source", ""))
revision = source_revision(source)
if not revision:
return [f"the platform's source names no revision ({source or 'none'}): rescrape it"]
return [
f"{relative} would be read at {url}, not at {revision}: rescrape the platform"
for relative, url in wanted.items()
if f"/{revision}/" not in url and not url.endswith(f"/{revision}")
]
_CODELOAD = re.compile(r"^https://codeload\.github\.com/([^/]+)/([^/]+)/tar\.gz/")
def _tarball_at(url: str, source: str) -> str:
"""The recorded tarball when the original is a tarball of the same repository.
RetroPie's declarations are spread over every scriptmodule, so its scraper
reads the repository archive. The archive the YAML records is the one at
the commit it was read from, the exporter's own URL names the branch.
"""
wanted, recorded = _CODELOAD.match(url), _CODELOAD.match(source)
if wanted and recorded and wanted.group(1, 2) == recorded.group(1, 2):
return source
return ""
_RAW_GITHUB = re.compile(r"^https://raw\.githubusercontent\.com/([^/]+)/([^/]+)/([^/]+)/")
def _at_revision(url: str, base: str) -> str:
"""A file of the pinned repository, read at the pinned revision, empty
when the URL is not a raw GitHub URL of that repository.
ROCKNIX's checker sits in packages/rocknix/, the emulators it names in
packages/virtual/: no shared directory, one revision.
"""
pinned, other = _RAW_GITHUB.match(base), _RAW_GITHUB.match(url)
if pinned and other and pinned.group(1, 2) == other.group(1, 2):
return pinned.group(0) + url[other.end():]
return ""
def collect_originals(
exporter: BaseExporter,
systems: dict,
upstream_dir: Path,
allow_fetch: bool,
scraped: dict | None = None,
refresh: bool = False,
) -> tuple[dict[str, str], list[str]]:
"""Gather the platform's own files, from disk or from upstream.
With fetching on, an existing file still goes through fetch(): reading
it straight from disk skipped the recorded URL, so a file cached under
one pin kept being patched after the platform YAML moved to the next.
"""
wanted = wanted_sources(exporter, systems, scraped)
root = upstream_dir / exporter.platform_name()
index = upstream_dir / SOURCES_INDEX
originals: dict[str, str] = {}
missing: list[str] = []
unpack = getattr(exporter, "unpack", None)
for relative, url in wanted.items():
path = root / relative
reader: Callable[[bytes], dict[str, str]] | None = (
unpack if callable(unpack) and relative.endswith((".zip", ".tar.gz")) else None
)
check: Callable[[bytes], object] = (
functools.partial(_read_archive, reader) if reader is not None else _read_text
)
try:
if allow_fetch:
payload = fetch(url, path, index, refresh, check)
elif path.exists():
payload = path.read_bytes()
else:
missing.append(
f"{relative}: not in {root}; rerun with --fetch to download it"
)
continue
if reader is not None:
originals.update(_read_archive(reader, payload))
keep = getattr(exporter, "keep_archive", None)
if callable(keep):
keep(relative, payload)
else:
originals[relative] = _read_text(payload)
# One platform's unreadable file fails that platform: raised, it
# stopped --all before the platforms after it.
except (OSError, http.client.HTTPException, OriginalUnreadable) as exc:
missing.append(f"{relative}: {exc}")
return originals, missing
class StaleTruth(ValueError):
"""The truth file no longer describes the profiles it was built from."""
@functools.cache
def _truth_sources(platforms_dir: str) -> tuple[dict, dict, dict | None]:
"""Registry, profiles and database, as generate_truth reads them."""
registry_path = Path(platforms_dir) / "_registry.yml"
registry: dict = {}
if registry_path.exists():
with open(registry_path) as handle:
registry = (yaml_load(handle) or {}).get("platforms", {})
profiles = load_emulator_profiles("emulators")
db = load_database(TRUTH_DB) if Path(TRUTH_DB).exists() else None
return registry, profiles, db
def current_truth(platform: str, config: dict, platforms_dir: str) -> dict:
"""The truth model generate_truth would write now, as YAML reads it back."""
registry, profiles, db = _truth_sources(platforms_dir)
model = generate_platform_truth(
platform, config, registry.get(platform, {}), profiles, db=db,
data_registry=load_data_dir_registry(platforms_dir),
)
return yaml_load(yaml.dump(model, default_flow_style=False, sort_keys=False,
allow_unicode=True)) or {}
def load_inputs(
platform: str, truth_dir: Path, platforms_dir: str
) -> tuple[dict | None, dict | None]:
"""The truth and the scraped config of a platform, None where absent.
A truth file is an artifact of the profiles: read at any age, one from
before `_required_by` existed silently undid the RetroPie guard that
reads it. One that no longer matches what generate_truth builds now is
refused.
"""
truth_file = truth_dir / f"{platform}.yml"
truth: dict | None = None
try:
config = load_platform_config(platform, platforms_dir)
except (FileNotFoundError, OSError):
config = None
if truth_file.exists():
with open(truth_file) as handle:
truth = yaml_load(handle) or {}
if config is not None and truth != current_truth(platform, config, platforms_dir):
raise StaleTruth(
f"{truth_file} no longer matches the profiles: run "
f"python scripts/generate_truth.py --platform {platform}"
)
return truth, native_layer(config)
def refresh_cache(
platform: str,
exporter_class: type,
truth_dir: Path,
platforms_dir: str,
upstream_dir: Path,
) -> tuple[bool, list[str]]:
"""Download a platform's own files again. Returns (ok, messages)."""
try:
truth, scraped = load_inputs(platform, truth_dir, platforms_dir)
except StaleTruth as exc:
return False, [str(exc)]
systems, _ = build_native_model(truth or {}, scraped)
exporter: BaseExporter = exporter_class()
wanted = wanted_sources(exporter, systems, scraped)
off_pin = unpinned(wanted, scraped)
if off_pin:
return False, off_pin
_, missing = collect_originals(
exporter, systems, upstream_dir, True, scraped, refresh=True
)
if missing:
return False, missing
return True, [f"{len(wanted)} file(s) fetched"]
@functools.cache
def _collection(db_path: str) -> tuple[dict, dict]:
"""The database and its archive index, read once for every platform."""
db = load_database(db_path)
return db, build_zip_contents_index(db)
def doubled_in(scraped: dict | None, platforms_dir: str) -> list[dict]:
"""The destinations the platform's own list declares for two files."""
if not scraped:
return []
db, zip_contents = _collection(TRUTH_DB)
return doubled_destinations(
scraped, load_emulator_profiles("emulators"), db, zip_contents,
load_data_dir_registry(platforms_dir),
)
def _count(number: int, noun: str, plural: str = "") -> str:
""""1 hash", "2 hashes": a count with its noun in the right number."""
plural = plural or noun + ("es" if noun.endswith(("sh", "ch", "s", "x")) else "s")
return f"{number} {noun if number == 1 else plural}"
@dataclass
class LandedChanges:
"""What an export changed in the platform's file, field by field.
`records` holds each change with its value before and after, so a
maintainer can check it against the diff. The lists of labels are read
from it, for the summary and the page.
"""
records: list[dict] = field(default_factory=list)
def _labels(self, kind: str) -> list[str]:
return [
f"{r['system']}/{r['name']} {r['field']}"
for r in self.records if r["kind"] == kind
]
@property
def applied(self) -> list[str]:
return self._labels("hash_updated")
@property
def filled(self) -> list[str]:
return self._labels("hash_filled")
@property
def cleared(self) -> list[str]:
return self._labels("hash_cleared")
@property
def resized(self) -> list[str]:
return [label.removesuffix(" size") for label in self._labels("size_updated")]
@property
def unsized(self) -> list[str]:
return [label.removesuffix(" size") for label in self._labels("size_removed")]
@property
def requirements(self) -> int:
return sum(r["kind"] == "required_aligned" for r in self.records)
@property
def lists(self) -> int:
"""Entries whose md5 is written as a list of accepted values."""
return sum(
isinstance(r["new"], list)
or (isinstance(r["new"], dict) and isinstance(r["new"].get("md5"), list))
for r in self.records
)
def _change(
kind: str, entry: NativeFile, field_name: str | None, old: object, new: object
) -> dict:
return {
"kind": kind,
"system": entry.native_system,
"name": entry.name,
"destination": entry.destination,
"field": field_name,
"old": old,
"new": new,
}
def _platform_value(entry: NativeFile, field_name: str) -> str | list[str]:
values = _hash_values(entry.platform or {}, field_name)
if (entry.platform or {}).get(f"{field_name}_list"):
return values
return ",".join(values)
def _written_value(exporter: BaseExporter, entry: NativeFile, field_name: str) -> str | list[str]:
"""A hash field as the render writes it: a list where the checker reads
one, so the report never shows several values as one."""
listed = exporter.written_list(entry, field_name)
return listed if listed is not None else exporter.written(entry, field_name)
def _added_fields(exporter: BaseExporter, entry: NativeFile) -> dict:
"""The fields an addition is written with, as the render chooses them."""
carried = exporter.carries()
written: dict[str, object] = {
name: value
for name in HASH_FIELDS
if name in carried and (value := _written_value(exporter, entry, name))
}
if "size" in carried and entry.size() is not None:
written["size"] = entry.size()
if "required" in carried:
written["required"] = exporter.required_value(entry)
return written
def landed_changes(exporter: BaseExporter, systems: dict) -> LandedChanges:
"""The changes the written file carries, with their values.
Only what the format states: a correction to a field the file has no
place for, or one its render keeps out, is not a change the maintainer
will find in the diff, and counting it would announce work the export
did not do. A hash written where the platform left none changes the
check from existence to content, so it is counted too. The truth taking
over an entry also rewrites its size and drops the platform's hashes it
does not declare: both are in the diff. An addition carries the fields
it is written with as its new value.
"""
changes = LandedChanges()
records = changes.records
for system in systems.values():
for entry in system.files:
if entry.platform is None:
if entry.name and exporter.lands(entry):
records.append(_change(
"added", entry, None, None, _added_fields(exporter, entry)
))
continue
if entry.name and exporter.names_anew(entry):
records.append(_change(
"added", entry, None, None, _added_fields(exporter, entry)
))
# Asked of the exporter: a format that names each entry's cores
# reads every entry of those cores, not only the paired one.
if (
entry.platform.get("required") is not None
and exporter.states(entry, "required")
and exporter.required_value(entry) != bool(entry.platform["required"])
):
records.append(_change(
"required_aligned", entry, "required",
bool(entry.platform["required"]), exporter.required_value(entry),
))
for field_name in entry.corrections:
if field_name == "required" or not exporter.states(entry, field_name):
continue
records.append(_change(
"hash_updated", entry, field_name,
_platform_value(entry, field_name),
_written_value(exporter, entry, field_name),
))
# A list the truth extends with values the platform's own lacks:
# no contradiction, so no correction in the model, and still a
# new value in the file.
for field_name in HASH_FIELDS:
listed = exporter.written_list(entry, field_name)
if (
listed is not None
and field_name not in entry.corrections
and field_name not in entry.filled
and listed != _hash_values(entry.platform, field_name)
and exporter.states(entry, field_name)
):
records.append(_change(
"hash_updated", entry, field_name,
_platform_value(entry, field_name), listed,
))
records.extend(
_change("hash_filled", entry, field_name, None,
_written_value(exporter, entry, field_name))
for field_name in entry.filled
if exporter.fills(entry, field_name)
)
theirs = entry.platform.get("size")
ours = entry.size()
if (
theirs
and ours
and _single_size(theirs) not in (None, ours)
and exporter.states(entry, "size")
):
records.append(_change(
"size_updated", entry, "size", _single_size(theirs), ours
))
elif (
theirs
and ours is None
and _single_size(theirs) is not None
and exporter.states(entry, "size")
):
# The truth took the entry over without a size of its own:
# System.dat's neocdz.zip line went out without size 953078.
records.append(_change(
"size_removed", entry, "size", _single_size(theirs), None
))
records.extend(
_change("hash_cleared", entry, field_name,
_platform_value(entry, field_name), None)
for field_name in HASH_FIELDS
if _hash_values(entry.platform, field_name)
and not entry.hashes(field_name)
and exporter.clears(entry, field_name)
)
# A value the render rewrote though the model reads it as the
# platform's own (RomM's sha1 with a leading space).
records.extend(
_change("hash_updated", entry, field_name, old, new)
for entry, field_name, old, new in getattr(exporter, "normalized_values", [])
)
return changes
def export_platform(
platform: str,
exporter_class: type,
truth_dir: Path,
output_dir: Path,
platforms_dir: str,
upstream_dir: Path,
allow_fetch: bool,
) -> tuple[bool, list[str]]:
"""Write one platform's corrected file. Returns (ok, messages)."""
try:
truth, scraped = load_inputs(platform, truth_dir, platforms_dir)
except StaleTruth as exc:
return False, [str(exc)]
if truth is None:
# Without a truth the export is the platform's file copied back, and
# it replaced the corrected one in exports/ on a fresh clone.
return False, [
f"{truth_dir / f'{platform}.yml'} is absent: run "
f"python scripts/generate_truth.py --platform {platform}"
]
systems, report = build_native_model(truth, scraped)
if not systems:
return False, ["nothing to write: neither the platform nor the truth has data"]
exporter: BaseExporter = exporter_class()
produced, issues, stopped = _produce(
exporter, systems, report, scraped, upstream_dir, allow_fetch,
)
if stopped:
return False, stopped
platform_dir = output_dir / platform
_remove_stale(platform_dir, set(produced))
_write_produced(platform_dir, produced, exporter.file_modes())
changes = landed_changes(exporter, systems)
applied, filled = changes.applied, changes.filled
resized, cleared = changes.resized, changes.cleared
unsized = changes.unsized
requirements = changes.requirements
landed, refused, lost = _entry_outcomes(exporter, systems)
own_summary = exporter.outcome(systems, produced)
summary = own_summary
if summary is None:
summary = _landed_summary(report, changes, landed, lost)
withheld = exporter.withheld()
unwritten = _unwritten(refused, withheld, report)
# Reported, never removed: the platform's file keeps every entry.
candidates = removal_candidates(
systems, scraped, load_emulator_profiles("emulators"),
load_data_dir_registry(platforms_dir),
)
# Reported, never rewritten: both declarations stay as the platform wrote them.
doubled = doubled_in(scraped, platforms_dir)
messages = _export_messages(summary, unwritten, candidates, doubled, withheld, changes)
write_report(output_dir / f"{platform}.json", {
"platform": platform,
"originals": wanted_sources(exporter, systems, scraped),
"files": sorted(produced),
"summary": summary,
"counts": None if own_summary is not None else {
"kept": report.files_kept,
"added": landed,
"not_added": refused,
"not_kept": lost,
},
"changes": changes.records,
"hashes_updated": applied,
"hashes_filled": filled,
"sizes_updated": resized,
"sizes_removed": unsized,
"hashes_cleared": cleared,
"required_aligned": requirements,
"withheld": list(withheld),
"found_by_content": report.labels,
"unattributed": report.unattributed,
"removal_candidates": candidates,
"doubled": doubled,
"invalid": issues,
})
return True, messages
def _produce(
exporter: BaseExporter,
systems: dict,
report: Report,
scraped: dict | None,
upstream_dir: Path,
allow_fetch: bool,
) -> tuple[dict, list[str], list[str]]:
"""The files the exporter renders, its validator's issues, and why the
export stops before writing (empty when it goes on)."""
off_pin = unpinned(wanted_sources(exporter, systems, scraped), scraped)
if off_pin:
return {}, [], off_pin
originals, missing = collect_originals(
exporter, systems, upstream_dir, allow_fetch, scraped
)
if missing:
return {}, [], [f"the platform's own file is required: {m}" for m in missing]
if exporter.needs_original() and not originals:
return {}, [], ["the platform's own file is required and none was read"]
try:
produced = exporter.render(systems, report, originals, scraped)
except ValueError as exc:
return {}, [], [str(exc)]
if not produced and not exporter.may_write_nothing():
return {}, [], ["the exporter produced no file"]
issues = exporter.validate(systems, produced)
if issues:
# Written first, a file its own validator refused replaced the
# published export and only the exit code said so.
invalid = [f"INVALID: {issue}" for issue in issues[:10]]
if len(issues) > 10:
invalid.append(f"and {len(issues) - 10} more validation failures")
return {}, issues, invalid
return produced, issues, []
def _entry_outcomes(exporter: BaseExporter, systems: dict) -> tuple[int, int, int]:
"""Additions written, additions refused, and platform entries lost."""
landed = 0
refused = 0
lost = 0
for system in systems.values():
for entry in system.files:
if not entry.name:
continue
if exporter.lands(entry):
landed += entry.platform is None
elif entry.platform is None:
refused += 1
else:
# The platform declares it and the format still cannot state
# it, so their own file loses a line. Worth saying out loud.
lost += 1
return landed, refused, lost
def _landed_summary(report: Report, changes: LandedChanges, landed: int, lost: int) -> str:
# What the written file carries, in the terms the exports page uses.
# What it does not carry is counted on a line of its own below.
parts = [f"{report.files_kept} kept"]
landed_counts = (
(landed, "file", "", "added"),
(len(changes.applied), "hash", "", "updated to the emulator source"),
(changes.requirements, "required flag", "", "aligned with the code"),
(len(changes.filled), "hash", "", "added to an existing entry"),
(len(changes.resized), "size", "", "updated to the emulator source"),
(len(changes.unsized), "size", "", "removed"),
(len(changes.cleared), "hash", "", "removed"),
(lost, "entry", "entries", "removed, the format cannot state them"),
(changes.lists, "md5 list", "", "written, any listed value passes"),
)
parts += [
f"{_count(number, noun, plural)} {verb}"
for number, noun, plural, verb in landed_counts
if number
]
return ", ".join(parts)
def _unwritten(refused: int, withheld: list[str], report: Report) -> list[str]:
return [
f"{_count(number, noun, plural)} {what}"
for number, noun, plural, what in (
(refused, "file", "", "the format or its checker cannot carry"),
(len(withheld), "update", "", "withheld"),
# A content-scanning core's names are labels: a list checked
# by path cannot hold them.
(report.labels, "entry", "entries", "found by content"),
(len(report.unattributed), "file", "",
"no single native system of the platform takes"),
)
if number
]
def _export_messages(
summary: str,
unwritten: list[str],
candidates: list[dict],
doubled: list[dict],
withheld: list[str],
changes: LandedChanges,
) -> list[str]:
messages = [summary]
if unwritten:
messages.append("not in the file: " + ", ".join(unwritten))
if candidates:
open_question = sum(c["verdict"] == "undetermined" for c in candidates)
messages.append(
f"{_count(len(candidates), 'entry', 'entries')} no examined core is known to open"
+ (f" ({open_question} undetermined)" if open_question else "")
+ ", listed in the report"
)
if doubled:
messages.append(
f"{_count(len(doubled), 'destination')} declared twice for two files"
", listed in the report"
)
messages.extend(f"withheld: {reason}" for reason in withheld)
for heading, labels in (
("hash updated", changes.applied),
("hash added", changes.filled),
("size updated", changes.resized),
("size removed", changes.unsized),
("hash removed", changes.cleared),
):
messages.extend(f"{heading}: {label}" for label in labels[:5])
if len(labels) > 5:
messages.append(f"and {len(labels) - 5} more")
return messages
def _write_produced(
root: Path, produced: dict[str, str | bytes], modes: dict[str, int]
) -> None:
"""Write each file as its bytes, whole or not at all, with its mode.
write_text translated line ends on Windows, so FirmwareDatabase.cs's
CRLF would have come out CR CR LF, and a run stopped mid-write left a
truncated file in exports/. The scratch file mkstemp makes is 0600: the
mode is set from what the platform's own file has.
"""
for relative, content in produced.items():
path = root / relative
path.parent.mkdir(parents=True, exist_ok=True)
data = content if isinstance(content, bytes) else content.encode("utf-8")
write_bytes_atomic(str(path), data)
path.chmod(modes.get(relative, 0o644))
def write_report(path: Path, report: dict) -> None:
"""What one platform's export changed, for the page that publishes it.
The run prints five examples per kind of change. The page lists them
all, so the maintainer reading it finds each line of the diff named.
A platform with nothing to write made no directory of its own: the
output directory itself may not exist yet.
"""
path.parent.mkdir(parents=True, exist_ok=True)
write_if_changed(str(path), json.dumps(report, indent=2) + "\n")
from exporter.native import export_platform, refresh_cache
from exporter.originals import DEFAULT_CACHE
def run(
+209
View File
@@ -0,0 +1,209 @@
"""What an export changed in a platform's file, field by field, with each
value before and after."""
from __future__ import annotations
from dataclasses import dataclass, field
from .base_exporter import BaseExporter
from resolve.reconcile import HASH_FIELDS, NativeFile, _hash_values, _single_size
@dataclass
class LandedChanges:
"""What an export changed in the platform's file, field by field.
`records` holds each change with its value before and after, so a
maintainer can check it against the diff. The lists of labels are read
from it, for the summary and the page.
"""
records: list[dict] = field(default_factory=list)
def _labels(self, kind: str) -> list[str]:
return [
f"{r['system']}/{r['name']} {r['field']}"
for r in self.records if r["kind"] == kind
]
@property
def applied(self) -> list[str]:
return self._labels("hash_updated")
@property
def filled(self) -> list[str]:
return self._labels("hash_filled")
@property
def cleared(self) -> list[str]:
return self._labels("hash_cleared")
@property
def resized(self) -> list[str]:
return [label.removesuffix(" size") for label in self._labels("size_updated")]
@property
def unsized(self) -> list[str]:
return [label.removesuffix(" size") for label in self._labels("size_removed")]
@property
def requirements(self) -> int:
return sum(r["kind"] == "required_aligned" for r in self.records)
@property
def lists(self) -> int:
"""Entries whose md5 is written as a list of accepted values."""
return sum(
isinstance(r["new"], list)
or (isinstance(r["new"], dict) and isinstance(r["new"].get("md5"), list))
for r in self.records
)
def _change(
kind: str, entry: NativeFile, field_name: str | None, old: object, new: object
) -> dict:
return {
"kind": kind,
"system": entry.native_system,
"name": entry.name,
"destination": entry.destination,
"field": field_name,
"old": old,
"new": new,
}
def _platform_value(entry: NativeFile, field_name: str) -> str | list[str]:
values = _hash_values(entry.platform or {}, field_name)
if (entry.platform or {}).get(f"{field_name}_list"):
return values
return ",".join(values)
def _written_value(exporter: BaseExporter, entry: NativeFile, field_name: str) -> str | list[str]:
"""A hash field as the render writes it: a list where the checker reads
one, so the report never shows several values as one."""
listed = exporter.written_list(entry, field_name)
return listed if listed is not None else exporter.written(entry, field_name)
def _added_fields(exporter: BaseExporter, entry: NativeFile) -> dict:
"""The fields an addition is written with, as the render chooses them."""
carried = exporter.carries()
written: dict[str, object] = {
name: value
for name in HASH_FIELDS
if name in carried and (value := _written_value(exporter, entry, name))
}
if "size" in carried and entry.size() is not None:
written["size"] = entry.size()
if "required" in carried:
written["required"] = exporter.required_value(entry)
return written
def landed_changes(exporter: BaseExporter, systems: dict) -> LandedChanges:
"""The changes the written file carries, with their values.
Only what the format states: a correction to a field the file has no
place for, or one its render keeps out, is not a change the maintainer
will find in the diff, and counting it would announce work the export
did not do. A hash written where the platform left none changes the
check from existence to content, so it is counted too. The truth taking
over an entry also rewrites its size and drops the platform's hashes it
does not declare: both are in the diff. An addition carries the fields
it is written with as its new value.
"""
changes = LandedChanges()
records = changes.records
for system in systems.values():
for entry in system.files:
if entry.platform is None:
if entry.name and exporter.lands(entry):
records.append(_change(
"added", entry, None, None, _added_fields(exporter, entry)
))
continue
if entry.name and exporter.names_anew(entry):
records.append(_change(
"added", entry, None, None, _added_fields(exporter, entry)
))
# Asked of the exporter: a format that names each entry's cores
# reads every entry of those cores, not only the paired one.
if (
entry.platform.get("required") is not None
and exporter.states(entry, "required")
and exporter.required_value(entry) != bool(entry.platform["required"])
):
records.append(_change(
"required_aligned", entry, "required",
bool(entry.platform["required"]), exporter.required_value(entry),
))
for field_name in entry.corrections:
if field_name == "required" or not exporter.states(entry, field_name):
continue
records.append(_change(
"hash_updated", entry, field_name,
_platform_value(entry, field_name),
_written_value(exporter, entry, field_name),
))
# A list the truth extends with values the platform's own lacks:
# no contradiction, so no correction in the model, and still a
# new value in the file.
for field_name in HASH_FIELDS:
listed = exporter.written_list(entry, field_name)
if (
listed is not None
and field_name not in entry.corrections
and field_name not in entry.filled
and listed != _hash_values(entry.platform, field_name)
and exporter.states(entry, field_name)
):
records.append(_change(
"hash_updated", entry, field_name,
_platform_value(entry, field_name), listed,
))
records.extend(
_change("hash_filled", entry, field_name, None,
_written_value(exporter, entry, field_name))
for field_name in entry.filled
if exporter.fills(entry, field_name)
)
theirs = entry.platform.get("size")
ours = entry.size()
if (
theirs
and ours
and _single_size(theirs) not in (None, ours)
and exporter.states(entry, "size")
):
records.append(_change(
"size_updated", entry, "size", _single_size(theirs), ours
))
elif (
theirs
and ours is None
and _single_size(theirs) is not None
and exporter.states(entry, "size")
):
# The truth took the entry over without a size of its own:
# System.dat's neocdz.zip line went out without size 953078.
records.append(_change(
"size_removed", entry, "size", _single_size(theirs), None
))
records.extend(
_change("hash_cleared", entry, field_name,
_platform_value(entry, field_name), None)
for field_name in HASH_FIELDS
if _hash_values(entry.platform, field_name)
and not entry.hashes(field_name)
and exporter.clears(entry, field_name)
)
# A value the render rewrote though the model reads it as the
# platform's own (RomM's sha1 with a leading space).
records.extend(
_change("hash_updated", entry, field_name, old, new)
for entry, field_name, old, new in getattr(exporter, "normalized_values", [])
)
return changes
+408
View File
@@ -0,0 +1,408 @@
"""One platform's own BIOS file, rewritten and corrected by the ground truth.
The truth model and the platform's YAML are read, the exporter renders the
file from the platform's original, and a report lists every change."""
from __future__ import annotations
import functools
import json
from pathlib import Path
import yaml
from core.artifacts import write_bytes_atomic, write_if_changed
from core.ziptools import build_zip_contents_index
from .base_exporter import BaseExporter
from .doubled import doubled_destinations
from .landed import LandedChanges, landed_changes
from .originals import collect_originals, unpinned, wanted_sources
from model.database import load_database
from model.platforms import load_platform_config, native_layer
from model.profiles import load_emulator_profiles
from model.registry import load_data_dir_registry
from model.safeparse import yaml_load
from resolve.categories import removal_candidates
from resolve.reconcile import Report, build_native_model
from resolve.truth import generate_platform_truth
# The database generate_truth reads by default.
TRUTH_DB = "database.json"
def _remove_stale(platform_dir: Path, produced: set[str]) -> None:
"""Remove what an earlier run wrote and this one does not.
RetroPie writes one scriptmodule per package it corrects and RetroDECK one
manifest per component: a package corrected by an older truth kept its
file beside a report saying it was no longer touched, and the directory
contradicted the run.
"""
if not platform_dir.is_dir():
return
for path in sorted(platform_dir.rglob("*"), reverse=True):
relative = path.relative_to(platform_dir).as_posix()
if path.is_file() and relative not in produced:
path.unlink()
elif path.is_dir() and not any(path.iterdir()):
path.rmdir()
class StaleTruth(ValueError):
"""The truth file no longer describes the profiles it was built from."""
@functools.cache
def _truth_sources(platforms_dir: str) -> tuple[dict, dict, dict | None]:
"""Registry, profiles and database, as generate_truth reads them."""
registry_path = Path(platforms_dir) / "_registry.yml"
registry: dict = {}
if registry_path.exists():
with open(registry_path) as handle:
registry = (yaml_load(handle) or {}).get("platforms", {})
profiles = load_emulator_profiles("emulators")
db = load_database(TRUTH_DB) if Path(TRUTH_DB).exists() else None
return registry, profiles, db
def current_truth(platform: str, config: dict, platforms_dir: str) -> dict:
"""The truth model generate_truth would write now, as YAML reads it back."""
registry, profiles, db = _truth_sources(platforms_dir)
model = generate_platform_truth(
platform, config, registry.get(platform, {}), profiles, db=db,
data_registry=load_data_dir_registry(platforms_dir),
)
return yaml_load(yaml.dump(model, default_flow_style=False, sort_keys=False,
allow_unicode=True)) or {}
def load_inputs(
platform: str, truth_dir: Path, platforms_dir: str
) -> tuple[dict | None, dict | None]:
"""The truth and the scraped config of a platform, None where absent.
A truth file is an artifact of the profiles: read at any age, one from
before `_required_by` existed silently undid the RetroPie guard that
reads it. One that no longer matches what generate_truth builds now is
refused.
"""
truth_file = truth_dir / f"{platform}.yml"
truth: dict | None = None
try:
config = load_platform_config(platform, platforms_dir)
except (FileNotFoundError, OSError):
config = None
if truth_file.exists():
with open(truth_file) as handle:
truth = yaml_load(handle) or {}
if config is not None and truth != current_truth(platform, config, platforms_dir):
raise StaleTruth(
f"{truth_file} no longer matches the profiles: run "
f"python scripts/generate_truth.py --platform {platform}"
)
return truth, native_layer(config)
def refresh_cache(
platform: str,
exporter_class: type,
truth_dir: Path,
platforms_dir: str,
upstream_dir: Path,
) -> tuple[bool, list[str]]:
"""Download a platform's own files again. Returns (ok, messages)."""
try:
truth, scraped = load_inputs(platform, truth_dir, platforms_dir)
except StaleTruth as exc:
return False, [str(exc)]
systems, _ = build_native_model(truth or {}, scraped)
exporter: BaseExporter = exporter_class()
wanted = wanted_sources(exporter, systems, scraped)
off_pin = unpinned(wanted, scraped)
if off_pin:
return False, off_pin
_, missing = collect_originals(
exporter, systems, upstream_dir, True, scraped, refresh=True
)
if missing:
return False, missing
return True, [f"{len(wanted)} file(s) fetched"]
@functools.cache
def _collection(db_path: str) -> tuple[dict, dict]:
"""The database and its archive index, read once for every platform."""
db = load_database(db_path)
return db, build_zip_contents_index(db)
def doubled_in(scraped: dict | None, platforms_dir: str) -> list[dict]:
"""The destinations the platform's own list declares for two files."""
if not scraped:
return []
db, zip_contents = _collection(TRUTH_DB)
return doubled_destinations(
scraped, load_emulator_profiles("emulators"), db, zip_contents,
load_data_dir_registry(platforms_dir),
)
def _count(number: int, noun: str, plural: str = "") -> str:
""""1 hash", "2 hashes": a count with its noun in the right number."""
plural = plural or noun + ("es" if noun.endswith(("sh", "ch", "s", "x")) else "s")
return f"{number} {noun if number == 1 else plural}"
def export_platform(
platform: str,
exporter_class: type,
truth_dir: Path,
output_dir: Path,
platforms_dir: str,
upstream_dir: Path,
allow_fetch: bool,
) -> tuple[bool, list[str]]:
"""Write one platform's corrected file. Returns (ok, messages)."""
try:
truth, scraped = load_inputs(platform, truth_dir, platforms_dir)
except StaleTruth as exc:
return False, [str(exc)]
if truth is None:
# Without a truth the export is the platform's file copied back, and
# it replaced the corrected one in exports/ on a fresh clone.
return False, [
f"{truth_dir / f'{platform}.yml'} is absent: run "
f"python scripts/generate_truth.py --platform {platform}"
]
systems, report = build_native_model(truth, scraped)
if not systems:
return False, ["nothing to write: neither the platform nor the truth has data"]
exporter: BaseExporter = exporter_class()
produced, issues, stopped = _produce(
exporter, systems, report, scraped, upstream_dir, allow_fetch,
)
if stopped:
return False, stopped
platform_dir = output_dir / platform
_remove_stale(platform_dir, set(produced))
_write_produced(platform_dir, produced, exporter.file_modes())
changes = landed_changes(exporter, systems)
applied, filled = changes.applied, changes.filled
resized, cleared = changes.resized, changes.cleared
unsized = changes.unsized
requirements = changes.requirements
landed, refused, lost = _entry_outcomes(exporter, systems)
own_summary = exporter.outcome(systems, produced)
summary = own_summary
if summary is None:
summary = _landed_summary(report, changes, landed, lost)
withheld = exporter.withheld()
unwritten = _unwritten(refused, withheld, report)
# Reported, never removed: the platform's file keeps every entry.
candidates = removal_candidates(
systems, scraped, load_emulator_profiles("emulators"),
load_data_dir_registry(platforms_dir),
)
# Reported, never rewritten: both declarations stay as the platform wrote them.
doubled = doubled_in(scraped, platforms_dir)
messages = _export_messages(summary, unwritten, candidates, doubled, withheld, changes)
write_report(output_dir / f"{platform}.json", {
"platform": platform,
"originals": wanted_sources(exporter, systems, scraped),
"files": sorted(produced),
"summary": summary,
"counts": None if own_summary is not None else {
"kept": report.files_kept,
"added": landed,
"not_added": refused,
"not_kept": lost,
},
"changes": changes.records,
"hashes_updated": applied,
"hashes_filled": filled,
"sizes_updated": resized,
"sizes_removed": unsized,
"hashes_cleared": cleared,
"required_aligned": requirements,
"withheld": list(withheld),
"found_by_content": report.labels,
"unattributed": report.unattributed,
"removal_candidates": candidates,
"doubled": doubled,
"invalid": issues,
})
return True, messages
def _produce(
exporter: BaseExporter,
systems: dict,
report: Report,
scraped: dict | None,
upstream_dir: Path,
allow_fetch: bool,
) -> tuple[dict, list[str], list[str]]:
"""The files the exporter renders, its validator's issues, and why the
export stops before writing (empty when it goes on)."""
off_pin = unpinned(wanted_sources(exporter, systems, scraped), scraped)
if off_pin:
return {}, [], off_pin
originals, missing = collect_originals(
exporter, systems, upstream_dir, allow_fetch, scraped
)
if missing:
return {}, [], [f"the platform's own file is required: {m}" for m in missing]
if exporter.needs_original() and not originals:
return {}, [], ["the platform's own file is required and none was read"]
try:
produced = exporter.render(systems, report, originals, scraped)
except ValueError as exc:
return {}, [], [str(exc)]
if not produced and not exporter.may_write_nothing():
return {}, [], ["the exporter produced no file"]
issues = exporter.validate(systems, produced)
if issues:
# Written first, a file its own validator refused replaced the
# published export and only the exit code said so.
invalid = [f"INVALID: {issue}" for issue in issues[:10]]
if len(issues) > 10:
invalid.append(f"and {len(issues) - 10} more validation failures")
return {}, issues, invalid
return produced, issues, []
def _entry_outcomes(exporter: BaseExporter, systems: dict) -> tuple[int, int, int]:
"""Additions written, additions refused, and platform entries lost."""
landed = 0
refused = 0
lost = 0
for system in systems.values():
for entry in system.files:
if not entry.name:
continue
if exporter.lands(entry):
landed += entry.platform is None
elif entry.platform is None:
refused += 1
else:
# The platform declares it and the format still cannot state
# it, so their own file loses a line. Worth saying out loud.
lost += 1
return landed, refused, lost
def _landed_summary(report: Report, changes: LandedChanges, landed: int, lost: int) -> str:
# What the written file carries, in the terms the exports page uses.
# What it does not carry is counted on a line of its own below.
parts = [f"{report.files_kept} kept"]
landed_counts = (
(landed, "file", "", "added"),
(len(changes.applied), "hash", "", "updated to the emulator source"),
(changes.requirements, "required flag", "", "aligned with the code"),
(len(changes.filled), "hash", "", "added to an existing entry"),
(len(changes.resized), "size", "", "updated to the emulator source"),
(len(changes.unsized), "size", "", "removed"),
(len(changes.cleared), "hash", "", "removed"),
(lost, "entry", "entries", "removed, the format cannot state them"),
(changes.lists, "md5 list", "", "written, any listed value passes"),
)
parts += [
f"{_count(number, noun, plural)} {verb}"
for number, noun, plural, verb in landed_counts
if number
]
return ", ".join(parts)
def _unwritten(refused: int, withheld: list[str], report: Report) -> list[str]:
return [
f"{_count(number, noun, plural)} {what}"
for number, noun, plural, what in (
(refused, "file", "", "the format or its checker cannot carry"),
(len(withheld), "update", "", "withheld"),
# A content-scanning core's names are labels: a list checked
# by path cannot hold them.
(report.labels, "entry", "entries", "found by content"),
(len(report.unattributed), "file", "",
"no single native system of the platform takes"),
)
if number
]
def _export_messages(
summary: str,
unwritten: list[str],
candidates: list[dict],
doubled: list[dict],
withheld: list[str],
changes: LandedChanges,
) -> list[str]:
messages = [summary]
if unwritten:
messages.append("not in the file: " + ", ".join(unwritten))
if candidates:
open_question = sum(c["verdict"] == "undetermined" for c in candidates)
messages.append(
f"{_count(len(candidates), 'entry', 'entries')} no examined core is known to open"
+ (f" ({open_question} undetermined)" if open_question else "")
+ ", listed in the report"
)
if doubled:
messages.append(
f"{_count(len(doubled), 'destination')} declared twice for two files"
", listed in the report"
)
messages.extend(f"withheld: {reason}" for reason in withheld)
for heading, labels in (
("hash updated", changes.applied),
("hash added", changes.filled),
("size updated", changes.resized),
("size removed", changes.unsized),
("hash removed", changes.cleared),
):
messages.extend(f"{heading}: {label}" for label in labels[:5])
if len(labels) > 5:
messages.append(f"and {len(labels) - 5} more")
return messages
def _write_produced(
root: Path, produced: dict[str, str | bytes], modes: dict[str, int]
) -> None:
"""Write each file as its bytes, whole or not at all, with its mode.
write_text translated line ends on Windows, so FirmwareDatabase.cs's
CRLF would have come out CR CR LF, and a run stopped mid-write left a
truncated file in exports/. The scratch file mkstemp makes is 0600: the
mode is set from what the platform's own file has.
"""
for relative, content in produced.items():
path = root / relative
path.parent.mkdir(parents=True, exist_ok=True)
data = content if isinstance(content, bytes) else content.encode("utf-8")
write_bytes_atomic(str(path), data)
path.chmod(modes.get(relative, 0o644))
def write_report(path: Path, report: dict) -> None:
"""What one platform's export changed, for the page that publishes it.
The run prints five examples per kind of change. The page lists them
all, so the maintainer reading it finds each line of the diff named.
A platform with nothing to write made no directory of its own: the
output directory itself may not exist yet.
"""
path.parent.mkdir(parents=True, exist_ok=True)
write_if_changed(str(path), json.dumps(report, indent=2) + "\n")
+340
View File
@@ -0,0 +1,340 @@
"""The platforms' own files an export patches: where each is read, at which
revision, and the cache that keeps them with the URL they came from."""
from __future__ import annotations
import contextlib
import functools
import http.client
import json
import re
import tarfile
import urllib.request
import zipfile
import zlib
from collections.abc import Callable
from pathlib import Path
from core.artifacts import file_lock, write_bytes_atomic, write_text_atomic
from core.cli import InputMissing
from .base_exporter import BaseExporter
DEFAULT_CACHE = ".cache/upstream-native"
SOURCES_INDEX = ".sources.json"
_USER_AGENT = "retrobios-exporter/1.0"
_MAX_BYTES = 64 * 1024 * 1024
class SourcesIndexUnreadable(InputMissing):
"""The cache's URL index exists and does not read as JSON."""
def _load_sources(index: Path | None) -> dict[str, str]:
"""The URL each cached file was fetched from.
An absent index records nothing. An index that does not read raises:
read as empty it let every cached original pass for current, and the
next download rewrote it with that one entry.
"""
if index is None or not index.is_file():
return {}
try:
return json.loads(index.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise SourcesIndexUnreadable(
f"{index} does not read ({exc}): remove it, then"
" python scripts/export_native.py --all --refresh-cache"
" downloads every original again and records its URL"
) from exc
def source_key(destination: Path, index: Path | None) -> str:
"""How the index names a cached file: its path below the cache root.
A key that repeated the cache directory as it was typed changed with the
working directory, and a file recorded from one place looked unrecorded
from another.
"""
if index is not None:
try:
return destination.resolve().relative_to(index.parent.resolve()).as_posix()
except ValueError:
pass
return str(destination)
def load_sources(upstream_dir: Path) -> dict[str, str]:
"""Cached file -> URL it was fetched from, for a whole cache directory."""
return _load_sources(upstream_dir / SOURCES_INDEX)
class OriginalUnreadable(ValueError):
"""A platform's file that is not what its format says it is."""
def _read_archive(unpack: Callable[[bytes], dict[str, str]], payload: bytes) -> dict[str, str]:
"""Unpack an original, naming the remedy when its bytes are not one."""
try:
return unpack(payload)
except (zipfile.BadZipFile, tarfile.TarError, EOFError, zlib.error, KeyError) as exc:
raise OriginalUnreadable(
f"archive unreadable ({exc}): --refresh-cache downloads it again"
) from exc
def _read_text(payload: bytes) -> str:
"""A text original, refused when it cannot be the platform's file.
An empty body or an HTML error page served with 200 parsed as a file
with no entries, and four exporters rebuilt the platform's file from our
data alone and said OK: libretro's quoted names and Recalbox's comments
were gone.
"""
text = payload.decode("utf-8", errors="replace")
head = text.lstrip()[:64].lower()
if not head:
raise OriginalUnreadable("empty file: --refresh-cache downloads it again")
if head.startswith(("<!doctype html", "<html")):
raise OriginalUnreadable(
"an HTML page, not the platform's file: --refresh-cache downloads it again"
)
return text
def fetch(
url: str,
destination: Path,
index: Path | None = None,
refresh: bool = False,
check: Callable[[bytes], object] | None = None,
) -> bytes:
"""Download an original once, then read it from the cache.
The cache path carries the file's own name and nothing of the revision it
came from, so a file fetched under one pin was served under every later
one and pinned_base() stopped having any effect after the first run. The
URL that produced each cached file is recorded beside the cache, and a
different URL refetches. A cache written before this index existed keeps
being served: nothing recorded means nothing contradicted.
A branch URL names no revision, so the same URL serves new bytes after
the platform moves. refresh downloads again whatever the cache holds:
it is what a rescrape calls, so the original and its transcription
describe the same moment.
"""
key = source_key(destination, index)
def locked() -> contextlib.AbstractContextManager[object]:
# The bytes and the URL that names them change together: written
# under two locks, two runs wanting two URLs for one path could leave
# one's bytes beside the other's index entry, and the wrong revision
# was then served as current.
if index is None:
return contextlib.nullcontext()
index.parent.mkdir(parents=True, exist_ok=True)
return file_lock(index.with_name(f".{index.name}.lock"))
with locked():
if (
not refresh
and destination.exists()
and _load_sources(index).get(key, url) == url
):
return destination.read_bytes()
request = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT})
with urllib.request.urlopen(request, timeout=60) as response:
payload = response.read(_MAX_BYTES + 1)
if len(payload) > _MAX_BYTES:
raise OriginalUnreadable(f"{url}: response larger than {_MAX_BYTES} bytes")
# An error page served with 200 replaced a good archive and was then
# served on every run: what does not read is never cached.
if check is not None:
check(payload)
destination.parent.mkdir(parents=True, exist_ok=True)
with locked():
write_bytes_atomic(str(destination), payload)
if index is not None:
# Platforms refresh in parallel: the index is read again under
# the lock, or the last writer erased what the others recorded.
recorded = _load_sources(index)
recorded[key] = url
write_text_atomic(
str(index), json.dumps(recorded, indent=2, sort_keys=True) + "\n"
)
return payload
def pinned_base(wanted: dict[str, str], scraped: dict | None) -> str:
"""The revision our transcription came from, when the YAML records it.
A scraper pins a stable tag (batocera-43.1, BizHawk 2.11.1) and writes
that URL into the platform YAML. Patching the branch tip instead would
correct a file our data never described.
"""
source = _raw_url(str((scraped or {}).get("source", "")))
tree = _GITHUB_TREE.match(source)
if tree:
# RetroDECK reads one manifest per component: the YAML records the
# tree at the commit read, and every file is taken at that commit.
return "https://raw.githubusercontent.com/{}/{}/{}/".format(*tree.groups())
for relative in wanted:
if source.endswith("/" + relative):
return source[: -len(relative)]
return ""
_GITHUB_TREE = re.compile(r"^https://github\.com/([^/]+)/([^/]+)/tree/([0-9a-f]{40})/?$")
def _raw_url(url: str) -> str:
"""A GitHub blob page names a revision but serves HTML, raw serves bytes."""
marker = "/blob/"
if url.startswith("https://github.com/") and marker in url:
owner_repo, _, path = url[len("https://github.com/") :].partition(marker)
return f"https://raw.githubusercontent.com/{owner_repo}/{path}"
return url
def wanted_sources(
exporter: BaseExporter, systems: dict, scraped: dict | None = None
) -> dict[str, str]:
"""Cache-relative name -> URL of every file the exporter patches."""
wanted = dict(exporter.native_sources())
components = getattr(exporter, "components", None)
component_url = getattr(exporter, "component_url", None)
if callable(components) and callable(component_url):
for component in components(systems):
wanted[f"{component}/component_manifest.json"] = component_url(
component
)
base = pinned_base(wanted, scraped)
if base:
wanted = {
relative: _at_revision(wanted[relative], base) or base + relative
for relative in wanted
}
source = str((scraped or {}).get("source", ""))
return {
relative: _tarball_at(url, source) or url for relative, url in wanted.items()
}
_REVISION = (
re.compile(r"^https://raw\.githubusercontent\.com/[^/]+/[^/]+/([^/]+)/"),
re.compile(r"^https://github\.com/[^/]+/[^/]+/(?:tree|blob)/([^/]+)"),
re.compile(r"^https://gitlab\.com/.+?/-/(?:raw|archive)/([^/]+)/"),
re.compile(r"^https://codeload\.github\.com/[^/]+/[^/]+/tar\.gz/([^/]+)$"),
)
def source_revision(source: str) -> str:
"""The revision a platform YAML's source: URL names, '' when none."""
for pattern in _REVISION:
match = pattern.match(source)
if match:
return match.group(1)
return ""
def unpinned(wanted: dict[str, str], scraped: dict | None) -> list[str]:
"""Every file the export would read off the revision the YAML records.
pinned_base() returned '' when the source named no revision or no
longer ended in the file, and the exporter's own branch URL was then
patched without a word: a file our transcription never described.
"""
source = str((scraped or {}).get("source", ""))
revision = source_revision(source)
if not revision:
return [f"the platform's source names no revision ({source or 'none'}): rescrape it"]
return [
f"{relative} would be read at {url}, not at {revision}: rescrape the platform"
for relative, url in wanted.items()
if f"/{revision}/" not in url and not url.endswith(f"/{revision}")
]
_CODELOAD = re.compile(r"^https://codeload\.github\.com/([^/]+)/([^/]+)/tar\.gz/")
def _tarball_at(url: str, source: str) -> str:
"""The recorded tarball when the original is a tarball of the same repository.
RetroPie's declarations are spread over every scriptmodule, so its scraper
reads the repository archive. The archive the YAML records is the one at
the commit it was read from, the exporter's own URL names the branch.
"""
wanted, recorded = _CODELOAD.match(url), _CODELOAD.match(source)
if wanted and recorded and wanted.group(1, 2) == recorded.group(1, 2):
return source
return ""
_RAW_GITHUB = re.compile(r"^https://raw\.githubusercontent\.com/([^/]+)/([^/]+)/([^/]+)/")
def _at_revision(url: str, base: str) -> str:
"""A file of the pinned repository, read at the pinned revision, empty
when the URL is not a raw GitHub URL of that repository.
ROCKNIX's checker sits in packages/rocknix/, the emulators it names in
packages/virtual/: no shared directory, one revision.
"""
pinned, other = _RAW_GITHUB.match(base), _RAW_GITHUB.match(url)
if pinned and other and pinned.group(1, 2) == other.group(1, 2):
return pinned.group(0) + url[other.end():]
return ""
def collect_originals(
exporter: BaseExporter,
systems: dict,
upstream_dir: Path,
allow_fetch: bool,
scraped: dict | None = None,
refresh: bool = False,
) -> tuple[dict[str, str], list[str]]:
"""Gather the platform's own files, from disk or from upstream.
With fetching on, an existing file still goes through fetch(): reading
it straight from disk skipped the recorded URL, so a file cached under
one pin kept being patched after the platform YAML moved to the next.
"""
wanted = wanted_sources(exporter, systems, scraped)
root = upstream_dir / exporter.platform_name()
index = upstream_dir / SOURCES_INDEX
originals: dict[str, str] = {}
missing: list[str] = []
unpack = getattr(exporter, "unpack", None)
for relative, url in wanted.items():
path = root / relative
reader: Callable[[bytes], dict[str, str]] | None = (
unpack if callable(unpack) and relative.endswith((".zip", ".tar.gz")) else None
)
check: Callable[[bytes], object] = (
functools.partial(_read_archive, reader) if reader is not None else _read_text
)
try:
if allow_fetch:
payload = fetch(url, path, index, refresh, check)
elif path.exists():
payload = path.read_bytes()
else:
missing.append(
f"{relative}: not in {root}; rerun with --fetch to download it"
)
continue
if reader is not None:
originals.update(_read_archive(reader, payload))
keep = getattr(exporter, "keep_archive", None)
if callable(keep):
keep(relative, payload)
else:
originals[relative] = _read_text(payload)
# One platform's unreadable file fails that platform: raised, it
# stopped --all before the platforms after it.
except (OSError, http.client.HTTPException, OriginalUnreadable) as exc:
missing.append(f"{relative}: {exc}")
return originals, missing
+5 -4
View File
@@ -129,11 +129,12 @@ class TheNativeIndexKeepsEveryPlatform(unittest.TestCase):
import io
import json
import export_native
from exporter import originals
from exporter.originals import SOURCES_INDEX, fetch
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as directory:
root = Path(directory)
index = root / export_native.SOURCES_INDEX
index = root / SOURCES_INDEX
class Response(io.BytesIO):
def __enter__(self):
@@ -147,9 +148,9 @@ class TheNativeIndexKeepsEveryPlatform(unittest.TestCase):
return Response(b"payload")
with mock.patch.object(
export_native.urllib.request, "urlopen", other_run_records_meanwhile
originals.urllib.request, "urlopen", other_run_records_meanwhile
):
export_native.fetch("https://a", root / "batocera" / "file", index)
fetch("https://a", root / "batocera" / "file", index)
recorded = json.loads(index.read_text())
self.assertEqual(recorded.get("retrobat/file.json"), "https://b")
self.assertEqual(recorded.get("batocera/file"), "https://a")
+1 -1
View File
@@ -19,7 +19,7 @@ from pathlib import Path
from resolve.localfile import resolve_local_file
from exporter import discover_exporters
from export_native import landed_changes
from exporter.landed import landed_changes
from resolve.reconcile import NativeFile, build_native_model
from exporter.batocera_exporter import md5_list_support
from scraper import rocknix_scraper
+2 -2
View File
@@ -31,7 +31,7 @@ class NativeCacheTests(unittest.TestCase):
self._tmp = tempfile.TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
self.cache = Path(self._tmp.name)
self.index = self.cache / cf.export_native.SOURCES_INDEX
self.index = self.cache / cf.SOURCES_INDEX
self.root = self.cache / "plat"
self.root.mkdir()
self.wanted = {"list.txt": "https://example.invalid/tag-2/list.txt"}
@@ -135,7 +135,7 @@ class PublishedExportTests(unittest.TestCase):
(output / f"{platform}.json").write_text("{}", encoding="utf-8")
return ok, [] if ok else ["the platform's own file is required"]
with mock.patch.object(cf.export_native, "export_platform", fake):
with mock.patch.object(cf, "export_platform", fake):
return cf.published_export_state(
"plat", object, Path("t"), Path("p"), Path("c"), self.published
)
+16 -16
View File
@@ -61,7 +61,7 @@ class RetroDeckWritesWhatItCounts(unittest.TestCase):
def test_an_appended_revision_is_not_counted_corrected(self):
# 64DD_IPL.bin declared twice (A, B), truth C: the render keeps both
# and appends C, and the summary said "1 hashes corrected".
from export_native import landed_changes
from exporter.landed import landed_changes
appended: set = set()
merged = RetroDeck._merge(
@@ -210,7 +210,7 @@ class RetroBatCountsOneAdditionPerPath(unittest.TestCase):
added: 78 additions announced for 75 items written."""
def test_an_addition_at_a_held_path_does_not_land(self):
from export_native import landed_changes
from exporter.landed import landed_changes
theirs = NativeFile("scph1001.bin", "scph1001.bin", "psx",
platform={"md5": A}, truth={"md5": A})
@@ -363,7 +363,7 @@ class EmuDeckWritesItsCorrections(unittest.TestCase):
self.assertIn(d, withheld[0])
def test_the_summary_reads_the_hook(self):
source = (Path(__file__).resolve().parents[1] / "scripts" / "export_native.py").read_text()
source = (Path(__file__).resolve().parents[1] / "scripts" / "exporter" / "native.py").read_text()
self.assertIn("withheld = exporter.withheld()", source)
@@ -397,7 +397,7 @@ class MisterCountsWhatItWrites(unittest.TestCase):
# The truth took the entry on a size contradiction and has no md5:
# the render kept MiSTer's hash, wrote the new size, and the summary
# announced the hash cleared.
from export_native import landed_changes
from exporter.landed import landed_changes
fe = NativeFile("boot.rom", "NES/boot.rom", "nes",
platform={"md5": A, "size": 100},
@@ -545,7 +545,7 @@ class RommKeepsItsOwnKeys(unittest.TestCase):
"""known_bios_files.json writes PLUTONIA.WAD's sha1 with a leading
space, which RomM compares as stored and never matches. The export
wrote it stripped and the summary named no change for it."""
from export_native import landed_changes
from exporter.landed import landed_changes
sha1 = "8" * 40
fe = NativeFile("PLUTONIA.WAD", "doom/PLUTONIA.WAD", "doom",
@@ -899,7 +899,7 @@ class SummaryCountsWhatTheTruthRewrites(unittest.TestCase):
)
def test_a_format_with_the_fields_counts_them(self):
from export_native import landed_changes
from exporter.landed import landed_changes
entry = self._entry()
changes = landed_changes(SystemDat(), {"neocd": NativeSystem("neocd", files=[entry])})
@@ -908,7 +908,7 @@ class SummaryCountsWhatTheTruthRewrites(unittest.TestCase):
self.assertEqual(changes.applied, ["neocd/neocdz.zip sha1"])
def test_a_format_without_them_does_not(self):
from export_native import landed_changes
from exporter.landed import landed_changes
from exporter.batocera_exporter import Exporter as Batocera
entry = self._entry()
@@ -927,14 +927,14 @@ class AStaleTruthIsRefused(unittest.TestCase):
import shutil
import tempfile
import export_native
from exporter.native import load_inputs, StaleTruth
root = Path(__file__).resolve().parents[1]
truth_dir = Path(tempfile.mkdtemp(dir=root / "tmp"))
self.addCleanup(shutil.rmtree, truth_dir, True)
(truth_dir / "retropie.yml").write_text("platform: retropie\nsystems: {}\n")
with self.assertRaises(export_native.StaleTruth):
export_native.load_inputs("retropie", truth_dir, str(root / "platforms"))
with self.assertRaises(StaleTruth):
load_inputs("retropie", truth_dir, str(root / "platforms"))
@@ -976,7 +976,7 @@ class TheSummaryCountsWhatTheFileCarries(unittest.TestCase):
)
def test_romm_drops_the_hashes_it_counts_cleared(self):
from export_native import landed_changes
from exporter.landed import landed_changes
from resolve.reconcile import Report
fe = self._contradicted()
@@ -994,7 +994,7 @@ class TheSummaryCountsWhatTheFileCarries(unittest.TestCase):
self.assertEqual(sorted(cleared), ["psx/scph5501.bin crc32", "psx/scph5501.bin sha1"])
def test_a_fill_no_record_holds_is_not_counted(self):
from export_native import landed_changes
from exporter.landed import landed_changes
fe = NativeFile(
"scph5501.bin", "scph5501.bin", "psx",
@@ -1016,7 +1016,7 @@ class TheSummaryCountsWhatTheFileCarries(unittest.TestCase):
self.assertNotIn("md5", merged[0])
def test_recalbox_counts_nothing_on_an_element_it_keeps(self):
from export_native import landed_changes
from exporter.landed import landed_changes
fe = NativeFile(
"scph5501.bin", "scph5501.bin", "psx",
@@ -1050,7 +1050,7 @@ class ARemovedSizeIsReported(unittest.TestCase):
took the entry over with no size: no counter named the removal."""
def test_the_removal_is_counted(self):
from export_native import landed_changes
from exporter.landed import landed_changes
from exporter.systemdat_exporter import Exporter as SystemDat
fe = NativeFile("neocdz.zip", "neocdz.zip", "SNK - NeoGeo CD",
@@ -1067,7 +1067,7 @@ class AnExtendedListIsReported(unittest.TestCase):
nothing. Only Batocera named the list it writes."""
def _records(self, exporter):
from export_native import landed_changes
from exporter.landed import landed_changes
platform = {"name": "f.bin", "md5": A, "core": "libretro/mesen"}
fe = NativeFile("f.bin", "f.bin", "s", platform=platform,
@@ -1085,7 +1085,7 @@ class AnExtendedListIsReported(unittest.TestCase):
)
def test_an_unchanged_value_reports_nothing(self):
from export_native import landed_changes
from exporter.landed import landed_changes
for exporter in (RetroDeck(), Recalbox()):
fe = NativeFile("f.bin", "f.bin", "s",
+1 -1
View File
@@ -17,7 +17,7 @@ import unittest
from pathlib import Path
from model.platforms import load_platform_config, _shared_yml_cache, _platform_config_cache
from export_native import load_inputs
from exporter.native import load_inputs
REPO_ROOT = Path(__file__).resolve().parent.parent
+18 -16
View File
@@ -14,7 +14,9 @@ import tempfile
import unittest
from pathlib import Path
import export_native
from exporter import native
from exporter.landed import landed_changes
from exporter.native import current_truth, export_platform, write_report
from siteexports import generate_exports_page, load_export_reports
ROOT = Path(__file__).resolve().parent.parent
@@ -38,7 +40,7 @@ class ExportReportIsWrittenAndRead(unittest.TestCase):
def test_report_round_trips_through_the_page_loader(self):
with tempfile.TemporaryDirectory(dir=ROOT / "tmp") as scratch:
report = _report("recalbox", ["es_bios.xml"])
export_native.write_report(Path(scratch) / "recalbox.json", report)
write_report(Path(scratch) / "recalbox.json", report)
(Path(scratch) / "recalbox").mkdir()
self.assertEqual(load_export_reports(scratch), [report])
@@ -47,11 +49,11 @@ class ExportReportIsWrittenAndRead(unittest.TestCase):
output directory was never made and the report crashed --all."""
with tempfile.TemporaryDirectory(dir=ROOT / "tmp") as scratch:
target = Path(scratch) / "fresh" / "retropie.json"
export_native.write_report(target, _report("retropie", []))
write_report(target, _report("retropie", []))
self.assertTrue(target.exists())
def test_export_keeps_every_change_not_the_printed_five(self):
source = (ROOT / "scripts" / "export_native.py").read_text(encoding="utf-8")
source = (ROOT / "scripts" / "exporter" / "native.py").read_text(encoding="utf-8")
body = source[source.index("def export_platform("):source.index("def write_report(")]
call = body[body.index("write_report("):]
for key, value in (
@@ -214,12 +216,12 @@ class TheRunReportStatesWhatTheFileCarries(unittest.TestCase):
]}}}
doubled = {"destination": "a.bin", "declarations": []}
with tempfile.TemporaryDirectory(dir=ROOT / "tmp") as scratch, \
mock.patch.object(export_native, "load_inputs",
mock.patch.object(native, "load_inputs",
return_value=(truth, scraped)), \
mock.patch.object(export_native, "unpinned", return_value=[]), \
mock.patch.object(export_native, "removal_candidates", return_value=[]), \
mock.patch.object(export_native, "doubled_in", return_value=[doubled]):
ok, messages = export_native.export_platform(
mock.patch.object(native, "unpinned", return_value=[]), \
mock.patch.object(native, "removal_candidates", return_value=[]), \
mock.patch.object(native, "doubled_in", return_value=[doubled]):
ok, messages = export_platform(
"plat", Plain, Path(scratch), Path(scratch) / "out",
str(ROOT / "platforms"), Path(scratch) / "cache", False,
)
@@ -323,7 +325,7 @@ class ReportedChangesAreTheDiff(unittest.TestCase):
if not original_path.is_file():
self.skipTest(f"no cached original for {platform}")
config = load_platform_config(platform, str(ROOT / "platforms"))
truth = export_native.current_truth(platform, config, str(ROOT / "platforms"))
truth = current_truth(platform, config, str(ROOT / "platforms"))
scraped = native_layer(config)
systems, report = build_native_model(truth, scraped)
exporter = discover_exporters()[platform]()
@@ -333,7 +335,7 @@ class ReportedChangesAreTheDiff(unittest.TestCase):
for p in (UPSTREAM_CACHE / platform).iterdir() if p.is_file()
}
produced = exporter.render(systems, report, originals, scraped)[filename]
changes = export_native.landed_changes(exporter, systems).records
changes = landed_changes(exporter, systems).records
return changes, original, produced, {"exporter": exporter, "systems": systems}
@staticmethod
@@ -400,7 +402,7 @@ class ReportedChangesAreTheDiff(unittest.TestCase):
if not archive.is_file():
self.skipTest("no cached original for retropie")
config = load_platform_config("retropie", str(ROOT / "platforms"))
truth = export_native.current_truth("retropie", config, str(ROOT / "platforms"))
truth = current_truth("retropie", config, str(ROOT / "platforms"))
scraped = native_layer(config)
systems, report = build_native_model(truth, scraped)
exporter = discover_exporters()["retropie"]()
@@ -412,7 +414,7 @@ class ReportedChangesAreTheDiff(unittest.TestCase):
before = exporter.modules({relative: originals[relative]})[relative][1]
after = exporter.modules({relative: text})[relative][1]
gained |= exporter._listed(after) - exporter._listed(before)
changes = export_native.landed_changes(exporter, systems).records
changes = landed_changes(exporter, systems).records
reported = {c["name"].lower() for c in changes if c["kind"] == "added"}
self.assertEqual(reported, gained)
self.assertEqual(
@@ -460,7 +462,7 @@ class ThePageShowsEachValueBeforeAndAfter(unittest.TestCase):
self.assertNotIn(glyph, self.page)
def test_the_report_carries_every_change(self):
source = (ROOT / "scripts" / "export_native.py").read_text(encoding="utf-8")
source = (ROOT / "scripts" / "exporter" / "native.py").read_text(encoding="utf-8")
body = source[source.index("def export_platform("):source.index("def write_report(")]
self.assertIn('"changes": changes.records,', body)
@@ -569,7 +571,7 @@ class RemovalCandidatesNeedAReadingNoCoreAnswers(unittest.TestCase):
self.assertNotIn("no entry the platform declares is removed", page)
def test_the_report_carries_the_list(self):
source = (ROOT / "scripts" / "export_native.py").read_text(encoding="utf-8")
source = (ROOT / "scripts" / "exporter" / "native.py").read_text(encoding="utf-8")
body = source[source.index("def export_platform("):source.index("def write_report(")]
self.assertIn('"removal_candidates": candidates,', body)
@@ -666,7 +668,7 @@ class ADestinationDeclaredTwiceIsNamed(unittest.TestCase):
self.assertEqual(self._doubled(), [])
def test_the_run_counts_it_and_the_report_carries_it(self):
source = (ROOT / "scripts" / "export_native.py").read_text(encoding="utf-8")
source = (ROOT / "scripts" / "exporter" / "native.py").read_text(encoding="utf-8")
body = source[source.index("def export_platform("):source.index("def write_report(")]
self.assertIn('"doubled": doubled,', body)
self.assertIn("declared twice for two files", body)
+33 -38
View File
@@ -35,14 +35,8 @@ from model.platforms import load_platform_config, native_layer
from model.safeparse import parse_untrusted_xml
from exporter import discover_exporters
from exporter.base_exporter import BaseExporter
from export_native import (
SOURCES_INDEX,
collect_originals,
fetch,
landed_changes,
pinned_base,
source_key,
)
from exporter.originals import SOURCES_INDEX, collect_originals, fetch, pinned_base, source_key
from exporter.landed import landed_changes
from resolve.reconcile import NativeFile, NativeSystem, Report, build_native_model
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -694,11 +688,11 @@ class ExporterRegistry(unittest.TestCase):
self.assertTrue(exporter.needs_original())
def test_an_export_without_its_original_writes_nothing(self):
import export_native
from exporter.native import export_platform
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
output = Path(tmp) / "out"
ok, messages = export_native.export_platform(
ok, messages = export_platform(
"retroarch", discover_exporters()["retroarch"],
REPO_ROOT / "dist" / "truth", output,
str(REPO_ROOT / "platforms"), Path(tmp) / "no-cache", False,
@@ -1013,27 +1007,27 @@ class PinnedRevision(unittest.TestCase):
"""Checked on five platforms by their base only: ROCKNIX's second
file, RetroDECK's manifests and RetroPie's tarball were never
looked at, and a URL that fell back to a branch passed."""
import export_native
from exporter.originals import unpinned, wanted_sources
for name, exporter_class in discover_exporters().items():
with self.subTest(platform=name):
config = native_layer(load_platform_config(name, str(REPO_ROOT / "platforms")))
systems, _ = build_native_model({}, config)
wanted = export_native.wanted_sources(exporter_class(), systems, config)
wanted = wanted_sources(exporter_class(), systems, config)
self.assertTrue(wanted)
self.assertEqual(export_native.unpinned(wanted, config), [])
self.assertEqual(unpinned(wanted, config), [])
def test_a_file_read_off_the_pinned_revision_is_named(self):
import export_native
from exporter.originals import unpinned
pinned = {"source": "https://raw.githubusercontent.com/o/r/v1.0/list.txt"}
self.assertEqual(export_native.unpinned(
self.assertEqual(unpinned(
{"list.txt": "https://raw.githubusercontent.com/o/r/v1.0/list.txt"}, pinned), [])
moved = export_native.unpinned(
moved = unpinned(
{"list.txt": "https://raw.githubusercontent.com/o/r/master/list.txt"}, pinned)
self.assertEqual(len(moved), 1)
self.assertIn("v1.0", moved[0])
bare = export_native.unpinned(
bare = unpinned(
{"x.json": "https://raw.githubusercontent.com/o/r/main/x.json"},
{"source": "https://github.com/RetroDECK/components"})
self.assertIn("names no revision", bare[0])
@@ -1090,14 +1084,14 @@ class CachedOriginal(unittest.TestCase):
"""A truncated index read as empty: the cached batocera-41 file was
served for a 43.1 URL, and the next download erased every other
platform's recorded URL."""
import export_native
from exporter.originals import SourcesIndexUnreadable
old = self._upstream("batocera-41.txt", "old")
target = self.cache / "plat" / "list.txt"
fetch(old, target, self.index)
self.index.write_text('{"plat/list.txt": "' + old + '",', encoding="utf-8")
new = self._upstream("batocera-43.txt", "new")
with self.assertRaises(export_native.SourcesIndexUnreadable) as caught:
with self.assertRaises(SourcesIndexUnreadable) as caught:
fetch(new, target, self.index)
self.assertIn("--refresh-cache", str(caught.exception))
self.assertTrue(self.index.read_text(encoding="utf-8").endswith(","))
@@ -1164,13 +1158,13 @@ class CachedOriginal(unittest.TestCase):
import fcntl
from unittest import mock
import export_native
from exporter import originals
url = self._upstream("v1.txt", "one")
target = self.cache / "plat" / "list.txt"
lock = self.index.with_name(f".{self.index.name}.lock")
held: list[bool] = []
write = export_native.write_bytes_atomic
write = originals.write_bytes_atomic
def probing(path, data):
with open(lock, "a") as handle:
@@ -1183,7 +1177,7 @@ class CachedOriginal(unittest.TestCase):
held.append(False)
write(path, data)
with mock.patch.object(export_native, "write_bytes_atomic", probing):
with mock.patch.object(originals, "write_bytes_atomic", probing):
fetch(url, target, self.index)
self.assertEqual(held, [True])
@@ -1221,12 +1215,12 @@ class CachedOriginal(unittest.TestCase):
import http.client
from unittest import mock
import export_native
from exporter import originals as exporter_originals
def cut(*_args, **_kwargs):
raise http.client.IncompleteRead(b"par")
with mock.patch.object(export_native, "fetch", cut):
with mock.patch.object(exporter_originals, "fetch", cut):
originals, missing = collect_originals(
_OneFileExporter("https://example.invalid/list.txt"), {}, self.cache, True
)
@@ -1557,7 +1551,7 @@ class AnExportLeavesNoStaleFile(unittest.TestCase):
holding the six files of the first run."""
def test_files_this_run_does_not_write_are_removed(self):
import export_native
from exporter.native import _remove_stale
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "retropie"
@@ -1568,13 +1562,13 @@ class AnExportLeavesNoStaleFile(unittest.TestCase):
gone_dir.mkdir()
for path in (kept, stale, gone_dir / "pcsx-rearmed.sh"):
path.write_text("old", encoding="utf-8")
export_native._remove_stale(root, {"scriptmodules/libretrocores/lr-mgba.sh"})
_remove_stale(root, {"scriptmodules/libretrocores/lr-mgba.sh"})
self.assertTrue(kept.exists())
self.assertFalse(stale.exists())
self.assertFalse(gone_dir.exists())
def test_the_export_clears_before_it_writes(self):
source = (REPO_ROOT / "scripts" / "export_native.py").read_text()
source = (REPO_ROOT / "scripts" / "exporter" / "native.py").read_text()
body = source[source.index("def export_platform("):]
self.assertLess(body.index("_remove_stale("), body.index("_write_produced("))
@@ -1587,11 +1581,11 @@ class AnExportIsWrittenAsItsBytes(unittest.TestCase):
def test_bytes_mode_and_atomicity(self):
import stat
import export_native
from exporter.native import _write_produced
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
root = Path(tmp)
export_native._write_produced(root, {
_write_produced(root, {
"FirmwareDatabase.cs": "a\r\nb\r\n",
"rocknix-systems": "#!/usr/bin/python\n",
}, {"rocknix-systems": 0o755})
@@ -1615,7 +1609,7 @@ class AnExportWithoutTruthIsRefused(unittest.TestCase):
uncorrected, said OK, and replaced the corrected export in exports/."""
def test_nothing_is_written_and_the_run_fails(self):
import export_native
from exporter.native import export_platform
exporter = discover_exporters()["batocera"]
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
@@ -1623,7 +1617,7 @@ class AnExportWithoutTruthIsRefused(unittest.TestCase):
published = output / "batocera" / "batocera-systems"
published.parent.mkdir(parents=True)
published.write_text("corrected", encoding="utf-8")
ok, messages = export_native.export_platform(
ok, messages = export_platform(
"batocera", exporter, Path(tmp) / "no-truth", output,
str(REPO_ROOT / "platforms"), Path(tmp) / "no-cache", False,
)
@@ -1642,7 +1636,8 @@ class AnInvalidExportIsNotWritten(unittest.TestCase):
def test_the_published_file_stays(self):
from unittest import mock
import export_native
from exporter import native as exporter_native
from exporter.native import export_platform
if not (UPSTREAM_CACHE / "romm").exists():
self.skipTest("upstream cache not populated")
@@ -1653,10 +1648,10 @@ class AnInvalidExportIsNotWritten(unittest.TestCase):
published = output / "romm" / "known_bios_files.json"
published.parent.mkdir(parents=True)
published.write_text("published", encoding="utf-8")
with mock.patch.object(export_native, "load_inputs",
with mock.patch.object(exporter_native, "load_inputs",
return_value=({"systems": {}}, config)), \
mock.patch.object(exporter, "validate", return_value=["bad entry"]):
ok, messages = export_native.export_platform(
ok, messages = export_platform(
"romm", exporter, Path(tmp), output,
str(REPO_ROOT / "platforms"), UPSTREAM_CACHE, False,
)
@@ -1852,7 +1847,7 @@ class RommSizeIsNeverNone(unittest.TestCase):
def test_an_entry_the_truth_takes_without_a_size_stays_whole(self):
"""RomM compares the size before any hash: the new md5 beside the
old size never verified, and the report said the size was removed."""
from export_native import landed_changes
from exporter.landed import landed_changes
exporter, systems, _, data = self._export(524288)
self.assertEqual(
@@ -2012,17 +2007,17 @@ class MisterDatabaseComesBackAsWritten(unittest.TestCase):
)
def test_bytes_are_written_untouched(self):
import export_native
from exporter.native import _write_produced
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
export_native._write_produced(Path(tmp), {"a.zip": b"PK\x03\x04\xff"}, {})
_write_produced(Path(tmp), {"a.zip": b"PK\x03\x04\xff"}, {})
self.assertEqual((Path(tmp) / "a.zip").read_bytes(), b"PK\x03\x04\xff")
def test_a_new_hash_without_a_size_leaves_the_entry_whole(self):
"""The Downloader checks each entry by size (fetch_file_worker.py:127):
the old size beside the new hash described no file, and the report
announced a size removal the database did not carry."""
from export_native import landed_changes
from exporter.landed import landed_changes
database = {"db_id": "bios_db", "files": {
"games/X/boot.rom": {"hash": "a" * 32, "size": 100, "url": "u"},
+1 -1
View File
@@ -34,7 +34,7 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = {
NOT_YET_PACKAGED = frozenset({
"archive_build", "auto_fetch", "autorun", "build_port", "campaign", "campaign_profiles",
"campaign_rules", "check_buildbot_system", "check_release_assets", "commit_rules", "core_probe",
"cross_reference", "dedup", "derivations", "export_native", "generate_event_schema",
"cross_reference", "dedup", "derivations", "generate_event_schema",
"generate_pack", "generate_readme", "generate_site", "manifestselect", "measurement_records",
"packextras", "packpaths", "packreadme", "packresolve", "packverify", "pin_installer",
"pr_checks", "provenance_report", "refresh_data_dirs",
+2 -2
View File
@@ -716,7 +716,7 @@ class UnreadableReleaseStopsTheScrape(unittest.TestCase):
self.assertRegex(recorded, f"(^|/){sha}(/|$)")
def test_the_export_reads_the_recorded_tarball(self):
from export_native import _tarball_at
from exporter.originals import _tarball_at
branch = "https://codeload.github.com/RetroPie/RetroPie-Setup/tar.gz/refs/heads/master"
pinned = "https://codeload.github.com/RetroPie/RetroPie-Setup/tar.gz/" + "a" * 40
@@ -725,7 +725,7 @@ class UnreadableReleaseStopsTheScrape(unittest.TestCase):
self.assertEqual(_tarball_at(branch, other), "")
def test_the_export_reads_every_component_at_the_recorded_tree(self):
from export_native import pinned_base
from exporter.originals import pinned_base
sha = "c" * 40
base = pinned_base(