mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-22 17:47:48 -06:00
refactor: move the mame ref audit into profiling
This commit is contained in:
1 parent
1ff9ba1ba9
commit
d36a5d4bc5
5 files changed
+123
-113
No files matched your search
@@ -20,110 +20,13 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from core import upstream
|
||||
from core.cli import add_repo_inputs, require_directory
|
||||
from model.sources import source_yaml_file
|
||||
from scraper.clex import blank_comments
|
||||
from scraper.mame_parser import MACHINE_MACROS
|
||||
|
||||
# An optional role word names the repository the lines are in.
|
||||
DRIVER_REF = re.compile(r"^(?:(source|upstream) )?(src/[\w./+-]+):(\d+)$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Finding:
|
||||
set_name: str
|
||||
path: str
|
||||
cited: int
|
||||
declared: int
|
||||
role: str = ""
|
||||
|
||||
def ref(self, line: int) -> str:
|
||||
return f"{self.role} {self.path}:{line}" if self.role else f"{self.path}:{line}"
|
||||
|
||||
|
||||
def declares(line: str, set_name: str) -> bool:
|
||||
"""Whether this line is the machine declaration of that set."""
|
||||
clean = blank_comments(line)
|
||||
match = MACHINE_MACROS.search(clean)
|
||||
if not match:
|
||||
return False
|
||||
args = clean[match.end():].split(",")
|
||||
return len(args) > 1 and args[1].strip() == set_name
|
||||
|
||||
|
||||
def audit(
|
||||
name: str, emulators_dir: str, cache_dir: str, offline: bool
|
||||
) -> tuple[list[Finding], int, int]:
|
||||
"""Findings, plus counts of refs that agree and of unjudgeable ones."""
|
||||
document = source_yaml_file(os.path.join(emulators_dir, f"{name}.yml")) or {}
|
||||
trees = {
|
||||
role: (upstream.parse_repo(str(document.get(role) or "")),
|
||||
str(document.get(f"{role}_commit") or ""))
|
||||
for role in ("source", "upstream")
|
||||
}
|
||||
if trees["source"][0] is None or not trees["source"][1]:
|
||||
return [], 0, 0
|
||||
sources: dict[tuple[str, str], list[str] | None] = {}
|
||||
findings: list[Finding] = []
|
||||
agreed = unjudged = 0
|
||||
for entry in document.get("files", []) or []:
|
||||
entry_name = str(entry.get("name", ""))
|
||||
match = DRIVER_REF.match(str(entry.get("source_ref") or ""))
|
||||
if not (entry_name.endswith(".zip") and match):
|
||||
continue
|
||||
role, path, cited = match.group(1) or "", match.group(2), int(match.group(3))
|
||||
repo, pin = trees[role or "source"]
|
||||
if repo is None or not pin:
|
||||
unjudged += 1
|
||||
continue
|
||||
if (role, path) not in sources:
|
||||
sources[(role, path)] = upstream.fetch_file(repo, pin, path, cache_dir, offline)
|
||||
lines = sources[(role, path)]
|
||||
if lines is None:
|
||||
continue
|
||||
set_name = entry_name[:-4]
|
||||
if cited <= len(lines) and declares(lines[cited - 1], set_name):
|
||||
agreed += 1
|
||||
continue
|
||||
found = [i for i, line in enumerate(lines, 1) if declares(line, set_name)]
|
||||
if len(found) != 1:
|
||||
# None: a device set or a bare ROM_START. Several: the driver
|
||||
# declares the name twice and only a reader can choose.
|
||||
unjudged += 1
|
||||
continue
|
||||
findings.append(Finding(set_name, path, cited, found[0], role))
|
||||
return findings, agreed, unjudged
|
||||
|
||||
|
||||
def rewrite(name: str, emulators_dir: str, findings: list[Finding]) -> int:
|
||||
"""Point each ref at the declaration, one entry at a time."""
|
||||
path = os.path.join(emulators_dir, f"{name}.yml")
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
text = handle.read()
|
||||
written = 0
|
||||
for finding in findings:
|
||||
anchor = f"- name: {finding.set_name}.zip"
|
||||
old = f'source_ref: "{finding.ref(finding.cited)}"'
|
||||
start = text.find(anchor)
|
||||
if start < 0:
|
||||
continue
|
||||
at = text.find(old, start)
|
||||
if at < 0:
|
||||
continue
|
||||
new = f'source_ref: "{finding.ref(finding.declared)}"'
|
||||
text = text[:at] + new + text[at + len(old):]
|
||||
written += 1
|
||||
if written:
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
handle.write(text)
|
||||
return written
|
||||
from profiling.mamerefs import audit, rewrite
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
"""MAME romset refs checked against the line that declares their own set."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from core import upstream
|
||||
from model.sources import source_yaml_file
|
||||
from scraper.clex import blank_comments
|
||||
from scraper.mame_parser import MACHINE_MACROS
|
||||
|
||||
# An optional role word names the repository the lines are in.
|
||||
DRIVER_REF = re.compile(r"^(?:(source|upstream) )?(src/[\w./+-]+):(\d+)$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Finding:
|
||||
set_name: str
|
||||
path: str
|
||||
cited: int
|
||||
declared: int
|
||||
role: str = ""
|
||||
|
||||
def ref(self, line: int) -> str:
|
||||
return f"{self.role} {self.path}:{line}" if self.role else f"{self.path}:{line}"
|
||||
|
||||
|
||||
def declares(line: str, set_name: str) -> bool:
|
||||
"""Whether this line is the machine declaration of that set."""
|
||||
clean = blank_comments(line)
|
||||
match = MACHINE_MACROS.search(clean)
|
||||
if not match:
|
||||
return False
|
||||
args = clean[match.end():].split(",")
|
||||
return len(args) > 1 and args[1].strip() == set_name
|
||||
|
||||
|
||||
def audit(
|
||||
name: str, emulators_dir: str, cache_dir: str, offline: bool
|
||||
) -> tuple[list[Finding], int, int]:
|
||||
"""Findings, plus counts of refs that agree and of unjudgeable ones."""
|
||||
document = source_yaml_file(os.path.join(emulators_dir, f"{name}.yml")) or {}
|
||||
trees = {
|
||||
role: (upstream.parse_repo(str(document.get(role) or "")),
|
||||
str(document.get(f"{role}_commit") or ""))
|
||||
for role in ("source", "upstream")
|
||||
}
|
||||
if trees["source"][0] is None or not trees["source"][1]:
|
||||
return [], 0, 0
|
||||
sources: dict[tuple[str, str], list[str] | None] = {}
|
||||
findings: list[Finding] = []
|
||||
agreed = unjudged = 0
|
||||
for entry in document.get("files", []) or []:
|
||||
entry_name = str(entry.get("name", ""))
|
||||
match = DRIVER_REF.match(str(entry.get("source_ref") or ""))
|
||||
if not (entry_name.endswith(".zip") and match):
|
||||
continue
|
||||
role, path, cited = match.group(1) or "", match.group(2), int(match.group(3))
|
||||
repo, pin = trees[role or "source"]
|
||||
if repo is None or not pin:
|
||||
unjudged += 1
|
||||
continue
|
||||
if (role, path) not in sources:
|
||||
sources[(role, path)] = upstream.fetch_file(repo, pin, path, cache_dir, offline)
|
||||
lines = sources[(role, path)]
|
||||
if lines is None:
|
||||
continue
|
||||
set_name = entry_name[:-4]
|
||||
if cited <= len(lines) and declares(lines[cited - 1], set_name):
|
||||
agreed += 1
|
||||
continue
|
||||
found = [i for i, line in enumerate(lines, 1) if declares(line, set_name)]
|
||||
if len(found) != 1:
|
||||
# None: a device set or a bare ROM_START. Several: the driver
|
||||
# declares the name twice and only a reader can choose.
|
||||
unjudged += 1
|
||||
continue
|
||||
findings.append(Finding(set_name, path, cited, found[0], role))
|
||||
return findings, agreed, unjudged
|
||||
|
||||
|
||||
def rewrite(name: str, emulators_dir: str, findings: list[Finding]) -> int:
|
||||
"""Point each ref at the declaration, one entry at a time."""
|
||||
path = os.path.join(emulators_dir, f"{name}.yml")
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
text = handle.read()
|
||||
written = 0
|
||||
for finding in findings:
|
||||
anchor = f"- name: {finding.set_name}.zip"
|
||||
old = f'source_ref: "{finding.ref(finding.cited)}"'
|
||||
start = text.find(anchor)
|
||||
if start < 0:
|
||||
continue
|
||||
at = text.find(old, start)
|
||||
if at < 0:
|
||||
continue
|
||||
new = f'source_ref: "{finding.ref(finding.declared)}"'
|
||||
text = text[:at] + new + text[at + len(old):]
|
||||
written += 1
|
||||
if written:
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
handle.write(text)
|
||||
return written
|
||||
@@ -35,6 +35,7 @@ COMMANDS = {
|
||||
"packs/slots.py", "resolve/collisions.py", "packs/slotscan.py", "packs/slotreport.py",
|
||||
),
|
||||
"validate_pr.py": ("resolve/review.py", "core/gitclone.py"),
|
||||
"mame_ref_audit.py": ("profiling/mamerefs.py",),
|
||||
"refresh_data_dirs.py": ("packs/datadirs.py",),
|
||||
"split_pack.py": ("packs/parts.py",),
|
||||
"dedup.py": ("model/nodedup.py",),
|
||||
|
||||
@@ -36,6 +36,8 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = {
|
||||
"probes": frozenset({"unattended", "scraper"}),
|
||||
# A pass that wrote profiles rebuilds the site's record of cited source paths.
|
||||
"profiling": frozenset({"sitegen"}),
|
||||
# The MAME ref audit reads machine declarations as the MAME scraper parses them.
|
||||
"profiling": frozenset({"scraper"}),
|
||||
"romrecipes": frozenset(),
|
||||
# The site prints the recipe counts and the dump-catalog coverage report
|
||||
# those two packages compute, serves the handheld launchers and prints the
|
||||
|
||||
@@ -13,8 +13,8 @@ import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import mame_ref_audit
|
||||
from mame_ref_audit import declares
|
||||
from profiling import mamerefs
|
||||
from profiling.mamerefs import declares
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
@@ -64,18 +64,18 @@ class TestAudit(unittest.TestCase):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.dir = self.tmp.name
|
||||
Path(self.dir, "p.yml").write_text(PROFILE, encoding="utf-8")
|
||||
self._fetch = mame_ref_audit.upstream.fetch_file
|
||||
mame_ref_audit.upstream.fetch_file = (
|
||||
self._fetch = mamerefs.upstream.fetch_file
|
||||
mamerefs.upstream.fetch_file = (
|
||||
lambda repo, sha, path, cache, offline=False:
|
||||
DRIVER if path.endswith("xavix.cpp") else ["ROM_START( soundbox )"]
|
||||
)
|
||||
|
||||
def tearDown(self):
|
||||
mame_ref_audit.upstream.fetch_file = self._fetch
|
||||
mamerefs.upstream.fetch_file = self._fetch
|
||||
self.tmp.cleanup()
|
||||
|
||||
def test_a_ref_pointing_elsewhere_is_reported_with_its_declaration(self):
|
||||
findings, agreed, unjudged = mame_ref_audit.audit("p", self.dir, ".c", False)
|
||||
findings, agreed, unjudged = mamerefs.audit("p", self.dir, ".c", False)
|
||||
self.assertEqual(agreed, 1, "ekarag cites its own line")
|
||||
self.assertEqual([f.set_name for f in findings], ["ekara"])
|
||||
self.assertEqual(findings[0].cited, 99)
|
||||
@@ -83,12 +83,12 @@ class TestAudit(unittest.TestCase):
|
||||
|
||||
def test_a_set_no_machine_declares_is_left_unjudged(self):
|
||||
"""A device archive takes its DEFINE_DEVICE_TYPE shortname."""
|
||||
_, _, unjudged = mame_ref_audit.audit("p", self.dir, ".c", False)
|
||||
_, _, unjudged = mamerefs.audit("p", self.dir, ".c", False)
|
||||
self.assertEqual(unjudged, 1)
|
||||
|
||||
def test_rewrite_moves_only_the_entry_that_owns_the_ref(self):
|
||||
findings, _, _ = mame_ref_audit.audit("p", self.dir, ".c", False)
|
||||
self.assertEqual(mame_ref_audit.rewrite("p", self.dir, findings), 1)
|
||||
findings, _, _ = mamerefs.audit("p", self.dir, ".c", False)
|
||||
self.assertEqual(mamerefs.rewrite("p", self.dir, findings), 1)
|
||||
text = Path(self.dir, "p.yml").read_text(encoding="utf-8")
|
||||
self.assertIn('source_ref: "src/mame/tvgames/xavix.cpp:2"', text)
|
||||
self.assertIn(
|
||||
@@ -97,9 +97,9 @@ class TestAudit(unittest.TestCase):
|
||||
)
|
||||
|
||||
def test_a_corrected_profile_reports_nothing(self):
|
||||
findings, _, _ = mame_ref_audit.audit("p", self.dir, ".c", False)
|
||||
mame_ref_audit.rewrite("p", self.dir, findings)
|
||||
again, agreed, _ = mame_ref_audit.audit("p", self.dir, ".c", False)
|
||||
findings, _, _ = mamerefs.audit("p", self.dir, ".c", False)
|
||||
mamerefs.rewrite("p", self.dir, findings)
|
||||
again, agreed, _ = mamerefs.audit("p", self.dir, ".c", False)
|
||||
self.assertEqual(again, [])
|
||||
self.assertEqual(agreed, 2)
|
||||
|
||||
@@ -112,16 +112,16 @@ class TestCorpusStaysCorrect(unittest.TestCase):
|
||||
"""
|
||||
|
||||
def test_every_mame_family_ref_names_its_own_set(self):
|
||||
cache = ROOT / mame_ref_audit.upstream.CACHE_DIR
|
||||
cache = ROOT / mamerefs.upstream.CACHE_DIR
|
||||
if not cache.is_dir():
|
||||
self.skipTest("no upstream cache")
|
||||
for name in ("mame", "mamearcade", "mamemess", "groovymame"):
|
||||
with self.subTest(emulator=name):
|
||||
try:
|
||||
findings, agreed, _ = mame_ref_audit.audit(
|
||||
findings, agreed, _ = mamerefs.audit(
|
||||
name, str(ROOT / "emulators"), str(cache), True
|
||||
)
|
||||
except mame_ref_audit.upstream.NotCachedError as exc:
|
||||
except mamerefs.upstream.NotCachedError as exc:
|
||||
# A cache that holds some drivers and not others is as
|
||||
# cold as an empty one for this profile.
|
||||
self.skipTest(f"{name}: {exc}")
|
||||
|
||||
Reference in new issue
Block a user