mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-22 17:47:48 -06:00
refactor: compute an export apart from writing it
This commit is contained in:
1 parent
745ab63e63
commit
b018681f06
5 files changed
+102
-47
No files matched your search
+72
-14
@@ -7,6 +7,7 @@ from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
@@ -149,6 +150,28 @@ def doubled_in(scraped: dict | None, platforms_dir: str) -> list[dict]:
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExportResult:
|
||||
"""One platform's export as computed: its files and report, or why it stops."""
|
||||
|
||||
platform: str
|
||||
ok: bool
|
||||
messages: list[str]
|
||||
produced: dict[str, str | bytes] = field(default_factory=dict)
|
||||
modes: dict[str, int] = field(default_factory=dict)
|
||||
report: dict | None = None
|
||||
|
||||
def tree(self) -> dict[str, bytes]:
|
||||
"""The bytes write_export puts under the output directory, by path."""
|
||||
tree = {
|
||||
f"{self.platform}/{relative}": _as_bytes(content)
|
||||
for relative, content in self.produced.items()
|
||||
}
|
||||
if self.report is not None:
|
||||
tree[f"{self.platform}.json"] = report_text(self.report).encode("utf-8")
|
||||
return tree
|
||||
|
||||
|
||||
def export_platform(
|
||||
platform: str,
|
||||
exporter_class: type,
|
||||
@@ -159,21 +182,53 @@ def export_platform(
|
||||
allow_fetch: bool,
|
||||
) -> tuple[bool, list[str]]:
|
||||
"""Write one platform's corrected file. Returns (ok, messages)."""
|
||||
result = build_export(
|
||||
platform, exporter_class, truth_dir, platforms_dir, upstream_dir, allow_fetch,
|
||||
)
|
||||
write_export(result, output_dir)
|
||||
return result.ok, result.messages
|
||||
|
||||
|
||||
def write_export(result: ExportResult, output_dir: Path) -> None:
|
||||
"""Put a computed export under output_dir: its files, then its report.
|
||||
|
||||
A failed export writes nothing, so the published one stays.
|
||||
"""
|
||||
if not result.ok or result.report is None:
|
||||
return
|
||||
platform_dir = output_dir / result.platform
|
||||
_remove_stale(platform_dir, set(result.produced))
|
||||
_write_produced(platform_dir, result.produced, result.modes)
|
||||
write_report(output_dir / f"{result.platform}.json", result.report)
|
||||
|
||||
|
||||
def build_export(
|
||||
platform: str,
|
||||
exporter_class: type,
|
||||
truth_dir: Path,
|
||||
platforms_dir: str,
|
||||
upstream_dir: Path,
|
||||
allow_fetch: bool,
|
||||
) -> ExportResult:
|
||||
"""One platform's corrected file and its report, nothing written."""
|
||||
try:
|
||||
truth, scraped = load_inputs(platform, truth_dir, platforms_dir)
|
||||
except StaleTruth as exc:
|
||||
return False, [str(exc)]
|
||||
return ExportResult(platform, 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, [
|
||||
return ExportResult(platform, 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"]
|
||||
return ExportResult(
|
||||
platform, False,
|
||||
["nothing to write: neither the platform nor the truth has data"],
|
||||
)
|
||||
|
||||
profiles = _profiles()
|
||||
exporter: BaseExporter = exporter_class(profiles)
|
||||
@@ -181,11 +236,7 @@ def export_platform(
|
||||
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())
|
||||
return ExportResult(platform, False, stopped)
|
||||
|
||||
changes = landed_changes(exporter, systems)
|
||||
applied, filled = changes.applied, changes.filled
|
||||
@@ -209,7 +260,7 @@ def export_platform(
|
||||
doubled = doubled_in(scraped, platforms_dir)
|
||||
messages = _export_messages(summary, unwritten, candidates, doubled, withheld, changes)
|
||||
|
||||
write_report(output_dir / f"{platform}.json", {
|
||||
return ExportResult(platform, True, messages, produced, exporter.file_modes(), {
|
||||
"platform": platform,
|
||||
"originals": wanted_sources(exporter, systems, scraped),
|
||||
"files": sorted(produced),
|
||||
@@ -234,7 +285,6 @@ def export_platform(
|
||||
"doubled": doubled,
|
||||
"invalid": issues,
|
||||
})
|
||||
return True, messages
|
||||
|
||||
|
||||
def _produce(
|
||||
@@ -386,11 +436,19 @@ def _write_produced(
|
||||
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)
|
||||
write_bytes_atomic(str(path), _as_bytes(content))
|
||||
path.chmod(modes.get(relative, 0o644))
|
||||
|
||||
|
||||
def _as_bytes(content: str | bytes) -> bytes:
|
||||
return content if isinstance(content, bytes) else content.encode("utf-8")
|
||||
|
||||
|
||||
def report_text(report: dict) -> str:
|
||||
"""The JSON text a report is written as."""
|
||||
return json.dumps(report, indent=2) + "\n"
|
||||
|
||||
|
||||
def write_report(path: Path, report: dict) -> None:
|
||||
"""What one platform's export changed, for the page that publishes it.
|
||||
|
||||
@@ -400,4 +458,4 @@ def write_report(path: Path, report: dict) -> None:
|
||||
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")
|
||||
write_if_changed(str(path), report_text(report))
|
||||
@@ -5,12 +5,11 @@ from __future__ import annotations
|
||||
import contextlib
|
||||
import io
|
||||
import sys
|
||||
import tempfile
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
from exporter import discover_exporters
|
||||
from exporter.native import StaleTruth, export_platform, load_inputs
|
||||
from exporter.native import StaleTruth, build_export, load_inputs
|
||||
from exporter.originals import SOURCES_INDEX, SourcesIndexUnreadable, load_sources, source_key, wanted_sources
|
||||
from model.platforms import inheritance_chain
|
||||
from model.registry import list_registered_platforms
|
||||
@@ -73,18 +72,14 @@ def published_export_state(
|
||||
that moves a hash leaves the published file behind until someone runs
|
||||
the export again, and this is what says so.
|
||||
"""
|
||||
scratch_root = Path("tmp")
|
||||
scratch_root.mkdir(exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(dir=scratch_root) as scratch:
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
ok, messages = export_platform(
|
||||
platform, exporter_class, truth_dir, Path(scratch),
|
||||
str(platforms_dir), cache_dir, False,
|
||||
)
|
||||
if not ok:
|
||||
return f"the export fails: {messages[0] if messages else 'no message'}"
|
||||
if _export_tree(Path(scratch), platform) != _export_tree(published, platform):
|
||||
return f"{published.as_posix()}/{platform} is not what the export writes now"
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
result = build_export(
|
||||
platform, exporter_class, truth_dir, str(platforms_dir), cache_dir, False,
|
||||
)
|
||||
if not result.ok:
|
||||
return f"the export fails: {result.messages[0] if result.messages else 'no message'}"
|
||||
if result.tree() != _export_tree(published, platform):
|
||||
return f"{published.as_posix()}/{platform} is not what the export writes now"
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ from pathlib import Path
|
||||
|
||||
from core import upstream
|
||||
from core.cli import InputMissing
|
||||
from exporter.native import ExportResult
|
||||
from exporter.originals import SOURCES_INDEX
|
||||
from freshness.catalogs import (
|
||||
NO_INTRO_MIRROR,
|
||||
@@ -188,16 +189,15 @@ class PublishedExportTests(unittest.TestCase):
|
||||
self.published = Path(self._tmp.name)
|
||||
(self.published / "plat").mkdir()
|
||||
(self.published / "plat" / "list.txt").write_text("a", encoding="utf-8")
|
||||
(self.published / "plat.json").write_text("{}", encoding="utf-8")
|
||||
(self.published / "plat.json").write_text("{}\n", encoding="utf-8")
|
||||
|
||||
def _state(self, written: str, ok: bool = True) -> str:
|
||||
def fake(platform, _cls, _truth, output, *_rest):
|
||||
(output / platform).mkdir(parents=True)
|
||||
(output / platform / "list.txt").write_text(written, encoding="utf-8")
|
||||
(output / f"{platform}.json").write_text("{}", encoding="utf-8")
|
||||
return ok, [] if ok else ["the platform's own file is required"]
|
||||
def fake(platform, *_rest):
|
||||
if not ok:
|
||||
return ExportResult(platform, False, ["the platform's own file is required"])
|
||||
return ExportResult(platform, True, [], {"list.txt": written}, report={})
|
||||
|
||||
with mock.patch("freshness.native.export_platform", fake):
|
||||
with mock.patch("freshness.native.build_export", fake):
|
||||
return published_export_state(
|
||||
"plat", object, Path("t"), Path("p"), Path("c"), self.published
|
||||
)
|
||||
|
||||
+13
-11
@@ -17,7 +17,7 @@ from pathlib import Path
|
||||
|
||||
from exporter import native
|
||||
from exporter.landed import landed_changes
|
||||
from exporter.native import current_truth, export_platform, write_report
|
||||
from exporter.native import build_export, current_truth, write_report
|
||||
from model.profiles import load_emulator_profiles
|
||||
from sitegen.exports import generate_exports_page, load_export_reports
|
||||
|
||||
@@ -56,8 +56,8 @@ class ExportReportIsWrittenAndRead(unittest.TestCase):
|
||||
|
||||
def test_export_keeps_every_change_not_the_printed_five(self):
|
||||
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("):]
|
||||
body = source[source.index("def build_export("):source.index("def write_report(")]
|
||||
call = body[body.index("ExportResult(platform, True"):]
|
||||
for key, value in (
|
||||
("hashes_updated", "applied"), ("hashes_filled", "filled"),
|
||||
("sizes_updated", "resized"), ("sizes_removed", "unsized"),
|
||||
@@ -223,12 +223,14 @@ class TheRunReportStatesWhatTheFileCarries(unittest.TestCase):
|
||||
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,
|
||||
result = build_export(
|
||||
"plat", Plain, Path(scratch), str(ROOT / "platforms"),
|
||||
Path(scratch) / "cache", False,
|
||||
)
|
||||
self.assertTrue(ok, messages)
|
||||
report = json.loads((Path(scratch) / "out" / "plat.json").read_text())
|
||||
messages = result.messages
|
||||
self.assertTrue(result.ok, messages)
|
||||
report = result.report
|
||||
assert report is not None
|
||||
self.assertEqual(report["doubled"], [doubled])
|
||||
self.assertIn(
|
||||
"1 destination declared twice for two files, listed in the report", messages
|
||||
@@ -469,7 +471,7 @@ class ThePageShowsEachValueBeforeAndAfter(unittest.TestCase):
|
||||
|
||||
def test_the_report_carries_every_change(self):
|
||||
source = (ROOT / "scripts" / "exporter" / "native.py").read_text(encoding="utf-8")
|
||||
body = source[source.index("def export_platform("):source.index("def write_report(")]
|
||||
body = source[source.index("def build_export("):source.index("def write_report(")]
|
||||
self.assertIn('"changes": changes.records,', body)
|
||||
|
||||
|
||||
@@ -578,7 +580,7 @@ class RemovalCandidatesNeedAReadingNoCoreAnswers(unittest.TestCase):
|
||||
|
||||
def test_the_report_carries_the_list(self):
|
||||
source = (ROOT / "scripts" / "exporter" / "native.py").read_text(encoding="utf-8")
|
||||
body = source[source.index("def export_platform("):source.index("def write_report(")]
|
||||
body = source[source.index("def build_export("):source.index("def write_report(")]
|
||||
self.assertIn('"removal_candidates": candidates,', body)
|
||||
|
||||
|
||||
@@ -675,7 +677,7 @@ class ADestinationDeclaredTwiceIsNamed(unittest.TestCase):
|
||||
|
||||
def test_the_run_counts_it_and_the_report_carries_it(self):
|
||||
source = (ROOT / "scripts" / "exporter" / "native.py").read_text(encoding="utf-8")
|
||||
body = source[source.index("def export_platform("):source.index("def write_report(")]
|
||||
body = source[source.index("def build_export("):source.index("def write_report(")]
|
||||
self.assertIn('"doubled": doubled,', body)
|
||||
self.assertIn("declared twice for two files", body)
|
||||
|
||||
|
||||
@@ -1618,7 +1618,7 @@ class AnExportLeavesNoStaleFile(unittest.TestCase):
|
||||
|
||||
def test_the_export_clears_before_it_writes(self):
|
||||
source = (REPO_ROOT / "scripts" / "exporter" / "native.py").read_text()
|
||||
body = source[source.index("def export_platform("):]
|
||||
body = source[source.index("def write_export("):]
|
||||
self.assertLess(body.index("_remove_stale("), body.index("_write_produced("))
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user