From cf03dcb2ef8626d9ca6822d0bc354cc2076aa53b Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:28:46 +0100 Subject: [PATCH] refactor: share CLI options and default paths core.paths holds the default database, platforms, emulators and bios paths, core.cli declares the options built on them (add_repo_inputs) and the --emulator/--system modes verify and generate_pack share. model.targets.target_scope answers --target for a command line, model.profiles.no_profile_for_systems the system with no emulator. tests/sources.declared_options reads the options a script declares through either form. --- scripts/auto_fetch.py | 19 +-------- scripts/bios_integrity.py | 4 +- scripts/check_release_assets.py | 6 +-- scripts/core/cli.py | 27 ++++++++++++ scripts/core/paths.py | 8 ++++ scripts/cross_reference.py | 18 +------- scripts/dedup.py | 9 +--- scripts/diff_truth.py | 6 +-- scripts/export_native.py | 6 +-- scripts/fileless_audit.py | 7 +--- scripts/generate_db.py | 6 +-- scripts/generate_games_index.py | 5 ++- scripts/generate_pack.py | 73 +++++++-------------------------- scripts/generate_readme.py | 10 +---- scripts/generate_site.py | 15 +------ scripts/generate_truth.py | 42 +++++-------------- scripts/identity.py | 6 +-- scripts/mame_ref_audit.py | 7 +--- scripts/model/cliargs.py | 4 +- scripts/model/platforms.py | 3 +- scripts/model/profiles.py | 13 +++++- scripts/model/releaserecord.py | 5 ++- scripts/model/romfolders.py | 5 ++- scripts/model/targets.py | 29 ++++++++++--- scripts/packs/coverage.py | 12 +++--- scripts/packs/emulatorcheck.py | 31 +++----------- scripts/packs/emulatorpack.py | 23 ++--------- scripts/packs/finalize.py | 5 ++- scripts/packs/manifest.py | 4 +- scripts/packs/platformpack.py | 13 ++---- scripts/packs/verdicts.py | 6 --- scripts/pipeline.py | 21 +++++----- scripts/profile_sync.py | 7 +--- scripts/profiling/bump.py | 5 ++- scripts/provenance_report.py | 3 +- scripts/region_audit.py | 7 +--- scripts/release/assets.py | 3 +- scripts/release/record.py | 5 ++- scripts/resolve/identity.py | 3 +- scripts/restore_large_files.py | 6 +-- scripts/romset_recipes.py | 19 +-------- scripts/sitegen/home.py | 3 +- scripts/sitegen/readme.py | 8 ++-- scripts/slots.py | 17 ++------ scripts/sync_release_assets.py | 4 +- scripts/validate_pr.py | 19 ++------- scripts/verify.py | 49 ++++------------------ tests/sources.py | 39 ++++++++++++++++++ tests/test_doc_surfaces.py | 12 +----- tests/test_system_selection.py | 8 ++-- 50 files changed, 260 insertions(+), 405 deletions(-) diff --git a/scripts/auto_fetch.py b/scripts/auto_fetch.py index 9b8a9f9fb..2a2441bf8 100644 --- a/scripts/auto_fetch.py +++ b/scripts/auto_fetch.py @@ -22,7 +22,7 @@ import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from model.cliargs import platform_arg, require_platform -from core.cli import require_directory +from core.cli import add_repo_inputs, require_directory from model.registry import list_registered_platforms from model.database import load_database from model.platforms import load_platform_config @@ -31,10 +31,6 @@ from acquire.fetch import fetch_missing, find_missing, generate_issue_body, look yaml = require_yaml() -DEFAULT_DB = "database.json" -DEFAULT_PLATFORMS_DIR = "platforms" -DEFAULT_BIOS_DIR = "bios" - def main() -> None: parser = argparse.ArgumentParser(allow_abbrev=False, description="Auto-fetch missing BIOS files") @@ -43,18 +39,7 @@ def main() -> None: parser.add_argument( "--dry-run", action="store_true", help="Don't download, just report" ) - parser.add_argument( - "--db", default=DEFAULT_DB, - help="database file to read (default: %(default)s)", - ) - parser.add_argument( - "--platforms-dir", default=DEFAULT_PLATFORMS_DIR, - help="platform YAML directory (default: %(default)s)", - ) - parser.add_argument( - "--bios-dir", default=DEFAULT_BIOS_DIR, - help="BIOS collection directory (default: %(default)s)", - ) + add_repo_inputs(parser, "db", "platforms", "bios") parser.add_argument( "--create-issues", action="store_true", help="Output GitHub Issue bodies" ) diff --git a/scripts/bios_integrity.py b/scripts/bios_integrity.py index 8904ce735..8bf7229b6 100644 --- a/scripts/bios_integrity.py +++ b/scripts/bios_integrity.py @@ -43,6 +43,7 @@ from dataclasses import dataclass, field from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from core.cli import add_repo_inputs from core.hashing import file_digest from model.largefiles import load_registered_paths @@ -193,8 +194,7 @@ def main() -> int: parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.split("\n\n")[0]) parser.add_argument("--apply", action="store_true", help="restore confirmed flips of committed files from HEAD") - parser.add_argument("--db", default="database.json", - help="database file to read (default: %(default)s)") + add_repo_inputs(parser, "db") parser.add_argument("--json", action="store_true", help="machine-readable report") args = parser.parse_args() diff --git a/scripts/check_release_assets.py b/scripts/check_release_assets.py index 9a2fd9b90..16a4de9e6 100644 --- a/scripts/check_release_assets.py +++ b/scripts/check_release_assets.py @@ -19,6 +19,7 @@ import json import subprocess import sys +from core.cli import add_repo_inputs from model.database import load_database from model.largefiles import registered_paths from release.assets import ( @@ -35,10 +36,7 @@ from release.assets import ( def main() -> int: parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.split("\n")[0]) - parser.add_argument( - "--db", default="database.json", - help="database file to read (default: %(default)s)", - ) + add_repo_inputs(parser, "db") parser.add_argument( "--gitignore", default=".gitignore", help="the .gitignore listing release-asset files (default: %(default)s)", diff --git a/scripts/core/cli.py b/scripts/core/cli.py index adf4daa30..b5d438d15 100644 --- a/scripts/core/cli.py +++ b/scripts/core/cli.py @@ -2,6 +2,7 @@ from __future__ import annotations +import argparse import os import signal import sys @@ -9,6 +10,7 @@ from collections.abc import Callable from pathlib import Path from core.artifacts import ArtifactDirectoryMissing, ArtifactLockBusy +from core.paths import BIOS_DIR, DB_FILE, EMULATORS_DIR, PLATFORMS_DIR # Every build script imports this module. verify.py, slots.py, validate_pr.py @@ -72,6 +74,31 @@ def suggest_names( return f"{listing_flag} lists all {total}." +REPO_INPUTS = { + "db": ("--db", DB_FILE, "database file to read"), + "platforms": ("--platforms-dir", PLATFORMS_DIR, "platform YAML directory"), + "emulators": ("--emulators-dir", EMULATORS_DIR, "emulator profile directory"), + "bios": ("--bios-dir", BIOS_DIR, "BIOS collection directory"), +} + + +def add_repo_inputs(parser: argparse.ArgumentParser, *inputs: str) -> None: + """Declare the repository inputs a command reads, in the order given: + any of "db", "platforms", "emulators", "bios".""" + for key in inputs: + flag, default, text = REPO_INPUTS[key] + parser.add_argument(flag, default=default, help=f"{text} (default: %(default)s)") + + +def add_emulator_selection(parser: argparse.ArgumentParser) -> None: + """The --emulator and --system modes that verify and generate_pack share.""" + parser.add_argument("--emulator", "-e", help="Emulator profile name(s), comma-separated") + parser.add_argument("--system", "-s", help="System ID(s), comma-separated") + parser.add_argument("--standalone", action="store_true", help="Use standalone mode") + parser.add_argument("--list-emulators", action="store_true", help="List available emulators") + parser.add_argument("--list-systems", action="store_true", help="List available systems") + + def _exit_on_signal(signum: int, _frame: object) -> None: sys.exit(128 + signum) diff --git a/scripts/core/paths.py b/scripts/core/paths.py index 221a44f74..572e23e5c 100644 --- a/scripts/core/paths.py +++ b/scripts/core/paths.py @@ -9,6 +9,14 @@ from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[2] +# The inputs a command reads unless told otherwise, relative to the +# repository root it runs from. +DB_FILE = "database.json" +PLATFORMS_DIR = "platforms" +EMULATORS_DIR = "emulators" +BIOS_DIR = "bios" + + def sanitize_pack_path(raw: str) -> str: """Strip traversal components from a relative destination. diff --git a/scripts/cross_reference.py b/scripts/cross_reference.py index edb444683..ac10cda60 100644 --- a/scripts/cross_reference.py +++ b/scripts/cross_reference.py @@ -19,6 +19,7 @@ import sys from dataclasses import dataclass sys.path.insert(0, os.path.dirname(__file__)) +from core.cli import add_repo_inputs from model.cliargs import platform_arg, list_emulator_profiles, require_platform from model.profiles import ProfileSelectionError, load_emulator_profiles, select_emulator_profiles from model.database import load_database @@ -34,7 +35,6 @@ from resolve.launchers import ( ) from packs.crossref import ( - DEFAULT_PLATFORMS_DIR, build_supplemental_index, cross_reference, declared_names, @@ -46,9 +46,6 @@ from packs.crossref import ( yaml = require_yaml() -DEFAULT_EMULATORS_DIR = "emulators" -DEFAULT_DB = "database.json" - # The --json key of the launcher reads category, beside the emulator keys. LAUNCHER_READS_KEY = "_launcher_reads_not_held" @@ -187,18 +184,7 @@ def print_report( def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(allow_abbrev=False, description="Emulator vs platform gap analysis") - parser.add_argument( - "--emulators-dir", default=DEFAULT_EMULATORS_DIR, - help="emulator profile directory (default: %(default)s)", - ) - parser.add_argument( - "--platforms-dir", default=DEFAULT_PLATFORMS_DIR, - help="platform YAML directory (default: %(default)s)", - ) - parser.add_argument( - "--db", default=DEFAULT_DB, - help="database file to read (default: %(default)s)", - ) + add_repo_inputs(parser, "emulators", "platforms", "db") parser.add_argument("--emulator", "-e", help="Analyze single emulator") parser.add_argument( "--platform", "-p", type=platform_arg, help="Restrict analysis to one platform's cores" diff --git a/scripts/dedup.py b/scripts/dedup.py index 91b202681..c6570ed2d 100644 --- a/scripts/dedup.py +++ b/scripts/dedup.py @@ -29,12 +29,10 @@ from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) from core.hashing import compute_hashes -from core.cli import require_directory +from core.cli import add_repo_inputs, require_directory from core.artifacts import write_text_atomic from model.nodedup import in_nodedup_dir -DEFAULT_BIOS_DIR = "bios" - def path_priority(path: str) -> tuple: """Lower score = better candidate to keep as canonical. @@ -353,10 +351,7 @@ def main() -> None: parser.add_argument( "--dry-run", action="store_true", help="Preview without deleting" ) - parser.add_argument( - "--bios-dir", default=DEFAULT_BIOS_DIR, - help="BIOS collection directory (default: %(default)s)", - ) + add_repo_inputs(parser, "bios") args = parser.parse_args() require_directory(args.bios_dir) diff --git a/scripts/diff_truth.py b/scripts/diff_truth.py index f95217931..c26532946 100644 --- a/scripts/diff_truth.py +++ b/scripts/diff_truth.py @@ -16,6 +16,7 @@ import os import sys sys.path.insert(0, os.path.dirname(__file__)) +from core.cli import add_repo_inputs from model.cliargs import platform_arg, require_platform from model.registry import list_registered_platforms from model.platforms import load_platform_config, native_layer @@ -206,10 +207,7 @@ def main() -> None: help="directory of the truth models generate_truth writes (default: " "%(default)s)", ) - parser.add_argument( - "--platforms-dir", default="platforms", - help="platform YAML directory (default: %(default)s)", - ) + add_repo_inputs(parser, "platforms") parser.add_argument( "--target", "-t", help="read the models generate_truth --target wrote, each under the " diff --git a/scripts/export_native.py b/scripts/export_native.py index f173d0846..96b5c539a 100644 --- a/scripts/export_native.py +++ b/scripts/export_native.py @@ -21,6 +21,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) +from core.cli import add_repo_inputs from model.cliargs import platform_arg, require_platform from model.registry import list_registered_platforms, load_data_dir_registry, load_platform_registry from exporter import discover_exporters @@ -103,10 +104,7 @@ def main() -> None: help="directory of the truth models generate_truth writes (default: " "%(default)s)", ) - parser.add_argument( - "--platforms-dir", default="platforms", - help="platform YAML directory (default: %(default)s)", - ) + add_repo_inputs(parser, "platforms") parser.add_argument( "--upstream-dir", default=DEFAULT_CACHE, diff --git a/scripts/fileless_audit.py b/scripts/fileless_audit.py index 61aba81b8..8a01b3e61 100644 --- a/scripts/fileless_audit.py +++ b/scripts/fileless_audit.py @@ -25,7 +25,7 @@ from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) from core import upstream -from core.cli import require_directory, suggest_names +from core.cli import add_repo_inputs, require_directory, suggest_names from profiling.citations import collect_citations from profiling.repos import select_views from model.sourceref import ref_role, split_source_ref @@ -109,10 +109,7 @@ def main() -> None: "--all", action="store_true", help="every profile that declares no files and has no answer yet", ) - parser.add_argument( - "--emulators-dir", default="emulators", - help="emulator profile directory (default: %(default)s)", - ) + add_repo_inputs(parser, "emulators") parser.add_argument( "--cache-dir", default=".cache", help="download cache directory (default: %(default)s)", diff --git a/scripts/generate_db.py b/scripts/generate_db.py index 042757d52..c3883d556 100644 --- a/scripts/generate_db.py +++ b/scripts/generate_db.py @@ -21,6 +21,7 @@ from datetime import datetime, timezone from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) +from core.cli import add_repo_inputs from model.dumpcatalog import annotate_provenance, DEFAULT_PROVENANCE_DIR, load_provenance_snapshots from core.hashing import compute_hashes from model.registry import list_registered_platforms @@ -41,7 +42,6 @@ yaml = require_yaml() CACHE_DIR = ".cache" CACHE_FILE = os.path.join(CACHE_DIR, "db_cache.json") -DEFAULT_BIOS_DIR = "bios" DEFAULT_OUTPUT = "database.json" SKIP_PATTERNS = {".git", ".github", "__pycache__", ".cache", ".DS_Store", "desktop.ini"} @@ -464,9 +464,7 @@ def _preserve_large_file_entries(files: dict, db_path: str) -> int: def main() -> int: parser = argparse.ArgumentParser(allow_abbrev=False, description="Generate multi-indexed BIOS database") parser.add_argument("--force", action="store_true", help="Force rehash all files") - parser.add_argument( - "--bios-dir", default=DEFAULT_BIOS_DIR, help="BIOS directory path" - ) + add_repo_inputs(parser, "bios") parser.add_argument( "--output", "-o", default=DEFAULT_OUTPUT, help="Output JSON file" ) diff --git a/scripts/generate_games_index.py b/scripts/generate_games_index.py index 2a8616ad9..8b91b267f 100644 --- a/scripts/generate_games_index.py +++ b/scripts/generate_games_index.py @@ -43,6 +43,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +from core.paths import EMULATORS_DIR, PLATFORMS_DIR from model.profiles import load_emulator_profiles from model.platforms import load_platform_config, native_layer from core.artifacts import repository_output_lock @@ -74,8 +75,8 @@ class Inputs: games: Path = GAMES romfolders: Path = Path("platforms") / "romfolders" install: Path = Path("install") - emulators: str = "emulators" - platforms: str = "platforms" + emulators: str = EMULATORS_DIR + platforms: str = PLATFORMS_DIR def dumps(document: object) -> str: diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index 03715c184..2e0eca553 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -41,10 +41,10 @@ from model.cliargs import ( print_platform_listing, list_system_ids, ) -from core.cli import require_directory +from core.cli import add_emulator_selection, add_repo_inputs, require_directory from model.targets import ( target_listing_line, - build_target_cores_cache, + target_scope, ) from model.systems import ( resolve_system_arg, @@ -67,10 +67,11 @@ from model.registry import ( list_registered_platforms, list_release_pack_platforms, load_data_dir_registry, + load_platform_registry, ) from model.database import load_database from model.platforms import load_platform_config -from model.safeparse import require_yaml, yaml_load +from model.safeparse import require_yaml from resolve import packfiles as packresolve from packs.datadirs import hold_data_dirs from model import region @@ -106,12 +107,7 @@ from packs.targets import generate_target_manifests, target_list yaml = require_yaml() -DEFAULT_PLATFORMS_DIR = "platforms" - - -DEFAULT_DB_FILE = "database.json" DEFAULT_OUTPUT_DIR = "dist" -DEFAULT_BIOS_DIR = "bios" def _json_artifact_kind(path: Path) -> str | None: @@ -354,10 +350,7 @@ def _run_manifest_mode( """Generate JSON manifests instead of ZIP packs.""" registry_path = os.path.join(args.platforms_dir, "_registry.yml") os.makedirs(args.output_dir, exist_ok=True) - registry: dict = {} - if os.path.exists(registry_path): - with open(registry_path) as _rf: - registry = yaml_load(_rf) or {} + platform_registry = load_platform_registry(args.platforms_dir) variants = ALL_VARIANTS if args.all_variants else ((args.source, args.required_only),) @@ -433,7 +426,7 @@ def _run_manifest_mode( alias_manifest["base_destination"] = alias_cfg.get( "base_destination", "" ) - alias_registry = registry.get("platforms", {}).get(alias_plat, {}) + alias_registry = platform_registry.get(alias_plat, {}) alias_install = alias_registry.get("install", {}) alias_manifest["detect"] = alias_install.get("detect", []) # Placed and completed as the representative's are: @@ -497,15 +490,9 @@ def _verify_packs_scope(args: argparse.Namespace) -> tuple[list[str], dict[str, # The target is checked as the build checks it: a mistyped one, or one # the platform does not publish, was dropped and the full pack verified # under it, `all OK` for a pack no build had made. - target_cores_cache: dict[str, set[str] | None] = {} - if args.target: - try: - target_cores_cache, platforms = build_target_cores_cache( - platforms, args.target, args.platforms_dir, is_all=args.all - ) - except (FileNotFoundError, ValueError) as e: - print(f"ERROR: {e}", file=sys.stderr) - sys.exit(1) + target_cores_cache, platforms = target_scope( + platforms, args.target, args.platforms_dir, is_all=args.all + ) return platforms, target_cores_cache @@ -1063,34 +1050,13 @@ def _build_parser() -> argparse.ArgumentParser: help="Generate the release packs (release_pack in the registry), or with" " --manifest the install manifests of every platform", ) - parser.add_argument( - "--emulator", "-e", help="Emulator profile name(s), comma-separated" - ) - parser.add_argument("--system", "-s", help="System ID(s), comma-separated") - parser.add_argument("--standalone", action="store_true", help="Use standalone mode") - parser.add_argument( - "--list-emulators", action="store_true", help="List available emulators" - ) - parser.add_argument( - "--list-systems", action="store_true", help="List available systems" - ) - parser.add_argument( - "--platforms-dir", default=DEFAULT_PLATFORMS_DIR, - help="platform YAML directory (default: %(default)s)", - ) - parser.add_argument("--db", default=DEFAULT_DB_FILE, help="Path to database.json") - parser.add_argument( - "--bios-dir", default=DEFAULT_BIOS_DIR, - help="BIOS collection directory (default: %(default)s)", - ) + add_emulator_selection(parser) + add_repo_inputs(parser, "platforms", "db", "bios") parser.add_argument( "--output-dir", "-o", default=DEFAULT_OUTPUT_DIR, help="directory the packs and manifests go to (default: %(default)s)", ) - parser.add_argument( - "--emulators-dir", default="emulators", - help="emulator profile directory (default: %(default)s)", - ) + add_repo_inputs(parser, "emulators") parser.add_argument( "--offline", action="store_true", @@ -1371,18 +1337,9 @@ def _run_platform_mode( # A mistyped target is refused before the output lock and the data # directory refresh: checked after them, `--target swich` waited on a # pipeline's caches before saying the target does not exist. - target_cores_cache: dict[str, set[str] | None] = {} - if args.target: - try: - target_cores_cache, platforms = build_target_cores_cache( - platforms, - args.target, - args.platforms_dir, - is_all=args.all, - ) - except (FileNotFoundError, ValueError) as e: - print(f"ERROR: {e}", file=sys.stderr) - sys.exit(1) + target_cores_cache, platforms = target_scope( + platforms, args.target, args.platforms_dir, is_all=args.all + ) emu_profiles = load_emulator_profiles(args.emulators_dir) if system_filter: diff --git a/scripts/generate_readme.py b/scripts/generate_readme.py index f661ef303..36bec2751 100644 --- a/scripts/generate_readme.py +++ b/scripts/generate_readme.py @@ -15,6 +15,7 @@ import os import sys sys.path.insert(0, os.path.dirname(__file__)) +from core.cli import add_repo_inputs from model.database import load_database from core.artifacts import repository_output_lock from sitegen.readme import write_readme, generate_readme @@ -22,14 +23,7 @@ from sitegen.readme import write_readme, generate_readme def main() -> None: parser = argparse.ArgumentParser(allow_abbrev=False, description="Generate slim README.md") - parser.add_argument( - "--db", default="database.json", - help="database file to read (default: %(default)s)", - ) - parser.add_argument( - "--platforms-dir", default="platforms", - help="platform YAML directory (default: %(default)s)", - ) + add_repo_inputs(parser, "db", "platforms") args = parser.parse_args() import contextlib diff --git a/scripts/generate_site.py b/scripts/generate_site.py index 5c338c506..32d7dec85 100644 --- a/scripts/generate_site.py +++ b/scripts/generate_site.py @@ -20,7 +20,7 @@ import sys from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) -from core.cli import require_directory +from core.cli import add_repo_inputs, require_directory from core.artifacts import ArtifactLockBusy, artifact_lock from sitegen.build import generate_site @@ -36,18 +36,7 @@ def main() -> None: allow_abbrev=False, description="Generate the documentation site from project data" ) - parser.add_argument( - "--db", default="database.json", - help="database file to read (default: %(default)s)", - ) - parser.add_argument( - "--platforms-dir", default="platforms", - help="platform YAML directory (default: %(default)s)", - ) - parser.add_argument( - "--emulators-dir", default="emulators", - help="emulator profile directory (default: %(default)s)", - ) + add_repo_inputs(parser, "db", "platforms", "emulators") parser.add_argument( "--site-dir", default=STARLIGHT_DIR, help="the Astro Starlight project the site is written into (default: %(default)s)", diff --git a/scripts/generate_truth.py b/scripts/generate_truth.py index e82abb654..2742d3639 100644 --- a/scripts/generate_truth.py +++ b/scripts/generate_truth.py @@ -13,23 +13,21 @@ import os import sys sys.path.insert(0, os.path.dirname(__file__)) -from model.targets import build_target_cores_cache, truth_target_dir +from core.paths import DB_FILE +from model.targets import target_scope, truth_target_dir from model.cliargs import platform_arg, require_platform -from model.registry import list_registered_platforms, load_data_dir_registry +from model.registry import list_registered_platforms, load_data_dir_registry, load_platform_registry from model.database import load_database from model.profiles import load_emulator_profiles from model.platforms import load_platform_config -from core.cli import require_directory -from model.safeparse import require_yaml, yaml_load +from core.cli import add_repo_inputs, require_directory +from model.safeparse import require_yaml from core.artifacts import write_text_atomic from resolve.truth import generate_platform_truth yaml = require_yaml() DEFAULT_OUTPUT_DIR = "dist/truth" -DEFAULT_PLATFORMS_DIR = "platforms" -DEFAULT_EMULATORS_DIR = "emulators" -DEFAULT_DB_FILE = "database.json" def parse_args(argv: list[str] | None = None) -> argparse.Namespace: @@ -51,17 +49,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace: default=None, help="hardware target filter", ) - parser.add_argument( - "--platforms-dir", - default=DEFAULT_PLATFORMS_DIR, - help="platform YAML directory (default: %(default)s)", - ) - parser.add_argument( - "--emulators-dir", - default=DEFAULT_EMULATORS_DIR, - help="emulator profile directory (default: %(default)s)", - ) - parser.add_argument("--db", default=DEFAULT_DB_FILE, help="database.json path") + add_repo_inputs(parser, "platforms", "emulators", "db") return parser.parse_args(argv) @@ -69,9 +57,7 @@ def main(argv: list[str] | None = None) -> None: args = parse_args(argv) require_directory(args.platforms_dir, "--platforms-dir") - registry_path = os.path.join(args.platforms_dir, "_registry.yml") - with open(registry_path) as f: - registry = (yaml_load(f) or {}).get("platforms", {}) + registry = load_platform_registry(args.platforms_dir, required=True) profiles = load_emulator_profiles(args.emulators_dir) data_registry = load_data_dir_registry(args.platforms_dir) @@ -79,7 +65,7 @@ def main(argv: list[str] | None = None) -> None: # Load database (optional) # The default may be absent, but a --db that was named must exist. db: dict | None = None - if args.db != DEFAULT_DB_FILE or os.path.exists(args.db): + if args.db != DB_FILE or os.path.exists(args.db): db = load_database(args.db) if args.all: @@ -93,15 +79,9 @@ def main(argv: list[str] | None = None) -> None: # A named platform without that target is refused, as verify and # generate_pack refuse it: skipped, it printed Done. and exited 0 with # no model written. --all leaves such platforms out and says so. - target_cores_cache: dict[str, set[str] | None] = {} - if args.target: - try: - target_cores_cache, platforms = build_target_cores_cache( - platforms, args.target, args.platforms_dir, is_all=args.all - ) - except (FileNotFoundError, ValueError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - sys.exit(1) + target_cores_cache, platforms = target_scope( + platforms, args.target, args.platforms_dir, is_all=args.all + ) # A target-narrowed model is a different artifact: written under the # platform's own name it overwrote the full one, and diff_truth then diff --git a/scripts/identity.py b/scripts/identity.py index f24ebda8c..3635b7b45 100644 --- a/scripts/identity.py +++ b/scripts/identity.py @@ -2,6 +2,7 @@ from __future__ import annotations +from core.cli import add_repo_inputs from resolve.identity import format_duplicate, scan @@ -12,10 +13,7 @@ def main() -> int: allow_abbrev=False, description="Report one content stored under identities that disagree.", ) - parser.add_argument( - "--bios-dir", default="bios", - help="BIOS collection directory (default: %(default)s)", - ) + add_repo_inputs(parser, "bios") parser.add_argument("--json", action="store_true", help="JSON output") parser.add_argument( "--strict", action="store_true", help="exit non-zero when any is found" diff --git a/scripts/mame_ref_audit.py b/scripts/mame_ref_audit.py index a42fc9b45..1f6320298 100644 --- a/scripts/mame_ref_audit.py +++ b/scripts/mame_ref_audit.py @@ -27,7 +27,7 @@ from dataclasses import dataclass sys.path.insert(0, os.path.dirname(__file__)) from core import upstream -from core.cli import require_directory +from core.cli import add_repo_inputs, require_directory from model.safeparse import yaml_load from scraper.mame_parser import MACHINE_MACROS, strip_comments @@ -129,10 +129,7 @@ def rewrite(name: str, emulators_dir: str, findings: list[Finding]) -> int: def main() -> None: parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.splitlines()[0]) parser.add_argument("emulators", nargs="+", help="MAME-family profiles to audit") - parser.add_argument( - "--emulators-dir", default="emulators", - help="emulator profile directory (default: %(default)s)", - ) + add_repo_inputs(parser, "emulators") parser.add_argument( "--cache-dir", default=upstream.CACHE_DIR, help="download cache directory (default: %(default)s)", diff --git a/scripts/model/cliargs.py b/scripts/model/cliargs.py index 957b6d841..dbdfaa5fe 100644 --- a/scripts/model/cliargs.py +++ b/scripts/model/cliargs.py @@ -16,7 +16,7 @@ from model.platforms import load_platform_config from model.profiles import load_emulator_profiles from model.registry import list_registered_platforms, list_release_pack_platforms from model.systems import platform_system_names, system_index -from core.paths import REPO_ROOT +from core.paths import PLATFORMS_DIR, REPO_ROOT def work_from_repo_root( @@ -62,7 +62,7 @@ def platform_arg(value: str) -> str: return value -def require_platform(name: str, platforms_dir: str = "platforms") -> None: +def require_platform(name: str, platforms_dir: str = PLATFORMS_DIR) -> None: """Exit with a usable message when no platform answers to a name. A typo used to end in a traceback (verify, cross_reference) or in "no diff --git a/scripts/model/platforms.py b/scripts/model/platforms.py index 4a0ca13b7..4a5427402 100644 --- a/scripts/model/platforms.py +++ b/scripts/model/platforms.py @@ -9,6 +9,7 @@ try: except ImportError: yaml = None +from core.paths import PLATFORMS_DIR from model.sources import source_yaml @@ -181,7 +182,7 @@ def _attach_rom_folders(config: dict, platform_name: str, platforms_dir: str) -> config["_rom_folders"] = [row for row in folders if isinstance(row, dict)] -def load_platform_config(platform_name: str, platforms_dir: str = "platforms") -> dict: +def load_platform_config(platform_name: str, platforms_dir: str = PLATFORMS_DIR) -> dict: """Load a platform config with inheritance and shared group resolution. This is the SINGLE implementation used by generate_pack, generate_readme, diff --git a/scripts/model/profiles.py b/scripts/model/profiles.py index 9c8ba0910..e9da1e094 100644 --- a/scripts/model/profiles.py +++ b/scripts/model/profiles.py @@ -15,7 +15,7 @@ except ImportError: from core.cli import InputMissing, suggest_names from model.alternatives import derive_member_requirements from model.sources import source_yaml -from model.systems import norm_system_id +from model.systems import norm_system_id, system_index from core.paths import REPO_ROOT @@ -52,6 +52,17 @@ def profiles_for_systems( return matching +def no_profile_for_systems(profiles: dict, system_ids: list[str], standalone: bool = False) -> str: + """Why profiles_for_systems found nothing, with the closest system ids.""" + kind = "standalone emulators" if standalone else "emulators" + all_systems = sorted({sid for p in profiles.values() for sid in p.get("systems", [])}) + # --list-systems merges spellings that differ in case or separator: + # the hint counted 579 spellings for the 532 lines it prints. + hint = suggest_names(system_ids, all_systems, "--list-systems", + listed=len(system_index(profiles))) + return f"No {kind} found for system(s): {', '.join(system_ids)}\n{hint}" + + def entry_system_ids(entry: dict, profile: dict) -> list[str]: """Systems a profile entry serves. diff --git a/scripts/model/releaserecord.py b/scripts/model/releaserecord.py index 75ce6c963..04e71e4db 100644 --- a/scripts/model/releaserecord.py +++ b/scripts/model/releaserecord.py @@ -5,6 +5,7 @@ from __future__ import annotations import json from pathlib import Path +from core.paths import PLATFORMS_DIR from model.registry import list_release_pack_platforms @@ -32,7 +33,7 @@ def get_page(platform: str, site: str = "") -> str: return f"{site}{GET_DIR}/{platform}/" -def advertised(record: dict, platforms_dir: str = "platforms") -> dict: +def advertised(record: dict, platforms_dir: str = PLATFORMS_DIR) -> dict: """The record as the download tables show it: release_pack platforms only. A release cut before a platform lost its release_pack still holds that @@ -51,7 +52,7 @@ def advertised(record: dict, platforms_dir: str = "platforms") -> dict: return {**record, "packs": packs} -def load_advertised(path: str | Path = RECORD, platforms_dir: str = "platforms") -> dict: +def load_advertised(path: str | Path = RECORD, platforms_dir: str = PLATFORMS_DIR) -> dict: """The committed record, reduced to the platforms a release publishes.""" return advertised(load_record(path), platforms_dir) diff --git a/scripts/model/romfolders.py b/scripts/model/romfolders.py index b9fb58b59..efcfc1a06 100644 --- a/scripts/model/romfolders.py +++ b/scripts/model/romfolders.py @@ -16,6 +16,7 @@ import re from dataclasses import dataclass, field from pathlib import Path +from core.paths import EMULATORS_DIR, PLATFORMS_DIR from model.systems import norm_system_id from model.registry import list_registered_platforms from model.profiles import load_emulator_profiles, preferred_profile, upstream_profile_index @@ -97,7 +98,7 @@ class SystemResolver: @classmethod def from_repo( - cls, emulators_dir: str = "emulators", platforms_dir: str = "platforms" + cls, emulators_dir: str = EMULATORS_DIR, platforms_dir: str = PLATFORMS_DIR ) -> SystemResolver: profiles = load_emulator_profiles(emulators_dir) use: dict[str, int] = {} @@ -159,7 +160,7 @@ class ProfileResolver: index: dict[str, set[str]] @classmethod - def from_repo(cls, emulators_dir: str = "emulators") -> ProfileResolver: + def from_repo(cls, emulators_dir: str = EMULATORS_DIR) -> ProfileResolver: return cls(upstream_profile_index(load_emulator_profiles(emulators_dir))) def resolve(self, core: str | None) -> str | None: diff --git a/scripts/model/targets.py b/scripts/model/targets.py index 76bc4cef0..179e4eedc 100644 --- a/scripts/model/targets.py +++ b/scripts/model/targets.py @@ -4,8 +4,10 @@ from __future__ import annotations import os import re +import sys from pathlib import Path +from core.paths import PLATFORMS_DIR from core.cli import SourceUnreadable, suggest_names from model.sources import source_yaml @@ -29,7 +31,7 @@ def _target_alias_index(targets: dict, overrides: dict) -> dict[str, str]: return alias_index -def platform_files_target(platform: str, target: str, platforms_dir: str = "platforms") -> bool: +def platform_files_target(platform: str, target: str, platforms_dir: str = PLATFORMS_DIR) -> bool: """Whether the platform's targets file knows this target, by any alias.""" targets_dir = os.path.join(platforms_dir, "targets") target_file = os.path.join(targets_dir, f"{platform}.yml") @@ -41,7 +43,7 @@ def platform_files_target(platform: str, target: str, platforms_dir: str = "plat def canonical_target_name( - platforms: list[str], target: str, platforms_dir: str = "platforms" + platforms: list[str], target: str, platforms_dir: str = PLATFORMS_DIR ) -> str: """The name a target is filed under, whichever alias was typed. @@ -66,7 +68,7 @@ def canonical_target_name( def truth_target_dir( - output_dir: str, platforms: list[str], target: str, platforms_dir: str = "platforms" + output_dir: str, platforms: list[str], target: str, platforms_dir: str = PLATFORMS_DIR ) -> str: """Where a target-narrowed truth model is written and read. @@ -84,7 +86,7 @@ def truth_target_dir( def load_target_config( platform_name: str, target: str, - platforms_dir: str = "platforms", + platforms_dir: str = PLATFORMS_DIR, ) -> set[str] | None: """Load target config and return the set of core names for the given target. @@ -169,7 +171,7 @@ def apply_target_overrides( def list_available_targets( platform_name: str, - platforms_dir: str = "platforms", + platforms_dir: str = PLATFORMS_DIR, ) -> list[dict]: """List available targets for a platform with their aliases. @@ -256,6 +258,23 @@ def build_target_cores_cache( return cache, kept +def target_scope( + platforms: list[str], + target: str | None, + platforms_dir: str, + is_all: bool = False, +) -> tuple[dict[str, set[str] | None], list[str]]: + """build_target_cores_cache for a command line: no target keeps every + platform unfiltered, a refused target ends the run with its reason.""" + if not target: + return {}, platforms + try: + return build_target_cores_cache(platforms, target, platforms_dir, is_all=is_all) + except (FileNotFoundError, ValueError) as exc: + print(f"ERROR: {exc}", file=sys.stderr) + sys.exit(1) + + def _unknown_target_message(target: str, platforms: list[str], platforms_dir: str) -> str: """A target no platform has, with the closest names any of them knows.""" import difflib diff --git a/scripts/packs/coverage.py b/scripts/packs/coverage.py index cdc50f607..f9cfa5e91 100644 --- a/scripts/packs/coverage.py +++ b/scripts/packs/coverage.py @@ -6,7 +6,7 @@ import os from dataclasses import dataclass, field from typing import TYPE_CHECKING, TypedDict -from core.paths import declared_destination +from core.paths import BIOS_DIR, EMULATORS_DIR, declared_destination from core.ziptools import build_zip_contents_index from model.alternatives import core_file_spares from model.declarations import OUTER_ROOTS, platform_declarations @@ -16,8 +16,6 @@ from packs import slots from packs.crossref import launcher_reads_not_held from packs.gaps import find_exclusion_notes, find_undeclared_files from packs.verdicts import ( - DEFAULT_BIOS_DIR, - DEFAULT_EMULATORS_DIR, RELEASE_ASSET_PENDING, Severity, Status, @@ -198,7 +196,7 @@ def _twin_index( from resolve.packfiles import preferred_entries as _preferred_entries preferred_entries = _preferred_entries( - verify_systems, db, DEFAULT_BIOS_DIR, base_dest, False, + verify_systems, db, BIOS_DIR, base_dest, False, zip_contents, True, ) winners = { @@ -306,7 +304,7 @@ def _resolve_for_platform( declared_destination(file_entry) ) local_path, status = resolve_declaration( - file_entry, db, DEFAULT_BIOS_DIR, zip_contents, data_dir_registry, + file_entry, db, BIOS_DIR, zip_contents, data_dir_registry, override, offline=True, ) if status in ("not_found", "hash_mismatch") and not run_is_offline(): @@ -690,7 +688,7 @@ def _platform_gaps( run.emulators_dir, run.db, run.emu_profiles, run.target_cores, region_drops, report_for_builder, ExtraResolver( - run.db, DEFAULT_BIOS_DIR, run.zip_contents, run.data_dir_registry, + run.db, BIOS_DIR, run.zip_contents, run.data_dir_registry, validation_index, validation_owners, profiles=run.profiles, pending_assets=True, ), @@ -741,7 +739,7 @@ class PlatformNarrowing(TypedDict, total=False): def verify_platform( config: dict, db: dict, - emulators_dir: str = DEFAULT_EMULATORS_DIR, + emulators_dir: str = EMULATORS_DIR, emu_profiles: dict | None = None, target_cores: set[str] | None = None, data_dir_registry: dict | None = None, diff --git a/scripts/packs/emulatorcheck.py b/scripts/packs/emulatorcheck.py index f881e3b9a..738375d07 100644 --- a/scripts/packs/emulatorcheck.py +++ b/scripts/packs/emulatorcheck.py @@ -7,22 +7,20 @@ import sys from collections.abc import Callable from dataclasses import dataclass, field -from core.cli import suggest_names from core.hashing import compute_hashes -from core.paths import REPO_ROOT +from core.paths import BIOS_DIR, REPO_ROOT from core.ziptools import build_zip_contents_index from model.alternatives import set_requirements, settle_sets, slot_set_keys from model.profiles import ( ProfileSelectionError, entry_serves_systems, load_emulator_profiles, + no_profile_for_systems, profiles_for_systems, select_emulator_profiles, ) from model.registry import load_data_dir_registry -from model.systems import system_index from packs.verdicts import ( - DEFAULT_BIOS_DIR, RELEASE_ASSET_PENDING, Severity, Status, @@ -353,7 +351,7 @@ class _EmulatorPack: local_path, resolve_status = self.pending(own_entry, *resolve_file( own_entry, self.db, - DEFAULT_BIOS_DIR, + BIOS_DIR, self.zip_contents, data_dir_registry=self.data_registry, offline=True, @@ -406,7 +404,7 @@ class _EmulatorPack: local_path, resolve_status = self.pending(file_entry, *resolve_file( {**with_archive_members(file_entry, files), "source_profile": emu_name}, self.db, - DEFAULT_BIOS_DIR, + BIOS_DIR, self.zip_contents, dest_hint=dest_hint, data_dir_registry=self.data_registry, @@ -464,7 +462,7 @@ class _EmulatorPack: # Judged by this emulator's own entries, as it runs its check, # through the selection the emulator pack makes. chosen, disagreement = validated_choice( - file_entry, local_path, self.db, self.validation_index, DEFAULT_BIOS_DIR, + file_entry, local_path, self.db, self.validation_index, BIOS_DIR, None, emulators={emu_name}, ) if disagreement: @@ -739,24 +737,7 @@ def verify_system( matching = profiles_for_systems(profiles, system_ids, standalone) if not matching: - all_systems: set[str] = set() - for p in profiles.values(): - all_systems.update(p.get("systems", [])) - if standalone: - print( - f"No standalone emulators found for system(s): {', '.join(system_ids)}", - file=sys.stderr, - ) - else: - print( - f"No emulators found for system(s): {', '.join(system_ids)}", - file=sys.stderr, - ) - # --list-systems merges spellings that differ in case or separator: - # the hint counted 579 spellings for the 532 lines it prints. - print(suggest_names(system_ids, sorted(all_systems), "--list-systems", - listed=len(system_index(profiles))), - file=sys.stderr) + print(no_profile_for_systems(profiles, system_ids, standalone), file=sys.stderr) sys.exit(1) return verify_emulator( diff --git a/scripts/packs/emulatorpack.py b/scripts/packs/emulatorpack.py index db06f3f92..d9680ca63 100644 --- a/scripts/packs/emulatorpack.py +++ b/scripts/packs/emulatorpack.py @@ -13,7 +13,6 @@ from collections.abc import Callable from dataclasses import dataclass, field from typing import TYPE_CHECKING, TypedDict -from core.cli import suggest_names from core.options import reject_unknown from core.paths import REPO_ROOT from core.ziptools import build_zip_contents_index @@ -22,11 +21,12 @@ from model.profiles import ( ProfileSelectionError, entry_serves_systems, load_emulator_profiles, + no_profile_for_systems, profiles_for_systems, select_emulator_profiles, ) from model.registry import load_data_dir_registry -from model.systems import MANUFACTURER_PREFIXES, system_index +from model.systems import MANUFACTURER_PREFIXES from packs.archive import ( PackRecord, Placed, @@ -567,24 +567,7 @@ def generate_system_pack( matching = profiles_for_systems(profiles, system_ids, standalone) if not matching: - all_systems: set[str] = set() - for p in profiles.values(): - all_systems.update(p.get("systems", [])) - if standalone: - print( - f"No standalone emulators found for system(s): {', '.join(system_ids)}", - file=sys.stderr, - ) - else: - print( - f"No emulators found for system(s): {', '.join(system_ids)}", - file=sys.stderr, - ) - # --list-systems merges spellings that differ in case or separator: - # the hint counted 579 spellings for the 532 lines it prints. - print(suggest_names(system_ids, sorted(all_systems), "--list-systems", - listed=len(system_index(profiles))), - file=sys.stderr) + print(no_profile_for_systems(profiles, system_ids, standalone), file=sys.stderr) return None # Named like the platform's --system tag: one spelling of a system is diff --git a/scripts/packs/finalize.py b/scripts/packs/finalize.py index 714622550..3c16511ce 100644 --- a/scripts/packs/finalize.py +++ b/scripts/packs/finalize.py @@ -13,6 +13,7 @@ from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, TypedDict +from core.paths import EMULATORS_DIR, PLATFORMS_DIR from core.artifacts import set_plain_mode from core.options import reject_unknown from model.registry import list_registered_platforms @@ -111,12 +112,12 @@ class FinalizeOptions(TypedDict, total=False): class _FinalizeSettings: """FinalizeOptions with their defaults.""" - platforms_dir: str = "platforms" + platforms_dir: str = PLATFORMS_DIR skip_conformance: bool = False data_registry: dict | None = None regions: list[str] | None = None target_name: str | None = None - emulators_dir: str = "emulators" + emulators_dir: str = EMULATORS_DIR no_game_data: bool = False pack_systems_by_name: dict[str, dict] | None = None built: Iterable[str] | None = None diff --git a/scripts/packs/manifest.py b/scripts/packs/manifest.py index 5ff7fb462..0054adaa7 100644 --- a/scripts/packs/manifest.py +++ b/scripts/packs/manifest.py @@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, TypedDict from core.artifacts import build_timestamp from core.options import reject_unknown -from core.paths import REPO_ROOT, declared_destination, sanitize_pack_path +from core.paths import EMULATORS_DIR, REPO_ROOT, declared_destination, sanitize_pack_path from model.declarations import OUTER_ROOTS, declared_root, outer_layout from model.platforms import load_platform_config from model.profiles import load_emulator_profiles @@ -109,7 +109,7 @@ class ManifestOptions(InstallListOptions, total=False): class _ManifestSettings: """ManifestOptions with their defaults.""" - emulators_dir: str = "emulators" + emulators_dir: str = EMULATORS_DIR zip_contents: dict | None = None emu_profiles: dict | None = None target_cores: set[str] | None = None diff --git a/scripts/packs/platformpack.py b/scripts/packs/platformpack.py index 06745fea2..cba4345bd 100644 --- a/scripts/packs/platformpack.py +++ b/scripts/packs/platformpack.py @@ -9,17 +9,16 @@ import tempfile import zipfile from collections.abc import Callable, Iterable from dataclasses import dataclass, field -from pathlib import Path from typing import TYPE_CHECKING, TypedDict +from model.registry import load_platform_registry from core.hashing import compute_hashes from core.options import reject_unknown -from core.paths import sanitize_pack_path +from core.paths import EMULATORS_DIR, sanitize_pack_path from model.alternatives import core_file_spares from model.declarations import OUTER_ROOTS, declared_root from model.platforms import load_platform_config from model.profiles import load_emulator_profiles -from model.safeparse import yaml_load from packs import slots from packs.archive import ( CASE_FOLDING_OS, @@ -313,7 +312,7 @@ class PackOptions(PackNarrowing, _PartScope, total=False): class _PackSettings: """PackOptions with their defaults.""" - emulators_dir: str = "emulators" + emulators_dir: str = EMULATORS_DIR zip_contents: dict | None = None data_registry: dict | None = None emu_profiles: dict | None = None @@ -1062,11 +1061,7 @@ class _PlatformPackBuild: def _platform_registry(platforms_dir: str) -> dict: """The platforms of _registry.yml, or nothing when the file is absent.""" - registry_path = Path(platforms_dir) / "_registry.yml" - if not registry_path.exists(): - return {} - with open(registry_path) as f: - return (yaml_load(f) or {}).get("platforms", {}) + return load_platform_registry(platforms_dir) def generate_pack( diff --git a/scripts/packs/verdicts.py b/scripts/packs/verdicts.py index edc664e38..350a87542 100644 --- a/scripts/packs/verdicts.py +++ b/scripts/packs/verdicts.py @@ -13,12 +13,6 @@ from resolve.validation import ( ) -DEFAULT_BIOS_DIR = "bios" - - -DEFAULT_EMULATORS_DIR = "emulators" - - # Status model: aligned with Batocera BiosStatus (batocera-systems:967-969) diff --git a/scripts/pipeline.py b/scripts/pipeline.py index 0739ff297..ad8e98733 100644 --- a/scripts/pipeline.py +++ b/scripts/pipeline.py @@ -69,6 +69,7 @@ if sys.version_info < (3, 9): sys.exit(f"pipeline.py needs Python 3.9 or newer, this is {sys.version.split()[0]}") sys.path.insert(0, str(Path(__file__).parent)) +from core.paths import DB_FILE, EMULATORS_DIR, PLATFORMS_DIR from core.artifacts import ( ArtifactLockBusy, artifact_lock, @@ -332,7 +333,7 @@ def _match_key(label: str) -> set[str]: } - {""} -def release_pack_keys(platforms_dir: str = "platforms") -> set[str]: +def release_pack_keys(platforms_dir: str = PLATFORMS_DIR) -> set[str]: """Comparable identities of the platforms --all builds a pack for: their registry ids and display names, normalized as _match_key does.""" from model.registry import list_release_pack_platforms @@ -452,7 +453,7 @@ _PACK_NOTES = re.compile( def _tree_members( - platform: str, platforms_dir: str, emulators_dir: str = "emulators", + platform: str, platforms_dir: str, emulators_dir: str = EMULATORS_DIR, ) -> dict[str, int]: """Archive path -> size of every file the platform's data trees can add.""" from packs import datatrees @@ -489,7 +490,7 @@ def _set_difference_lines(label: str, credited: set[str], written: set[str]) -> def check_pack_destinations( - destinations_file: str, pack_output: str, platforms_dir: str = "platforms", + destinations_file: str, pack_output: str, platforms_dir: str = PLATFORMS_DIR, ) -> bool: """Compare the paths verify credits with the members of each archive. @@ -567,8 +568,8 @@ def emulator_variants(profiles: list[dict], full: bool) -> list[tuple[str, dict] def check_emulator_packs( - emulators_dir: str = "emulators", platforms_dir: str = "platforms", - db_path: str = "database.json", full: bool = False, + emulators_dir: str = EMULATORS_DIR, platforms_dir: str = PLATFORMS_DIR, + db_path: str = DB_FILE, full: bool = False, ) -> bool: """Build every emulator and system pack in memory and compare it with verify. @@ -731,8 +732,8 @@ def narrowed_variants( def check_narrowed_packs( - emulators_dir: str = "emulators", platforms_dir: str = "platforms", - db_path: str = "database.json", full: bool = False, + emulators_dir: str = EMULATORS_DIR, platforms_dir: str = PLATFORMS_DIR, + db_path: str = DB_FILE, full: bool = False, ) -> bool: """Build each narrowed platform pack in memory and compare it with verify. @@ -852,8 +853,8 @@ def split_differences( def check_split_packs( - emulators_dir: str = "emulators", platforms_dir: str = "platforms", - db_path: str = "database.json", + emulators_dir: str = EMULATORS_DIR, platforms_dir: str = PLATFORMS_DIR, + db_path: str = DB_FILE, ) -> bool: """Build each platform's --split parts in memory and compare them with the full pack: the parts must add up to it, path for path and byte for @@ -972,7 +973,7 @@ def _refuse_unapplied_flags( def _refuse_offline_without_caches( - parser: argparse.ArgumentParser, args: argparse.Namespace, platforms_dir: str = "platforms", + parser: argparse.ArgumentParser, args: argparse.Namespace, platforms_dir: str = PLATFORMS_DIR, ) -> None: """An offline run that builds packs needs the data directories cached. diff --git a/scripts/profile_sync.py b/scripts/profile_sync.py index db43fe67a..9af122678 100644 --- a/scripts/profile_sync.py +++ b/scripts/profile_sync.py @@ -25,7 +25,7 @@ from profiling import version_basis from model.systems import norm_system_id, system_index from core.github import github_token from model.profiles import load_emulator_profiles -from core.cli import suggest_names +from core.cli import add_repo_inputs, suggest_names from profiling.bump import DEFAULT_CACHE, write_version from profiling.realign import realign_prose from profiling.reports import ProfileReport @@ -113,10 +113,7 @@ def build_parser() -> argparse.ArgumentParser: "base with HEAD (default: the project's main line, upstream/main or " "origin/main when that remote names the project, fetched otherwise)", ) - parser.add_argument( - "--emulators-dir", default="emulators", - help="emulator profile directory (default: %(default)s)", - ) + add_repo_inputs(parser, "emulators") parser.add_argument("--system", help="keep profiles covering this system") parser.add_argument("--type", dest="type_", help="keep profiles of this type") parser.add_argument("--stale-before", help="keep profiles profiled before a date") diff --git a/scripts/profiling/bump.py b/scripts/profiling/bump.py index 4a15ea760..0b4a0dd09 100644 --- a/scripts/profiling/bump.py +++ b/scripts/profiling/bump.py @@ -8,6 +8,7 @@ import re import sys from pathlib import Path +from core.paths import PLATFORMS_DIR import yaml from core import upstream @@ -92,7 +93,7 @@ def _platform_cores(emulators_dir: str, platforms_dir: str) -> tuple[tuple[str, def shipping_platforms( - name: str, emulators_dir: str, platforms_dir: str = "platforms", + name: str, emulators_dir: str, platforms_dir: str = PLATFORMS_DIR, ) -> list[str]: """The registered platforms whose cores resolve to this profile.""" return [ @@ -107,7 +108,7 @@ def shipping_platforms( def bump_commit( path: Path, report: ProfileReport, accept_changed: bool = False, cache_dir: str = DEFAULT_CACHE, offline: bool = False, - platforms_dir: str = "platforms", + platforms_dir: str = PLATFORMS_DIR, ) -> bool: """Advance source_commit to HEAD when nothing needs a read again. diff --git a/scripts/provenance_report.py b/scripts/provenance_report.py index a52b7cd64..e98596c34 100644 --- a/scripts/provenance_report.py +++ b/scripts/provenance_report.py @@ -24,6 +24,7 @@ import os import sys sys.path.insert(0, os.path.dirname(__file__)) +from core.cli import add_repo_inputs from model.dumpcatalog import DEFAULT_PROVENANCE_DIR, load_provenance_snapshots from model.database import load_database from model.profiles import load_emulator_profiles @@ -60,7 +61,7 @@ def _print_missing(entry: dict, derived: dict[str, dict]) -> None: def main() -> int: parser = argparse.ArgumentParser(allow_abbrev=False, description="Dump-catalog coverage report") - parser.add_argument("--db", default="database.json", help="Database path") + add_repo_inputs(parser, "db") parser.add_argument( "--provenance-dir", default=DEFAULT_PROVENANCE_DIR, diff --git a/scripts/region_audit.py b/scripts/region_audit.py index 129298f21..55ea8026e 100644 --- a/scripts/region_audit.py +++ b/scripts/region_audit.py @@ -16,6 +16,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) +from core.cli import add_repo_inputs from model.database import load_database from model.profiles import load_emulator_profiles from resolve.regionaudit import build_report @@ -67,11 +68,7 @@ def main() -> int: allow_abbrev=False, description="Cross-check profile region: values against No-Intro provenance" ) - parser.add_argument("--db", default="database.json", help="Path to database.json") - parser.add_argument( - "--emulators-dir", default="emulators", - help="emulator profile directory (default: %(default)s)", - ) + add_repo_inputs(parser, "db", "emulators") parser.add_argument("--json", action="store_true", help="Machine-readable output") args = parser.parse_args() from model.cliargs import work_from_repo_root diff --git a/scripts/release/assets.py b/scripts/release/assets.py index 39a3cb59f..1ca370c04 100644 --- a/scripts/release/assets.py +++ b/scripts/release/assets.py @@ -10,6 +10,7 @@ from collections.abc import Iterable from pathlib import Path from typing import NamedTuple +from core.paths import EMULATORS_DIR from core.hashing import file_digest from model.composition import composition_tier from model.largefiles import LARGE_FILES_RELEASE, LARGE_FILES_REPO, asset_names, registered_paths @@ -234,7 +235,7 @@ def render_notes( return "\n".join(out) -def profile_descriptions(emulators_dir: str = "emulators") -> dict[str, str]: +def profile_descriptions(emulators_dir: str = EMULATORS_DIR) -> dict[str, str]: """Name -> description, from the first profile that declares the file.""" from model.profiles import load_emulator_profiles diff --git a/scripts/release/record.py b/scripts/release/record.py index 78a4a25a2..b16c05708 100644 --- a/scripts/release/record.py +++ b/scripts/release/record.py @@ -6,6 +6,7 @@ import json import zipfile from pathlib import Path +from core.paths import PLATFORMS_DIR from core.artifacts import artifact_lock from model.registry import list_release_pack_platforms from model.releaserecord import SCHEMA_VERSION, pack_name_for @@ -20,7 +21,7 @@ class NotAReleasePackError(Exception): """A pack in the directory is not the full pack of a registered platform.""" -def release_owners(platforms_dir: str = "platforms") -> dict[str, list[str]]: +def release_owners(platforms_dir: str = PLATFORMS_DIR) -> dict[str, list[str]]: """Full pack file name to the platforms it serves, as the builder names it. Rebuilt from the name builder, never matched by substring: matched by @@ -43,7 +44,7 @@ def release_owners(platforms_dir: str = "platforms") -> dict[str, list[str]]: def build_record( dist: Path, tag: str, - platforms_dir: str = "platforms", + platforms_dir: str = PLATFORMS_DIR, owners: dict[str, list[str]] | None = None, ) -> dict: """Read every pack of a directory, parts counted once across them. diff --git a/scripts/resolve/identity.py b/scripts/resolve/identity.py index 73d8e17a1..2a65842ae 100644 --- a/scripts/resolve/identity.py +++ b/scripts/resolve/identity.py @@ -18,6 +18,7 @@ from __future__ import annotations from dataclasses import dataclass from pathlib import Path +from core.paths import BIOS_DIR from core.hashing import file_digest @@ -63,7 +64,7 @@ def _manufacturer(path: Path, root: Path) -> str: return parts[0] if len(parts) > 1 else "" -def scan(bios_dir: str = "bios") -> list[Duplicate]: +def scan(bios_dir: str = BIOS_DIR) -> list[Duplicate]: """Group the tree by content and keep the groups that cross makers. Only files that share a size can share a content, so a size held by one diff --git a/scripts/restore_large_files.py b/scripts/restore_large_files.py index d77f3e071..372a1db47 100644 --- a/scripts/restore_large_files.py +++ b/scripts/restore_large_files.py @@ -19,6 +19,7 @@ from __future__ import annotations import argparse import os +from core.cli import add_repo_inputs from release.restore import restore @@ -28,10 +29,7 @@ def main() -> None: "--cache", default=".cache/large", help="where release assets are cached (default: %(default)s)", ) - parser.add_argument( - "--db", default="database.json", - help="database file to read (default: %(default)s)", - ) + add_repo_inputs(parser, "db") parser.add_argument( "--gitignore", default=".gitignore", help="the .gitignore listing release-asset files (default: %(default)s)", diff --git a/scripts/romset_recipes.py b/scripts/romset_recipes.py index 3b59f703e..44e373c16 100644 --- a/scripts/romset_recipes.py +++ b/scripts/romset_recipes.py @@ -50,7 +50,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) -from core.cli import require_directory +from core.cli import add_repo_inputs, require_directory from core.torrentzip import zlib_ng_version from model.database import load_database from model.profiles import load_emulator_profiles @@ -218,22 +218,7 @@ def main() -> int: help="write reconstructions to .variants/ (implies --missing)", ) parser.add_argument("--json", action="store_true", help="machine-readable output") - parser.add_argument( - "--bios-dir", default="bios", - help="BIOS collection directory (default: %(default)s)", - ) - parser.add_argument( - "--platforms-dir", default="platforms", - help="platform YAML directory (default: %(default)s)", - ) - parser.add_argument( - "--emulators-dir", default="emulators", - help="emulator profile directory (default: %(default)s)", - ) - parser.add_argument( - "--db", default="database.json", - help="database file to read (default: %(default)s)", - ) + add_repo_inputs(parser, "bios", "platforms", "emulators", "db") parser.add_argument( "--dat-recipes", default="recipes", diff --git a/scripts/sitegen/home.py b/scripts/sitegen/home.py index 22f4ad1c1..b8e6572f2 100644 --- a/scripts/sitegen/home.py +++ b/scripts/sitegen/home.py @@ -4,6 +4,7 @@ from __future__ import annotations import html +from core.paths import PLATFORMS_DIR from model.composition import compute_composition from model.guides import DEVICE_GROUPS, GROUP_TILES, GUIDES, Guide, TRUST_ITEMS, setup_count from model.platforms import load_platform_config @@ -82,7 +83,7 @@ def generate_home( coverages: dict, profiles: dict, registry: dict | None = None, - platforms_dir: str = "platforms", + platforms_dir: str = PLATFORMS_DIR, ) -> str: """The page someone lands on knowing nothing: what a BIOS file is, whether they need one, and the three steps to get the right ones. diff --git a/scripts/sitegen/readme.py b/scripts/sitegen/readme.py index 205542d54..ba71c1372 100644 --- a/scripts/sitegen/readme.py +++ b/scripts/sitegen/readme.py @@ -17,7 +17,7 @@ from model import releaserecord from core.artifacts import write_if_changed from core.cli import InputMissing from core.github import github_token -from core.paths import REPO_ROOT +from core.paths import DB_FILE, PLATFORMS_DIR, REPO_ROOT from model.composition import compute_composition, count_catalog_matched from model.declarations import declared_root from model.guides import PACKAGE_COMMAND, install_command @@ -177,7 +177,7 @@ def platform_coverages( db: dict, data_registry: dict | None = None, emulators_dir: str = _EMULATORS_DIR, - db_path: str = "database.json", + db_path: str = DB_FILE, report: Callable[[str, dict], None] | None = None, ) -> dict[str, dict]: """compute_coverage for each platform, read from the cache when its @@ -294,7 +294,7 @@ def asset_links( def download_links( platform_name: str, record: dict, label: str, attrs: str = "", button: Callable[[str, str], str] | None = None, - site: str = "", platforms_dir: str = "platforms", page: str | None = None, + site: str = "", platforms_dir: str = PLATFORMS_DIR, page: str | None = None, ) -> str: """The download cell of a platform: its permanent get/ page. @@ -584,7 +584,7 @@ def archive_line(counts: dict[str, int]) -> str: f" ([rebuilding an archive]({SITE_URL}wiki/archive-recipes/))") -def generate_readme(db: dict, platforms_dir: str, db_path: str = "database.json") -> str: +def generate_readme(db: dict, platforms_dir: str, db_path: str = DB_FILE) -> str: total_files = db.get("total_files", 0) ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") diff --git a/scripts/slots.py b/scripts/slots.py index cc666c09a..291a6282a 100644 --- a/scripts/slots.py +++ b/scripts/slots.py @@ -20,6 +20,8 @@ feeds the report this module prints. from __future__ import annotations +from core.paths import PLATFORMS_DIR +from core.cli import add_repo_inputs from model.cliargs import platform_arg, require_platform from model.database import load_database from model.platforms import load_platform_config @@ -117,7 +119,7 @@ def format_conflict(conflict: Conflict) -> str: def scan_platform( - platform: str, profiles: dict, db: dict, platforms_dir: str = "platforms", + platform: str, profiles: dict, db: dict, platforms_dir: str = PLATFORMS_DIR, target_cores: set[str] | None = None, ) -> list[Conflict]: """Conflicts on one platform, using the cores that platform actually runs.""" @@ -154,18 +156,7 @@ def main() -> int: "--platform", "-p", type=platform_arg, help="one platform instead of all", ) - parser.add_argument( - "--db", default="database.json", - help="database file to read (default: %(default)s)", - ) - parser.add_argument( - "--platforms-dir", default="platforms", - help="platform YAML directory (default: %(default)s)", - ) - parser.add_argument( - "--emulators-dir", default="emulators", - help="emulator profile directory (default: %(default)s)", - ) + add_repo_inputs(parser, "db", "platforms", "emulators") parser.add_argument("--json", action="store_true", help="JSON output") parser.add_argument( "--target", "-t", help="judge only the cores a hardware target builds", diff --git a/scripts/sync_release_assets.py b/scripts/sync_release_assets.py index 547b537e2..11a55e07d 100644 --- a/scripts/sync_release_assets.py +++ b/scripts/sync_release_assets.py @@ -28,6 +28,7 @@ import subprocess import sys from pathlib import Path +from core.cli import add_repo_inputs from model.database import load_database from release.sync import OUT_OF_DATE, open_findings, plan_uploads, upload_all @@ -35,8 +36,7 @@ from release.sync import OUT_OF_DATE, open_findings, plan_uploads, upload_all def main() -> int: parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.split("\n\n")[0]) parser.add_argument("--apply", action="store_true", help="upload (default: dry run)") - parser.add_argument("--db", default="database.json", - help="database file to read (default: %(default)s)") + add_repo_inputs(parser, "db") args = parser.parse_args() root = Path.cwd() diff --git a/scripts/validate_pr.py b/scripts/validate_pr.py index 6aa876f11..75af1eb35 100644 --- a/scripts/validate_pr.py +++ b/scripts/validate_pr.py @@ -26,8 +26,9 @@ from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) +from core.paths import DB_FILE from model.database import load_database -from core.cli import require_directory +from core.cli import add_repo_inputs, require_directory try: import yaml @@ -41,10 +42,6 @@ from resolve.review import ( validate_file, ) -DEFAULT_DB = "database.json" -DEFAULT_PLATFORMS_DIR = "platforms" -DEFAULT_EMULATORS_DIR = "emulators" - def get_changed_files() -> list[str]: """BIOS files this checkout changes against the project's main line. @@ -160,7 +157,7 @@ def _load_database_if_any(path: str) -> dict | None: duplicate and placement checks unchecked. A damaged one did the same after a warning. """ - if path == DEFAULT_DB and not os.path.exists(path): + if path == DB_FILE and not os.path.exists(path): return None return load_database(path) @@ -171,15 +168,7 @@ def main() -> None: parser.add_argument( "--changed", action="store_true", help="Auto-detect changed BIOS files" ) - parser.add_argument("--db", default=DEFAULT_DB, help="Path to database.json") - parser.add_argument( - "--platforms-dir", default=DEFAULT_PLATFORMS_DIR, - help="platform YAML directory (default: %(default)s)", - ) - parser.add_argument( - "--emulators-dir", default=DEFAULT_EMULATORS_DIR, - help="emulator profile directory (default: %(default)s)", - ) + add_repo_inputs(parser, "db", "platforms", "emulators") # One output format: --json beside --markdown printed JSON and dropped # the markdown without a word. formats = parser.add_mutually_exclusive_group() diff --git a/scripts/verify.py b/scripts/verify.py index caff0e473..5d57c3d06 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -32,12 +32,13 @@ from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) +from core.cli import add_emulator_selection, add_repo_inputs from resolve.contentlayout import TARGET_KEY from model.targets import ( canonical_target_name, target_listing_line, list_available_targets, - build_target_cores_cache, + target_scope, ) from model.cliargs import ( platform_arg, @@ -74,13 +75,10 @@ from packs.report import ( print_emulator_result, print_platform_result, ) -from packs.verdicts import DEFAULT_EMULATORS_DIR, Severity, Status +from packs.verdicts import Severity, Status yaml = require_yaml() -DEFAULT_DB = "database.json" -DEFAULT_PLATFORMS_DIR = "platforms" - def _refuse_listing_narrowings( args: argparse.Namespace, parser: argparse.ArgumentParser @@ -180,17 +178,7 @@ def _build_parser() -> argparse.ArgumentParser: parser.add_argument( "--all", action="store_true", help="Verify every registered platform" ) - parser.add_argument( - "--emulator", "-e", help="Emulator profile name(s), comma-separated" - ) - parser.add_argument("--system", "-s", help="System ID(s), comma-separated") - parser.add_argument("--standalone", action="store_true", help="Use standalone mode") - parser.add_argument( - "--list-emulators", action="store_true", help="List available emulators" - ) - parser.add_argument( - "--list-systems", action="store_true", help="List available systems" - ) + add_emulator_selection(parser) parser.add_argument( "--list-platforms", action="store_true", help="List available platforms" ) @@ -213,18 +201,7 @@ def _build_parser() -> argparse.ArgumentParser: help="Report on the pack built with --required-only: files the code " "runs without are left out", ) - parser.add_argument( - "--db", default=DEFAULT_DB, - help="database file to read (default: %(default)s)", - ) - parser.add_argument( - "--platforms-dir", default=DEFAULT_PLATFORMS_DIR, - help="platform YAML directory (default: %(default)s)", - ) - parser.add_argument( - "--emulators-dir", default=DEFAULT_EMULATORS_DIR, - help="emulator profile directory (default: %(default)s)", - ) + add_repo_inputs(parser, "db", "platforms", "emulators") parser.add_argument( "--verbose", "-v", @@ -332,19 +309,11 @@ def _target_scope( platform_systems: list[str] | None, ) -> tuple[dict[str, set[str] | None], list[str]]: """The cores of each platform on --target, and the platforms that have it.""" - target_cores_cache: dict[str, set[str] | None] = {} if not args.target: - return target_cores_cache, platforms - try: - target_cores_cache, platforms = build_target_cores_cache( - platforms, - args.target, - args.platforms_dir, - is_all=args.all, - ) - except (FileNotFoundError, ValueError) as e: - print(f"ERROR: {e}", file=sys.stderr) - sys.exit(1) + return {}, platforms + target_cores_cache, platforms = target_scope( + platforms, args.target, args.platforms_dir, is_all=args.all + ) # A system the target leaves no core for was reported 0/0 with exit 0, # where generate_pack refuses the same request. if platform_systems: diff --git a/tests/sources.py b/tests/sources.py index b15eb063f..17abd6efb 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -7,6 +7,8 @@ command keeps its options, the packages keep the rest. from __future__ import annotations +import ast +from functools import cache from pathlib import Path SCRIPTS = Path(__file__).resolve().parents[1] / "scripts" @@ -107,3 +109,40 @@ def script_paths(name: str) -> tuple[Path, ...]: def script_source(name: str) -> str: """The text of a script and of the package modules that hold its code.""" return "\n".join(path.read_text(encoding="utf-8") for path in script_paths(name)) + + +def _helper_options(function: str) -> frozenset[str]: + """The long options a core.cli helper declares through add_argument.""" + tree = ast.parse((SCRIPTS / "core" / "cli.py").read_text(encoding="utf-8")) + body = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == function) + return frozenset(_add_argument_flags(body)) + + +def _add_argument_flags(tree: ast.AST) -> set[str]: + return { + arg.value + for node in ast.walk(tree) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr == "add_argument" + for arg in node.args + if isinstance(arg, ast.Constant) and isinstance(arg.value, str) and arg.value.startswith("--") + } + + +@cache +def declared_options(source: str) -> frozenset[str]: + """The long options a script's source declares: its add_argument calls and + the shared ones core.cli's add_repo_inputs and add_emulator_selection add.""" + from core.cli import REPO_INPUTS + + tree = ast.parse(source) + found = _add_argument_flags(tree) + for node in ast.walk(tree): + if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Name): + continue + if node.func.id == "add_repo_inputs": + found |= {REPO_INPUTS[arg.value][0] for arg in node.args[1:] + if isinstance(arg, ast.Constant) and arg.value in REPO_INPUTS} + elif node.func.id == "add_emulator_selection": + found |= _helper_options("add_emulator_selection") + return frozenset(found) diff --git a/tests/test_doc_surfaces.py b/tests/test_doc_surfaces.py index 6d78cfd3c..7ee26e261 100644 --- a/tests/test_doc_surfaces.py +++ b/tests/test_doc_surfaces.py @@ -10,9 +10,8 @@ tool prints, and a size is the one the release record holds. from __future__ import annotations import tests -from tests.sources import script_source +from tests.sources import declared_options, script_source -import ast import contextlib import re import unittest @@ -529,14 +528,7 @@ def parser_options(script: str) -> frozenset[str]: """The long options *script* declares through add_argument, with the shared ones of scraper_cli for a scraper that hands its parser over.""" source = (REPO_ROOT / script).read_text(encoding="utf-8") - tree = ast.parse(source) - found = set() - for node in ast.walk(tree): - if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) - and node.func.attr == "add_argument"): - found.update(arg.value for arg in node.args - if isinstance(arg, ast.Constant) and isinstance(arg.value, str) - and arg.value.startswith("--")) + found = set(declared_options(source)) if "scraper_cli(" in source and script != "scripts/scraper/base_scraper.py": found |= parser_options("scripts/scraper/base_scraper.py") return frozenset(found) diff --git a/tests/test_system_selection.py b/tests/test_system_selection.py index 081464949..16496c163 100644 --- a/tests/test_system_selection.py +++ b/tests/test_system_selection.py @@ -29,6 +29,7 @@ from packs import archive from packs import emulatorpack from packs import md5pack from tests.scratchtree import scratch_checkout, snapshot +from tests.sources import declared_options REPO_ROOT = Path(__file__).resolve().parent.parent @@ -215,7 +216,7 @@ class AMissingDatabaseIsNamed(unittest.TestCase): def _taking_db(self) -> list[str]: return sorted( path.name for path in (REPO_ROOT / "scripts").glob("*.py") - if re.search(r'add_argument\(\s*"--db"', path.read_text(encoding="utf-8")) + if "--db" in declared_options(path.read_text(encoding="utf-8")) ) def test_every_script_names_the_missing_file(self): @@ -253,7 +254,7 @@ class AMissingBiosDirIsRefused(unittest.TestCase): out = str(Path(scratch.name) / "out") taking = sorted( path.name for path in (REPO_ROOT / "scripts").glob("*.py") - if re.search(r'add_argument\(\s*"--bios-dir"', path.read_text(encoding="utf-8")) + if "--bios-dir" in declared_options(path.read_text(encoding="utf-8")) and path.name != "generate_db.py" ) self.assertGreater(len(taking), 4) @@ -271,11 +272,10 @@ class AMissingBiosDirIsRefused(unittest.TestCase): def _scripts_taking(flag: str) -> list[Path]: - pattern = re.compile(rf'add_argument\(\s*"{re.escape(flag)}"') return [ path for path in sorted((REPO_ROOT / "scripts").glob("*.py")) + sorted((REPO_ROOT / "scripts" / "scraper").glob("*.py")) - if pattern.search(path.read_text(encoding="utf-8")) + if flag in declared_options(path.read_text(encoding="utf-8")) ]