refactor: move the fileless audit into profiling

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 14:59:03 +01:00
1 parent d36a5d4bc5
commit d6a0b33521
4 files changed
+111 -98

No files matched your search

+2 -81
View File
@@ -20,86 +20,13 @@ from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from core import upstream
from core.cli import add_repo_inputs, require_directory
from profiling.citations import collect_citations
from profiling.repos import select_views
from model.sourceref import ref_role, split_source_ref
from model.profiles import ProfileSelectionError, load_emulator_profiles, resolve_profile_name
from model.sources import source_yaml_file
# Ways a program asks for somewhere to read from.
SIGNALS = (
"RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY",
"GET_SYSTEM_DIRECTORY",
"system_directory",
"get_system_directory",
)
SOURCE_SUFFIX = (".c", ".cpp", ".cc", ".cxx", ".h", ".hpp", ".m", ".mm")
def cited_paths(document: dict) -> list[str]:
"""Source paths the profile points at, in document order, deduplicated."""
seen: list[str] = []
for citation in collect_citations(document):
for part in split_source_ref(citation.ref):
path = ref_role(part.path)[1]
if path.endswith(SOURCE_SUFFIX) and path not in seen:
seen.append(path)
return seen
def audit(
name: str, emulators_dir: str, cache_dir: str, offline: bool
) -> list[tuple[str, str]] | None:
"""Signals found in the sources a fileless profile cites."""
document = source_yaml_file(os.path.join(emulators_dir, f"{name}.yml")) or {}
if document.get("files"):
return None
if document.get("type") == "alias":
# The same binary under another name: its files are its target's.
return None
if str(document.get("exclusion_note") or "").strip():
# Someone read this one and wrote down why nothing is declared. The
# check exists to find the profiles nobody has answered yet, and an
# answer that goes stale shows up as a drifting ref instead.
return None
if document.get("data_directories"):
# The load is declared, as a directory rather than a file. dinothawr
# reads system_dir/dinothawr/ and says so there. That is coverage, not
# an assertion waiting to age.
return None
views = select_views(document, cache_dir, offline)
if not views:
return []
hits: list[tuple[str, str]] = []
for path in cited_paths(document)[:40]:
for view in views:
lines = upstream.fetch_file(view.repo, view.pin, path, cache_dir, offline)
if lines is None:
continue
for signal in SIGNALS:
if any(signal in line for line in lines):
hits.append((path, signal))
break
break
return hits
def _settled_before_reading(document: dict) -> bool:
"""A profile answered without its sources: files, an exclusion note, or
a declared data directory (see audit)."""
return bool(
document.get("files")
or document.get("type") == "alias"
or str(document.get("exclusion_note") or "").strip()
or document.get("data_directories")
)
from profiling.fileless import audit, unanswered_profiles
def main() -> None:
@@ -132,13 +59,7 @@ def main() -> None:
except ProfileSelectionError as exc:
raise SystemExit(f"ERROR: {exc}") from None
if args.all:
known = sorted(path.stem for path in Path(args.emulators_dir).glob("*.yml"))
names = []
for name in known:
if not _settled_before_reading(
source_yaml_file(Path(args.emulators_dir) / f"{name}.yml") or {}
):
names.append(name)
names = unanswered_profiles(args.emulators_dir)
flagged = unreachable = 0
for name in names:
+89
View File
@@ -0,0 +1,89 @@
"""Profiles that declare no files, read for a source that asks for a directory."""
from __future__ import annotations
import os
from pathlib import Path
from core import upstream
from model.sourceref import ref_role, split_source_ref
from model.sources import source_yaml_file
from profiling.citations import collect_citations
from profiling.repos import select_views
# Ways a program asks for somewhere to read from.
SIGNALS = (
"RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY",
"GET_SYSTEM_DIRECTORY",
"system_directory",
"get_system_directory",
)
SOURCE_SUFFIX = (".c", ".cpp", ".cc", ".cxx", ".h", ".hpp", ".m", ".mm")
def cited_paths(document: dict) -> list[str]:
"""Source paths the profile points at, in document order, deduplicated."""
seen: list[str] = []
for citation in collect_citations(document):
for part in split_source_ref(citation.ref):
path = ref_role(part.path)[1]
if path.endswith(SOURCE_SUFFIX) and path not in seen:
seen.append(path)
return seen
def audit(
name: str, emulators_dir: str, cache_dir: str, offline: bool
) -> list[tuple[str, str]] | None:
"""Signals found in the sources a fileless profile cites."""
document = source_yaml_file(os.path.join(emulators_dir, f"{name}.yml")) or {}
if document.get("files"):
return None
if document.get("type") == "alias":
# The same binary under another name: its files are its target's.
return None
if str(document.get("exclusion_note") or "").strip():
# Someone read this one and wrote down why nothing is declared. The
# check exists to find the profiles nobody has answered yet, and an
# answer that goes stale shows up as a drifting ref instead.
return None
if document.get("data_directories"):
# The load is declared, as a directory rather than a file. dinothawr
# reads system_dir/dinothawr/ and says so there. That is coverage, not
# an assertion waiting to age.
return None
views = select_views(document, cache_dir, offline)
if not views:
return []
hits: list[tuple[str, str]] = []
for path in cited_paths(document)[:40]:
for view in views:
lines = upstream.fetch_file(view.repo, view.pin, path, cache_dir, offline)
if lines is None:
continue
for signal in SIGNALS:
if any(signal in line for line in lines):
hits.append((path, signal))
break
break
return hits
def settled_before_reading(document: dict) -> bool:
"""A profile answered without its sources: files, an exclusion note, or
a declared data directory (see audit)."""
return bool(
document.get("files")
or document.get("type") == "alias"
or str(document.get("exclusion_note") or "").strip()
or document.get("data_directories")
)
def unanswered_profiles(emulators_dir: str) -> list[str]:
"""Every profile under emulators_dir that is not settled before reading."""
known = sorted(path.stem for path in Path(emulators_dir).glob("*.yml"))
return [
name for name in known
if not settled_before_reading(source_yaml_file(Path(emulators_dir) / f"{name}.yml") or {})
]
+2
View File
@@ -36,6 +36,8 @@ COMMANDS = {
),
"validate_pr.py": ("resolve/review.py", "core/gitclone.py"),
"mame_ref_audit.py": ("profiling/mamerefs.py",),
"fileless_audit.py": ("profiling/fileless.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",),
+18 -17
View File
@@ -17,6 +17,7 @@ from pathlib import Path
from unittest import mock
import fileless_audit
from profiling import fileless
ROOT = Path(__file__).resolve().parent.parent
@@ -40,29 +41,29 @@ class TestFilelessAudit(unittest.TestCase):
self.tmp = tempfile.TemporaryDirectory()
self.dir = self.tmp.name
self._orig = (
fileless_audit.select_views,
fileless_audit.upstream.fetch_file,
fileless_audit.collect_citations,
fileless.select_views,
fileless.upstream.fetch_file,
fileless.collect_citations,
)
class View:
repo = "repo"
pin = "pinsha"
fileless_audit.select_views = lambda doc, cache, offline: [View()]
fileless_audit.collect_citations = lambda doc: [
fileless.select_views = lambda doc, cache, offline: [View()]
fileless.collect_citations = lambda doc: [
type("C", (), {"ref": "libretro.c:10"})()
]
self.source = ASKS
fileless_audit.upstream.fetch_file = (
fileless.upstream.fetch_file = (
lambda repo, sha, path, cache, offline=False: self.source
)
def tearDown(self):
(
fileless_audit.select_views,
fileless_audit.upstream.fetch_file,
fileless_audit.collect_citations,
fileless.select_views,
fileless.upstream.fetch_file,
fileless.collect_citations,
) = self._orig
self.tmp.cleanup()
@@ -70,7 +71,7 @@ class TestFilelessAudit(unittest.TestCase):
Path(self.dir, "p.yml").write_text(body, encoding="utf-8")
def _run(self):
return fileless_audit.audit("p", self.dir, ".c", False)
return fileless.audit("p", self.dir, ".c", False)
def test_a_fileless_profile_whose_source_asks_is_flagged(self):
self._write(BASE)
@@ -128,7 +129,7 @@ class TestCommandLine(unittest.TestCase):
return audit(name)
return []
with mock.patch.object(sys, "argv", ["fileless_audit.py", *argv,
with mock.patch.object(sys, "argv", ["fileless.py", *argv,
"--emulators-dir", self.tmp.name]), \
mock.patch.object(fileless_audit, "audit", side_effect=fake), \
mock.patch("sys.stderr"), mock.patch("sys.stdout"), self.assertRaises(SystemExit) as caught:
@@ -146,7 +147,7 @@ class TestCommandLine(unittest.TestCase):
def test_an_unreachable_source_fails_the_run(self):
def unreachable(name):
raise fileless_audit.upstream.UpstreamError("HTTP 403")
raise fileless.upstream.UpstreamError("HTTP 403")
code, _ = self._main("open", audit=unreachable)
self.assertEqual(code, 1)
@@ -164,31 +165,31 @@ class TestCorpusIsAnswered(unittest.TestCase):
self.skipTest("no upstream cache")
from model.safeparse import yaml_load
fetch = fileless_audit.upstream.fetch_file
fetch = fileless.upstream.fetch_file
read = []
def counted(*args, **kwargs):
# A cold path is unread here, not absent.
try:
lines = fetch(*args, **kwargs)
except fileless_audit.upstream.NotCachedError:
except fileless.upstream.NotCachedError:
return None
if lines is not None:
read.append(args[2])
return lines
flagged = []
with mock.patch.object(fileless_audit.upstream, "fetch_file", counted):
with mock.patch.object(fileless.upstream, "fetch_file", counted):
for path in sorted((ROOT / "emulators").glob("*.yml")):
with path.open(encoding="utf-8") as handle:
document = yaml_load(handle) or {}
if document.get("files"):
continue
try:
hits = fileless_audit.audit(
hits = fileless.audit(
path.stem, str(ROOT / "emulators"), str(ROOT / ".cache"), True
)
except fileless_audit.upstream.NotCachedError:
except fileless.upstream.NotCachedError:
# A cold branch tip is unread too, not a branch gone.
continue
if hits: