From 9cb1e613b0aba8d289d41b2920217d3246886568 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:30:20 +0100 Subject: [PATCH] refactor: move review files and report to resolve --- scripts/resolve/reviewfiles.py | 87 ++++++++++++++++++ scripts/resolve/reviewreport.py | 64 +++++++++++++ scripts/validate_pr.py | 153 ++------------------------------ tests/sources.py | 8 +- tests/test_layers.py | 7 +- tests/test_refresh_failures.py | 18 ++-- tests/test_validate_pr.py | 8 +- tests/test_validate_pr_flow.py | 4 +- 8 files changed, 179 insertions(+), 170 deletions(-) create mode 100644 scripts/resolve/reviewfiles.py create mode 100644 scripts/resolve/reviewreport.py diff --git a/scripts/resolve/reviewfiles.py b/scripts/resolve/reviewfiles.py new file mode 100644 index 000000000..5a0bc4343 --- /dev/null +++ b/scripts/resolve/reviewfiles.py @@ -0,0 +1,87 @@ +"""The files a review reads and writes: a branch's changed BIOS files, folders expanded, files placed.""" + +from __future__ import annotations + +import os +import shutil +import sys +from pathlib import Path +from typing import TYPE_CHECKING + +from core.gitclone import compare_base, git_lines + +if TYPE_CHECKING: + from resolve.review import ValidationResult + + +def get_changed_files() -> list[str]: + """BIOS files this checkout changes against the project's main line. + + Committed changes are read against the project's main line: the remote + that names the project (upstream/ first, then origin/), or + the project's main fetched when no remote does. Uncommitted and + untracked files count too, + since CONTRIBUTING has the file copied into bios/ before any commit. + A git that fails outright is an error, never "nothing changed". + """ + changed: list[str] = [] + base = compare_base() + committed = git_lines("diff", "--name-only", f"{base}...HEAD") if base else None + compared = committed is not None + changed.extend(committed or []) + staged = git_lines("diff", "--cached", "--name-only") + local = git_lines("diff", "--name-only") + untracked = git_lines("ls-files", "--others", "--exclude-standard", "--", "bios") + if staged is None and local is None and untracked is None: + raise RuntimeError("git cannot read this checkout") + for found in (staged, local, untracked): + changed.extend(found or []) + if not compared: + print( + "no upstream/ or origin/ main line to compare against, reading the " + "staged, modified and untracked files only", + file=sys.stderr, + ) + return [f for f in dict.fromkeys(changed) if f.startswith("bios/") and os.path.isfile(f)] + + +def expand_folders(paths: list[str]) -> list[str]: + """Each folder named replaced by the files under it, subfolders included. + + A card's BIOS folder was refused as "Not a regular file", and the + contributor had to list its files by hand. A link inside the folder + stays listed, so it is refused like a named one, and an empty folder + stays as itself to be reported. + """ + out: list[str] = [] + for path in paths: + if not os.path.isdir(path) or os.path.islink(path): + out.append(path) + continue + found = sorted( + str(f) for f in Path(path).rglob("*") if f.is_symlink() or f.is_file() + ) + out.extend(found or [path]) + return out + + +def place(results: list[ValidationResult]) -> list[str]: + """Copy each placeable file to its destination, never over a file. + + The report named the folder of each file and left 40 copies from a card + to be made by hand, each .variants/ name retyped. The source is copied, + not moved: it is often a card or another tree the contributor keeps. + """ + placed = [] + for r in results: + if not (r.passed and r.destination and not r.outcome): + continue + target = Path(r.destination) + if target.exists(): + print(f"not placed: {target} exists", file=sys.stderr) + continue + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(r.filepath, target) + placed.append(r.destination) + print(f"placed {r.filepath} at {r.destination}", file=sys.stderr) + return placed diff --git a/scripts/resolve/reviewreport.py b/scripts/resolve/reviewreport.py new file mode 100644 index 000000000..f12935f37 --- /dev/null +++ b/scripts/resolve/reviewreport.py @@ -0,0 +1,64 @@ +"""A review's results as JSON rows, a pull request comment, or terminal lines.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from resolve.review import ValidationResult + +# The terminal's word for each check status; any other status is "info". +MARKERS = {"PASS": "ok", "FAIL": "fail", "WARN": "warn"} + + +def json_rows(results: list[ValidationResult]) -> list[dict]: + """One JSON object per file reviewed.""" + return [ + { + "file": r.filepath, + "passed": r.passed, + # A file that failed, unread or refused, is not a new one. + "outcome": r.outcome or ("new" if r.passed else "failed"), + "destination": r.destination, + "sha1": r.sha1, + "md5": r.md5, + "size": r.size, + "checks": [{"status": s, "message": m} for s, m in r.checks], + } + for r in results + ] + + +def markdown_report(results: list[ValidationResult]) -> str: + """The report posted as a pull request comment.""" + lines = ["## BIOS Validation Report", ""] + held = sum(r.outcome == "held" for r in results) + unknown = sum(r.outcome == "unknown" for r in results) + review = ", ".join(part for part in ( + f"{held} already held" if held else "", + f"{unknown} not recognised" if unknown else "", + ) if part) + status = ("some checks failed" if not all(r.passed for r in results) + else f"no check failed, to review: {review}" if review + else "all checks passed") + lines.append(f"**Status**: {status}") + lines.append("") + + for r in results: + lines.append(r.to_markdown()) + lines.append("") + + return "\n".join(lines) + + +def text_lines(results: list[ValidationResult]) -> list[str]: + """The terminal report, each file headed by a blank line.""" + lines: list[str] = [] + for r in results: + lines.extend(("", f"[{r.status}] {r.filepath}")) + if r.sha1: + lines.append(f" SHA1: {r.sha1}") + lines.append(f" MD5: {r.md5}") + lines.append(f" Size: {r.size:,}") + lines.extend(f" [{MARKERS.get(s, 'info')}] {m}" for s, m in r.checks) + return lines diff --git a/scripts/validate_pr.py b/scripts/validate_pr.py index 8243ea63f..ac140aa19 100644 --- a/scripts/validate_pr.py +++ b/scripts/validate_pr.py @@ -20,77 +20,15 @@ from __future__ import annotations import argparse import json import os -import shutil import sys -from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) from model.database import load_optional_database from core.cli import add_repo_inputs, require_directory - -try: - import yaml -except ImportError: - yaml = None -from core.gitclone import compare_base, git_lines -from resolve.review import ( - ValidationResult, - load_platform_hashes, - load_profile_hashes, - validate_file, -) - - -def get_changed_files() -> list[str]: - """BIOS files this checkout changes against the project's main line. - - Committed changes are read against the project's main line: the remote - that names the project (upstream/ first, then origin/), or - the project's main fetched when no remote does. Uncommitted and - untracked files count too, - since CONTRIBUTING has the file copied into bios/ before any commit. - A git that fails outright is an error, never "nothing changed". - """ - changed: list[str] = [] - base = compare_base() - committed = git_lines("diff", "--name-only", f"{base}...HEAD") if base else None - compared = committed is not None - changed.extend(committed or []) - staged = git_lines("diff", "--cached", "--name-only") - local = git_lines("diff", "--name-only") - untracked = git_lines("ls-files", "--others", "--exclude-standard", "--", "bios") - if staged is None and local is None and untracked is None: - raise RuntimeError("git cannot read this checkout") - for found in (staged, local, untracked): - changed.extend(found or []) - if not compared: - print( - "no upstream/ or origin/ main line to compare against, reading the " - "staged, modified and untracked files only", - file=sys.stderr, - ) - return [f for f in dict.fromkeys(changed) if f.startswith("bios/") and os.path.isfile(f)] - - -def expand_folders(paths: list[str]) -> list[str]: - """Each folder named replaced by the files under it, subfolders included. - - A card's BIOS folder was refused as "Not a regular file", and the - contributor had to list its files by hand. A link inside the folder - stays listed, so it is refused like a named one, and an empty folder - stays as itself to be reported. - """ - out: list[str] = [] - for path in paths: - if not os.path.isdir(path) or os.path.islink(path): - out.append(path) - continue - found = sorted( - str(f) for f in Path(path).rglob("*") if f.is_symlink() or f.is_file() - ) - out.extend(found or [path]) - return out +from resolve.review import load_platform_hashes, load_profile_hashes, validate_file +from resolve.reviewfiles import expand_folders, get_changed_files, place +from resolve.reviewreport import json_rows, markdown_report, text_lines def _files_to_validate( @@ -115,28 +53,6 @@ def _files_to_validate( return files -def place(results: list[ValidationResult]) -> list[str]: - """Copy each placeable file to its destination, never over a file. - - The report named the folder of each file and left 40 copies from a card - to be made by hand, each .variants/ name retyped. The source is copied, - not moved: it is often a card or another tree the contributor keeps. - """ - placed = [] - for r in results: - if not (r.passed and r.destination and not r.outcome): - continue - target = Path(r.destination) - if target.exists(): - print(f"not placed: {target} exists", file=sys.stderr) - continue - target.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(r.filepath, target) - placed.append(r.destination) - print(f"placed {r.filepath} at {r.destination}", file=sys.stderr) - return placed - - def main() -> None: parser = argparse.ArgumentParser(allow_abbrev=False, description="Validate BIOS file contributions") parser.add_argument("files", nargs="*", help="Files to validate") @@ -180,71 +96,20 @@ def main() -> None: platform_hashes = load_platform_hashes(args.platforms_dir, db) profile_hashes = load_profile_hashes(args.emulators_dir, db) - results = [] - for f in files: - result = validate_file(f, db, platform_hashes, profile_hashes) - results.append(result) - - all_passed = all(r.passed for r in results) + results = [validate_file(f, db, platform_hashes, profile_hashes) for f in files] if args.json: - output = [ - { - "file": r.filepath, - "passed": r.passed, - # A file that failed, unread or refused, is not a new one. - "outcome": r.outcome or ("new" if r.passed else "failed"), - "destination": r.destination, - "sha1": r.sha1, - "md5": r.md5, - "size": r.size, - "checks": [{"status": s, "message": m} for s, m in r.checks], - } - for r in results - ] - print(json.dumps(output, indent=2)) + print(json.dumps(json_rows(results), indent=2)) elif args.markdown: - lines = ["## BIOS Validation Report", ""] - held = sum(r.outcome == "held" for r in results) - unknown = sum(r.outcome == "unknown" for r in results) - review = ", ".join(part for part in ( - f"{held} already held" if held else "", - f"{unknown} not recognised" if unknown else "", - ) if part) - status = ("some checks failed" if not all_passed - else f"no check failed, to review: {review}" if review - else "all checks passed") - lines.append(f"**Status**: {status}") - lines.append("") - - for r in results: - lines.append(r.to_markdown()) - lines.append("") - - print("\n".join(lines)) + print(markdown_report(results)) else: - for r in results: - print(f"\n[{r.status}] {r.filepath}") - if r.sha1: - print(f" SHA1: {r.sha1}") - print(f" MD5: {r.md5}") - print(f" Size: {r.size:,}") - for s, m in r.checks: - marker = ( - "ok" - if s == "PASS" - else "fail" - if s == "FAIL" - else "warn" - if s == "WARN" - else "info" - ) - print(f" [{marker}] {m}") + for line in text_lines(results): + print(line) if args.place: place(results) - if not all_passed: + if not all(r.passed for r in results): sys.exit(1) diff --git a/tests/sources.py b/tests/sources.py index ea6eda1d7..e190e914d 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -34,17 +34,11 @@ COMMANDS = { "slots.py": ( "packs/slots.py", "resolve/collisions.py", "packs/slotscan.py", "packs/slotreport.py", ), - "validate_pr.py": ("resolve/review.py", "core/gitclone.py"), + "validate_pr.py": ("resolve/review.py", "resolve/reviewfiles.py", "resolve/reviewreport.py", "core/gitclone.py"), "mame_ref_audit.py": ("profiling/mamerefs.py",), "fileless_audit.py": ("profiling/fileless.py",), "bundled_only.py": ("packs/bundledonly.py",), "export_native.py": ("exporter/runner.py", "exporter/native.py", "exporter/originals.py", "exporter/landed.py"), - "mame_ref_audit.py": ("profiling/mamerefs.py",), - "fileless_audit.py": ("profiling/fileless.py",), - "bundled_only.py": ("packs/bundledonly.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",), diff --git a/tests/test_layers.py b/tests/test_layers.py index 3cfb85c59..f8231ee1d 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -34,10 +34,9 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = { # A campaign commits its findings the way the unattended jobs commit, and a # standalone probe lists an emulator's releases through the one GitHub reader. "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"}), + # A pass that wrote profiles rebuilds the site's record of cited source paths, + # and the MAME ref audit reads machine declarations as the MAME scraper parses them. + "profiling": frozenset({"sitegen", "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 diff --git a/tests/test_refresh_failures.py b/tests/test_refresh_failures.py index 76d9deb89..85c497dd7 100644 --- a/tests/test_refresh_failures.py +++ b/tests/test_refresh_failures.py @@ -56,7 +56,7 @@ class GitThatCannotAnswer(unittest.TestCase): proc = subprocess.run( [sys.executable, "-c", ( f"import sys; sys.path.insert(0, {str(REPO_ROOT / 'scripts')!r}); " - "import validate_pr; print(validate_pr.get_changed_files())" + "from resolve import reviewfiles; print(reviewfiles.get_changed_files())" )], cwd=tmp, capture_output=True, text=True, timeout=60, check=False, ) @@ -86,14 +86,14 @@ class AProjectMainThatCannotBeFetched(unittest.TestCase): cli.run_cli(worktree.project_base) self.assertEqual(ended.exception.code, 1) self.assertEqual(err.getvalue(), "ERROR: no main\n") - import validate_pr + from resolve import reviewfiles with self.assertRaises(RuntimeError): - validate_pr.get_changed_files() + reviewfiles.get_changed_files() def test_both_tools_compare_against_the_same_line(self): - import validate_pr from core import gitclone from profiling import worktree + from resolve import reviewfiles diffs: list[tuple[str, ...]] = [] @@ -105,9 +105,9 @@ class AProjectMainThatCannotBeFetched(unittest.TestCase): with mock.patch.object(gitclone, "project_main_line", return_value=None), \ mock.patch.object(gitclone, "git_lines", side_effect=lines), \ - mock.patch.object(validate_pr, "git_lines", side_effect=lines): + mock.patch.object(reviewfiles, "git_lines", side_effect=lines): self.assertEqual(worktree.project_base(), "origin/main") - validate_pr.get_changed_files() + reviewfiles.get_changed_files() self.assertIn(("diff", "--name-only", "origin/main...HEAD"), diffs) @@ -128,7 +128,7 @@ class ChangesNotYetCommittedAreRead(unittest.TestCase): proc = subprocess.run( [sys.executable, "-c", ( f"import sys; sys.path.insert(0, {str(REPO_ROOT / 'scripts')!r}); " - "import validate_pr; print(validate_pr.get_changed_files())" + "from resolve import reviewfiles; print(reviewfiles.get_changed_files())" )], cwd=tmp, capture_output=True, text=True, timeout=60, check=False, ) @@ -151,9 +151,9 @@ class AForkPushedToItsOwnMain(unittest.TestCase): return subprocess.run( [sys.executable, "-c", ( f"import sys; sys.path.insert(0, {str(REPO_ROOT / 'scripts')!r}); " - "import validate_pr; from core import gitclone; " + "from resolve import reviewfiles; from core import gitclone; " f"gitclone.PROJECT_URLS = ({project!r},); " - "print(validate_pr.get_changed_files())" + "print(reviewfiles.get_changed_files())" )], cwd=clone, capture_output=True, text=True, timeout=60, check=False, ) diff --git a/tests/test_validate_pr.py b/tests/test_validate_pr.py index 9dd8d56b5..ade5317e0 100644 --- a/tests/test_validate_pr.py +++ b/tests/test_validate_pr.py @@ -16,7 +16,7 @@ import tempfile import unittest from pathlib import Path -import validate_pr +from resolve import reviewfiles from resolve import review REPO_ROOT = Path(__file__).resolve().parent.parent @@ -61,7 +61,7 @@ class FileShapeChecks(_Fixture): self._bios_file("card/bios/sub/b.bin") (self.tmp / "empty").mkdir() self.assertEqual( - validate_pr.expand_folders(["card", "empty", "loose.bin"]), + reviewfiles.expand_folders(["card", "empty", "loose.bin"]), [str(Path("card/bios/a.bin")), str(Path("card/bios/sub/b.bin")), "empty", "loose.bin"], ) result = review.validate_file("empty", None, EMPTY_HASHES) @@ -174,10 +174,10 @@ class AFileOnlyACoreReadsIsKnown(_Fixture): # Copied under the declared name, never over a file, and only once. card = self._bios_file("card/B.BIN", missing) named = review.validate_file(card, db, EMPTY_HASHES, known) - self.assertEqual(validate_pr.place([named]), [named.destination]) + self.assertEqual(reviewfiles.place([named]), [named.destination]) self.assertEqual((self.tmp / named.destination).read_bytes(), missing) self.assertTrue((self.tmp / card).is_file()) - self.assertEqual(validate_pr.place([named]), []) + self.assertEqual(reviewfiles.place([named]), []) unknown = review.validate_file(self._bios_file("card/x.bin"), db, EMPTY_HASHES, known) self.assertEqual((unknown.outcome, unknown.destination), ("unknown", "")) placed = review.validate_file( diff --git a/tests/test_validate_pr_flow.py b/tests/test_validate_pr_flow.py index dfc052ac8..e64bae9a5 100644 --- a/tests/test_validate_pr_flow.py +++ b/tests/test_validate_pr_flow.py @@ -20,7 +20,7 @@ from pathlib import Path import yaml -import validate_pr +from resolve import reviewfiles from core import gitclone from resolve import review @@ -209,7 +209,7 @@ class AnUnfetchedUpstreamIsFetched(unittest.TestCase): os.chdir(clone) try: with mock.patch.object(gitclone, "PROJECT_URLS", (str(project),)): - self.assertEqual(validate_pr.get_changed_files(), ["bios/new.bin"]) + self.assertEqual(reviewfiles.get_changed_files(), ["bios/new.bin"]) finally: os.chdir(cwd)