refactor: split long functions of the tools

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 08:25:26 +01:00
1 parent ddcdd14cca
commit 54521380dc
4 files changed
+183 -168

No files matched your search

+21 -20
View File
@@ -65,6 +65,18 @@ def parse_sums(text: str) -> dict[str, str]:
return sums
def _registry_findings(packs: dict, released: set[str]) -> list[Finding]:
"""Each platform marked release_pack has a pack, and each pack serves one."""
served = {p for pack in packs.values() for p in pack.get("platforms", ())}
findings = [Finding("no-pack", platform, "release_pack: true, no pack in release.json")
for platform in sorted(released - served)]
findings.extend(Finding(
"not-released", pack_name,
"serves no platform marked release_pack in platforms/_registry.yml",
) for pack_name, pack in sorted(packs.items()) if not set(pack.get("platforms", ())) & released)
return findings
def compare_release(
record: dict,
sums: dict[str, str],
@@ -84,18 +96,7 @@ def compare_release(
if record.get("tag") != tag:
findings.append(Finding("tag", tag, f"release.json records {record.get('tag')}"))
if released is not None:
packs = record.get("packs", {})
served = {p for pack in packs.values() for p in pack.get("platforms", ())}
for platform in sorted(released - served):
findings.append(Finding(
"no-pack", platform, "release_pack: true, no pack in release.json"
))
for pack_name, pack in sorted(packs.items()):
if not set(pack.get("platforms", ())) & released:
findings.append(Finding(
"not-released", pack_name,
"serves no platform marked release_pack in platforms/_registry.yml",
))
findings += _registry_findings(record.get("packs", {}), released)
recorded = {
name: pack_name
@@ -105,14 +106,14 @@ def compare_release(
expected = set(recorded) | set(sums) | {SUMS} | set(local_files or ())
allowed = expected | {SIGNATURE}
for name in sorted(expected - set(assets)):
findings.append(Finding("missing", name, "not attached to the release"))
for name in sorted(set(assets) - allowed):
findings.append(Finding("extra", name, "attached but neither recorded nor listed"))
for name in sorted(set(recorded) - set(sums)):
findings.append(Finding("unlisted", name, f"absent from {SUMS}"))
for name in sorted(set(sums) - set(recorded)):
findings.append(Finding("unrecorded", name, f"listed in {SUMS}, absent from release.json"))
findings.extend(Finding("missing", name, "not attached to the release")
for name in sorted(expected - set(assets)))
findings.extend(Finding("extra", name, "attached but neither recorded nor listed")
for name in sorted(set(assets) - allowed))
findings.extend(Finding("unlisted", name, f"absent from {SUMS}")
for name in sorted(set(recorded) - set(sums)))
findings.extend(Finding("unrecorded", name, f"listed in {SUMS}, absent from release.json")
for name in sorted(set(sums) - set(recorded)))
wanted = {**sums, **(local_files or {})}
for name, digest in sorted(wanted.items()):
+46 -58
View File
@@ -252,55 +252,30 @@ def sha1_blob(data: bytes) -> str:
return hashlib.sha1(data).hexdigest()
def classify_file(filepath: str) -> tuple:
"""Determine (Manufacturer, Console) for a file path from a branch.
ARCADE_ROM_PREFIXES = (
"roms/fba/",
"roms/fbneo/",
"roms/mame/",
"roms/mame-libretro/",
"roms/neogeo/",
"roms/naomi/",
"roms/atomiswave/",
"roms/macintosh/",
)
Returns None if the file should be skipped.
"""
name = os.path.basename(filepath)
if name in SKIP_FILES:
return None
ext = os.path.splitext(name)[1].lower()
if ext in SKIP_EXTENSIONS:
def _strip_branch_prefix(filepath: str) -> str | None:
"""The path below its bios/ or arcade roms/ folder, None for any other
roms/ path."""
if filepath.startswith("roms/") and not filepath.startswith(ARCADE_ROM_PREFIXES):
return None
for prefix in ("bios/", "BIOS/", *ARCADE_ROM_PREFIXES):
if filepath.startswith(prefix):
return filepath[len(prefix) :]
return filepath
clean = filepath
for prefix in (
"bios/",
"BIOS/",
"roms/fba/",
"roms/fbneo/",
"roms/mame/",
"roms/mame-libretro/",
"roms/neogeo/",
"roms/naomi/",
"roms/atomiswave/",
"roms/macintosh/",
):
if clean.startswith(prefix):
clean = clean[len(prefix) :]
break
if filepath.startswith("roms/") and not any(
filepath.startswith(p)
for p in (
"roms/fba/",
"roms/fbneo/",
"roms/mame/",
"roms/mame-libretro/",
"roms/neogeo/",
"roms/naomi/",
"roms/atomiswave/",
"roms/macintosh/",
)
):
return None
for prefix, target in PATH_PREFIX_MAP.items():
if clean.startswith(prefix):
return target
def _classify_by_name(name: str, filepath: str) -> tuple[str, str] | None:
if name in BIOS_FILE_MAP:
return BIOS_FILE_MAP[name]
@@ -324,19 +299,33 @@ def classify_file(filepath: str) -> tuple:
if name.endswith(".zip") and filepath.startswith(("roms/", "BIOS/")):
return ("Arcade", "Arcade")
if "saves/" in filepath:
return None
if name.endswith(".chd"):
return None
if name.endswith((".img", ".lst", ".dat")) and "saves/" in filepath:
return None
return None
def classify_file(filepath: str) -> tuple[str, str] | None:
"""Determine (Manufacturer, Console) for a file path from a branch.
Returns None if the file should be skipped.
"""
name = os.path.basename(filepath)
if name in SKIP_FILES:
return None
ext = os.path.splitext(name)[1].lower()
if ext in SKIP_EXTENSIONS:
return None
clean = _strip_branch_prefix(filepath)
if clean is None:
return None
for prefix, target in PATH_PREFIX_MAP.items():
if clean.startswith(prefix):
return target
return _classify_by_name(name, filepath)
def get_subpath(filepath: str, manufacturer: str, console: str) -> str:
"""Get the sub-path within the console directory (for nested files like neocd/*)."""
name = os.path.basename(filepath)
@@ -373,7 +362,7 @@ def extract_from_branches(target: Path, dry_run: bool, existing_hashes: set) ->
continue
result = subprocess.run(
["git", "ls-tree", "-r", "--name-only", ref], capture_output=True, text=True
["git", "ls-tree", "-r", "--name-only", ref], capture_output=True, text=True, check=False
)
files = result.stdout.strip().split("\n")
print(f"\n Branch '{branch}': {len(files)} files")
@@ -551,9 +540,8 @@ def main() -> None:
".gitignore",
}
for d in sorted(source.iterdir()):
if d.name not in known and not d.name.startswith("."):
if d.is_dir():
print(f"\nWARNING: Unmapped directory: {d.name}")
if d.name not in known and not d.name.startswith(".") and d.is_dir():
print(f"\nWARNING: Unmapped directory: {d.name}")
print(f"\nTotal: {moved} files migrated, {len(existing_hashes)} unique hashes")
+95 -78
View File
@@ -56,6 +56,7 @@ import re
import subprocess
import sys
import time
from collections.abc import Callable
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from dataclasses import dataclass
from functools import lru_cache
@@ -220,7 +221,7 @@ def plan_jobs(
for finding in findings:
status = finding.get("status")
area = finding.get("area")
area = str(finding.get("area") or "")
subject = str(finding.get("subject") or "")
if status == "ERROR":
@@ -360,6 +361,96 @@ def _export_refresh(platform: str) -> list[str]:
return [sys.executable, "scripts/export_native.py", "--platform", platform]
def _platform_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
entry = registry.get(subject) or {}
scraper = entry.get("scraper")
if not scraper:
return None
return [
sys.executable,
"-m",
f"scripts.scraper.{scraper}_scraper",
"-o",
f"platforms/{subject}.yml",
*(str(a) for a in entry.get("rescrape_args") or ()),
]
def _target_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
# "<platform> cores" rows list buildbot names without a profile. No
# scraper fixes that, a human writes `cores:` or _overrides.yml.
if subject.endswith(" cores"):
return None
entry = registry.get(subject) or {}
module = entry.get("target_scraper")
if not module:
return None
return [
sys.executable,
"-m",
f"scripts.scraper.targets.{module}_scraper",
"-o",
f"platforms/targets/{subject}.yml",
]
def _data_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
if subject not in _data_dir_keys():
# "_data_dirs.yml" and "buildbot system" name the registry and
# what it does not track yet: a human adds the entry.
return None
return [
sys.executable,
"scripts/refresh_data_dirs.py",
"--key",
subject,
"--force",
]
def _catalog_command(subject: str, registry: dict[str, dict]) -> list[str] | None:
if subject == "mame recipes":
return [
sys.executable,
"-m",
"scripts.scraper.romset_dat_importer",
"--source",
"mame",
"--fetch",
]
if subject == "fbneo recipes":
return [
sys.executable,
"-m",
"scripts.scraper.romset_dat_importer",
"--source",
"fbneo",
"--fetch",
]
if subject in ("no-intro games", "redump games"):
# The game DATs download without a browser, unlike the BIOS ones.
return [
sys.executable,
"-m",
"scripts.scraper.game_dat_importer",
"--source",
subject.split()[0],
"--fetch",
"--refresh",
"--floor",
]
# redump / no-intro / tosec need manual DAT download.
return None
_AREA_COMMANDS: dict[str, Callable[[str, dict[str, dict]], list[str] | None]] = {
"platforms": _platform_command,
"targets": _target_command,
"data": _data_command,
"catalogs": _catalog_command,
}
def _command_for(
area: str, subject: str, registry: dict[str, dict]
) -> list[str] | None:
@@ -369,87 +460,13 @@ def _command_for(
# truth comes first and the original follows (Job.then).
return _truth_refresh(subject)
if area == "platforms":
entry = registry.get(subject) or {}
scraper = entry.get("scraper")
if not scraper:
return None
return [
sys.executable,
"-m",
f"scripts.scraper.{scraper}_scraper",
"-o",
f"platforms/{subject}.yml",
*(str(a) for a in entry.get("rescrape_args") or ()),
]
if area == "targets":
# "<platform> cores" rows list buildbot names without a profile. No
# scraper fixes that, a human writes `cores:` or _overrides.yml.
if subject.endswith(" cores"):
return None
entry = registry.get(subject) or {}
module = entry.get("target_scraper")
if not module:
return None
return [
sys.executable,
"-m",
f"scripts.scraper.targets.{module}_scraper",
"-o",
f"platforms/targets/{subject}.yml",
]
if area == "data":
if subject not in _data_dir_keys():
# "_data_dirs.yml" and "buildbot system" name the registry and
# what it does not track yet: a human adds the entry.
return None
return [
sys.executable,
"scripts/refresh_data_dirs.py",
"--key",
subject,
"--force",
]
if area == "ci" and subject == "install.py pin":
# The pin is the hash of the committed install.py, nothing to judge.
return [sys.executable, "scripts/pin_installer.py"]
if area == "catalogs":
if subject == "mame recipes":
return [
sys.executable,
"-m",
"scripts.scraper.romset_dat_importer",
"--source",
"mame",
"--fetch",
]
if subject == "fbneo recipes":
return [
sys.executable,
"-m",
"scripts.scraper.romset_dat_importer",
"--source",
"fbneo",
"--fetch",
]
if subject in ("no-intro games", "redump games"):
# The game DATs download without a browser, unlike the BIOS ones.
return [
sys.executable,
"-m",
"scripts.scraper.game_dat_importer",
"--source",
subject.split()[0],
"--fetch",
"--refresh",
"--floor",
]
# redump / no-intro / tosec need manual DAT download.
return None
builder = _AREA_COMMANDS.get(area)
if builder:
return builder(subject, registry)
# coreinfo, ci, profiles: never auto-refresh.
return None
+21 -12
View File
@@ -57,6 +57,23 @@ def _name_is(name: bytes, wanted: bytes, compared: int) -> bool:
return True
def _after_reset(data: bytes, reset_compare: int, missing_reset: str) -> int | None:
"""The offset past the RESET entry, or past the last entry searched when
the walk goes on without one, None where the code gives up."""
pos = 0
for _ in range(SEARCH_ENTRIES):
if pos + ENTRY_SIZE > len(data):
return None
name = data[pos:pos + NAME_SIZE]
pos += ENTRY_SIZE
if _name_is(name, b"RESET", reset_compare):
break
else:
if missing_reset == REJECT:
return None
return pos
def walk(data: bytes, spec: dict) -> Romdir | None:
"""The ROM directory walk one fork's LoadBiosVersion runs, or None.
@@ -84,18 +101,10 @@ def walk(data: bytes, spec: dict) -> Romdir | None:
missing_reset = spec.get("missing_reset", ENDS_WALK)
offset_mask = (1 << int(spec.get("offset_width", 64))) - 1
pos = 0
for _ in range(SEARCH_ENTRIES):
if pos + ENTRY_SIZE > size:
return None
name = data[pos:pos + NAME_SIZE]
pos += ENTRY_SIZE
if _name_is(name, b"RESET", reset_compare):
break
else:
if missing_reset == REJECT:
return None
found = _after_reset(data, reset_compare, missing_reset)
if found is None:
return None
pos = found
entry = data[pos - ENTRY_SIZE:pos]
offset = 0
romver: bytes | None = None