From f896893b6e0e060853a6e4fee5f39e86a407df5f Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:19:45 +0100 Subject: [PATCH] fix: bios migration says each error once biosmigrate printed its progress and each failed copy, then migrate.py printed the same failures again. The library now says its steps through the caller's callback and returns the failures, and the command prints each once. --- scripts/devtools/biosmigrate.py | 28 ++++++------ scripts/migrate.py | 4 +- tests/test_bios_migrate.py | 76 +++++++++++++++++++++++++++++++++ wiki/testing-guide.md | 1 + 4 files changed, 95 insertions(+), 14 deletions(-) create mode 100644 tests/test_bios_migrate.py diff --git a/scripts/devtools/biosmigrate.py b/scripts/devtools/biosmigrate.py index a023385ee..cd7960978 100644 --- a/scripts/devtools/biosmigrate.py +++ b/scripts/devtools/biosmigrate.py @@ -4,6 +4,7 @@ from __future__ import annotations import hashlib import shutil +from collections.abc import Callable from pathlib import Path from acquire.fetch import LEGACY_BRANCHES, legacy_branch_blob, legacy_branch_files @@ -66,16 +67,18 @@ def sha1_blob(data: bytes) -> str: return hashlib.sha1(data).hexdigest() -def extract_from_branches(target: Path, dry_run: bool, existing_hashes: set[str]) -> int: - """Extract BIOS files from all branches into the target structure.""" +def extract_from_branches( + target: Path, dry_run: bool, existing_hashes: set[str], say: Callable[[str], None], +) -> int: + """Extract BIOS files from all branches into the target structure, each step said.""" extracted = 0 for branch in LEGACY_BRANCHES: files = legacy_branch_files(branch) if files is None: - print(f" Branch {branch} not found, skipping") + say(f" Branch {branch} not found, skipping") continue - print(f"\n Branch '{branch}': {len(files)} files") + say(f"\n Branch '{branch}': {len(files)} files") branch_extracted = 0 for filepath in files: @@ -109,20 +112,22 @@ def extract_from_branches(target: Path, dry_run: bool, existing_hashes: set[str] if not dry_run: dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(content) - print(f" {label}: {filepath} -> {dest.relative_to(target)}") + say(f" {label}: {filepath} -> {dest.relative_to(target)}") existing_hashes.add(file_hash) branch_extracted += 1 - print(f" -> {branch_extracted} new files from {branch}") + say(f" -> {branch_extracted} new files from {branch}") extracted += branch_extracted return extracted def migrate_local( - source: Path, target: Path, dry_run: bool, + source: Path, target: Path, dry_run: bool, say: Callable[[str], None], ) -> tuple[int, int, list[tuple[Path, str]], set[str]]: - """Migrate files from local flat structure to Manufacturer/Console hierarchy.""" + """Migrate files from local flat structure to Manufacturer/Console hierarchy, + each step said and each failed copy returned. + """ moved = 0 skipped = 0 errors: list[tuple[Path, str]] = [] @@ -139,7 +144,7 @@ def migrate_local( if not files: continue - print(f" {old_dir_name}/ -> bios/{manufacturer}/{console}/") + say(f" {old_dir_name}/ -> bios/{manufacturer}/{console}/") if not dry_run: new_path.mkdir(parents=True, exist_ok=True) @@ -147,18 +152,17 @@ def migrate_local( for f in files: dest = new_path / f.name if dest.exists(): - print(f" SKIP (exists): {f.name}") + say(f" SKIP (exists): {f.name}") skipped += 1 continue if dry_run: - print(f" COPY: {f.name}") + say(f" COPY: {f.name}") else: try: shutil.copy2(str(f), str(dest)) except OSError as e: errors.append((f, str(e))) - print(f" ERROR: {f.name}: {e}") continue existing_hashes.add(file_digest(f)) diff --git a/scripts/migrate.py b/scripts/migrate.py index cf7327ef2..f9b9730ff 100644 --- a/scripts/migrate.py +++ b/scripts/migrate.py @@ -56,14 +56,14 @@ def main() -> None: print("=== Phase 1: Local files (libretro branch) ===") moved, skipped, errors, existing_hashes = migrate_local( - source, target, args.dry_run + source, target, args.dry_run, print ) action = "Would copy" if args.dry_run else "Copied" print(f"\n{action} {moved} files, skipped {skipped}") if args.include_branches: print("\n=== Phase 2: Extracting from other branches ===") - branch_count = extract_from_branches(target, args.dry_run, existing_hashes) + branch_count = extract_from_branches(target, args.dry_run, existing_hashes, print) print(f"\n{action} {branch_count} additional files from branches") moved += branch_count diff --git a/tests/test_bios_migrate.py b/tests/test_bios_migrate.py new file mode 100644 index 000000000..019136f4d --- /dev/null +++ b/tests/test_bios_migrate.py @@ -0,0 +1,76 @@ +"""The flat-tree migration says its plan through the caller, and a failed copy reaches the command once.""" + +from __future__ import annotations + +import tests + +import contextlib +import io +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from devtools import biosmigrate + +REPO_ROOT = Path(__file__).resolve().parents[1] + + +class MigrationSaysItsPlan(unittest.TestCase): + def setUp(self) -> None: + self.dir = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.dir, True) + self.source = self.dir / "src" + self.target = self.dir / "bios" + flat = self.source / "Sony - PlayStation" + flat.mkdir(parents=True) + (flat / "scph5501.bin").write_bytes(b"a" * 16) + (flat / "scph1001.bin").write_bytes(b"b" * 16) + held = self.target / "Sony" / "PlayStation" + held.mkdir(parents=True) + (held / "scph1001.bin").write_bytes(b"b" * 16) + + def test_a_dry_run_returns_its_plan_without_printing(self): + said: list[str] = [] + out = io.StringIO() + with contextlib.redirect_stdout(out): + moved, skipped, errors, hashes = biosmigrate.migrate_local( + self.source, self.target, True, said.append) + self.assertEqual(out.getvalue(), "") + self.assertEqual((moved, skipped, errors, len(hashes)), (1, 1, [], 1)) + self.assertEqual(said, [" Sony - PlayStation/ -> bios/Sony/PlayStation/", + " SKIP (exists): scph1001.bin", + " COPY: scph5501.bin"]) + self.assertFalse((self.target / "Sony" / "PlayStation" / "scph5501.bin").exists()) + + def test_a_failed_copy_is_returned_not_said(self): + said: list[str] = [] + with mock.patch.object(biosmigrate.shutil, "copy2", side_effect=OSError("denied")): + moved, _, errors, _ = biosmigrate.migrate_local( + self.source, self.target, False, said.append) + self.assertEqual(moved, 0) + self.assertEqual([(f.name, e) for f, e in errors], [("scph5501.bin", "denied")]) + self.assertFalse(any("denied" in line for line in said)) + + def test_the_command_names_each_error_once(self): + flat = self.source / "Sony - PlayStation" + (self.target / "Sony" / "PlayStation").chmod(0o500) + self.addCleanup((self.target / "Sony" / "PlayStation").chmod, 0o700) + if os.access(self.target / "Sony" / "PlayStation", os.W_OK): + self.skipTest("running as a user every folder lets write") + proc = subprocess.run( + [sys.executable, str(REPO_ROOT / "scripts" / "migrate.py"), + "--source", str(self.source), "--target", str(self.target)], + capture_output=True, text=True, check=False, cwd=self.dir, + ) + self.assertEqual(proc.returncode, 1, proc.stderr) + self.assertEqual(proc.stdout.count("scph5501.bin: "), 1, proc.stdout) + self.assertIn(f" {flat / 'scph5501.bin'}: ", proc.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/wiki/testing-guide.md b/wiki/testing-guide.md index fc1395b84..b2f02ad07 100644 --- a/wiki/testing-guide.md +++ b/wiki/testing-guide.md @@ -78,6 +78,7 @@ Every module in `tests/`, by the area it guards. | Standalone emulators | the release asset EmuDeck's rule picks, the AppImage offset, the Xvfb framebuffer reader, the settings written and the oracle the verdicts use, with no emulator run | `test_standalone_probe` | | Pack probe | the cores a platform runs for a system, staging grown to a fixed point, runs mapped to pack and manifest entries, the line and its schema, the probe lock per run, that no page shows its lines. One class builds a real pack narrowed to PlayStation and lays it out both ways, from the archive and with `install.py --dest`, and skips without the collection | `test_pack_probe` | | Automation runner, disk cleanup, asset sync and bit-flip repair | fake jobs, git repositories with a bare origin and session worktrees, a committed file with one bit flipped, canned CI runs in place of `gh` | `test_autorun` | +| Flat-tree migration | a flat system folder copied into a temporary tree, its plan said through the caller, and a failed copy named once by `migrate.py` | `test_bios_migrate` | | Truth and native export | synthetic + cached originals | `test_export_counts`, `test_export_native_layer`, `test_export_report`, `test_exporters`, `test_truth_data_dir_readers`, `test_truth_diff`, `test_truth_layout` | | Scrapers, upstream and provenance | inline sources, synthetic | `test_auto_fetch_lookup`, `test_batocera_md5_list`, `test_find_embedded`, `test_report_excerpt`, `test_check_freshness`, `test_cited_lines`, `test_contributing_text`, `test_coverage_cache`, `test_data_dir_refs`, `test_dataclass_defaults`, `test_dedup`, `test_doc_pages`, `test_doc_surfaces`, `test_elec_scrapers`, `test_fbneo_parser`, `test_find_pinned_revision`, `test_hash_merge`, `test_launchers`, `test_launchers_amberelec`, `test_launchers_emudeck`, `test_launchers_emuelec`, `test_launchers_knulli`, `test_launchers_recalbox`, `test_launchers_retrobat`, `test_launchers_retrodeck`, `test_launchers_retropie`, `test_launchers_rocknix`, `test_lines`, `test_listxml`, `test_mame_devices`, `test_mame_parser`, `test_mame_ref_audit`, `test_optional_dependencies`, `test_pin_build`, `test_profile_sync`, `test_prose_style`, `test_provenance`, `test_refresh_data_dirs`, `test_refresh_failures`, `test_refresh_stale`, `test_retired_files`, `test_retrodeck_component_md5`, `test_retrodeck_scraper_errors`, `test_romset_recipes`, `test_schema_semantic_gate`, `test_scraper_contract`, `test_scraper_dropped`, `test_scraper_network`, `test_site_agents`, `test_site_arcade_boards`, `test_site_availability`, `test_site_bootstrap`, `test_site_built_gate`, `test_site_components`, `test_site_console_folders`, `test_site_content_data`, `test_site_copy`, `test_site_cores`, `test_site_css`, `test_site_demo`, `test_site_density_cards`, `test_site_emulator_page`, `test_site_emulators`, `test_site_entry`, `test_site_entry_tables`, `test_site_exports`, `test_site_freshness`, `test_site_funnel`, `test_site_images`, `test_site_inputs`, `test_site_insights`, `test_site_integration`, `test_site_nav`, `test_site_page_text`, `test_site_picker`, `test_site_platform_density`, `test_site_platform_hashes`, `test_site_privacy`, `test_site_pronouns`, `test_site_reference`, `test_site_render`, `test_site_search`, `test_site_steps`, `test_site_system_links`, `test_site_system_names`, `test_site_system_sections`, `test_site_systems`, `test_site_validation`, `test_site_wanted`, `test_site_weight`, `test_site_wiki`, `test_site_write`, `test_source_ref_targets`, `test_text`, `test_upstream`, `test_upstream_index`, `test_validate_pr`, `test_validate_pr_flow`, `test_validate_pr_hashes`, `test_version_basis`, `test_workflow_paths` | | Games on the card | small DATs, listxml and setup sources, a fake fetcher, fixture install lists, and the committed data against its schemas | `test_arcade_parents`, `test_game_catalogs`, `test_game_headers`, `test_game_regions`, `test_games_index`, `test_romfolders_card`, `test_romfolders_es` |