mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-22 17:47:48 -06:00
refactor: move three dev commands into devtools
This commit is contained in:
1 parent
2486c06932
commit
cadca657a3
12 files changed
+834
-757
No files matched your search
@@ -1 +1 @@
|
||||
"""The repository's own rules: commit messages and the checks CI runs on a pull request."""
|
||||
"""The repository's own tooling: commit rules, pull request checks, the test runner, disk cleanup, the bios/ migration."""
|
||||
@@ -0,0 +1,271 @@
|
||||
"""The Manufacturer/Console folder a legacy BIOS path belongs to, read from its name and folder."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
BIOS_FILE_MAP = {
|
||||
"panafz": ("3DO Company", "3DO"),
|
||||
"goldstar.bin": ("3DO Company", "3DO"),
|
||||
"sanyotry.bin": ("3DO Company", "3DO"),
|
||||
"3do_arcade_saot.bin": ("3DO Company", "3DO"),
|
||||
"3dobios.zip": ("3DO Company", "3DO"),
|
||||
"cpc464.rom": ("Amstrad", "CPC"),
|
||||
"cpc664.rom": ("Amstrad", "CPC"),
|
||||
"cpc6128.rom": ("Amstrad", "CPC"),
|
||||
"neogeo.zip": ("SNK", "Neo Geo"),
|
||||
"pgm.zip": ("Arcade", "Arcade"),
|
||||
"skns.zip": ("Arcade", "Arcade"),
|
||||
"bubsys.zip": ("Arcade", "Arcade"),
|
||||
"cchip.zip": ("Arcade", "Arcade"),
|
||||
"decocass.zip": ("Arcade", "Arcade"),
|
||||
"isgsm.zip": ("Arcade", "Arcade"),
|
||||
"midssio.zip": ("Arcade", "Arcade"),
|
||||
"nmk004.zip": ("Arcade", "Arcade"),
|
||||
"ym2608.zip": ("Arcade", "Arcade"),
|
||||
"qsound.zip": ("Arcade", "Arcade"),
|
||||
"ATARIBAS.ROM": ("Atari", "400-800"),
|
||||
"ATARIOSA.ROM": ("Atari", "400-800"),
|
||||
"ATARIOSB.ROM": ("Atari", "400-800"),
|
||||
"ATARIXL.ROM": ("Atari", "400-800"),
|
||||
"BB01R4_OS.ROM": ("Atari", "400-800"),
|
||||
"XEGAME.ROM": ("Atari", "400-800"),
|
||||
"5200.rom": ("Atari", "5200"),
|
||||
"7800 BIOS (U).rom": ("Atari", "7800"),
|
||||
"7800 BIOS (E).rom": ("Atari", "7800"),
|
||||
"lynxboot.img": ("Atari", "Lynx"),
|
||||
"tos.img": ("Atari", "ST"),
|
||||
"colecovision.rom": ("Coleco", "ColecoVision"),
|
||||
"coleco.rom": ("Coleco", "ColecoVision"),
|
||||
"kick33180.A500": ("Commodore", "Amiga"),
|
||||
"kick34005.A500": ("Commodore", "Amiga"),
|
||||
"kick34005.CDTV": ("Commodore", "Amiga"),
|
||||
"kick37175.A500": ("Commodore", "Amiga"),
|
||||
"kick37350.A600": ("Commodore", "Amiga"),
|
||||
"kick39106.A1200": ("Commodore", "Amiga"),
|
||||
"kick39106.A4000": ("Commodore", "Amiga"),
|
||||
"kick40060.CD32": ("Commodore", "Amiga"),
|
||||
"kick40060.CD32.ext": ("Commodore", "Amiga"),
|
||||
"kick40063.A600": ("Commodore", "Amiga"),
|
||||
"kick40068.A1200": ("Commodore", "Amiga"),
|
||||
"kick40068.A4000": ("Commodore", "Amiga"),
|
||||
"sl31253.bin": ("Fairchild", "Channel F"),
|
||||
"sl31254.bin": ("Fairchild", "Channel F"),
|
||||
"sl90025.bin": ("Fairchild", "Channel F"),
|
||||
"prboom.wad": ("Id Software", "Doom"),
|
||||
"ecwolf.pk3": ("Id Software", "Wolfenstein 3D"),
|
||||
"MacII.ROM": ("Apple", "Macintosh II"),
|
||||
"MacIIx.ROM": ("Apple", "Macintosh II"),
|
||||
"vMac.ROM": ("Apple", "Macintosh II"),
|
||||
"o2rom.bin": ("Magnavox", "Odyssey2"),
|
||||
"g7400.bin": ("Philips", "Videopac+"),
|
||||
"jopac.bin": ("Philips", "Videopac+"),
|
||||
"exec.bin": ("Mattel", "Intellivision"),
|
||||
"grom.bin": ("Mattel", "Intellivision"),
|
||||
"ECS.bin": ("Mattel", "Intellivision"),
|
||||
"IVOICE.BIN": ("Mattel", "Intellivision"),
|
||||
"MSX.ROM": ("Microsoft", "MSX"),
|
||||
"MSX2.ROM": ("Microsoft", "MSX"),
|
||||
"MSX2EXT.ROM": ("Microsoft", "MSX"),
|
||||
"MSX2P.ROM": ("Microsoft", "MSX"),
|
||||
"MSX2PEXT.ROM": ("Microsoft", "MSX"),
|
||||
"syscard1.pce": ("NEC", "PC Engine"),
|
||||
"syscard2.pce": ("NEC", "PC Engine"),
|
||||
"syscard2u.pce": ("NEC", "PC Engine"),
|
||||
"syscard3.pce": ("NEC", "PC Engine"),
|
||||
"syscard3u.pce": ("NEC", "PC Engine"),
|
||||
"gexpress.pce": ("NEC", "PC Engine"),
|
||||
"pcfx.rom": ("NEC", "PC-FX"),
|
||||
"disksys.rom": ("Nintendo", "Famicom Disk System"),
|
||||
"gba_bios.bin": ("Nintendo", "Game Boy Advance"),
|
||||
"gb_bios.bin": ("Nintendo", "Game Boy"),
|
||||
"dmg_boot.bin": ("Nintendo", "Game Boy"),
|
||||
"gbc_bios.bin": ("Nintendo", "Game Boy Color"),
|
||||
"BS-X.bin": ("Nintendo", "Satellaview"),
|
||||
"sgb_bios.bin": ("Nintendo", "Super Game Boy"),
|
||||
"sgb_boot.bin": ("Nintendo", "Super Game Boy"),
|
||||
"sgb2_boot.bin": ("Nintendo", "Super Game Boy"),
|
||||
"SGB1.sfc": ("Nintendo", "Super Game Boy"),
|
||||
"SGB2.sfc": ("Nintendo", "Super Game Boy"),
|
||||
"bios7.bin": ("Nintendo", "Nintendo DS"),
|
||||
"bios9.bin": ("Nintendo", "Nintendo DS"),
|
||||
"firmware.bin": ("Nintendo", "Nintendo DS"),
|
||||
"biosnds7.bin": ("Nintendo", "Nintendo DS"),
|
||||
"biosnds9.bin": ("Nintendo", "Nintendo DS"),
|
||||
"dsfirmware.bin": ("Nintendo", "Nintendo DS"),
|
||||
"biosdsi7.bin": ("Nintendo", "Nintendo DS"),
|
||||
"biosdsi9.bin": ("Nintendo", "Nintendo DS"),
|
||||
"dsifirmware.bin": ("Nintendo", "Nintendo DS"),
|
||||
"bios.min": ("Nintendo", "Pokemon Mini"),
|
||||
"64DD_IPL.bin": ("Nintendo", "Nintendo 64DD"),
|
||||
"dc_boot.bin": ("Sega", "Dreamcast"),
|
||||
"dc_flash.bin": ("Sega", "Dreamcast"),
|
||||
"bios.gg": ("Sega", "Game Gear"),
|
||||
"bios_E.sms": ("Sega", "Master System"),
|
||||
"bios_J.sms": ("Sega", "Master System"),
|
||||
"bios_U.sms": ("Sega", "Master System"),
|
||||
"bios_CD_E.bin": ("Sega", "Mega CD"),
|
||||
"bios_CD_J.bin": ("Sega", "Mega CD"),
|
||||
"bios_CD_U.bin": ("Sega", "Mega CD"),
|
||||
"bios_MD.bin": ("Sega", "Mega Drive"),
|
||||
"mpr-17933.bin": ("Sega", "Saturn"),
|
||||
"mpr-18811-mx.ic1": ("Sega", "Saturn"),
|
||||
"mpr-19367-mx.ic1": ("Sega", "Saturn"),
|
||||
"saturn_bios.bin": ("Sega", "Saturn"),
|
||||
"sega_101.bin": ("Sega", "Saturn"),
|
||||
"stvbios.zip": ("Sega", "Saturn"),
|
||||
"scph1001.bin": ("Sony", "PlayStation"),
|
||||
"SCPH1001.BIN": ("Sony", "PlayStation"),
|
||||
"scph5500.bin": ("Sony", "PlayStation"),
|
||||
"scph5501.bin": ("Sony", "PlayStation"),
|
||||
"scph5502.bin": ("Sony", "PlayStation"),
|
||||
"scph7001.bin": ("Sony", "PlayStation"),
|
||||
"scph101.bin": ("Sony", "PlayStation"),
|
||||
"ps1_rom.bin": ("Sony", "PlayStation"),
|
||||
"psxonpsp660.bin": ("Sony", "PlayStation"),
|
||||
"PSXONPSP660.BIN": ("Sony", "PlayStation Portable"),
|
||||
"scummvm.zip": ("ScummVM", "ScummVM"),
|
||||
"MT32_CONTROL.ROM": ("Roland", "MT-32"),
|
||||
"MT32_PCM.ROM": ("Roland", "MT-32"),
|
||||
}
|
||||
|
||||
PATH_PREFIX_MAP = {
|
||||
"neocd/": ("SNK", "Neo Geo CD"),
|
||||
"dc/": ("Sega", "Dreamcast"),
|
||||
"np2kai/": ("NEC", "PC-98"),
|
||||
"quasi88/": ("NEC", "PC-98"),
|
||||
"keropi/": ("Sharp", "X68000"),
|
||||
"xmil/": ("Sharp", "X1"),
|
||||
"fuse/": ("Sinclair", "ZX Spectrum"),
|
||||
"vice/": ("Commodore", "C128"),
|
||||
"bk/": ("Elektronika", "BK"),
|
||||
"dragon/": ("Dragon", "Dragon"),
|
||||
"oricutron/": ("Tangerine", "Oric"),
|
||||
"trs80coco/": ("Tandy", "CoCo"),
|
||||
"ti994a/": ("Texas Instruments", "TI-99"),
|
||||
"gamecube/": ("Nintendo", "GameCube"),
|
||||
"Mupen64plus/": ("Nintendo", "Nintendo 64DD"),
|
||||
"ps2/": ("Sony", "PlayStation 2"),
|
||||
"fmtowns/": ("Fujitsu", "FM Towns"),
|
||||
"mame/": ("Arcade", "MAME"),
|
||||
"fbneo/": ("Arcade", "Arcade"),
|
||||
"saves/3ds/": ("Nintendo", "3DS"),
|
||||
"saves/citra-emu/": ("Nintendo", "3DS"),
|
||||
"saves/dolphin-emu/": ("Nintendo", "Wii"),
|
||||
"saves/xbox/": ("Microsoft", "Xbox"),
|
||||
"cemu/": ("Nintendo", "Wii U"),
|
||||
"wsh57/": ("Other", "Misc"),
|
||||
"Machines/COL - ColecoVision/": ("Coleco", "ColecoVision"),
|
||||
"Machines/Shared Roms/": ("Microsoft", "MSX"),
|
||||
"Sony - PlayStation 2/": ("Sony", "PlayStation 2"),
|
||||
"Sony - PlayStation/": ("Sony", "PlayStation"),
|
||||
}
|
||||
|
||||
TOS_PATTERN_MAP = {
|
||||
"tos": ("Atari", "ST"),
|
||||
}
|
||||
|
||||
SKIP_LARGE_ROM_DIRS = {"roms/"}
|
||||
|
||||
SKIP_FILES = {
|
||||
"README.md",
|
||||
".gitignore",
|
||||
"desktop.ini",
|
||||
"telemetry_id",
|
||||
"citra_log.txt",
|
||||
}
|
||||
SKIP_EXTENSIONS = {".txt", ".log", ".pem", ".nvm", ".ctg", ".exe", ".bat", ".sh"}
|
||||
|
||||
|
||||
ARCADE_ROM_PREFIXES = (
|
||||
"roms/fba/",
|
||||
"roms/fbneo/",
|
||||
"roms/mame/",
|
||||
"roms/mame-libretro/",
|
||||
"roms/neogeo/",
|
||||
"roms/naomi/",
|
||||
"roms/atomiswave/",
|
||||
"roms/macintosh/",
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _classify_by_name(name: str, filepath: str) -> tuple[str, str] | None:
|
||||
if name in BIOS_FILE_MAP:
|
||||
return BIOS_FILE_MAP[name]
|
||||
|
||||
for prefix, target in BIOS_FILE_MAP.items():
|
||||
if name.lower().startswith(prefix.lower()) and len(prefix) > 3:
|
||||
return target
|
||||
|
||||
if name.startswith("tos") and name.endswith(".img"):
|
||||
return ("Atari", "ST")
|
||||
|
||||
if name.startswith("kick") and (name.endswith(".rom") or "." in name):
|
||||
return ("Commodore", "Amiga")
|
||||
|
||||
if name.startswith("amiga-"):
|
||||
return ("Commodore", "Amiga")
|
||||
|
||||
if name.upper().startswith("SCPH"):
|
||||
if "70004" in name or "39001" in name or "30004" in name or "10000" in name:
|
||||
return ("Sony", "PlayStation 2")
|
||||
return ("Sony", "PlayStation")
|
||||
|
||||
if name.endswith(".zip") and filepath.startswith(("roms/", "BIOS/")):
|
||||
return ("Arcade", "Arcade")
|
||||
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)
|
||||
|
||||
clean = filepath
|
||||
for prefix in ("bios/", "BIOS/"):
|
||||
if clean.startswith(prefix):
|
||||
clean = clean[len(prefix) :]
|
||||
break
|
||||
|
||||
for prefix in PATH_PREFIX_MAP:
|
||||
if clean.startswith(prefix):
|
||||
remaining = clean[len(prefix) :]
|
||||
if "/" in remaining:
|
||||
return remaining
|
||||
return remaining
|
||||
|
||||
return name
|
||||
@@ -0,0 +1,201 @@
|
||||
"""The move of a flat BIOS tree and of the legacy branches' files into bios/Manufacturer/Console/."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
from acquire.fetch import LEGACY_BRANCHES, legacy_branch_blob, legacy_branch_files
|
||||
from core.hashing import compute_hashes
|
||||
from devtools.biosclassify import classify_file, get_subpath
|
||||
|
||||
SYSTEM_MAP = {
|
||||
"3DO Company, The - 3DO": ("3DO Company", "3DO"),
|
||||
"Arcade": ("Arcade", "Arcade"),
|
||||
"Atari - 400-800": ("Atari", "400-800"),
|
||||
"Atari - 5200": ("Atari", "5200"),
|
||||
"Atari - 7800": ("Atari", "7800"),
|
||||
"Atari - Lynx": ("Atari", "Lynx"),
|
||||
"Atari - ST": ("Atari", "ST"),
|
||||
"Coleco - ColecoVision": ("Coleco", "ColecoVision"),
|
||||
"Commodore - Amiga": ("Commodore", "Amiga"),
|
||||
"Fairchild Channel F": ("Fairchild", "Channel F"),
|
||||
"Id Software - Doom": ("Id Software", "Doom"),
|
||||
"J2ME": ("Java", "J2ME"),
|
||||
"MacII": ("Apple", "Macintosh II"),
|
||||
"Magnavox - Odyssey2": ("Magnavox", "Odyssey2"),
|
||||
"Mattel - Intellivision": ("Mattel", "Intellivision"),
|
||||
"Microsoft - MSX": ("Microsoft", "MSX"),
|
||||
"NEC - PC Engine - TurboGrafx 16 - SuperGrafx": ("NEC", "PC Engine"),
|
||||
"NEC - PC-98": ("NEC", "PC-98"),
|
||||
"NEC - PC-FX": ("NEC", "PC-FX"),
|
||||
"Nintendo - Famicom Disk System": ("Nintendo", "Famicom Disk System"),
|
||||
"Nintendo - Game Boy Advance": ("Nintendo", "Game Boy Advance"),
|
||||
"Nintendo - GameCube": ("Nintendo", "GameCube"),
|
||||
"Nintendo - Gameboy": ("Nintendo", "Game Boy"),
|
||||
"Nintendo - Gameboy Color": ("Nintendo", "Game Boy Color"),
|
||||
"Nintendo - Nintendo 64DD": ("Nintendo", "Nintendo 64DD"),
|
||||
"Nintendo - Nintendo DS": ("Nintendo", "Nintendo DS"),
|
||||
"Nintendo - Nintendo Entertainment System": ("Nintendo", "NES"),
|
||||
"Nintendo - Pokemon Mini": ("Nintendo", "Pokemon Mini"),
|
||||
"Nintendo - Satellaview": ("Nintendo", "Satellaview"),
|
||||
"Nintendo - SuFami Turbo": ("Nintendo", "SuFami Turbo"),
|
||||
"Nintendo - Super Game Boy": ("Nintendo", "Super Game Boy"),
|
||||
"Nintendo - Super Nintendo Entertainment System": ("Nintendo", "SNES"),
|
||||
"Phillips - Videopac+": ("Philips", "Videopac+"),
|
||||
"SNK - NeoGeo CD": ("SNK", "Neo Geo CD"),
|
||||
"ScummVM": ("ScummVM", "ScummVM"),
|
||||
"Sega - Dreamcast": ("Sega", "Dreamcast"),
|
||||
"Sega - Game Gear": ("Sega", "Game Gear"),
|
||||
"Sega - Master System - Mark III": ("Sega", "Master System"),
|
||||
"Sega - Mega CD - Sega CD": ("Sega", "Mega CD"),
|
||||
"Sega - Mega Drive - Genesis": ("Sega", "Mega Drive"),
|
||||
"Sega - Saturn": ("Sega", "Saturn"),
|
||||
"Sharp - X1": ("Sharp", "X1"),
|
||||
"Sharp - X68000": ("Sharp", "X68000"),
|
||||
"Sinclair - ZX Spectrum": ("Sinclair", "ZX Spectrum"),
|
||||
"Sony - PlayStation": ("Sony", "PlayStation"),
|
||||
"Sony - PlayStation Portable": ("Sony", "PlayStation Portable"),
|
||||
"Wolfenstein 3D": ("Id Software", "Wolfenstein 3D"),
|
||||
}
|
||||
|
||||
|
||||
def sha1_blob(data: bytes) -> str:
|
||||
"""Compute SHA1 hash of raw bytes."""
|
||||
return hashlib.sha1(data).hexdigest()
|
||||
|
||||
|
||||
def extract_from_branches(target: Path, dry_run: bool, existing_hashes: set) -> int:
|
||||
"""Extract BIOS files from all branches into the target structure."""
|
||||
extracted = 0
|
||||
|
||||
for branch in LEGACY_BRANCHES:
|
||||
files = legacy_branch_files(branch)
|
||||
if files is None:
|
||||
print(f" Branch {branch} not found, skipping")
|
||||
continue
|
||||
print(f"\n Branch '{branch}': {len(files)} files")
|
||||
|
||||
branch_extracted = 0
|
||||
for filepath in files:
|
||||
classification = classify_file(filepath)
|
||||
if classification is None:
|
||||
continue
|
||||
|
||||
manufacturer, console = classification
|
||||
subpath = get_subpath(filepath, manufacturer, console)
|
||||
dest_dir = target / manufacturer / console
|
||||
dest = dest_dir / subpath
|
||||
|
||||
content = legacy_branch_blob(branch, filepath)
|
||||
if content is None:
|
||||
continue
|
||||
|
||||
file_hash = sha1_blob(content)
|
||||
|
||||
if file_hash in existing_hashes:
|
||||
continue
|
||||
|
||||
if dest.exists():
|
||||
existing_hash = compute_hashes(dest)["sha1"]
|
||||
if existing_hash == file_hash:
|
||||
existing_hashes.add(file_hash)
|
||||
continue
|
||||
variant_dir = dest_dir / ".variants"
|
||||
variant_name = f"{dest.name}.{file_hash[:8]}"
|
||||
dest = variant_dir / variant_name
|
||||
|
||||
if dest.exists():
|
||||
continue
|
||||
|
||||
if dry_run:
|
||||
print(f" VARIANT: {filepath} -> {dest.relative_to(target)}")
|
||||
else:
|
||||
variant_dir.mkdir(parents=True, exist_ok=True)
|
||||
with open(dest, "wb") as f:
|
||||
f.write(content)
|
||||
print(f" VARIANT: {filepath} -> {dest.relative_to(target)}")
|
||||
existing_hashes.add(file_hash)
|
||||
branch_extracted += 1
|
||||
continue
|
||||
|
||||
if dry_run:
|
||||
print(f" NEW: {filepath} -> {dest.relative_to(target)}")
|
||||
else:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(dest, "wb") as f:
|
||||
f.write(content)
|
||||
print(f" NEW: {filepath} -> {dest.relative_to(target)}")
|
||||
|
||||
existing_hashes.add(file_hash)
|
||||
branch_extracted += 1
|
||||
|
||||
print(f" -> {branch_extracted} new files from {branch}")
|
||||
extracted += branch_extracted
|
||||
|
||||
return extracted
|
||||
|
||||
|
||||
def migrate_local(source: Path, target: Path, dry_run: bool) -> tuple:
|
||||
"""Migrate files from local flat structure to Manufacturer/Console hierarchy."""
|
||||
moved = 0
|
||||
skipped = 0
|
||||
errors = []
|
||||
existing_hashes = set()
|
||||
|
||||
for old_dir_name, (manufacturer, console) in sorted(SYSTEM_MAP.items()):
|
||||
old_path = source / old_dir_name
|
||||
if not old_path.is_dir():
|
||||
continue
|
||||
|
||||
new_path = target / manufacturer / console
|
||||
files = [f for f in old_path.iterdir() if f.is_file()]
|
||||
|
||||
if not files:
|
||||
continue
|
||||
|
||||
print(f" {old_dir_name}/ -> bios/{manufacturer}/{console}/")
|
||||
|
||||
if not dry_run:
|
||||
new_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for f in files:
|
||||
dest = new_path / f.name
|
||||
if dest.exists():
|
||||
print(f" SKIP (exists): {f.name}")
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
if dry_run:
|
||||
print(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
|
||||
|
||||
file_hash = compute_hashes(f)["sha1"]
|
||||
existing_hashes.add(file_hash)
|
||||
moved += 1
|
||||
|
||||
return moved, skipped, errors, existing_hashes
|
||||
|
||||
|
||||
def unmapped_directories(source: Path) -> list[str]:
|
||||
"""Folders of the source that no system maps and that are not the repository's own."""
|
||||
known = set(SYSTEM_MAP.keys()) | {
|
||||
"bios",
|
||||
"scripts",
|
||||
"platforms",
|
||||
"schemas",
|
||||
".github",
|
||||
".cache",
|
||||
".git",
|
||||
"README.md",
|
||||
".gitignore",
|
||||
}
|
||||
return [d.name for d in sorted(source.iterdir())
|
||||
if d.name not in known and not d.name.startswith(".") and d.is_dir()]
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Which idle session worktrees and tmp/ entries can go, their removal, and the free space left."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
GENERATED = re.compile(
|
||||
r"^(database\.json|install/.*\.json|exports/.*\.json|README\.md|CONTRIBUTING\.md"
|
||||
r"|website/src/data/[^/]+\.json)$"
|
||||
)
|
||||
KEPT_TMP = ("acquire",)
|
||||
AUTOMATION_WORKTREE = Path(".cache") / "autorun" / "worktree"
|
||||
ALERT_GB = 100
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Decision:
|
||||
path: Path
|
||||
kind: str # worktree, tmp
|
||||
action: str # remove, keep
|
||||
reason: str
|
||||
|
||||
|
||||
def git(cwd: Path, *args: str, check: bool = True) -> str:
|
||||
proc = subprocess.run(
|
||||
["git", "-C", str(cwd), *args], capture_output=True, text=True, check=False,
|
||||
)
|
||||
if check and proc.returncode != 0:
|
||||
raise RuntimeError(f"git {' '.join(args)}: {proc.stderr.strip()}")
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def main_checkout(cwd: Path) -> Path:
|
||||
"""The main checkout, also when run from inside a linked worktree."""
|
||||
common = git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir").strip()
|
||||
return Path(common).parent
|
||||
|
||||
|
||||
def busy_paths() -> set[str]:
|
||||
"""Every working directory and open file of every readable process."""
|
||||
found: set[str] = set()
|
||||
proc = Path("/proc")
|
||||
if not proc.is_dir():
|
||||
return found
|
||||
for pid in proc.iterdir():
|
||||
if not pid.name.isdigit():
|
||||
continue
|
||||
links = [pid / "cwd"]
|
||||
with contextlib.suppress(OSError):
|
||||
links += list((pid / "fd").iterdir())
|
||||
for link in links:
|
||||
try:
|
||||
found.add(os.readlink(link))
|
||||
except OSError:
|
||||
continue
|
||||
return found
|
||||
|
||||
|
||||
def inside(path: Path, root: Path) -> bool:
|
||||
return str(path) == str(root) or str(path).startswith(f"{root}/")
|
||||
|
||||
|
||||
def in_use(path: Path, busy: Iterable[str]) -> bool:
|
||||
root = str(path)
|
||||
prefix = f"{root}/"
|
||||
return any(b == root or b.startswith(prefix) for b in busy)
|
||||
|
||||
|
||||
def age_hours(path: Path, now: float) -> float:
|
||||
return (now - path.stat().st_mtime) / 3600
|
||||
|
||||
|
||||
def real_changes(worktree: Path) -> list[str]:
|
||||
"""Modified tracked paths that are neither deletions nor generated files."""
|
||||
out = git(worktree, "status", "--porcelain", "--untracked-files=no")
|
||||
paths = []
|
||||
for line in out.splitlines():
|
||||
if len(line) < 4 or line[:2].strip() == "D":
|
||||
continue
|
||||
path = line[3:].split(" -> ")[-1].strip('"')
|
||||
if not GENERATED.match(path):
|
||||
paths.append(path)
|
||||
return paths
|
||||
|
||||
|
||||
def linked_worktrees(repo: Path) -> list[Path]:
|
||||
"""Every linked worktree of the checkout, wherever it lives."""
|
||||
out = git(repo, "worktree", "list", "--porcelain")
|
||||
paths = [Path(line[len("worktree "):]) for line in out.splitlines()
|
||||
if line.startswith("worktree ")]
|
||||
return [p for p in paths if p != repo]
|
||||
|
||||
|
||||
def session_worktrees(repo: Path) -> list[Path]:
|
||||
"""Linked worktrees inside the checkout, the automation worktree aside."""
|
||||
keep = repo / AUTOMATION_WORKTREE
|
||||
return [p for p in linked_worktrees(repo) if inside(p, repo) and p != keep]
|
||||
|
||||
|
||||
def judge_worktree(path: Path, busy: Iterable[str], hours: float, now: float) -> Decision:
|
||||
if in_use(path, busy):
|
||||
return Decision(path, "worktree", "keep", "in use")
|
||||
age = age_hours(path, now)
|
||||
if age <= hours:
|
||||
return Decision(path, "worktree", "keep", f"{age:.0f}h recent")
|
||||
real = real_changes(path)
|
||||
if real:
|
||||
return Decision(path, "worktree", "keep", f"uncommitted code: {len(real)} files")
|
||||
return Decision(path, "worktree", "remove", f"{age:.0f}h old, clean")
|
||||
|
||||
|
||||
def judge_tmp(
|
||||
repo: Path, busy: Iterable[str], hours: float, now: float,
|
||||
worktrees: Iterable[Path] = (),
|
||||
) -> list[Decision]:
|
||||
tmp = repo / "tmp"
|
||||
if not tmp.is_dir():
|
||||
return []
|
||||
worktrees = list(worktrees)
|
||||
decisions = []
|
||||
for entry in sorted(tmp.iterdir()):
|
||||
if entry.name in KEPT_TMP or entry.name.endswith(".bundle"):
|
||||
action, reason = "keep", "backup"
|
||||
elif any(inside(w, entry) for w in worktrees):
|
||||
action, reason = "keep", "holds a worktree"
|
||||
elif age_hours(entry, now) <= hours:
|
||||
action, reason = "keep", "recent"
|
||||
elif in_use(entry, busy):
|
||||
action, reason = "keep", "in use"
|
||||
else:
|
||||
action, reason = "remove", "old"
|
||||
decisions.append(Decision(entry, "tmp", action, reason))
|
||||
return decisions
|
||||
|
||||
|
||||
def plan(repo: Path, busy: Iterable[str], hours: float, now: float) -> list[Decision]:
|
||||
busy = set(busy)
|
||||
worktrees = [judge_worktree(w, busy, hours, now) for w in session_worktrees(repo)
|
||||
if w.is_dir()]
|
||||
return worktrees + judge_tmp(repo, busy, hours, now, linked_worktrees(repo))
|
||||
|
||||
|
||||
def apply(repo: Path, decisions: Iterable[Decision]) -> list[str]:
|
||||
"""Carry out the removals, and return the failures."""
|
||||
failures = []
|
||||
removed_worktree = False
|
||||
for d in decisions:
|
||||
if d.action != "remove":
|
||||
continue
|
||||
if d.kind == "worktree":
|
||||
git(repo, "worktree", "unlock", str(d.path), check=False)
|
||||
proc = subprocess.run(
|
||||
["git", "-C", str(repo), "worktree", "remove", "--force", str(d.path)],
|
||||
capture_output=True, text=True, check=False,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
failures.append(f"{d.path}: {proc.stderr.strip()}")
|
||||
removed_worktree = True
|
||||
continue
|
||||
try:
|
||||
if d.path.is_dir() and not d.path.is_symlink():
|
||||
shutil.rmtree(d.path)
|
||||
else:
|
||||
d.path.unlink()
|
||||
except OSError as exc:
|
||||
failures.append(f"{d.path}: {exc}")
|
||||
if removed_worktree:
|
||||
git(repo, "worktree", "prune", check=False)
|
||||
return failures
|
||||
|
||||
|
||||
def disk_line(path: Path, alert_gb: float) -> tuple[str, bool]:
|
||||
usage = shutil.disk_usage(path)
|
||||
free, total = usage.free / 1024 ** 3, usage.total / 1024 ** 3
|
||||
low = free < alert_gb
|
||||
line = f"disk: {free:.0f} GB free of {total:.0f} GB"
|
||||
if low:
|
||||
line += f"\nALERT: free space under {alert_gb:.0f} GB"
|
||||
return line, low
|
||||
@@ -0,0 +1,143 @@
|
||||
"""The test suite run one module per process: the order, each run, the reruns and the timings kept."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable, Iterable
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from core.paths import REPO_ROOT as ROOT
|
||||
|
||||
TESTS = ROOT / "tests"
|
||||
WORK = ROOT / "tmp" / "test-runs"
|
||||
DURATIONS = ROOT / "tmp" / "test-durations.json"
|
||||
# The pty and site-build tests time themselves out under load: more than a
|
||||
# third of the cores at once made them fail for no other reason.
|
||||
DEFAULT_JOBS = max(1, min(6, (os.cpu_count() or 2) // 3))
|
||||
|
||||
# Lines of a failed module's tracebacks printed in the summary.
|
||||
FAILURE_LINES = 200
|
||||
_RAN = re.compile(r"^Ran (\d+) tests? in ([\d.]+)s$", re.M)
|
||||
_COUNTS = re.compile(r"(failures|errors|skipped|expected failures|unexpected successes)=(\d+)")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Result:
|
||||
module: str
|
||||
code: int
|
||||
seconds: float
|
||||
tests: int = 0
|
||||
failures: int = 0
|
||||
errors: int = 0
|
||||
skipped: int = 0
|
||||
log: Path | None = None
|
||||
crashed_then: int | None = None
|
||||
|
||||
@property
|
||||
def passed(self) -> bool:
|
||||
return self.code == 0 if self.crashed_then is None else self.crashed_then == 0
|
||||
|
||||
|
||||
def modules() -> list[str]:
|
||||
return sorted(f"tests.{path.stem}" for path in TESTS.glob("test_*.py"))
|
||||
|
||||
|
||||
def load_durations() -> dict[str, float]:
|
||||
try:
|
||||
data = json.loads(DURATIONS.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except (OSError, ValueError) as exc:
|
||||
print(f"note: {DURATIONS} not read ({exc}), modules weighed by size", file=sys.stderr)
|
||||
return {}
|
||||
return {str(name): float(value) for name, value in data.items()
|
||||
if isinstance(value, (int, float))}
|
||||
|
||||
|
||||
def weight(module: str, durations: dict[str, float]) -> float:
|
||||
"""Seconds the module took last time, else its size as a stand-in."""
|
||||
if module in durations:
|
||||
return durations[module]
|
||||
path = TESTS / f"{module.split('.', 1)[1]}.py"
|
||||
return path.stat().st_size / 2000 if path.exists() else 0.0
|
||||
|
||||
|
||||
def parse(result: Result, text: str) -> None:
|
||||
ran = _RAN.findall(text)
|
||||
if ran:
|
||||
result.tests = int(ran[-1][0])
|
||||
tail = text[text.rfind("\nRan "):] if "\nRan " in text else text
|
||||
for name, count in _COUNTS.findall(tail):
|
||||
if name == "failures":
|
||||
result.failures = int(count)
|
||||
elif name == "errors":
|
||||
result.errors = int(count)
|
||||
elif name == "skipped":
|
||||
result.skipped = int(count)
|
||||
|
||||
|
||||
def run_module(module: str, env: dict[str, str], logs: Path) -> Result:
|
||||
scratch = WORK / "scratch" / module
|
||||
scratch.mkdir(parents=True, exist_ok=True)
|
||||
log = logs / f"{module}.log"
|
||||
started = time.monotonic()
|
||||
with log.open("w", encoding="utf-8") as out:
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "-m", "unittest", module], cwd=ROOT, stdout=out,
|
||||
stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
|
||||
env={**env, "RETROBIOS_TEST_SCRATCH": str(scratch)}, check=False,
|
||||
)
|
||||
result = Result(module, proc.returncode, time.monotonic() - started, log=log)
|
||||
parse(result, log.read_text(encoding="utf-8", errors="replace"))
|
||||
return result
|
||||
|
||||
|
||||
def run_all(order: Iterable[str], jobs: int, env: dict[str, str], logs: Path,
|
||||
say: Callable[[str], None]) -> list[Result]:
|
||||
"""Every module, `jobs` at a time, each failure said as it ends."""
|
||||
results: list[Result] = []
|
||||
with ThreadPoolExecutor(max_workers=jobs) as pool:
|
||||
running = [pool.submit(run_module, name, env, logs) for name in order]
|
||||
for done in as_completed(running):
|
||||
result = done.result()
|
||||
results.append(result)
|
||||
if result.code != 0:
|
||||
why = f"signal {-result.code}" if result.code < 0 else "failed"
|
||||
say(f" {why}: {result.module} ({result.seconds:.0f} s)")
|
||||
return results
|
||||
|
||||
|
||||
def rerun_crashed(results: Iterable[Result], env: dict[str, str], logs: Path,
|
||||
say: Callable[[str], None]) -> None:
|
||||
"""A module a signal killed is the host's doing until it fails alone."""
|
||||
for result in results:
|
||||
if result.code < 0:
|
||||
say(f" again, alone: {result.module}")
|
||||
again = run_module(result.module, env, logs)
|
||||
result.crashed_then = again.code
|
||||
result.tests, result.failures, result.errors, result.skipped = (
|
||||
again.tests, again.failures, again.errors, again.skipped)
|
||||
|
||||
|
||||
def save_durations(durations: dict[str, float], results: Iterable[Result]) -> None:
|
||||
"""The timings of this run over the previous ones, a crashed run left out."""
|
||||
timed = {**durations, **{r.module: round(r.seconds, 1) for r in results if r.code >= 0}}
|
||||
DURATIONS.write_text(json.dumps(timed, indent=1, sort_keys=True), encoding="utf-8")
|
||||
|
||||
|
||||
def failure_excerpt(log: Path) -> list[str]:
|
||||
"""The tracebacks unittest wrote in a module's log, at most a page."""
|
||||
text = log.read_text(encoding="utf-8", errors="replace")
|
||||
start = text.find("\n" + "=" * 70)
|
||||
shown = (text[start:] if start >= 0 else text).strip().splitlines()
|
||||
lines = shown[:FAILURE_LINES]
|
||||
if len(shown) > FAILURE_LINES:
|
||||
lines.append(f"... {len(shown) - FAILURE_LINES} more lines in the log")
|
||||
return lines
|
||||
Reference in new issue
Block a user